RecipeHelperImpl.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2018, 2019, 2020 shedaniel
  3. * Licensed under the MIT License (the "License").
  4. */
  5. package me.shedaniel.rei.impl;
  6. import com.google.common.collect.Lists;
  7. import com.google.common.collect.Maps;
  8. import com.google.common.collect.Sets;
  9. import me.shedaniel.math.api.Rectangle;
  10. import me.shedaniel.rei.RoughlyEnoughItemsCore;
  11. import me.shedaniel.rei.api.*;
  12. import me.shedaniel.rei.api.plugins.REIPluginV0;
  13. import me.shedaniel.rei.utils.CollectionUtils;
  14. import net.minecraft.client.gui.screen.ingame.ContainerScreen;
  15. import net.minecraft.recipe.Recipe;
  16. import net.minecraft.recipe.RecipeManager;
  17. import net.minecraft.util.ActionResult;
  18. import net.minecraft.util.Identifier;
  19. import org.jetbrains.annotations.ApiStatus;
  20. import java.util.*;
  21. import java.util.function.Function;
  22. import java.util.function.Predicate;
  23. import java.util.stream.Collectors;
  24. @ApiStatus.Internal
  25. public class RecipeHelperImpl implements RecipeHelper {
  26. private static final Comparator<DisplayVisibilityHandler> VISIBILITY_HANDLER_COMPARATOR;
  27. @SuppressWarnings("rawtypes")
  28. private static final Comparator<Recipe> RECIPE_COMPARATOR = Comparator.comparing((Recipe o) -> o.getId().getNamespace()).thenComparing(o -> o.getId().getPath());
  29. static {
  30. Comparator<DisplayVisibilityHandler> comparator = Comparator.comparingDouble(DisplayVisibilityHandler::getPriority);
  31. VISIBILITY_HANDLER_COMPARATOR = comparator.reversed();
  32. }
  33. private final List<AutoTransferHandler> autoTransferHandlers = Lists.newLinkedList();
  34. private final List<RecipeFunction> recipeFunctions = Lists.newLinkedList();
  35. private final List<ScreenClickArea> screenClickAreas = Lists.newLinkedList();
  36. private final int[] recipeCount = {0};
  37. private final Map<Identifier, List<RecipeDisplay>> recipeCategoryListMap = Maps.newLinkedHashMap();
  38. private final Map<RecipeCategory<?>, Identifier> categories = Maps.newLinkedHashMap();
  39. private final Map<Identifier, RecipeCategory<?>> reversedCategories = Maps.newHashMap();
  40. private final Map<Identifier, ButtonAreaSupplier> autoCraftAreaSupplierMap = Maps.newLinkedHashMap();
  41. private final Map<Identifier, List<List<EntryStack>>> categoryWorkingStations = Maps.newLinkedHashMap();
  42. private final List<DisplayVisibilityHandler> displayVisibilityHandlers = Lists.newLinkedList();
  43. private final List<LiveRecipeGenerator<RecipeDisplay>> liveRecipeGenerators = Lists.newLinkedList();
  44. private RecipeManager recipeManager;
  45. private boolean arePluginsLoading = false;
  46. @Override
  47. public List<EntryStack> findCraftableEntriesByItems(List<EntryStack> inventoryItems) {
  48. List<EntryStack> craftables = new ArrayList<>();
  49. for (List<RecipeDisplay> value : recipeCategoryListMap.values())
  50. for (RecipeDisplay recipeDisplay : Lists.newArrayList(value)) {
  51. int slotsCraftable = 0;
  52. List<List<EntryStack>> requiredInput = recipeDisplay.getRequiredEntries();
  53. for (List<EntryStack> slot : requiredInput) {
  54. if (slot.isEmpty()) {
  55. slotsCraftable++;
  56. continue;
  57. }
  58. back:
  59. for (EntryStack possibleType : inventoryItems) {
  60. for (EntryStack slotPossible : slot)
  61. if (possibleType.equals(slotPossible)) {
  62. slotsCraftable++;
  63. break back;
  64. }
  65. }
  66. }
  67. if (slotsCraftable == recipeDisplay.getRequiredEntries().size())
  68. craftables.addAll(recipeDisplay.getOutputEntries());
  69. }
  70. return craftables.stream().distinct().collect(Collectors.toList());
  71. }
  72. @Override
  73. public boolean arePluginsLoading() {
  74. return arePluginsLoading;
  75. }
  76. @Override
  77. public void registerCategory(RecipeCategory<?> category) {
  78. categories.put(category, category.getIdentifier());
  79. reversedCategories.put(category.getIdentifier(), category);
  80. recipeCategoryListMap.put(category.getIdentifier(), Lists.newArrayList());
  81. categoryWorkingStations.put(category.getIdentifier(), Lists.newArrayList());
  82. }
  83. @SafeVarargs
  84. @Override
  85. public final void registerWorkingStations(Identifier category, List<EntryStack>... workingStations) {
  86. categoryWorkingStations.get(category).addAll(Arrays.asList(workingStations));
  87. }
  88. @Override
  89. public void registerWorkingStations(Identifier category, EntryStack... workingStations) {
  90. categoryWorkingStations.get(category).addAll(Arrays.stream(workingStations).map(Collections::singletonList).collect(Collectors.toList()));
  91. }
  92. @Override
  93. public List<List<EntryStack>> getWorkingStations(Identifier category) {
  94. return categoryWorkingStations.get(category);
  95. }
  96. @Override
  97. public void registerDisplay(Identifier categoryIdentifier, RecipeDisplay display) {
  98. if (!recipeCategoryListMap.containsKey(categoryIdentifier))
  99. return;
  100. recipeCount[0]++;
  101. recipeCategoryListMap.get(categoryIdentifier).add(display);
  102. }
  103. private void registerDisplay(Identifier categoryIdentifier, RecipeDisplay display, int index) {
  104. if (!recipeCategoryListMap.containsKey(categoryIdentifier))
  105. return;
  106. recipeCount[0]++;
  107. recipeCategoryListMap.get(categoryIdentifier).add(index, display);
  108. }
  109. @Override
  110. public Map<RecipeCategory<?>, List<RecipeDisplay>> getRecipesFor(EntryStack stack) {
  111. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  112. for (Map.Entry<RecipeCategory<?>, Identifier> entry : categories.entrySet()) {
  113. RecipeCategory<?> category = entry.getKey();
  114. Identifier categoryId = entry.getValue();
  115. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  116. for (RecipeDisplay display : Lists.newArrayList(recipeCategoryListMap.get(categoryId))) {
  117. for (EntryStack outputStack : display.getOutputEntries())
  118. if (stack.equals(outputStack) && isDisplayVisible(display)) {
  119. set.add(display);
  120. break;
  121. }
  122. }
  123. if (!set.isEmpty())
  124. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  125. }
  126. for (LiveRecipeGenerator<RecipeDisplay> liveRecipeGenerator : liveRecipeGenerators) {
  127. RecipeCategory<?> category = getCategory(liveRecipeGenerator.getCategoryIdentifier());
  128. Optional<List<RecipeDisplay>> recipeFor = liveRecipeGenerator.getRecipeFor(stack);
  129. if (recipeFor.isPresent()) {
  130. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  131. for (RecipeDisplay display : recipeFor.get()) {
  132. if (isDisplayVisible(display))
  133. set.add(display);
  134. }
  135. if (!set.isEmpty())
  136. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  137. }
  138. }
  139. return result;
  140. }
  141. @Override
  142. public RecipeCategory<?> getCategory(Identifier identifier) {
  143. return reversedCategories.get(identifier);
  144. }
  145. @Override
  146. public RecipeManager getRecipeManager() {
  147. return recipeManager;
  148. }
  149. private boolean isStackWorkStationOfCategory(Identifier category, EntryStack stack) {
  150. for (List<EntryStack> stacks : getWorkingStations(category)) {
  151. for (EntryStack entryStack : stacks) {
  152. if (entryStack.equalsIgnoreTagsAndAmount(stack))
  153. return true;
  154. }
  155. }
  156. return false;
  157. }
  158. @Override
  159. public Map<RecipeCategory<?>, List<RecipeDisplay>> getUsagesFor(EntryStack stack) {
  160. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  161. for (Map.Entry<RecipeCategory<?>, Identifier> entry : categories.entrySet()) {
  162. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  163. RecipeCategory<?> category = entry.getKey();
  164. Identifier categoryId = entry.getValue();
  165. for (RecipeDisplay display : Lists.newArrayList(recipeCategoryListMap.get(categoryId))) {
  166. back:
  167. for (List<EntryStack> input : display.getInputEntries()) {
  168. for (EntryStack otherEntry : input) {
  169. if (otherEntry.equals(stack)) {
  170. if (isDisplayVisible(display))
  171. set.add(display);
  172. break back;
  173. }
  174. }
  175. }
  176. }
  177. if (isStackWorkStationOfCategory(categoryId, stack)) {
  178. set.addAll(Lists.newArrayList(recipeCategoryListMap.get(categoryId)));
  179. }
  180. if (!set.isEmpty())
  181. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  182. }
  183. for (LiveRecipeGenerator<RecipeDisplay> liveRecipeGenerator : liveRecipeGenerators) {
  184. RecipeCategory<?> category = getCategory(liveRecipeGenerator.getCategoryIdentifier());
  185. Optional<List<RecipeDisplay>> recipeFor = liveRecipeGenerator.getUsageFor(stack);
  186. if (recipeFor.isPresent()) {
  187. Set<RecipeDisplay> set = Sets.newLinkedHashSet();
  188. for (RecipeDisplay display : recipeFor.get()) {
  189. if (isDisplayVisible(display))
  190. set.add(display);
  191. }
  192. if (!set.isEmpty())
  193. CollectionUtils.getOrPutEmptyList(result, category).addAll(set);
  194. }
  195. }
  196. return result;
  197. }
  198. @Override
  199. public List<RecipeCategory<?>> getAllCategories() {
  200. return Lists.newArrayList(categories.keySet());
  201. }
  202. @Override
  203. public Optional<ButtonAreaSupplier> getAutoCraftButtonArea(RecipeCategory<?> category) {
  204. if (!autoCraftAreaSupplierMap.containsKey(category.getIdentifier()))
  205. return Optional.ofNullable(bounds -> new Rectangle(bounds.getMaxX() - 16, bounds.getMaxY() - 16, 10, 10));
  206. return Optional.ofNullable(autoCraftAreaSupplierMap.get(category.getIdentifier()));
  207. }
  208. @Override
  209. public void registerAutoCraftButtonArea(Identifier category, ButtonAreaSupplier rectangle) {
  210. if (rectangle == null) {
  211. autoCraftAreaSupplierMap.remove(category);
  212. } else
  213. autoCraftAreaSupplierMap.put(category, rectangle);
  214. }
  215. public void recipesLoaded(RecipeManager recipeManager) {
  216. long startTime = System.currentTimeMillis();
  217. arePluginsLoading = true;
  218. ScreenHelper.clearLastRecipeScreenData();
  219. recipeCount[0] = 0;
  220. this.recipeManager = recipeManager;
  221. this.recipeCategoryListMap.clear();
  222. this.categories.clear();
  223. this.reversedCategories.clear();
  224. this.autoCraftAreaSupplierMap.clear();
  225. this.screenClickAreas.clear();
  226. this.categoryWorkingStations.clear();
  227. this.recipeFunctions.clear();
  228. this.displayVisibilityHandlers.clear();
  229. this.liveRecipeGenerators.clear();
  230. this.autoTransferHandlers.clear();
  231. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetData();
  232. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetCache();
  233. BaseBoundsHandler baseBoundsHandler = new BaseBoundsHandlerImpl();
  234. DisplayHelper.getInstance().registerBoundsHandler(baseBoundsHandler);
  235. ((DisplayHelperImpl) DisplayHelper.getInstance()).setBaseBoundsHandler(baseBoundsHandler);
  236. List<REIPluginEntry> plugins = RoughlyEnoughItemsCore.getPlugins();
  237. plugins.sort(Comparator.comparingInt(REIPluginEntry::getPriority).reversed());
  238. RoughlyEnoughItemsCore.LOGGER.info("[REI] Loading %d plugins: %s", plugins.size(), plugins.stream().map(REIPluginEntry::getPluginIdentifier).map(Identifier::toString).collect(Collectors.joining(", ")));
  239. Collections.reverse(plugins);
  240. ((EntryRegistryImpl) EntryRegistry.getInstance()).reset();
  241. List<REIPluginV0> reiPluginV0s = new ArrayList<>();
  242. for (REIPluginEntry plugin : plugins) {
  243. try {
  244. if (plugin instanceof REIPluginV0) {
  245. ((REIPluginV0) plugin).preRegister();
  246. reiPluginV0s.add((REIPluginV0) plugin);
  247. }
  248. } catch (Throwable e) {
  249. RoughlyEnoughItemsCore.LOGGER.error("[REI] " + plugin.getPluginIdentifier().toString() + " plugin failed to pre register!", e);
  250. }
  251. }
  252. for (REIPluginV0 plugin : reiPluginV0s) {
  253. Identifier identifier = plugin.getPluginIdentifier();
  254. try {
  255. plugin.registerBounds(DisplayHelper.getInstance());
  256. plugin.registerEntries(EntryRegistry.getInstance());
  257. plugin.registerPluginCategories(this);
  258. plugin.registerRecipeDisplays(this);
  259. plugin.registerOthers(this);
  260. } catch (Throwable e) {
  261. RoughlyEnoughItemsCore.LOGGER.error("[REI] " + identifier.toString() + " plugin failed to load!", e);
  262. }
  263. }
  264. for (REIPluginV0 plugin : reiPluginV0s) {
  265. Identifier identifier = plugin.getPluginIdentifier();
  266. try {
  267. plugin.postRegister();
  268. } catch (Throwable e) {
  269. RoughlyEnoughItemsCore.LOGGER.error("[REI] " + identifier.toString() + " plugin failed to post register!", e);
  270. }
  271. }
  272. if (!recipeFunctions.isEmpty()) {
  273. @SuppressWarnings("rawtypes") List<Recipe> allSortedRecipes = getAllSortedRecipes();
  274. Collections.reverse(allSortedRecipes);
  275. for (RecipeFunction recipeFunction : recipeFunctions) {
  276. try {
  277. for (Recipe<?> recipe : CollectionUtils.filter(allSortedRecipes, recipe -> recipeFunction.recipeFilter.test(recipe))) {
  278. registerDisplay(recipeFunction.category, (RecipeDisplay) recipeFunction.mappingFunction.apply(recipe), 0);
  279. }
  280. } catch (Exception e) {
  281. RoughlyEnoughItemsCore.LOGGER.error("[REI] Failed to add recipes!", e);
  282. }
  283. }
  284. }
  285. if (getDisplayVisibilityHandlers().isEmpty())
  286. registerRecipeVisibilityHandler(new DisplayVisibilityHandler() {
  287. @Override
  288. public ActionResult handleDisplay(RecipeCategory<?> category, RecipeDisplay display) {
  289. return ActionResult.SUCCESS;
  290. }
  291. @Override
  292. public float getPriority() {
  293. return -1f;
  294. }
  295. });
  296. // Clear Cache
  297. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetCache();
  298. ScreenHelper.getOptionalOverlay().ifPresent(overlay -> overlay.shouldReInit = true);
  299. arePluginsLoading = false;
  300. // Remove duplicate entries
  301. ((EntryRegistryImpl) EntryRegistry.getInstance()).distinct();
  302. // Clear Cache Again!
  303. ((DisplayHelperImpl) DisplayHelper.getInstance()).resetCache();
  304. ScreenHelper.getOptionalOverlay().ifPresent(overlay -> overlay.shouldReInit = true);
  305. displayVisibilityHandlers.sort(VISIBILITY_HANDLER_COMPARATOR);
  306. long usedTime = System.currentTimeMillis() - startTime;
  307. RoughlyEnoughItemsCore.LOGGER.info("[REI] Registered %d stack entries, %d recipes displays, %d exclusion zones suppliers, %d bounds handler, %d visibility handlers and %d categories (%s) in %d ms.", EntryRegistry.getInstance().getStacksList().size(), recipeCount[0], DisplayHelper.getInstance().getBaseBoundsHandler().supplierSize(), DisplayHelper.getInstance().getAllBoundsHandlers().size(), getDisplayVisibilityHandlers().size(), categories.size(), categories.keySet().stream().map(RecipeCategory::getCategoryName).collect(Collectors.joining(", ")), usedTime);
  308. }
  309. @Override
  310. public AutoTransferHandler registerAutoCraftingHandler(AutoTransferHandler handler) {
  311. autoTransferHandlers.add(handler);
  312. return handler;
  313. }
  314. @Override
  315. public List<AutoTransferHandler> getSortedAutoCraftingHandler() {
  316. return autoTransferHandlers.stream().sorted(Comparator.comparingDouble(AutoTransferHandler::getPriority).reversed()).collect(Collectors.toList());
  317. }
  318. @Override
  319. public int getRecipeCount() {
  320. return recipeCount[0];
  321. }
  322. @Override
  323. @SuppressWarnings("rawtypes")
  324. public List<Recipe> getAllSortedRecipes() {
  325. return getRecipeManager().values().stream().sorted(RECIPE_COMPARATOR).collect(Collectors.toList());
  326. }
  327. @Override
  328. public Map<RecipeCategory<?>, List<RecipeDisplay>> getAllRecipes() {
  329. Map<RecipeCategory<?>, List<RecipeDisplay>> result = Maps.newLinkedHashMap();
  330. for (Map.Entry<RecipeCategory<?>, Identifier> entry : categories.entrySet()) {
  331. RecipeCategory<?> category = entry.getKey();
  332. Identifier categoryId = entry.getValue();
  333. List<RecipeDisplay> displays = Lists.newArrayList(recipeCategoryListMap.get(categoryId));
  334. if (displays != null) {
  335. displays.removeIf(this::isDisplayNotVisible);
  336. if (!displays.isEmpty())
  337. result.put(category, displays);
  338. }
  339. }
  340. return result;
  341. }
  342. @Override
  343. public List<RecipeDisplay> getAllRecipesFromCategory(RecipeCategory<?> category) {
  344. return Lists.newArrayList(recipeCategoryListMap.get(category.getIdentifier()));
  345. }
  346. @Override
  347. public void registerRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  348. displayVisibilityHandlers.add(visibilityHandler);
  349. }
  350. @Override
  351. public void unregisterRecipeVisibilityHandler(DisplayVisibilityHandler visibilityHandler) {
  352. displayVisibilityHandlers.remove(visibilityHandler);
  353. }
  354. @Override
  355. public List<DisplayVisibilityHandler> getDisplayVisibilityHandlers() {
  356. return Collections.unmodifiableList(displayVisibilityHandlers);
  357. }
  358. @Override
  359. public boolean isDisplayNotVisible(RecipeDisplay display) {
  360. return !isDisplayVisible(display);
  361. }
  362. @Override
  363. public boolean isDisplayVisible(RecipeDisplay display) {
  364. RecipeCategory<?> category = getCategory(display.getRecipeCategory());
  365. try {
  366. for (DisplayVisibilityHandler displayVisibilityHandler : displayVisibilityHandlers) {
  367. ActionResult visibility = displayVisibilityHandler.handleDisplay(category, display);
  368. if (visibility != ActionResult.PASS)
  369. return visibility == ActionResult.SUCCESS;
  370. }
  371. } catch (Throwable throwable) {
  372. RoughlyEnoughItemsCore.LOGGER.error("[REI] Failed to check if the recipe is visible!", throwable);
  373. }
  374. return true;
  375. }
  376. @Override
  377. public void registerScreenClickArea(Rectangle rectangle, Class<? extends ContainerScreen<?>> screenClass, Identifier... categories) {
  378. this.screenClickAreas.add(new ScreenClickAreaImpl(screenClass, rectangle, categories));
  379. }
  380. @Override
  381. public <T extends Recipe<?>> void registerRecipes(Identifier category, Class<T> recipeClass, Function<T, RecipeDisplay> mappingFunction) {
  382. recipeFunctions.add(new RecipeFunction(category, recipe -> recipeClass.isAssignableFrom(recipe.getClass()), mappingFunction));
  383. }
  384. @Override
  385. public <T extends Recipe<?>> void registerRecipes(Identifier category,
  386. @SuppressWarnings("rawtypes") Function<Recipe, Boolean> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  387. recipeFunctions.add(new RecipeFunction(category, recipeFilter::apply, mappingFunction));
  388. }
  389. @Override
  390. public <T extends Recipe<?>> void registerRecipes(Identifier category,
  391. @SuppressWarnings("rawtypes") Predicate<Recipe> recipeFilter, Function<T, RecipeDisplay> mappingFunction) {
  392. recipeFunctions.add(new RecipeFunction(category, recipeFilter, mappingFunction));
  393. }
  394. @Override
  395. public void registerLiveRecipeGenerator(LiveRecipeGenerator<?> liveRecipeGenerator) {
  396. liveRecipeGenerators.add((LiveRecipeGenerator<RecipeDisplay>) liveRecipeGenerator);
  397. }
  398. @Override
  399. public List<ScreenClickArea> getScreenClickAreas() {
  400. return screenClickAreas;
  401. }
  402. private static class ScreenClickAreaImpl implements ScreenClickArea {
  403. Class<? extends ContainerScreen<?>> screenClass;
  404. Rectangle rectangle;
  405. Identifier[] categories;
  406. private ScreenClickAreaImpl(Class<? extends ContainerScreen<?>> screenClass, Rectangle rectangle, Identifier[] categories) {
  407. this.screenClass = screenClass;
  408. this.rectangle = rectangle;
  409. this.categories = categories;
  410. }
  411. public Class<? extends ContainerScreen<?>> getScreenClass() {
  412. return screenClass;
  413. }
  414. public Rectangle getRectangle() {
  415. return rectangle;
  416. }
  417. public Identifier[] getCategories() {
  418. return categories;
  419. }
  420. }
  421. @SuppressWarnings("rawtypes")
  422. private static class RecipeFunction {
  423. Identifier category;
  424. Predicate<Recipe> recipeFilter;
  425. Function mappingFunction;
  426. public RecipeFunction(Identifier category, Predicate<Recipe> recipeFilter, Function<?, RecipeDisplay> mappingFunction) {
  427. this.category = category;
  428. this.recipeFilter = recipeFilter;
  429. this.mappingFunction = mappingFunction;
  430. }
  431. }
  432. }