RecipeHelperImpl.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /*
  2. * This file is licensed under the MIT License, part of Roughly Enough Items.
  3. * Copyright (c) 2018, 2019, 2020 shedaniel
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in all
  13. * copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. package me.shedaniel.rei.impl;
  24. import com.google.common.base.Stopwatch;
  25. import com.google.common.collect.*;
  26. import me.shedaniel.math.Rectangle;
  27. import me.shedaniel.rei.RoughlyEnoughItemsCore;
  28. import me.shedaniel.rei.api.*;
  29. import me.shedaniel.rei.api.fluid.FluidSupportProvider;
  30. import me.shedaniel.rei.api.plugins.REIPluginV0;
  31. import me.shedaniel.rei.api.subsets.SubsetsRegistry;
  32. import me.shedaniel.rei.impl.subsets.SubsetsRegistryImpl;
  33. import me.shedaniel.rei.utils.CollectionUtils;
  34. import net.fabricmc.api.EnvType;
  35. import net.fabricmc.api.Environment;
  36. import net.minecraft.Util;
  37. import net.minecraft.client.gui.screens.Screen;
  38. import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
  39. import net.minecraft.resources.ResourceLocation;
  40. import net.minecraft.world.InteractionResult;
  41. import net.minecraft.world.InteractionResultHolder;
  42. import net.minecraft.world.item.crafting.Recipe;
  43. import net.minecraft.world.item.crafting.RecipeManager;
  44. import org.apache.commons.lang3.tuple.MutablePair;
  45. import org.jetbrains.annotations.ApiStatus;
  46. import org.jetbrains.annotations.NotNull;
  47. import org.jetbrains.annotations.Nullable;
  48. import java.util.*;
  49. import java.util.function.Consumer;
  50. import java.util.function.Function;
  51. import java.util.function.Predicate;
  52. import java.util.stream.Collectors;
  53. import java.util.stream.Stream;
  54. @ApiStatus.Internal
  55. @Environment(EnvType.CLIENT)
  56. public class RecipeHelperImpl implements RecipeHelper {
  57. private static final Comparator<FocusedStackProvider> FOCUSED_STACK_PROVIDER_COMPARATOR = Comparator.comparingDouble(FocusedStackProvider::getPriority).reversed();
  58. private static final Comparator<DisplayVisibilityHandler> VISIBILITY_HANDLER_COMPARATOR = Comparator.comparingDouble(DisplayVisibilityHandler::getPriority).reversed();
  59. @SuppressWarnings("rawtypes")
  60. private static final Comparator<Recipe> RECIPE_COMPARATOR = Comparator.comparing((Recipe o) -> o.getId().getNamespace()).thenComparing(o -> o.getId().getPath());
  61. private final List<FocusedStackProvider> focusedStackProviders = Lists.newArrayList();
  62. private final List<AutoTransferHandler> autoTransferHandlers = Lists.newArrayList();
  63. private final List<RecipeFunction> recipeFunctions = Lists.newArrayList();
  64. private final List<ScreenClickArea> screenClickAreas = Lists.newArrayList();
  65. private final int[] recipeCount = {0};
  66. private final Map<ResourceLocation, List<RecipeDisplay>> recipeDisplays = Maps.newHashMap();
  67. private final BiMap<RecipeCategory<?>, ResourceLocation> categories = HashBiMap.create();
  68. private final Map<ResourceLocation, ButtonAreaSupplier> autoCraftAreaSupplierMap = Maps.newHashMap();
  69. private final Map<ResourceLocation, List<List<EntryStack>>> categoryWorkingStations = Maps.newHashMap();
  70. private final List<DisplayVisibilityHandler> displayVisibilityHandlers = Lists.newArrayList();
  71. private final List<LiveRecipeGenerator<RecipeDisplay>> liveRecipeGenerators = Lists.newArrayList();
  72. private RecipeManager recipeManager;
  73. private boolean arePluginsLoading = false;
  74. @Override
  75. public List<EntryStack> findCraftableEntriesByItems(Iterable<EntryStack> inventoryItems) {
  76. List<EntryStack> craftables = new ArrayList<>();
  77. for (List<RecipeDisplay> value : recipeDisplays.values())
  78. for (RecipeDisplay recipeDisplay : Lists.newArrayList(value)) {
  79. int slotsCraftable = 0;
  80. List<List<EntryStack>> requiredInput = recipeDisplay.getRequiredEntries();
  81. for (List<EntryStack> slot : requiredInput) {
  82. if (slot.isEmpty()) {
  83. slotsCraftable++;
  84. continue;
  85. }
  86. back:
  87. for (EntryStack possibleType : inventoryItems) {
  88. for (EntryStack slotPossible : slot)
  89. if (possibleType.equals(slotPossible)) {
  90. slotsCraftable++;
  91. break back;
  92. }
  93. }
  94. }
  95. if (slotsCraftable == recipeDisplay.getRequiredEntries().size())
  96. recipeDisplay.getResultingEntries().stream().flatMap(Collection::stream).collect(Collectors.toCollection(() -> craftables));
  97. }
  98. return craftables.stream().distinct().collect(Collectors.toList());
  99. }
  100. @Override
  101. public boolean arePluginsLoading() {
  102. return arePluginsLoading;
  103. }
  104. @Override
  105. public void registerCategory(RecipeCategory<?> category) {
  106. categories.put(category, category.getIdentifier());
  107. recipeDisplays.put(category.getIdentifier(), Lists.newArrayList());
  108. categoryWorkingStations.put(category.getIdentifier(), Lists.newArrayList());
  109. }
  110. @SafeVarargs
  111. @Override
  112. public final void registerWorkingStations(ResourceLocation category, List<EntryStack>... workingStations) {
  113. categoryWorkingStations.get(category).addAll(Arrays.asList(workingStations));
  114. }
  115. @Override
  116. public void registerWorkingStations(ResourceLocation category, EntryStack... workingStations) {
  117. categoryWorkingStations.get(category).addAll(Stream.of(workingStations).map(Collections::singletonList).collect(Collectors.toList()));
  118. }
  119. @Override
  120. public List<List<EntryStack>> getWorkingStations(ResourceLocation category) {
  121. return categoryWorkingStations.get(category);
  122. }
  123. @Override
  124. public void registerDisplay(RecipeDisplay display) {
  125. ResourceLocation identifier = Objects.requireNonNull(display.getRecipeCategory());
  126. if (!recipeDisplays.containsKey(identifier))
  127. return;
  128. recipeCount[0]++;
  129. recipeDisplays.get(identifier).add(display);
  130. }
  131. private void registerDisplay(ResourceLocation categoryIdentifier, RecipeDisplay display, int index) {
  132. if (!recipeDisplays.containsKey(categoryIdentifier))
  133. return;
  134. recipeCount[0]++;
  135. recipeDisplays.get(categoryIdentifier).add(index, display);
  136. }
  137. @Override
  138. public Map<RecipeCategory<?>, List<RecipeDisplay>> buildMapFor(ClientHelper.ViewSearchBuilder builder) {
  139. Stopwatch stopwatch = Stopwatch.createStarted();
  140. Set<ResourceLocation> categories = builder.getCategories();
  141. List<EntryStack> recipesFor = builder.getRecipesFor();
  142. List<EntryStack> usagesFor = builder.getUsagesFor();
  143. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  144. for (Map.Entry<RecipeCategory<?>, ResourceLocation> entry : this.categories.entrySet()) {
  145. RecipeCategory<?> category = entry.getKey();
  146. ResourceLocation categoryId = entry.getValue();
  147. List<RecipeDisplay> allRecipesFromCategory = getAllRecipesFromCategory(category);
  148. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  149. if (categories.contains(categoryId)) {
  150. for (RecipeDisplay display : allRecipesFromCategory) {
  151. if (isDisplayVisible(display)) {
  152. set.add(display);
  153. }
  154. }
  155. if (!set.isEmpty()) {
  156. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  157. }
  158. continue;
  159. }
  160. for (RecipeDisplay display : allRecipesFromCategory) {
  161. if (!isDisplayVisible(display)) continue;
  162. if (!recipesFor.isEmpty()) {
  163. back:
  164. for (List<EntryStack> results : display.getResultingEntries()) {
  165. for (EntryStack otherEntry : results) {
  166. for (EntryStack stack : recipesFor) {
  167. if (otherEntry.equals(stack)) {
  168. set.add(display);
  169. break back;
  170. }
  171. }
  172. }
  173. }
  174. }
  175. if (!usagesFor.isEmpty()) {
  176. back:
  177. for (List<EntryStack> input : display.getInputEntries()) {
  178. for (EntryStack otherEntry : input) {
  179. for (EntryStack stack : usagesFor) {
  180. if (otherEntry.equals(stack)) {
  181. set.add(display);
  182. break back;
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. for (EntryStack stack : usagesFor) {
  190. if (isStackWorkStationOfCategory(categoryId, stack)) {
  191. set.addAll(allRecipesFromCategory);
  192. break;
  193. }
  194. }
  195. if (!set.isEmpty()) {
  196. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  197. }
  198. }
  199. for (LiveRecipeGenerator<RecipeDisplay> liveRecipeGenerator : liveRecipeGenerators) {
  200. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  201. for (EntryStack stack : recipesFor) {
  202. Optional<List<RecipeDisplay>> recipeForDisplays = liveRecipeGenerator.getRecipeFor(stack);
  203. if (recipeForDisplays.isPresent()) {
  204. for (RecipeDisplay display : recipeForDisplays.get()) {
  205. if (isDisplayVisible(display))
  206. set.add(display);
  207. }
  208. }
  209. }
  210. for (EntryStack stack : usagesFor) {
  211. Optional<List<RecipeDisplay>> usageForDisplays = liveRecipeGenerator.getUsageFor(stack);
  212. if (usageForDisplays.isPresent()) {
  213. for (RecipeDisplay display : usageForDisplays.get()) {
  214. if (isDisplayVisible(display))
  215. set.add(display);
  216. }
  217. }
  218. }
  219. Optional<List<RecipeDisplay>> displaysGenerated = liveRecipeGenerator.getDisplaysGenerated(builder);
  220. if (displaysGenerated.isPresent()) {
  221. for (RecipeDisplay display : displaysGenerated.get()) {
  222. if (isDisplayVisible(display))
  223. set.add(display);
  224. }
  225. }
  226. if (!set.isEmpty()) {
  227. CollectionUtils.getOrPutEmptyList(result, getCategory(liveRecipeGenerator.getCategoryIdentifier())).addAll(set);
  228. }
  229. }
  230. String message = String.format("Built Recipe View in %s for %d categories, %d recipes for, %d usages for and %d live recipe generators.",
  231. stopwatch.stop().toString(), categories.size(), recipesFor.size(), usagesFor.size(), liveRecipeGenerators.size());
  232. if (ConfigObject.getInstance().doDebugSearchTimeRequired()) {
  233. RoughlyEnoughItemsCore.LOGGER.info(message);
  234. } else {
  235. RoughlyEnoughItemsCore.LOGGER.trace(message);
  236. }
  237. return result;
  238. }
  239. @Override
  240. public Map<RecipeCategory<?>, List<RecipeDisplay>> getRecipesFor(EntryStack stack) {
  241. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addRecipesFor(stack));
  242. }
  243. @Override
  244. public RecipeCategory<?> getCategory(ResourceLocation identifier) {
  245. return categories.inverse().get(identifier);
  246. }
  247. @Override
  248. public RecipeManager getRecipeManager() {
  249. return recipeManager;
  250. }
  251. private boolean isStackWorkStationOfCategory(ResourceLocation category, EntryStack stack) {
  252. for (List<EntryStack> stacks : getWorkingStations(category)) {
  253. for (EntryStack entryStack : stacks) {
  254. if (entryStack.equalsIgnoreTagsAndAmount(stack))
  255. return true;
  256. }
  257. }
  258. return false;
  259. }
  260. @Override
  261. public Map<RecipeCategory<?>, List<RecipeDisplay>> getUsagesFor(EntryStack stack) {
  262. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addUsagesFor(stack));
  263. }
  264. @Override
  265. public List<RecipeCategory<?>> getAllCategories() {
  266. return Lists.newArrayList(categories.keySet());
  267. }
  268. @Override
  269. public Optional<ButtonAreaSupplier> getAutoCraftButtonArea(RecipeCategory<?> category) {
  270. if (!autoCraftAreaSupplierMap.containsKey(category.getIdentifier()))
  271. return Optional.ofNullable(bounds -> new Rectangle(bounds.getMaxX() - 16, bounds.getMaxY() - 16, 10, 10));
  272. return Optional.ofNullable(autoCraftAreaSupplierMap.get(category.getIdentifier()));
  273. }
  274. @Override
  275. public void registerAutoCraftButtonArea(ResourceLocation category, ButtonAreaSupplier rectangle) {
  276. if (rectangle == null) {
  277. autoCraftAreaSupplierMap.remove(category);
  278. } else
  279. autoCraftAreaSupplierMap.put(category, rectangle);
  280. }
  281. private void startSection(MutablePair<Stopwatch, String> sectionData, String section) {
  282. sectionData.setRight(section);
  283. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\"", section);
  284. sectionData.getLeft().start();
  285. }
  286. private void endSection(MutablePair<Stopwatch, String> sectionData) {
  287. sectionData.getLeft().stop();
  288. String section = sectionData.getRight();
  289. RoughlyEnoughItemsCore.LOGGER.debug("Reloading Section: \"%s\" done in %s", section, sectionData.getLeft().toString());
  290. sectionData.getLeft().reset();
  291. }
  292. private void pluginSection(MutablePair<Stopwatch, String> sectionData, String sectionName, List<REIPluginV0> list, Consumer<REIPluginV0> consumer) {
  293. for (REIPluginV0 plugin : list) {
  294. try {
  295. startSection(sectionData, sectionName + " for " + plugin.getPluginIdentifier().toString());
  296. consumer.accept(plugin);
  297. endSection(sectionData);
  298. } catch (Throwable e) {
  299. RoughlyEnoughItemsCore.LOGGER.error(plugin.getPluginIdentifier().toString() + " plugin failed to " + sectionName + "!", e);
  300. }
  301. }
  302. }
  303. public void tryRecipesLoaded(RecipeManager recipeManager) {
  304. try {
  305. recipesLoaded(recipeManager);
  306. } catch (Throwable throwable) {
  307. throwable.printStackTrace();
  308. }
  309. arePluginsLoading = false;
  310. }
  311. public void recipesLoaded(RecipeManager recipeManager) {
  312. long startTime = Util.getMillis();
  313. MutablePair<Stopwatch, String> sectionData = new MutablePair<>(Stopwatch.createUnstarted(), "");
  314. startSection(sectionData, "reset-data");
  315. arePluginsLoading = true;
  316. ScreenHelper.clearLastRecipeScreenData();
  317. recipeCount[0] = 0;
  318. this.recipeManager = recipeManager;
  319. this.recipeDisplays.clear();
  320. this.categories.clear();
  321. this.autoCraftAreaSupplierMap.clear();
  322. this.screenClickAreas.clear();
  323. this.categoryWorkingStations.clear();
  324. this.recipeFunctions.clear();
  325. this.displayVisibilityHandlers.clear();
  326. this.liveRecipeGenerators.clear();
  327. this.autoTransferHandlers.clear();
  328. this.focusedStackProviders.clear();
  329. DisplayHelperImpl displayHelper = (DisplayHelperImpl) DisplayHelper.getInstance();
  330. EntryRegistryImpl entryRegistry = (EntryRegistryImpl) EntryRegistry.getInstance();
  331. ((SubsetsRegistryImpl) SubsetsRegistry.getInstance()).reset();
  332. ((FluidSupportProviderImpl) FluidSupportProvider.getInstance()).reset();
  333. displayHelper.resetData();
  334. displayHelper.resetCache();
  335. BaseBoundsHandler baseBoundsHandler = new BaseBoundsHandlerImpl();
  336. displayHelper.registerHandler(baseBoundsHandler);
  337. displayHelper.setBaseBoundsHandler(baseBoundsHandler);
  338. List<REIPluginEntry> plugins = RoughlyEnoughItemsCore.getPlugins();
  339. plugins.sort(Comparator.comparingInt(REIPluginEntry::getPriority).reversed());
  340. RoughlyEnoughItemsCore.LOGGER.info("Reloading REI, registered %d plugins: %s", plugins.size(), plugins.stream().map(REIPluginEntry::getPluginIdentifier).map(ResourceLocation::toString).collect(Collectors.joining(", ")));
  341. Collections.reverse(plugins);
  342. entryRegistry.reset();
  343. List<REIPluginV0> reiPluginV0s = new ArrayList<>();
  344. endSection(sectionData);
  345. for (REIPluginEntry plugin : plugins) {
  346. try {
  347. if (plugin instanceof REIPluginV0) {
  348. startSection(sectionData, "pre-register for " + plugin.getPluginIdentifier().toString());
  349. ((REIPluginV0) plugin).preRegister();
  350. reiPluginV0s.add((REIPluginV0) plugin);
  351. endSection(sectionData);
  352. }
  353. } catch (Throwable e) {
  354. RoughlyEnoughItemsCore.LOGGER.error(plugin.getPluginIdentifier().toString() + " plugin failed to pre register!", e);
  355. }
  356. }
  357. pluginSection(sectionData, "register-bounds", reiPluginV0s, plugin -> plugin.registerBounds(displayHelper));
  358. pluginSection(sectionData, "register-entries", reiPluginV0s, plugin -> plugin.registerEntries(entryRegistry));
  359. pluginSection(sectionData, "register-categories", reiPluginV0s, plugin -> plugin.registerPluginCategories(this));
  360. pluginSection(sectionData, "register-displays", reiPluginV0s, plugin -> plugin.registerRecipeDisplays(this));
  361. pluginSection(sectionData, "register-others", reiPluginV0s, plugin -> plugin.registerOthers(this));
  362. pluginSection(sectionData, "post-register", reiPluginV0s, REIPluginV0::postRegister);
  363. startSection(sectionData, "recipe-functions");
  364. if (!recipeFunctions.isEmpty()) {
  365. @SuppressWarnings("rawtypes") List<Recipe> allSortedRecipes = getAllSortedRecipes();
  366. for (int i = allSortedRecipes.size() - 1; i >= 0; i--) {
  367. Recipe recipe = allSortedRecipes.get(i);
  368. for (RecipeFunction recipeFunction : recipeFunctions) {
  369. try {
  370. if (recipeFunction.recipeFilter.test(recipe)) {
  371. registerDisplay(recipeFunction.category, (RecipeDisplay) recipeFunction.mappingFunction.apply(recipe), 0);
  372. }
  373. } catch (Throwable e) {
  374. RoughlyEnoughItemsCore.LOGGER.error("Failed to add recipes!", e);
  375. }
  376. }
  377. }
  378. }
  379. endSection(sectionData);
  380. startSection(sectionData, "fill-handlers");
  381. if (getDisplayVisibilityHandlers().isEmpty())
  382. registerRecipeVisibilityHandler(new DisplayVisibilityHandler() {
  383. @Override
  384. public InteractionResult handleDisplay(RecipeCategory<?> category, RecipeDisplay display) {
  385. return InteractionResult.SUCCESS;
  386. }
  387. @Override
  388. public float getPriority() {
  389. return -1f;
  390. }
  391. });
  392. registerFocusedStackProvider(new FocusedStackProvider() {
  393. @Override
  394. @NotNull
  395. public InteractionResultHolder<EntryStack> provide(Screen screen) {
  396. if (screen instanceof AbstractContainerScreen) {
  397. AbstractContainerScreen<?> containerScreen = (AbstractContainerScreen<?>) screen;
  398. if (containerScreen.hoveredSlot != null && !containerScreen.hoveredSlot.getItem().isEmpty())
  399. return InteractionResultHolder.success(EntryStack.create(containerScreen.hoveredSlot.getItem()));
  400. }
  401. return InteractionResultHolder.pass(EntryStack.empty());
  402. }
  403. @Override
  404. public double getPriority() {
  405. return -1.0;
  406. }
  407. });
  408. displayHelper.registerHandler(new OverlayDecider() {
  409. @Override
  410. public boolean isHandingScreen(Class<?> screen) {
  411. return true;
  412. }
  413. @Override
  414. public InteractionResult shouldScreenBeOverlayed(Class<?> screen) {
  415. return AbstractContainerScreen.class.isAssignableFrom(screen) ? InteractionResult.SUCCESS : InteractionResult.PASS;
  416. }
  417. @Override
  418. public float getPriority() {
  419. return -10;
  420. }
  421. });
  422. endSection(sectionData);
  423. // Clear Cache
  424. displayHelper.resetCache();
  425. REIHelper.getInstance().getOverlay().ifPresent(REIOverlay::queueReloadOverlay);
  426. startSection(sectionData, "entry-registry-finalise");
  427. // Finish Reload
  428. entryRegistry.finishReload();
  429. endSection(sectionData);
  430. startSection(sectionData, "entry-registry-refilter");
  431. arePluginsLoading = false;
  432. entryRegistry.refilter();
  433. endSection(sectionData);
  434. startSection(sectionData, "finalizing");
  435. // Clear Cache Again!
  436. displayHelper.resetCache();
  437. REIHelper.getInstance().getOverlay().ifPresent(REIOverlay::queueReloadOverlay);
  438. displayVisibilityHandlers.sort(VISIBILITY_HANDLER_COMPARATOR);
  439. endSection(sectionData);
  440. long usedTime = Util.getMillis() - startTime;
  441. RoughlyEnoughItemsCore.LOGGER.info("Reloaded %d stack entries, %d recipes displays, %d exclusion zones suppliers, %d overlay deciders, %d visibility handlers and %d categories (%s) in %dms.",
  442. entryRegistry.getEntryStacks().count(), recipeCount[0], BaseBoundsHandler.getInstance().supplierSize(), displayHelper.getAllOverlayDeciders().size(), getDisplayVisibilityHandlers().size(), categories.size(), categories.keySet().stream().map(RecipeCategory::getCategoryName).collect(Collectors.joining(", ")), usedTime);
  443. }
  444. @Override
  445. public AutoTransferHandler registerAutoCraftingHandler(AutoTransferHandler handler) {
  446. autoTransferHandlers.add(handler);
  447. autoTransferHandlers.sort(Comparator.comparingDouble(AutoTransferHandler::getPriority).reversed());
  448. return handler;
  449. }
  450. @Override
  451. public void registerFocusedStackProvider(FocusedStackProvider provider) {
  452. focusedStackProviders.add(provider);
  453. focusedStackProviders.sort(FOCUSED_STACK_PROVIDER_COMPARATOR);
  454. }
  455. @Override
  456. @Nullable
  457. public EntryStack getScreenFocusedStack(Screen screen) {
  458. for (FocusedStackProvider provider : focusedStackProviders) {
  459. InteractionResultHolder<EntryStack> result = Objects.requireNonNull(provider.provide(screen));
  460. if (result.getResult() == InteractionResult.SUCCESS) {
  461. if (!result.getObject().isEmpty())
  462. return result.getObject();
  463. return null;
  464. } else if (result.getResult() == InteractionResult.FAIL)
  465. return null;
  466. }
  467. return null;
  468. }
  469. @Override
  470. public List<AutoTransferHandler> getSortedAutoCraftingHandler() {
  471. return autoTransferHandlers;
  472. }
  473. @Override
  474. public int getRecipeCount() {
  475. return recipeCount[0];
  476. }
  477. @Override
  478. @SuppressWarnings("rawtypes")
  479. public List<Recipe> getAllSortedRecipes() {
  480. return getRecipeManager().getRecipes().parallelStream().sorted(RECIPE_COMPARATOR).collect(Collectors.toList());
  481. }
  482. @Override
  483. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipes() {
  484. return buildMapFor(ClientHelper.ViewSearchBuilder.builder().addAllCategories());
  485. }
  486. @Override
  487. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipesNoHandlers() {
  488. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  489. for (Map.Entry<RecipeCategory<?>, ResourceLocation> entry : categories.entrySet()) {
  490. RecipeCategory<?> category = entry.getKey();
  491. ResourceLocation categoryId = entry.getValue();
  492. List<RecipeDisplay> displays = recipeDisplays.get(categoryId);
  493. if (displays != null && !displays.isEmpty()) {
  494. result.put(category, displays);
  495. }
  496. }
  497. return result;
  498. }
  499. @Override
  500. public List<RecipeDisplay> getAllRecipesFromCategory(RecipeCategory<?> category) {
  501. return recipeDisplays.get(category.getIdentifier());
  502. }
  503. @Override
  504. public void registerRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  505. displayVisibilityHandlers.add(visibilityHandler);
  506. }
  507. @Override
  508. public void unregisterRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  509. displayVisibilityHandlers.remove(visibilityHandler);
  510. }
  511. @Override
  512. public List<DisplayVisibilityHandler> getDisplayVisibilityHandlers() {
  513. return Collections.unmodifiableList(displayVisibilityHandlers);
  514. }
  515. @Override
  516. public boolean isDisplayNotVisible(RecipeDisplay display) {
  517. return !isDisplayVisible(display);
  518. }
  519. @Override
  520. public boolean isDisplayVisible(RecipeDisplay display) {
  521. RecipeCategory<?> category = getCategory(display.getRecipeCategory());
  522. try {
  523. for (DisplayVisibilityHandler displayVisibilityHandler : displayVisibilityHandlers) {
  524. InteractionResult visibility = displayVisibilityHandler.handleDisplay(category, display);
  525. if (visibility != InteractionResult.PASS)
  526. return visibility == InteractionResult.SUCCESS;
  527. }
  528. } catch (Throwable throwable) {
  529. RoughlyEnoughItemsCore.LOGGER.error("Failed to check if the recipe is visible!", throwable);
  530. }
  531. return true;
  532. }
  533. @Override
  534. public void registerScreenClickArea(Rectangle rectangle, Class<? extends AbstractContainerScreen<?>> screenClass, ResourceLocation... categories) {
  535. this.screenClickAreas.add(new ScreenClickAreaImpl(screenClass, rectangle, categories));
  536. }
  537. @Override
  538. public <T extends Recipe<?>> void registerRecipes(ResourceLocation category, Class<T> recipeClass, Function<T, RecipeDisplay> mappingFunction) {
  539. recipeFunctions.add(new RecipeFunction(category, recipe -> recipeClass.isAssignableFrom(recipe.getClass()), mappingFunction));
  540. }
  541. @Override
  542. public <T extends Recipe<?>> void registerRecipes(ResourceLocation category,
  543. @SuppressWarnings("rawtypes") Function<Recipe, Boolean> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  544. recipeFunctions.add(new RecipeFunction(category, recipeFilter::apply, mappingFunction));
  545. }
  546. @Override
  547. public <T extends Recipe<?>> void registerRecipes(ResourceLocation category,
  548. @SuppressWarnings("rawtypes") Predicate<Recipe> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  549. recipeFunctions.add(new RecipeFunction(category, recipeFilter, mappingFunction));
  550. }
  551. @Override
  552. public void registerLiveRecipeGenerator(LiveRecipeGenerator<?> liveRecipeGenerator) {
  553. liveRecipeGenerators.add((LiveRecipeGenerator<RecipeDisplay>) liveRecipeGenerator);
  554. }
  555. @Override
  556. public List<ScreenClickArea> getScreenClickAreas() {
  557. return screenClickAreas;
  558. }
  559. private static class ScreenClickAreaImpl implements ScreenClickArea {
  560. private Class<? extends AbstractContainerScreen<?>> screenClass;
  561. private Rectangle rectangle;
  562. private ResourceLocation[] categories;
  563. private ScreenClickAreaImpl(Class<? extends AbstractContainerScreen<?>> screenClass, Rectangle rectangle, ResourceLocation[] categories) {
  564. this.screenClass = screenClass;
  565. this.rectangle = rectangle;
  566. this.categories = categories;
  567. }
  568. public Class<? extends AbstractContainerScreen<?>> getScreenClass() {
  569. return screenClass;
  570. }
  571. public Rectangle getRectangle() {
  572. return rectangle;
  573. }
  574. public ResourceLocation[] getCategories() {
  575. return categories;
  576. }
  577. }
  578. @SuppressWarnings("rawtypes")
  579. private static class RecipeFunction {
  580. private ResourceLocation category;
  581. private Predicate<Recipe> recipeFilter;
  582. private Function mappingFunction;
  583. public RecipeFunction(ResourceLocation category, Predicate<Recipe> recipeFilter, Function<?, RecipeDisplay> mappingFunction) {
  584. this.category = category;
  585. this.recipeFilter = recipeFilter;
  586. this.mappingFunction = mappingFunction;
  587. }
  588. }
  589. }