RoughlyEnoughItemsCore.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*
  2. * Roughly Enough Items by Danielshe.
  3. * Licensed under the MIT License.
  4. */
  5. package me.shedaniel.rei;
  6. import com.google.common.collect.Lists;
  7. import com.google.common.collect.Maps;
  8. import me.shedaniel.cloth.hooks.ClothClientHooks;
  9. import me.shedaniel.math.impl.PointHelper;
  10. import me.shedaniel.rei.api.*;
  11. import me.shedaniel.rei.api.annotations.Internal;
  12. import me.shedaniel.rei.api.plugins.REIPluginV0;
  13. import me.shedaniel.rei.gui.ContainerScreenOverlay;
  14. import me.shedaniel.rei.impl.*;
  15. import me.shedaniel.rei.listeners.RecipeBookButtonWidgetHooks;
  16. import me.shedaniel.rei.listeners.RecipeBookGuiHooks;
  17. import net.fabricmc.api.ClientModInitializer;
  18. import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
  19. import net.fabricmc.loader.api.FabricLoader;
  20. import net.fabricmc.loader.api.ModContainer;
  21. import net.minecraft.client.MinecraftClient;
  22. import net.minecraft.client.gui.Element;
  23. import net.minecraft.client.gui.screen.Screen;
  24. import net.minecraft.client.gui.screen.ingame.AbstractContainerScreen;
  25. import net.minecraft.client.gui.screen.ingame.CraftingTableScreen;
  26. import net.minecraft.client.gui.screen.ingame.CreativeInventoryScreen;
  27. import net.minecraft.client.gui.screen.ingame.InventoryScreen;
  28. import net.minecraft.client.gui.screen.recipebook.RecipeBookGhostSlots;
  29. import net.minecraft.client.gui.screen.recipebook.RecipeBookProvider;
  30. import net.minecraft.client.gui.screen.recipebook.RecipeBookWidget;
  31. import net.minecraft.client.gui.widget.TextFieldWidget;
  32. import net.minecraft.client.gui.widget.TexturedButtonWidget;
  33. import net.minecraft.client.resource.language.I18n;
  34. import net.minecraft.container.CraftingTableContainer;
  35. import net.minecraft.container.Slot;
  36. import net.minecraft.item.ItemStack;
  37. import net.minecraft.item.Items;
  38. import net.minecraft.recipe.Ingredient;
  39. import net.minecraft.text.LiteralText;
  40. import net.minecraft.util.ActionResult;
  41. import net.minecraft.util.Identifier;
  42. import org.apache.logging.log4j.LogManager;
  43. import org.apache.logging.log4j.Logger;
  44. import java.util.LinkedList;
  45. import java.util.List;
  46. import java.util.Map;
  47. import java.util.Optional;
  48. import java.util.concurrent.CompletableFuture;
  49. import java.util.concurrent.ExecutorService;
  50. import java.util.concurrent.Executors;
  51. import java.util.concurrent.atomic.AtomicLong;
  52. @Internal
  53. public class RoughlyEnoughItemsCore implements ClientModInitializer {
  54. @Internal
  55. public static final Logger LOGGER;
  56. @SuppressWarnings("deprecation")
  57. private static final RecipeHelper RECIPE_HELPER = new RecipeHelperImpl();
  58. @SuppressWarnings("deprecation")
  59. private static final EntryRegistry ENTRY_REGISTRY = new EntryRegistryImpl();
  60. @SuppressWarnings("deprecation")
  61. private static final DisplayHelper DISPLAY_HELPER = new DisplayHelperImpl();
  62. private static final Map<Identifier, REIPluginEntry> plugins = Maps.newHashMap();
  63. private static final ExecutorService SYNC_RECIPES = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "REI-SyncRecipes"));
  64. private static ConfigManager configManager;
  65. static {
  66. LOGGER = LogManager.getFormatterLogger("REI");
  67. }
  68. @Deprecated
  69. public static RecipeHelper getRecipeHelper() {
  70. return RECIPE_HELPER;
  71. }
  72. @Deprecated
  73. public static ConfigManager getConfigManager() {
  74. return configManager;
  75. }
  76. @Deprecated
  77. public static EntryRegistry getEntryRegistry() {
  78. return ENTRY_REGISTRY;
  79. }
  80. @Deprecated
  81. public static DisplayHelper getDisplayHelper() {
  82. return DISPLAY_HELPER;
  83. }
  84. /**
  85. * Registers a REI plugin
  86. *
  87. * @param identifier the identifier of the plugin
  88. * @param plugin the plugin instance
  89. * @return the plugin itself
  90. * @deprecated Check REI wiki
  91. */
  92. @Deprecated
  93. public static REIPluginEntry registerPlugin(REIPluginEntry plugin) {
  94. plugins.put(plugin.getPluginIdentifier(), plugin);
  95. RoughlyEnoughItemsCore.LOGGER.debug("[REI] Registered plugin %s from %s", plugin.getPluginIdentifier().toString(), plugin.getClass().getSimpleName());
  96. return plugin;
  97. }
  98. public static List<REIPluginEntry> getPlugins() {
  99. return new LinkedList<>(plugins.values());
  100. }
  101. public static Optional<Identifier> getPluginIdentifier(REIPluginEntry plugin) {
  102. for (Identifier identifier : plugins.keySet())
  103. if (identifier != null && plugins.get(identifier).equals(plugin))
  104. return Optional.of(identifier);
  105. return Optional.empty();
  106. }
  107. public static boolean hasPermissionToUsePackets() {
  108. try {
  109. MinecraftClient.getInstance().getNetworkHandler().getCommandSource().hasPermissionLevel(0);
  110. return hasOperatorPermission() && canUsePackets();
  111. } catch (NullPointerException e) {
  112. return true;
  113. }
  114. }
  115. public static boolean hasOperatorPermission() {
  116. try {
  117. return MinecraftClient.getInstance().getNetworkHandler().getCommandSource().hasPermissionLevel(1);
  118. } catch (NullPointerException e) {
  119. return true;
  120. }
  121. }
  122. public static boolean canUsePackets() {
  123. return ClientSidePacketRegistry.INSTANCE.canServerReceive(RoughlyEnoughItemsNetwork.CREATE_ITEMS_PACKET) && ClientSidePacketRegistry.INSTANCE.canServerReceive(RoughlyEnoughItemsNetwork.DELETE_ITEMS_PACKET);
  124. }
  125. @SuppressWarnings("deprecation")
  126. @Override
  127. public void onInitializeClient() {
  128. configManager = new ConfigManagerImpl();
  129. registerClothEvents();
  130. discoverPluginEntries();
  131. for (ModContainer modContainer : FabricLoader.getInstance().getAllMods()) {
  132. if (modContainer.getMetadata().containsCustomValue("roughlyenoughitems:plugins"))
  133. RoughlyEnoughItemsCore.LOGGER.error("[REI] REI plugin from " + modContainer.getMetadata().getId() + " is not loaded because it is too old!");
  134. }
  135. ClientSidePacketRegistry.INSTANCE.register(RoughlyEnoughItemsNetwork.CREATE_ITEMS_MESSAGE_PACKET, (packetContext, packetByteBuf) -> {
  136. ItemStack stack = packetByteBuf.readItemStack();
  137. String player = packetByteBuf.readString(32767);
  138. packetContext.getPlayer().addChatMessage(new LiteralText(I18n.translate("text.rei.cheat_items").replaceAll("\\{item_name}", SearchArgument.tryGetItemStackName(stack.copy())).replaceAll("\\{item_count}", stack.copy().getCount() + "").replaceAll("\\{player_name}", player)), false);
  139. });
  140. ClientSidePacketRegistry.INSTANCE.register(RoughlyEnoughItemsNetwork.NOT_ENOUGH_ITEMS_PACKET, (packetContext, packetByteBuf) -> {
  141. Screen currentScreen = MinecraftClient.getInstance().currentScreen;
  142. if (currentScreen instanceof CraftingTableScreen) {
  143. RecipeBookWidget recipeBookGui = ((RecipeBookProvider) currentScreen).getRecipeBookGui();
  144. RecipeBookGhostSlots ghostSlots = ((RecipeBookGuiHooks) recipeBookGui).rei_getGhostSlots();
  145. ghostSlots.reset();
  146. List<List<ItemStack>> input = Lists.newArrayList();
  147. int mapSize = packetByteBuf.readInt();
  148. for (int i = 0; i < mapSize; i++) {
  149. List<ItemStack> list = Lists.newArrayList();
  150. int count = packetByteBuf.readInt();
  151. for (int j = 0; j < count; j++) {
  152. list.add(packetByteBuf.readItemStack());
  153. }
  154. input.add(list);
  155. }
  156. ghostSlots.addSlot(Ingredient.ofItems(Items.STONE), 381203812, 12738291);
  157. CraftingTableContainer container = ((CraftingTableScreen) currentScreen).getContainer();
  158. for (int i = 0; i < input.size(); i++) {
  159. List<ItemStack> stacks = input.get(i);
  160. if (!stacks.isEmpty()) {
  161. Slot slot = container.getSlot(i + container.getCraftingResultSlotIndex() + 1);
  162. ghostSlots.addSlot(Ingredient.ofStacks(stacks.toArray(new ItemStack[0])), slot.xPosition, slot.yPosition);
  163. }
  164. }
  165. }
  166. });
  167. }
  168. @SuppressWarnings("deprecation")
  169. private void discoverPluginEntries() {
  170. for (REIPluginEntry reiPlugin : FabricLoader.getInstance().getEntrypoints("rei_plugins", REIPluginEntry.class)) {
  171. try {
  172. if (!REIPluginV0.class.isAssignableFrom(reiPlugin.getClass()))
  173. throw new IllegalArgumentException("REI plugin is too old!");
  174. registerPlugin(reiPlugin);
  175. } catch (Exception e) {
  176. e.printStackTrace();
  177. RoughlyEnoughItemsCore.LOGGER.error("[REI] Can't load REI plugins from %s: %s", reiPlugin.getClass(), e.getLocalizedMessage());
  178. }
  179. }
  180. for (REIPluginV0 reiPlugin : FabricLoader.getInstance().getEntrypoints("rei_plugins_v0", REIPluginV0.class)) {
  181. try {
  182. registerPlugin(reiPlugin);
  183. } catch (Exception e) {
  184. e.printStackTrace();
  185. RoughlyEnoughItemsCore.LOGGER.error("[REI] Can't load REI plugins from %s: %s", reiPlugin.getClass(), e.getLocalizedMessage());
  186. }
  187. }
  188. }
  189. @SuppressWarnings("deprecation")
  190. private void registerClothEvents() {
  191. final Identifier recipeButtonTex = new Identifier("textures/gui/recipe_button.png");
  192. AtomicLong lastSync = new AtomicLong(-1);
  193. ClothClientHooks.SYNC_RECIPES.register((minecraftClient, recipeManager, synchronizeRecipesS2CPacket) -> {
  194. if (lastSync.get() > 0 && System.currentTimeMillis() - lastSync.get() <= 5000) {
  195. RoughlyEnoughItemsCore.LOGGER.warn("[REI] Suppressing Sync Recipes!");
  196. return;
  197. }
  198. lastSync.set(System.currentTimeMillis());
  199. if (ConfigManager.getInstance().getConfig().doesRegisterRecipesInAnotherThread()) {
  200. CompletableFuture.runAsync(() -> ((RecipeHelperImpl) RecipeHelper.getInstance()).recipesLoaded(recipeManager), SYNC_RECIPES);
  201. } else {
  202. ((RecipeHelperImpl) RecipeHelper.getInstance()).recipesLoaded(recipeManager);
  203. }
  204. });
  205. ClothClientHooks.SCREEN_ADD_BUTTON.register((minecraftClient, screen, abstractButtonWidget) -> {
  206. if (ConfigManager.getInstance().getConfig().doesDisableRecipeBook() && screen instanceof AbstractContainerScreen && abstractButtonWidget instanceof TexturedButtonWidget)
  207. if (((RecipeBookButtonWidgetHooks) abstractButtonWidget).rei_getTexture().equals(recipeButtonTex))
  208. return ActionResult.FAIL;
  209. return ActionResult.PASS;
  210. });
  211. ClothClientHooks.SCREEN_INIT_POST.register((minecraftClient, screen, screenHooks) -> {
  212. if (screen instanceof AbstractContainerScreen) {
  213. if (screen instanceof InventoryScreen && minecraftClient.interactionManager.hasCreativeInventory())
  214. return;
  215. ScreenHelper.setLastContainerScreen((AbstractContainerScreen<?>) screen);
  216. boolean alreadyAdded = false;
  217. for (Element element : Lists.newArrayList(screenHooks.cloth_getInputListeners()))
  218. if (ContainerScreenOverlay.class.isAssignableFrom(element.getClass()))
  219. if (alreadyAdded)
  220. screenHooks.cloth_getInputListeners().remove(element);
  221. else
  222. alreadyAdded = true;
  223. if (!alreadyAdded)
  224. screenHooks.cloth_getInputListeners().add(ScreenHelper.getLastOverlay(true, false));
  225. }
  226. });
  227. ClothClientHooks.SCREEN_RENDER_POST.register((minecraftClient, screen, i, i1, v) -> {
  228. if (screen instanceof AbstractContainerScreen)
  229. ScreenHelper.getLastOverlay().render(i, i1, v);
  230. });
  231. ClothClientHooks.SCREEN_MOUSE_DRAGGED.register((minecraftClient, screen, v, v1, i, v2, v3) -> {
  232. if (screen instanceof AbstractContainerScreen)
  233. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().mouseDragged(v, v1, i, v2, v3))
  234. return ActionResult.SUCCESS;
  235. return ActionResult.PASS;
  236. });
  237. ClothClientHooks.SCREEN_MOUSE_CLICKED.register((minecraftClient, screen, v, v1, i) -> {
  238. if (screen instanceof CreativeInventoryScreen)
  239. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().mouseClicked(v, v1, i)) {
  240. screen.setFocused(ScreenHelper.getLastOverlay());
  241. if (i == 0)
  242. screen.setDragging(true);
  243. return ActionResult.SUCCESS;
  244. }
  245. return ActionResult.PASS;
  246. });
  247. ClothClientHooks.SCREEN_MOUSE_SCROLLED.register((minecraftClient, screen, v, v1, v2) -> {
  248. if (screen instanceof AbstractContainerScreen)
  249. if (ScreenHelper.isOverlayVisible() && ScreenHelper.getLastOverlay().isInside(PointHelper.fromMouse()) && ScreenHelper.getLastOverlay().mouseScrolled(v, v1, v2))
  250. return ActionResult.SUCCESS;
  251. return ActionResult.PASS;
  252. });
  253. ClothClientHooks.SCREEN_CHAR_TYPED.register((minecraftClient, screen, character, keyCode) -> {
  254. if (screen instanceof AbstractContainerScreen)
  255. if (ScreenHelper.getLastOverlay().charTyped(character, keyCode))
  256. return ActionResult.SUCCESS;
  257. return ActionResult.PASS;
  258. });
  259. ClothClientHooks.SCREEN_LATE_RENDER.register((minecraftClient, screen, i, i1, v) -> {
  260. if (!ScreenHelper.isOverlayVisible())
  261. return;
  262. if (screen instanceof AbstractContainerScreen)
  263. ScreenHelper.getLastOverlay().lateRender(i, i1, v);
  264. });
  265. ClothClientHooks.SCREEN_KEY_PRESSED.register((minecraftClient, screen, i, i1, i2) -> {
  266. if (screen.getFocused() != null && screen.getFocused() instanceof TextFieldWidget || (screen.getFocused() instanceof RecipeBookWidget && ((RecipeBookGuiHooks) screen.getFocused()).rei_getSearchField() != null && ((RecipeBookGuiHooks) screen.getFocused()).rei_getSearchField().isFocused()))
  267. return ActionResult.PASS;
  268. if (screen instanceof AbstractContainerScreen)
  269. if (ScreenHelper.getLastOverlay().keyPressed(i, i1, i2))
  270. return ActionResult.SUCCESS;
  271. if (screen instanceof AbstractContainerScreen && configManager.getConfig().doesDisableRecipeBook() && configManager.getConfig().doesFixTabCloseContainer())
  272. if (i == 258 && minecraftClient.options.keyInventory.matchesKey(i, i1)) {
  273. minecraftClient.player.closeContainer();
  274. return ActionResult.SUCCESS;
  275. }
  276. return ActionResult.PASS;
  277. });
  278. }
  279. }