From d9916e983313e5b1d30eb7957f997080ef3110fe Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 18:18:43 -0600 Subject: [PATCH 01/82] Pain --- .../crafting/IToolbeltSupportingRecipe.java | 45 +++ .../api/items/toolitem/ItemGTToolbelt.java | 320 ++++++++++++++++++ .../java/gregtech/client/ClientProxy.java | 23 ++ .../common/crafting/FluidReplaceRecipe.java | 2 + .../common/crafting/GTShapedOreRecipe.java | 68 +++- .../common/crafting/GTShapelessOreRecipe.java | 93 +++-- .../java/gregtech/common/items/ToolItems.java | 9 +- src/main/java/gregtech/core/CoreModule.java | 2 + .../PacketToolbeltSelectionChange.java | 41 +++ .../resources/assets/gregtech/lang/en_us.lang | 2 + 10 files changed, 535 insertions(+), 70 deletions(-) create mode 100644 src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java create mode 100644 src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java create mode 100644 src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java new file mode 100644 index 00000000000..82e161fb167 --- /dev/null +++ b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java @@ -0,0 +1,45 @@ +package gregtech.api.crafting; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.util.NonNullList; +import net.minecraftforge.common.ForgeHooks; +import net.minecraftforge.common.util.RecipeMatcher; + +import org.jetbrains.annotations.NotNull; + +public interface IToolbeltSupportingRecipe extends IRecipe { + + ThreadLocal initNeedsToolbeltHandlingHelper = new ThreadLocal<>(); + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) + return toolbelt.supportsIngredient(stack, ingredient); + else return ingredient.apply(stack); + } + + @Override + default @NotNull NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList ret = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + for (int i = 0; i < ret.size(); i++) { + ret.set(i, inv.getStackInSlot(i)); + } + int[] matches = RecipeMatcher.findMatches(ret, this.getIngredients()); + if (matches != null) { + for (int i = 0; i < ret.size(); i++) { + ItemStack stack = ret.get(i); + Ingredient ingredient = this.getIngredients().get(matches[i]); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + toolbelt.damageTools(stack, ingredient); + } + ret.set(i, ForgeHooks.getContainerItem(stack)); + } + } else ret.replaceAll(ForgeHooks::getContainerItem); + return ret; + } +} diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java new file mode 100644 index 00000000000..416bb5f4ced --- /dev/null +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -0,0 +1,320 @@ +package gregtech.api.items.toolitem; + +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; + +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.SlotGroupWidget; + +import gregtech.api.GTValues; +import gregtech.api.GregTechAPI; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; +import gregtech.api.unification.OreDictUnifier; + +import gregtech.api.util.LocalizationUtils; + +import gregtech.core.network.packets.PacketToolbeltSelectionChange; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; + +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ICapabilityProvider; +import net.minecraftforge.common.util.INBTSerializable; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.ItemStackHandler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; + +public class ItemGTToolbelt extends ItemGTTool { + + protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); + + private final ItemStack orestack; + + public ItemGTToolbelt(String domain, String id, Supplier markerItem) { + super(domain, id, -1, new ToolDefinitionBuilder().cannotAttack().attackSpeed(-2.4F).build(), null, + false, new HashSet<>(), "", new ArrayList<>(), + markerItem); + this.orestack = new ItemStack(this, 1, GTValues.W); + } + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + if (player.isSneaking()) { + if (!world.isRemote) { + ItemGuiFactory.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } else return definition$onItemRightClick(world, player, hand); + } + + @Override + public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { + ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 192); + + ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); + + SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); + slotGroupWidget.flex() + .coverChildren() + .startDefaultMode() + .leftRel(0.5f); + slotGroupWidget.flex().top(7); + slotGroupWidget.flex().endDefaultMode(); + slotGroupWidget.debugName("toolbelt_inventory"); + String key = "toolbelt"; + for (int i = 0; i < 27; i++) { + slotGroupWidget.child(new ItemSlot() + .slot(SyncHandlers.itemSlot(handler, i)) + .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) + .pos(i % 9 * 18, i / 9 * 18) + .debugName("slot_" + i)); + } + panel.child(slotGroupWidget); + + return panel.bindPlayerInventory(); + } + + public static boolean isToolbeltableOredict(String oredict) { + return VALID_OREDICTS.contains(oredict); + } + + public void registerValidOredict(String oredict) { + VALID_OREDICTS.add(oredict); + OreDictUnifier.registerOre(this.orestack, oredict); + } + + @Override + public int getMaxDamage(@NotNull ItemStack stack) { + return -1; + } + + @Override + public @NotNull Set getToolClasses(@NotNull ItemStack stack) { + return getHandler(stack).toolClasses; + } + + @Override + public boolean hasContainerItem(@NotNull ItemStack stack) { + return true; + } + + @Override + public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { + return stack.copy(); + } + + public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { + return getHandler(stack).checkIngredientAgainstTools(ingredient, false); + } + + public void damageTools(ItemStack stack, Ingredient ingredient) { + getHandler(stack).checkIngredientAgainstTools(ingredient, true); + } + + private ToolStackHandler getHandler(ItemStack stack) { + return (ToolStackHandler) stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); + } + + @Override + public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagCompound nbt) { + return new ToolbeltCapabilityProvider(); + } + + public void changeSelectedTool(int direction, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (direction > 0) handler.incrementSelectedSlot(); + else handler.decrementSelectedSlot(); + GregTechAPI.networkHandler.sendToServer( + new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); + } + + public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (slot == null || slot < 0 || slot >= handler.getSlots()) handler.selectedSlot = null; + else handler.selectedSlot = slot; + } + + @Override + public @NotNull String getItemStackDisplayName(@NotNull ItemStack stack) { + ItemStack tool = getHandler(stack).getSelectedStack(); + String selectedToolDisplay = ""; + if (tool != null) { + selectedToolDisplay = " (" + tool.getDisplayName() + ")"; + } + return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); + } + + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + + + private final ToolStackHandler handler = new ToolStackHandler(); + + @Override + public boolean hasCapability(@NotNull Capability capability, EnumFacing facing) { + return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY; + } + + @SuppressWarnings("unchecked") + @Override + public T getCapability(@NotNull Capability capability, EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) handler; + else return null; + } + + @Override + public NBTTagCompound serializeNBT() { + return this.handler.serializeNBT(); + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + this.handler.deserializeNBT(nbt); + } + } + + protected static class ToolStackHandler extends ItemStackHandler { + + private @Nullable Integer selectedSlot = null; + + protected final ItemTool[] tools = new ItemTool[this.getSlots()]; + protected final IGTTool[] gtTools = new IGTTool[this.getSlots()]; + protected final Set toolClasses = new ObjectOpenHashSet<>(); + public final Set oreDicts = new ObjectOpenHashSet<>(); + + public ToolStackHandler() { + super(27); + } + + public void incrementSelectedSlot() { + for (int slot = (this.selectedSlot == null ? -1 : this.selectedSlot) + 1; slot != this.getSlots(); slot++) { + if (this.getStackInSlot(slot).isEmpty()) continue; + this.selectedSlot = slot; + return; + } + this.selectedSlot = null; + } + + public void decrementSelectedSlot() { + for (int slot = (this.selectedSlot == null ? this.getSlots() : this.selectedSlot) - 1; slot != -1; slot--) { + if (this.getStackInSlot(slot).isEmpty()) continue; + this.selectedSlot = slot; + return; + } + this.selectedSlot = null; + } + + public @Nullable Integer getSelectedSlot() { + return selectedSlot; + } + + public ItemStack getSelectedStack() { + if (getSelectedSlot() == null) return null; + else return this.stacks.get(getSelectedSlot()); + } + + @Override + public boolean isItemValid(int slot, @NotNull ItemStack stack) { + return stack.getItem() instanceof ItemTool || stack.getItem() instanceof IGTTool; + } + + @Override + protected void onContentsChanged(int slot) { + this.updateSlot(slot); + this.update(); + + super.onContentsChanged(slot); + } + + @Override + public NBTTagCompound serializeNBT() { + NBTTagCompound tag = super.serializeNBT(); + if (this.selectedSlot != null) tag.setByte("SelectedSlot", this.selectedSlot.byteValue()); + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + super.deserializeNBT(nbt); + if (nbt.hasKey("SelectedSlot")) this.selectedSlot = (int) nbt.getByte("SelectedSlot"); + } + + @Override + protected void onLoad() { + super.onLoad(); + for (int i = 0; i < this.getSlots(); i++) { + this.updateSlot(i); + } + this.update(); + } + + protected void updateSlot(int slot) { + Item item = this.getStackInSlot(slot).getItem(); + if (item instanceof ItemTool tool) { + tools[slot] = tool; + } else { + tools[slot] = null; + } + if (item instanceof IGTTool tool) { + gtTools[slot] = tool; + } else { + gtTools[slot] = null; + } + } + + protected void update() { + this.oreDicts.clear(); + Arrays.stream(gtTools).filter(Objects::nonNull).map(igtTool -> { + Set set = new ObjectOpenHashSet<>(igtTool.getSecondaryOreDicts()); + set.add(igtTool.getOreDictName()); + return set; + }).forEach(this.oreDicts::addAll); + this.oreDicts.retainAll(VALID_OREDICTS); + + this.toolClasses.clear(); + for (int i = 0; i < this.getSlots(); i++) { + if (tools[i] != null) this.toolClasses.addAll(tools[i].getToolClasses(stacks.get(i))); + } + } + + public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraftingDamage) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (ingredient.test(stack)) { + if (doCraftingDamage && stack.getItem().hasContainerItem(stack)) { + this.setStackInSlot(i, stack.getItem().getContainerItem(stack)); + } + return true; + } + } + return false; + } + } +} diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 7fb4773d478..193a8327ab0 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -1,9 +1,12 @@ package gregtech.client; +import com.cleanroommc.modularui.utils.math.functions.limit.Min; + import gregtech.api.GTValues; import gregtech.api.fluids.GTFluidRegistration; import gregtech.api.items.metaitem.MetaOreDictItem; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.terminal.TerminalRegistry; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; @@ -34,19 +37,23 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.ContainerPlayer; import net.minecraft.inventory.ContainerWorkbench; import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.client.event.ModelRegistryEvent; +import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.Constants; import net.minecraftforge.event.entity.player.ItemTooltipEvent; @@ -315,4 +322,20 @@ private static boolean hasActuallyAdvancedInfo(List tooltip) { public boolean isFancyGraphics() { return Minecraft.getMinecraft().gameSettings.fancyGraphics; } + + @SubscribeEvent(priority = EventPriority.HIGH) + public static void onMouseEvent(@NotNull MouseEvent event) { + EntityPlayerSP player = Minecraft.getMinecraft().player; + if (event.getDwheel() != 0 && player.isSneaking()) { + ItemStack stack = player.getHeldItemMainhand(); + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt toolbelt) { + stack = stack.copy(); + toolbelt.changeSelectedTool(event.getDwheel(), stack); + InventoryPlayer inv = Minecraft.getMinecraft().player.inventory; + inv.mainInventory.set(inv.currentItem, stack); + event.setCanceled(true); + } + } + } } diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index f3addd44339..61733e309fd 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -23,6 +23,8 @@ public class FluidReplaceRecipe extends GTShapedOreRecipe { public FluidReplaceRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(isClearing, group, result, recipe); + // there is no possible way that we require toolbelt handling, but make sure it isn't enabled. + this.toolbeltHandling = false; } @NotNull diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index a014bd89292..7b60f40b119 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -1,5 +1,7 @@ package gregtech.common.crafting; +import gregtech.api.crafting.IToolbeltSupportingRecipe; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.util.GTLog; import gregtech.api.util.GTStringUtils; @@ -31,21 +33,26 @@ import java.util.HashMap; import java.util.Set; -public class GTShapedOreRecipe extends ShapedOreRecipe { +public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSupportingRecipe { boolean isClearing; + boolean toolbeltHandling; public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result, parseShaped(isClearing, recipe)); this.isClearing = isClearing; + this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); + initNeedsToolbeltHandlingHelper.set(false); } // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. - // the on difference is calling getIngredient of this class. + // the only difference is calling getIngredient of this class. public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { + initNeedsToolbeltHandlingHelper.set(false); + CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); int idx = 0; @@ -126,23 +133,19 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object return ret; } - // a copy of the CraftingHelper getIngredient method. - // the only difference is checking for a filled bucket and making - // it an GTFluidCraftingIngredient protected static Ingredient getIngredient(boolean isClearing, Object obj) { - if (obj instanceof Ingredient) return (Ingredient) obj; - else if (obj instanceof ItemStack) { - ItemStack ing = (ItemStack) obj; - if (ing.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { - IFluidHandlerItem handler = ing.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, + if (obj instanceof Ingredient ing) return ing; + else if (obj instanceof ItemStack stk) { + if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + IFluidHandlerItem handler = stk.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); if (handler != null) { FluidStack drained = handler.drain(Integer.MAX_VALUE, false); if (drained != null && drained.amount > 0) { - return new GTFluidCraftingIngredient(((ItemStack) obj).copy()); + return new GTFluidCraftingIngredient(stk.copy()); } if (!isClearing) { - ItemStack i = ((ItemStack) obj).copy(); + ItemStack i = (stk).copy(); try { return ingredientNBT.newInstance(i); } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { @@ -152,23 +155,52 @@ else if (obj instanceof ItemStack) { } } } - return Ingredient.fromStacks(((ItemStack) obj).copy()); - } else if (obj instanceof Item) return Ingredient.fromItem((Item) obj); - else if (obj instanceof Block) - return Ingredient.fromStacks(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); - else if (obj instanceof String) return new OreIngredient((String) obj); + return Ingredient.fromStacks(stk.copy()); + } else if (obj instanceof Item itm) return Ingredient.fromItem(itm); + else if (obj instanceof Block blk) + return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); + else if (obj instanceof String str) { + if (ItemGTToolbelt.isToolbeltableOredict(str)) + initNeedsToolbeltHandlingHelper.set(true); + return new OreIngredient(str); + } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); return null; } + @Override + protected boolean checkMatch(@NotNull InventoryCrafting inv, int startX, int startY, boolean mirror) { + if (this.toolbeltHandling) { + for (int x = 0; x < inv.getWidth(); x++) { + for (int y = 0; y < inv.getHeight(); y++) { + int subX = x - startX; + int subY = y - startY; + Ingredient target = Ingredient.EMPTY; + + if (subX >= 0 && subY >= 0 && subX < width && subY < height) { + if (mirror) { + target = input.get(width - subX - 1 + subY * width); + } else { + target = input.get(subX + subY * width); + } + } + + if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(target, inv.getStackInRowAndColumn(x, y))) + return false; + } + } + return true; + } else return super.checkMatch(inv, startX, startY, mirror); + } + @Override public @NotNull NonNullList getRemainingItems(@NotNull InventoryCrafting inv) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return super.getRemainingItems(inv); + return IToolbeltSupportingRecipe.super.getRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index 6d0ee689b32..7d39669e5f6 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,42 +1,35 @@ package gregtech.common.crafting; -import gregtech.api.util.GTLog; -import gregtech.api.util.GTStringUtils; +import com.google.common.collect.Lists; + +import gregtech.api.crafting.IToolbeltSupportingRecipe; -import net.minecraft.block.Block; import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.crafting.IngredientNBT; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import net.minecraftforge.fml.relauncher.ReflectionHelper; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.OreIngredient; +import net.minecraft.world.World; +import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; -import com.google.gson.JsonElement; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; +import java.util.List; -public class GTShapelessOreRecipe extends ShapelessOreRecipe { +public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbeltSupportingRecipe { boolean isClearing; - public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, - ItemStack.class); + boolean toolbeltHandling; public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); + initNeedsToolbeltHandlingHelper.set(false); + this.isClearing = isClearing; for (Object in : recipe) { - Ingredient ing = getIngredient(isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -49,43 +42,41 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull throw new RuntimeException(ret.toString()); } } + this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); + initNeedsToolbeltHandlingHelper.set(false); } - // a copy of the CraftingHelper getIngredient method. - // the only difference is checking for a filled bucket and making - // it an GTFluidCraftingIngredient - private static Ingredient getIngredient(boolean isClearing, Object obj) { - if (obj instanceof Ingredient) return (Ingredient) obj; - else if (obj instanceof ItemStack) { - ItemStack ing = (ItemStack) obj; - if (ing.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { - IFluidHandlerItem handler = ing.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, - null); - if (handler != null) { - FluidStack drained = handler.drain(Integer.MAX_VALUE, false); - if (drained != null && drained.amount > 0) { - return new GTFluidCraftingIngredient(((ItemStack) obj).copy()); - } - if (!isClearing) { - ItemStack i = ((ItemStack) obj).copy(); - try { - return ingredientNBT.newInstance(i); - } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { - GTLog.logger.error("Failure to instantiate an IngredientNBT of item {}", - GTStringUtils.prettyPrintItemStack(i)); - } - } + @Override + public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { + if (this.toolbeltHandling) { + // I can't wrap my head around the 'simple' shapeless logic, so no simple toolbelt handling. + int ingredientCount = 0; + List items = Lists.newArrayList(); + + for (int i = 0; i < inv.getSizeInventory(); ++i) + { + ItemStack itemstack = inv.getStackInSlot(i); + if (!itemstack.isEmpty()) + { + ++ingredientCount; + items.add(itemstack); } } - return Ingredient.fromStacks(((ItemStack) obj).copy()); - } else if (obj instanceof Item) return Ingredient.fromItem((Item) obj); - else if (obj instanceof Block) - return Ingredient.fromStacks(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); - else if (obj instanceof String) return new OreIngredient((String) obj); - else if (obj instanceof JsonElement) - throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); - return null; + if (ingredientCount != this.input.size()) + return false; + + int[] matches = RecipeMatcher.findMatches(items, this.input); + if (matches != null) { + for (int i = 0; i < items.size(); i++) { + ItemStack stack = items.get(i); + Ingredient ingredient = this.input.get(matches[i]); + if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(ingredient, stack)) return false; + } + return true; + } else return false; + + } else return super.matches(inv, world); } @Override @@ -93,7 +84,7 @@ else if (obj instanceof JsonElement) if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return super.getRemainingItems(inv); + return IToolbeltSupportingRecipe.super.getRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 5545387ef7c..04c6a0e7f79 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -58,6 +58,7 @@ public final class ToolItems { public static IGTTool WIRECUTTER_LV; public static IGTTool WIRECUTTER_HV; public static IGTTool WIRECUTTER_IV; + public static ItemGTToolbelt TOOLBELT; private ToolItems() {/**/} @@ -66,6 +67,8 @@ public static List getAllTools() { } public static void init() { + TOOLBELT = (ItemGTToolbelt) register(new ItemGTToolbelt(GTValues.MODID, "toolbelt", + null)); SWORD = register(ItemGTSword.Builder.of(GTValues.MODID, "sword") .toolStats(b -> b.attacking() .attackDamage(3.0F).attackSpeed(-2.4F)) @@ -379,8 +382,12 @@ public static void registerOreDict() { final ItemStack stack = new ItemStack(tool.get(), 1, GTValues.W); if (tool.getOreDictName() != null) { OreDictUnifier.registerOre(stack, tool.getOreDictName()); + TOOLBELT.registerValidOredict(tool.getOreDictName()); } - tool.getSecondaryOreDicts().forEach(oreDict -> OreDictUnifier.registerOre(stack, oreDict)); + tool.getSecondaryOreDicts().forEach(oreDict -> { + OreDictUnifier.registerOre(stack, oreDict); + TOOLBELT.registerValidOredict(oreDict); + }); }); } } diff --git a/src/main/java/gregtech/core/CoreModule.java b/src/main/java/gregtech/core/CoreModule.java index c05116355f7..839806e7446 100644 --- a/src/main/java/gregtech/core/CoreModule.java +++ b/src/main/java/gregtech/core/CoreModule.java @@ -62,6 +62,7 @@ import gregtech.core.network.packets.PacketPluginSynced; import gregtech.core.network.packets.PacketRecoverMTE; import gregtech.core.network.packets.PacketReloadShaders; +import gregtech.core.network.packets.PacketToolbeltSelectionChange; import gregtech.core.network.packets.PacketUIClientAction; import gregtech.core.network.packets.PacketUIOpen; import gregtech.core.network.packets.PacketUIWidgetUpdate; @@ -228,6 +229,7 @@ public void registerPackets() { GregTechAPI.networkHandler.registerPacket(PacketNotifyCapeChange.class); GregTechAPI.networkHandler.registerPacket(PacketReloadShaders.class); GregTechAPI.networkHandler.registerPacket(PacketClipboardNBTUpdate.class); + GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.class); } @Override diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java new file mode 100644 index 00000000000..96b14b1c47c --- /dev/null +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -0,0 +1,41 @@ +package gregtech.core.network.packets; + +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.api.network.IPacket; +import gregtech.api.network.IServerExecutor; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.EnumHand; + +public class PacketToolbeltSelectionChange implements IPacket, IServerExecutor { + + private int slot; + + public PacketToolbeltSelectionChange() {} + + public PacketToolbeltSelectionChange(int slot) { + this.slot = slot; + } + + @Override + public void encode(PacketBuffer buf) { + buf.writeByte(slot); + } + + @Override + public void decode(PacketBuffer buf) { + this.slot = buf.readByte(); + } + + @Override + public void executeServer(NetHandlerPlayServer handler) { + ItemStack stack = handler.player.getHeldItemMainhand(); + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt toolbelt) { + toolbelt.setSelectedTool(slot, stack); + } + } +} diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index 729c9210520..19bf46898d9 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1027,6 +1027,8 @@ item.gt.tool.plunger.tooltip=§8Removes Fluids from Machines item.gt.tool.wire_cutter_lv.name=%s Wire Cutter (LV) item.gt.tool.wire_cutter_hv.name=%s Wire Cutter (HV) item.gt.tool.wire_cutter_iv.name=%s Wire Cutter (IV) +item.gt.tool.toolbelt.name=%s Toolbelt%s +item.gt.tool.toolbelt.tooltip=Holds too many tools for too many jobs. item.gt.tool.tooltip.crafting_uses=§a%s Crafting Uses From 31dfb44e06d5c4d13fdafccf8a4aeffa1cc0e2b7 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 18:46:15 -0600 Subject: [PATCH 02/82] Recipe & texture --- .../recipe/handlers/ToolRecipeHandler.java | 9 +++++++++ .../gregtech/models/item/tools/toolbelt.json | 7 +++++++ .../textures/items/tools/toolbelt_belt.png | Bin 0 -> 192 bytes .../textures/items/tools/toolbelt_loops.png | Bin 0 -> 177 bytes 4 files changed, 16 insertions(+) create mode 100644 src/main/resources/assets/gregtech/models/item/tools/toolbelt.json create mode 100644 src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png create mode 100644 src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png diff --git a/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java b/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java index 1997631a38c..84e5cd91450 100644 --- a/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java +++ b/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java @@ -19,6 +19,7 @@ import gregtech.common.items.MetaItems; import gregtech.common.items.ToolItems; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.ResourceLocation; @@ -215,6 +216,14 @@ private static void processTool(OrePrefix prefix, Material material, ToolPropert } } + if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING)) { + addToolRecipe(material, ToolItems.TOOLBELT, false, + "SSS", "LLL", "RSR", + 'L', Items.LEATHER, + 'S', new UnificationEntry(OrePrefix.screw, material), + 'R', new UnificationEntry(OrePrefix.ring, material)); + } + addToolRecipe(material, ToolItems.SCREWDRIVER, true, " fS", " Sh", "W ", 'S', rod, diff --git a/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json b/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json new file mode 100644 index 00000000000..25e4069ef67 --- /dev/null +++ b/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json @@ -0,0 +1,7 @@ +{ + "parent": "item/handheld", + "textures": { + "layer0": "gregtech:items/tools/toolbelt_belt", + "layer1": "gregtech:items/tools/toolbelt_loops" + } +} diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png new file mode 100644 index 0000000000000000000000000000000000000000..b8e9021431ea0046ebe5743d23bac2ec3bfa687a GIT binary patch literal 192 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|Dm+~rLoEE0 zQx*sq1g)5#c!hz@L!xCx_h0sl*?Ievw0tI9Jk|}H4o|%LxWvdu@QeeHd6_S; n?%4DjZoCa@Dqck@4DLo+f@^+g?f|-h!PC{xWt~$(69WSP5ZFYA literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png new file mode 100644 index 0000000000000000000000000000000000000000..c351831679459d2785e6da182d3aa7cd938d66e3 GIT binary patch literal 177 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|GCf@!LoEE0 zQx*sq1g)5#xI^;7g$p0#MbvnCc_a3=`O3K}dNfX)D0ukV+GxqNb8|WspTB*3)*$_y zjEE(V>$Pjwc(SjpIhe&@X1OS*v5I^3>lLq=CiuR5`SL-73qNzrqr Date: Tue, 4 Jun 2024 20:59:12 -0600 Subject: [PATCH 03/82] Finalize in-world handling --- .../crafting/IToolbeltSupportingRecipe.java | 2 +- .../api/items/toolitem/ItemGTToolbelt.java | 91 +++++++++++++----- .../api/items/toolitem/ToolHelper.java | 93 ++++++++++--------- 3 files changed, 119 insertions(+), 67 deletions(-) diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java index 82e161fb167..7e55d8da228 100644 --- a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java +++ b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java @@ -35,7 +35,7 @@ static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { ItemStack stack = ret.get(i); Ingredient ingredient = this.getIngredients().get(matches[i]); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - toolbelt.damageTools(stack, ingredient); + toolbelt.craftDamageTools(stack, ingredient); } ret.set(i, ForgeHooks.getContainerItem(stack)); } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 416bb5f4ced..b9e0dc38c25 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -9,6 +9,8 @@ import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.google.common.collect.ImmutableSet; + import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; @@ -37,7 +39,6 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; -import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; @@ -64,6 +65,26 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem) this.orestack = new ItemStack(this, 1, GTValues.W); } + @Override + public int getDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.getItemDamage(); + }return super.getDamage(stack); + } + + @Override + public void setDamage(@NotNull ItemStack stack, int damage) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.setItemDamage(damage); + } else super.setDamage(stack, damage); + } + + public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { + return getHandler(stack).getSelectedStack(); + } + @Override public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, @NotNull EnumHand hand) { @@ -77,9 +98,10 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem) @Override public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { - ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 192); - ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); + int heightBonus = (handler.getSlots() / 9) * 18; + + ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); slotGroupWidget.flex() @@ -89,8 +111,7 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.flex().top(7); slotGroupWidget.flex().endDefaultMode(); slotGroupWidget.debugName("toolbelt_inventory"); - String key = "toolbelt"; - for (int i = 0; i < 27; i++) { + for (int i = 0; i < handler.getSlots(); i++) { slotGroupWidget.child(new ItemSlot() .slot(SyncHandlers.itemSlot(handler, i)) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) @@ -111,14 +132,9 @@ public void registerValidOredict(String oredict) { OreDictUnifier.registerOre(this.orestack, oredict); } - @Override - public int getMaxDamage(@NotNull ItemStack stack) { - return -1; - } - @Override public @NotNull Set getToolClasses(@NotNull ItemStack stack) { - return getHandler(stack).toolClasses; + return getHandler(stack).getToolClasses(true); } @Override @@ -135,7 +151,7 @@ public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { return getHandler(stack).checkIngredientAgainstTools(ingredient, false); } - public void damageTools(ItemStack stack, Ingredient ingredient) { + public void craftDamageTools(ItemStack stack, Ingredient ingredient) { getHandler(stack).checkIngredientAgainstTools(ingredient, true); } @@ -145,7 +161,7 @@ private ToolStackHandler getHandler(ItemStack stack) { @Override public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagCompound nbt) { - return new ToolbeltCapabilityProvider(); + return new ToolbeltCapabilityProvider(stack); } public void changeSelectedTool(int direction, ItemStack stack) { @@ -172,10 +188,15 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); } - protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + protected class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + + protected final Supplier slotCountSupplier; + private @Nullable ToolStackHandler handler; - private final ToolStackHandler handler = new ToolStackHandler(); + public ToolbeltCapabilityProvider(ItemStack stack) { + slotCountSupplier = () -> (int) (ItemGTToolbelt.super.getTotalHarvestLevel(stack) * 5.4f); + } @Override public boolean hasCapability(@NotNull Capability capability, EnumFacing facing) { @@ -185,23 +206,34 @@ public boolean hasCapability(@NotNull Capability capability, EnumFacing facin @SuppressWarnings("unchecked") @Override public T getCapability(@NotNull Capability capability, EnumFacing facing) { - if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) handler; + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) this.getHandler(0); else return null; } @Override public NBTTagCompound serializeNBT() { - return this.handler.serializeNBT(); + return this.getHandler(0).serializeNBT(); } @Override public void deserializeNBT(NBTTagCompound nbt) { - this.handler.deserializeNBT(nbt); + // make sure we can load all the slots, no matter what we're supposed to be limited to. + int minsize = nbt.hasKey("Size") ? nbt.getInteger("Size") : 0; + // .copy() prevents double damage ticks in singleplayer + this.getHandler(minsize).deserializeNBT(nbt.copy()); + } + + protected ToolStackHandler getHandler(int minsize) { + int slots = Math.max(slotCountSupplier.get(), minsize); + if (handler == null || handler.getSlots() != slots) handler = new ToolStackHandler(slots); + return handler; } } protected static class ToolStackHandler extends ItemStackHandler { + private static final Set EMPTY = ImmutableSet.of(); + private @Nullable Integer selectedSlot = null; protected final ItemTool[] tools = new ItemTool[this.getSlots()]; @@ -209,8 +241,8 @@ protected static class ToolStackHandler extends ItemStackHandler { protected final Set toolClasses = new ObjectOpenHashSet<>(); public final Set oreDicts = new ObjectOpenHashSet<>(); - public ToolStackHandler() { - super(27); + public ToolStackHandler(int size) { + super(size); } public void incrementSelectedSlot() { @@ -235,14 +267,29 @@ public void decrementSelectedSlot() { return selectedSlot; } - public ItemStack getSelectedStack() { + public @Nullable ItemStack getSelectedStack() { if (getSelectedSlot() == null) return null; else return this.stacks.get(getSelectedSlot()); } + public Set getToolClasses(boolean defaultEmpty) { + ItemStack selectedStack = getSelectedStack(); + if (selectedStack != null) { + if (selectedStack.getItem() instanceof ItemTool tool) { + return tool.getToolClasses(selectedStack); + } else if (selectedStack.getItem() instanceof IGTTool tool) { + return tool.getToolClasses(selectedStack); + } + } + if (defaultEmpty) return EMPTY; + return toolClasses; + } + @Override public boolean isItemValid(int slot, @NotNull ItemStack stack) { - return stack.getItem() instanceof ItemTool || stack.getItem() instanceof IGTTool; + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt) return false; + return item instanceof ItemTool || item instanceof IGTTool; } @Override diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 23d3145ca9b..f894664d1dd 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -254,58 +254,63 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa * @param damage how much damage the stack will take */ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBase entity, int damage) { - if (!(stack.getItem() instanceof IGTTool)) { + if (!(stack.getItem() instanceof IGTTool tool)) { if (entity != null) stack.damageItem(damage, entity); - } else { - if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { + return; + } else if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selectedStack = toolbelt.getSelectedItem(stack); + if (selectedStack != null) { + damageItem(selectedStack, entity, damage); return; } - IGTTool tool = (IGTTool) stack.getItem(); - if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { - Random random = entity == null ? GTValues.RNG : entity.getRNG(); - if (tool.isElectric()) { - int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; - IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, - null); - if (electricItem != null) { - electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); - if (electricItem.getCharge() > 0 && - random.nextInt(100) >= ConfigHolder.tools.rngDamageElectricTools) { - return; - } - } else { - throw new IllegalStateException( - "Electric tool does not have an attached electric item capability."); - } - } - int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); - int negated = 0; - for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { - if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { - negated++; + } + if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { + return; + } + if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { + Random random = entity == null ? GTValues.RNG : entity.getRNG(); + if (tool.isElectric()) { + int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; + IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, + null); + if (electricItem != null) { + electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); + if (electricItem.getCharge() > 0 && + random.nextInt(100) >= ConfigHolder.tools.rngDamageElectricTools) { + return; } + } else { + throw new IllegalStateException( + "Electric tool does not have an attached electric item capability."); } - damage -= negated; - if (damage <= 0) { - return; - } - int newDurability = stack.getItemDamage() + damage; - if (entity instanceof EntityPlayerMP) { - CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); + } + int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); + int negated = 0; + for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { + if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { + negated++; } - stack.setItemDamage(newDurability); - if (newDurability > stack.getMaxDamage()) { - if (entity instanceof EntityPlayer) { - StatBase stat = StatList.getObjectBreakStats(stack.getItem()); - if (stat != null) { - ((EntityPlayer) entity).addStat(stat); - } - } - if (entity != null) { - entity.renderBrokenItemStack(stack); + } + damage -= negated; + if (damage <= 0) { + return; + } + int newDurability = stack.getItemDamage() + damage; + if (entity instanceof EntityPlayerMP) { + CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); + } + stack.setItemDamage(newDurability); + if (newDurability > stack.getMaxDamage()) { + if (entity instanceof EntityPlayer) { + StatBase stat = StatList.getObjectBreakStats(stack.getItem()); + if (stat != null) { + ((EntityPlayer) entity).addStat(stat); } - stack.shrink(1); } + if (entity != null) { + entity.renderBrokenItemStack(stack); + } + stack.shrink(1); } } } From 58705fb1269cb343c775d1f7f58ea29befddb729 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 20:59:33 -0600 Subject: [PATCH 04/82] Spotless --- .../api/items/toolitem/ItemGTToolbelt.java | 35 ++++++++----------- .../java/gregtech/client/ClientProxy.java | 2 -- .../common/crafting/GTShapedOreRecipe.java | 3 +- .../common/crafting/GTShapelessOreRecipe.java | 9 ++--- .../PacketToolbeltSelectionChange.java | 1 - 5 files changed, 19 insertions(+), 31 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index b9e0dc38c25..e538e468aaf 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,28 +1,13 @@ package gregtech.api.items.toolitem; -import com.cleanroommc.modularui.factory.HandGuiData; -import com.cleanroommc.modularui.factory.ItemGuiFactory; -import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.value.sync.GuiSyncManager; - -import com.cleanroommc.modularui.value.sync.SyncHandlers; -import com.cleanroommc.modularui.widgets.ItemSlot; -import com.cleanroommc.modularui.widgets.SlotGroupWidget; - -import com.google.common.collect.ImmutableSet; - import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.OreDictUnifier; - import gregtech.api.util.LocalizationUtils; - import gregtech.core.network.packets.PacketToolbeltSelectionChange; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; @@ -33,7 +18,6 @@ import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; - import net.minecraft.util.EnumHand; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; @@ -42,6 +26,15 @@ import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.google.common.collect.ImmutableSet; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -70,7 +63,8 @@ public int getDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { selected.getItemDamage(); - }return super.getDamage(stack); + } + return super.getDamage(stack); } @Override @@ -113,8 +107,8 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i)) - .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) + .slot(SyncHandlers.itemSlot(handler, i)) + .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); } @@ -185,7 +179,8 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { if (tool != null) { selectedToolDisplay = " (" + tool.getDisplayName() + ")"; } - return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); + return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), + selectedToolDisplay); } protected class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 193a8327ab0..571f617d849 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -1,7 +1,5 @@ package gregtech.client; -import com.cleanroommc.modularui.utils.math.functions.limit.Min; - import gregtech.api.GTValues; import gregtech.api.fluids.GTFluidRegistration; import gregtech.api.items.metaitem.MetaOreDictItem; diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 7b60f40b119..aa29bf06576 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -163,8 +163,7 @@ else if (obj instanceof String str) { if (ItemGTToolbelt.isToolbeltableOredict(str)) initNeedsToolbeltHandlingHelper.set(true); return new OreIngredient(str); - } - else if (obj instanceof JsonElement) + } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); return null; diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index 7d39669e5f6..e0ceff95e51 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,7 +1,5 @@ package gregtech.common.crafting; -import com.google.common.collect.Lists; - import gregtech.api.crafting.IToolbeltSupportingRecipe; import net.minecraft.inventory.InventoryCrafting; @@ -13,6 +11,7 @@ import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; +import com.google.common.collect.Lists; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -53,11 +52,9 @@ public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { int ingredientCount = 0; List items = Lists.newArrayList(); - for (int i = 0; i < inv.getSizeInventory(); ++i) - { + for (int i = 0; i < inv.getSizeInventory(); ++i) { ItemStack itemstack = inv.getStackInSlot(i); - if (!itemstack.isEmpty()) - { + if (!itemstack.isEmpty()) { ++ingredientCount; items.add(itemstack); } diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java index 96b14b1c47c..f2978076e44 100644 --- a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -8,7 +8,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.PacketBuffer; -import net.minecraft.util.EnumHand; public class PacketToolbeltSelectionChange implements IPacket, IServerExecutor { From 7c37fa806f12a1132d7084fcbae78be022d5b9bf Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 21:54:42 -0600 Subject: [PATCH 05/82] Maintenance --- .../api/items/toolitem/ItemGTToolbelt.java | 17 ++++++ .../api/items/toolitem/ToolHelper.java | 7 +++ .../MetaTileEntityMaintenanceHatch.java | 55 +++++++++---------- 3 files changed, 49 insertions(+), 30 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index e538e468aaf..24b27bad50f 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -141,6 +141,11 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { return stack.copy(); } + public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, + @Nullable EntityPlayer entityPlayer) { + return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); + } + public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { return getHandler(stack).checkIngredientAgainstTools(ingredient, false); } @@ -346,6 +351,18 @@ protected void update() { } } + public boolean checkMaintenanceAgainstTools(String toolClass, boolean doCraftingDamage, + @Nullable EntityPlayer entityPlayer) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (ToolHelper.isTool(stack, toolClass)) { + if (doCraftingDamage) ToolHelper.damageItemWhenCrafting(stack, entityPlayer); + return true; + } + } + return false; + } + public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraftingDamage) { for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index f894664d1dd..c4f92284be8 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -220,6 +220,13 @@ public static ItemStack getAndSetToolData(IGTTool tool, Material material, int m * @param entity entity that has damaged this stack */ public static void damageItemWhenCrafting(@NotNull ItemStack stack, @Nullable EntityLivingBase entity) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selectedStack = toolbelt.getSelectedItem(stack); + if (selectedStack != null) { + damageItemWhenCrafting(selectedStack, entity); + return; + } + } int damage = 2; if (stack.getItem() instanceof IGTTool) { damage = ((IGTTool) stack.getItem()).getToolStats().getToolDamagePerCraft(stack); diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index dda660e024f..8437b2674ce 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -9,6 +9,7 @@ import gregtech.api.gui.widgets.ClickButtonWidget; import gregtech.api.gui.widgets.SlotWidget; import gregtech.api.items.itemhandlers.GTItemStackHandler; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.metatileentity.MetaTileEntity; @@ -50,6 +51,7 @@ import java.math.BigDecimal; import java.math.RoundingMode; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -260,24 +262,12 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { if (((problems >> index) & 1) == 0) { proceed = true; switch (index) { - case 0: - toolsToMatch.set(0, ToolClasses.WRENCH); - break; - case 1: - toolsToMatch.set(1, ToolClasses.SCREWDRIVER); - break; - case 2: - toolsToMatch.set(2, ToolClasses.SOFT_MALLET); - break; - case 3: - toolsToMatch.set(3, ToolClasses.HARD_HAMMER); - break; - case 4: - toolsToMatch.set(4, ToolClasses.WIRE_CUTTER); - break; - case 5: - toolsToMatch.set(5, ToolClasses.CROWBAR); - break; + case 0 -> toolsToMatch.set(0, ToolClasses.WRENCH); + case 1 -> toolsToMatch.set(1, ToolClasses.SCREWDRIVER); + case 2 -> toolsToMatch.set(2, ToolClasses.SOFT_MALLET); + case 3 -> toolsToMatch.set(3, ToolClasses.HARD_HAMMER); + case 4 -> toolsToMatch.set(4, ToolClasses.WIRE_CUTTER); + case 5 -> toolsToMatch.set(5, ToolClasses.CROWBAR); } } } @@ -285,37 +275,42 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { return; } + mainfor: for (int i = 0; i < toolsToMatch.size(); i++) { String toolToMatch = toolsToMatch.get(i); if (toolToMatch != null) { // Try to use the item in the player's "hand" (under the cursor) ItemStack heldItem = entityPlayer.inventory.getItemStack(); - if (ToolHelper.isTool(heldItem, toolToMatch)) { + if (heldItem.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.damageAgainstMaintenanceProblem(heldItem, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(i); + setTaped(false); + continue; + } + } else if (ToolHelper.isTool(heldItem, toolToMatch)) { fixProblemWithTool(i, heldItem, entityPlayer); if (toolsToMatch.stream().allMatch(Objects::isNull)) { return; } + continue; } // Then try all the remaining inventory slots for (ItemStack itemStack : entityPlayer.inventory.mainInventory) { - if (ToolHelper.isTool(itemStack, toolToMatch)) { - fixProblemWithTool(i, itemStack, entityPlayer); - - if (toolsToMatch.stream().allMatch(Objects::isNull)) { - return; + if (itemStack.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.damageAgainstMaintenanceProblem(itemStack, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(i); + setTaped(false); + continue mainfor; } - } - } + } else if (ToolHelper.isTool(itemStack, toolToMatch)) { + fixProblemWithTool(i, itemStack, entityPlayer); - for (ItemStack stack : entityPlayer.inventory.mainInventory) { - if (ToolHelper.isTool(stack, toolToMatch)) { - ((IMaintenance) this.getController()).setMaintenanceFixed(i); - ToolHelper.damageItemWhenCrafting(stack, entityPlayer); if (toolsToMatch.stream().allMatch(Objects::isNull)) { return; } + continue mainfor; } } } From d8079df861d142ba352a6d601676b14812d7dbff Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 22:06:27 -0600 Subject: [PATCH 06/82] Shift-click --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 24b27bad50f..52548b54033 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,5 +1,7 @@ package gregtech.api.items.toolitem; +import com.cleanroommc.modularui.widgets.slot.SlotGroup; + import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; @@ -97,6 +99,9 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); + SlotGroup group = new SlotGroup("toolbelt_inventory", 9); + guiSyncManager.registerSlotGroup(group); + SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); slotGroupWidget.flex() .coverChildren() @@ -107,7 +112,7 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i)) + .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group)) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); From b2162f95ab4cdd472150fbc5097ef400684355c1 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 22:07:26 -0600 Subject: [PATCH 07/82] Spotless, once more --- src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 3 +-- .../multi/multiblockpart/MetaTileEntityMaintenanceHatch.java | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 52548b54033..c958357eadc 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,7 +1,5 @@ package gregtech.api.items.toolitem; -import com.cleanroommc.modularui.widgets.slot.SlotGroup; - import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; @@ -35,6 +33,7 @@ import com.cleanroommc.modularui.value.sync.SyncHandlers; import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.cleanroommc.modularui.widgets.slot.SlotGroup; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index 8437b2674ce..c28ddc32860 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -51,7 +51,6 @@ import java.math.BigDecimal; import java.math.RoundingMode; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; From affb2f5116a3c5229c56cf7d7634d06d3d6cdd7e Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 22:32:47 -0600 Subject: [PATCH 08/82] Passthrough methods --- .../api/items/toolitem/ItemGTToolbelt.java | 244 +++++++++++++++--- 1 file changed, 215 insertions(+), 29 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index c958357eadc..c3d8668c511 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -8,8 +8,13 @@ import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; @@ -19,10 +24,14 @@ import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; @@ -35,6 +44,7 @@ import com.cleanroommc.modularui.widgets.SlotGroupWidget; import com.cleanroommc.modularui.widgets.slot.SlotGroup; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multimap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -42,6 +52,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; @@ -59,38 +70,10 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem) this.orestack = new ItemStack(this, 1, GTValues.W); } - @Override - public int getDamage(@NotNull ItemStack stack) { - ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { - selected.getItemDamage(); - } - return super.getDamage(stack); - } - - @Override - public void setDamage(@NotNull ItemStack stack, int damage) { - ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { - selected.setItemDamage(damage); - } else super.setDamage(stack, damage); - } - public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { return getHandler(stack).getSelectedStack(); } - @Override - public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - if (player.isSneaking()) { - if (!world.isRemote) { - ItemGuiFactory.open((EntityPlayerMP) player, hand); - } - return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); - } else return definition$onItemRightClick(world, player, hand); - } - @Override public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); @@ -131,10 +114,213 @@ public void registerValidOredict(String oredict) { } @Override - public @NotNull Set getToolClasses(@NotNull ItemStack stack) { + public float getDestroySpeed(@NotNull ItemStack stack, @NotNull IBlockState state) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getDestroySpeed(selected, state); + } else return definition$getDestroySpeed(stack, state); + } + + @Override + public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase target, + @NotNull EntityLivingBase attacker) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().hitEntity(selected, target, attacker); + } else return definition$hitEntity(stack, target, attacker); + } + + @Override + public boolean onBlockStartBreak(@NotNull ItemStack itemstack, @NotNull BlockPos pos, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(itemstack).getSelectedStack(); + if (selected != null) { + return selected.getItem().onBlockStartBreak(selected, pos, player); + } else return definition$onBlockStartBreak(itemstack, pos, player); + } + + @Override + public boolean onBlockDestroyed(@NotNull ItemStack stack, @NotNull World worldIn, @NotNull IBlockState state, + @NotNull BlockPos pos, @NotNull EntityLivingBase entityLiving) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().onBlockDestroyed(selected, worldIn, state, pos, entityLiving); + } else return definition$onBlockDestroyed(stack, worldIn, state, pos, entityLiving); + } + + @Override + public boolean getIsRepairable(@NotNull ItemStack toRepair, @NotNull ItemStack repair) { + // I think this lets repairs go through to the selected tool, in combination with the setDamage passthroughs? + // Idk testing required. + ItemStack selected = getHandler(toRepair).getSelectedStack(); + if (selected != null) { + return selected.getItem().getIsRepairable(selected, repair); + } else return definition$getIsRepairable(toRepair, repair); + } + + @NotNull + @Override + public Multimap getAttributeModifiers(@NotNull EntityEquipmentSlot slot, + @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getAttributeModifiers(slot, selected); + } else return definition$getAttributeModifiers(slot, stack); + } + + @Override + public int getHarvestLevel(@NotNull ItemStack stack, @NotNull String toolClass, @Nullable EntityPlayer player, + @Nullable IBlockState blockState) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getHarvestLevel(stack, toolClass, player, blockState); + } else return super.getHarvestLevel(stack, toolClass, player, blockState); + } + + @NotNull + @Override + public Set getToolClasses(@NotNull ItemStack stack) { return getHandler(stack).getToolClasses(true); } + @Override + public boolean canDisableShield(@NotNull ItemStack stack, @NotNull ItemStack shield, + @NotNull EntityLivingBase entity, @NotNull EntityLivingBase attacker) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().canDisableShield(selected, shield, entity, attacker); + } else return definition$canDisableShield(stack, shield, entity, attacker); + } + + @Override + public boolean doesSneakBypassUse(@NotNull ItemStack stack, @NotNull IBlockAccess world, @NotNull BlockPos pos, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().doesSneakBypassUse(selected, world, pos, player); + } else return definition$doesSneakBypassUse(stack, world, pos, player); + } + + @Override + public boolean onEntitySwing(@NotNull EntityLivingBase entityLiving, @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().onEntitySwing(entityLiving, selected); + } else return definition$onEntitySwing(entityLiving, stack); + } + + @Override + public boolean canDestroyBlockInCreative(@NotNull World world, @NotNull BlockPos pos, @NotNull ItemStack stack, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().canDestroyBlockInCreative(world, pos, selected, player); + } else return definition$canDestroyBlockInCreative(world, pos, stack, player); + } + + @Override + public boolean shouldCauseReequipAnimation(@NotNull ItemStack oldStack, @NotNull ItemStack newStack, + boolean slotChanged) { + return false; + } + + @Override + public boolean isDamaged(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().isDamaged(selected); + } else return definition$isDamaged(stack); + } + + @Override + public int getDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.getItemDamage(); + } + return super.getDamage(stack); + } + + @Override + public int getMaxDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getMaxDamage(selected); + } else return definition$getMaxDamage(stack); + } + + @Override + public void setDamage(@NotNull ItemStack stack, int damage) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.setItemDamage(damage); + } else super.setDamage(stack, damage); + } + + @Override + public double getDurabilityForDisplay(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getDurabilityForDisplay(selected); + } else return definition$getDurabilityForDisplay(stack); + } + + @NotNull + @Override + public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing side, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null) { + return selected.getItem().onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } else return definition$onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } + + @NotNull + @Override + public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null) { + return selected.getItem().onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } else return definition$onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + if (player.isSneaking()) { + if (!world.isRemote) { + ItemGuiFactory.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } else { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null) { + return selected.getItem().onItemRightClick(world, player, hand); + } else return definition$onItemRightClick(world, player, hand); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void addInformation(@NotNull ItemStack stack, @Nullable World world, @NotNull List tooltip, + @NotNull ITooltipFlag flag) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.getItem().addInformation(selected, world, tooltip, flag); + } else definition$addInformation(stack, world, tooltip, flag); + } + + @Override + public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().canHarvestBlock(state, selected); + } else return ToolHelper.isToolEffective(state, getToolClasses(stack), getTotalHarvestLevel(stack)); + } + @Override public boolean hasContainerItem(@NotNull ItemStack stack) { return true; From 307ef1448d13cfdcf11540ba0770265ca1a562bc Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 23:15:17 -0600 Subject: [PATCH 09/82] Less cringe --- .../crafting/IToolbeltSupportingRecipe.java | 2 -- .../java/gregtech/api/recipes/ModHandler.java | 6 ++-- .../common/crafting/GTShapedOreRecipe.java | 31 +++++++++++++------ .../common/crafting/GTShapelessOreRecipe.java | 9 +++--- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java index 7e55d8da228..c4d050e2082 100644 --- a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java +++ b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java @@ -14,8 +14,6 @@ public interface IToolbeltSupportingRecipe extends IRecipe { - ThreadLocal initNeedsToolbeltHandlingHelper = new ThreadLocal<>(); - @SuppressWarnings("BooleanMethodIsAlwaysInverted") static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) diff --git a/src/main/java/gregtech/api/recipes/ModHandler.java b/src/main/java/gregtech/api/recipes/ModHandler.java index 10e55ea68b1..a96b1d9077e 100644 --- a/src/main/java/gregtech/api/recipes/ModHandler.java +++ b/src/main/java/gregtech/api/recipes/ModHandler.java @@ -317,10 +317,10 @@ private static boolean validateRecipeWithOutput(@NotNull String regName, @NotNul private static void addRecipe(@NotNull String regName, @NotNull ItemStack result, boolean isNBTClearing, boolean isMirrored, @NotNull Object... recipe) { - IRecipe shapedOreRecipe = new GTShapedOreRecipe(isNBTClearing, null, result.copy(), + IRecipe shapedOreRecipe = GTShapedOreRecipe.create(isNBTClearing, null, result.copy(), finalizeShapedRecipeInput(recipe)) - .setMirrored(isMirrored) - .setRegistryName(regName); + .setMirrored(isMirrored) + .setRegistryName(regName); registerRecipe(shapedOreRecipe); } diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index aa29bf06576..c7b4f67bab5 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -32,6 +32,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSupportingRecipe { @@ -40,19 +41,29 @@ public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSuppo public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); - public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { - super(group, result, parseShaped(isClearing, recipe)); + private GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, + @NotNull ItemStack result, Object... recipe) { + super(group, result, parseShaped(toolbeltHandling, isClearing, recipe)); this.isClearing = isClearing; - this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); - initNeedsToolbeltHandlingHelper.set(false); + } + + public static GTShapedOreRecipe create(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, + Object... recipe) { + AtomicBoolean toolbeltHandling = new AtomicBoolean(false); + GTShapedOreRecipe out = new GTShapedOreRecipe(toolbeltHandling, isClearing, group, result, recipe); + return out.setToolbeltHandling(toolbeltHandling.get()); + } + + private GTShapedOreRecipe setToolbeltHandling(boolean toolbeltHandling) { + this.toolbeltHandling = toolbeltHandling; + return this; } // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. // the only difference is calling getIngredient of this class. - public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { - initNeedsToolbeltHandlingHelper.set(false); - + public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHandling, boolean isClearing, + Object... recipe) { CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); int idx = 0; @@ -95,7 +106,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object for (; idx < recipe.length; idx += 2) { Character chr = (Character) recipe[idx]; Object in = recipe[idx + 1]; - Ingredient ing = getIngredient(isClearing, in); + Ingredient ing = getIngredient(toolbeltHandling, isClearing, in); if (' ' == chr) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); @@ -133,7 +144,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object return ret; } - protected static Ingredient getIngredient(boolean isClearing, Object obj) { + protected static Ingredient getIngredient(AtomicBoolean toolbeltHandling, boolean isClearing, Object obj) { if (obj instanceof Ingredient ing) return ing; else if (obj instanceof ItemStack stk) { if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { @@ -161,7 +172,7 @@ else if (obj instanceof Block blk) return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); else if (obj instanceof String str) { if (ItemGTToolbelt.isToolbeltableOredict(str)) - initNeedsToolbeltHandlingHelper.set(true); + toolbeltHandling.set(true); return new OreIngredient(str); } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index e0ceff95e51..fb620ea9927 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -15,6 +15,7 @@ import org.jetbrains.annotations.NotNull; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbeltSupportingRecipe { @@ -24,11 +25,10 @@ public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbel public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); - initNeedsToolbeltHandlingHelper.set(false); - this.isClearing = isClearing; + AtomicBoolean needsToolbelt = new AtomicBoolean(false); for (Object in : recipe) { - Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(needsToolbelt, isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -41,8 +41,7 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull throw new RuntimeException(ret.toString()); } } - this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); - initNeedsToolbeltHandlingHelper.set(false); + this.toolbeltHandling = needsToolbelt.get(); } @Override From aca0e87ffaf6a7d385966c811ea8557fa8e40be5 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 23:42:34 -0600 Subject: [PATCH 10/82] Oops --- .../java/gregtech/common/crafting/FluidReplaceRecipe.java | 4 +++- src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index 61733e309fd..5cfd1571d47 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -16,13 +16,15 @@ import org.jetbrains.annotations.NotNull; +import java.util.concurrent.atomic.AtomicBoolean; + /** * A recipe which inputs a single Fluid Container, and outputs the same Fluid Container with a new contained Fluid */ public class FluidReplaceRecipe extends GTShapedOreRecipe { public FluidReplaceRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { - super(isClearing, group, result, recipe); + super(new AtomicBoolean(false), isClearing, group, result, recipe); // there is no possible way that we require toolbelt handling, but make sure it isn't enabled. this.toolbeltHandling = false; } diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index c7b4f67bab5..3cf67667b5d 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -41,8 +41,8 @@ public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSuppo public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); - private GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, - @NotNull ItemStack result, Object... recipe) { + protected GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, + @NotNull ItemStack result, Object... recipe) { super(group, result, parseShaped(toolbeltHandling, isClearing, recipe)); this.isClearing = isClearing; } From 0fc4a3d7cda40f5e936200311071c11d843cc45d Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 11:02:10 -0600 Subject: [PATCH 11/82] Passthrough / toolbelt detection improvements --- .../gregtech/api/items/toolitem/IGTTool.java | 28 ++++++++-- .../api/items/toolitem/ItemGTToolbelt.java | 56 ++++++++++++++++--- .../api/items/toolitem/ToolHelper.java | 43 +++++++++++++- .../toolitem/behavior/IToolBehavior.java | 49 +++++++++++++--- .../gregtech/common/ToolEventHandlers.java | 5 ++ .../items/tool/BlockRotatingBehavior.java | 6 +- .../common/items/tool/GrassPathBehavior.java | 7 +-- .../items/tool/HarvestCropsBehavior.java | 7 +-- .../common/items/tool/HoeGroundBehavior.java | 7 +-- .../common/items/tool/PlungerBehavior.java | 6 +- .../common/items/tool/RotateRailBehavior.java | 6 +- .../common/items/tool/TorchPlaceBehavior.java | 7 +-- 12 files changed, 179 insertions(+), 48 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 94ae45effb9..bca752b4cab 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -636,8 +636,13 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand) == + if (behavior.onItemUseFirst(stack, player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } @@ -648,8 +653,14 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + ItemStack stack = player.getHeldItem(hand); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { + if (behavior.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ) == + EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } } @@ -659,20 +670,25 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default ActionResult definition$onItemRightClick(World world, EntityPlayer player, EnumHand hand) { ItemStack stack = player.getHeldItem(hand); + ItemStack original = stack; + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { PlayerInventoryHolder.openHandItemUI(player, hand); - return ActionResult.newResult(EnumActionResult.SUCCESS, stack); + return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemRightClick(world, player, hand).getType() == EnumActionResult.SUCCESS) { - return ActionResult.newResult(EnumActionResult.SUCCESS, stack); + if (behavior.onItemRightClick(stack, world, player, hand).getType() == EnumActionResult.SUCCESS) { + return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } - return ActionResult.newResult(EnumActionResult.PASS, stack); + return ActionResult.newResult(EnumActionResult.PASS, original); } default void definition$getSubItems(@NotNull NonNullList items) { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index c3d8668c511..f6558f46a48 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -5,6 +5,10 @@ import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.OreDictUnifier; +import gregtech.api.unification.material.Material; +import gregtech.api.unification.material.Materials; +import gregtech.api.unification.material.properties.PropertyKey; +import gregtech.api.unification.material.properties.ToolProperty; import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; @@ -25,6 +29,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; @@ -57,6 +62,8 @@ import java.util.Set; import java.util.function.Supplier; +import static gregtech.api.items.toolitem.ToolHelper.MATERIAL_KEY; + public class ItemGTToolbelt extends ItemGTTool { protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); @@ -236,9 +243,8 @@ public boolean isDamaged(@NotNull ItemStack stack) { public int getDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { - selected.getItemDamage(); - } - return super.getDamage(stack); + return selected.getItem().getDamage(selected); + } else return super.getDamage(stack); } @Override @@ -253,7 +259,7 @@ public int getMaxDamage(@NotNull ItemStack stack) { public void setDamage(@NotNull ItemStack stack, int damage) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { - selected.setItemDamage(damage); + selected.getItem().setDamage(selected, damage); } else super.setDamage(stack, damage); } @@ -261,7 +267,10 @@ public void setDamage(@NotNull ItemStack stack, int damage) { public double getDurabilityForDisplay(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { - return selected.getItem().getDurabilityForDisplay(selected); + double dis = selected.getItem().getDurabilityForDisplay(selected); + // vanillaesque tools need to be inverted + if (!(selected.getItem() instanceof IGTTool)) dis = 1 - dis; + return dis; } else return definition$getDurabilityForDisplay(stack); } @@ -321,6 +330,30 @@ public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack st } else return ToolHelper.isToolEffective(state, getToolClasses(stack), getTotalHarvestLevel(stack)); } + @Override + public void wrenchUsed(EntityPlayer player, EnumHand hand, ItemStack wrench, RayTraceResult rayTrace) { + ItemStack selected = getHandler(wrench).getSelectedStack(); + if (selected != null && selected.getItem() instanceof IGTTool tool) { + tool.wrenchUsed(player, hand, selected, rayTrace); + } else super.wrenchUsed(player, hand, wrench, rayTrace); + } + + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { + ItemStack selected = getHandler(item).getSelectedStack(); + if (selected != null && selected.getItem() instanceof IGTTool tool) { + tool.toolUsed(selected, user, pos); + } else super.toolUsed(item, user, pos); + } + + @Override + public void used(@NotNull EnumHand hand, @NotNull EntityPlayer player, @NotNull BlockPos pos) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null && selected.getItem() instanceof IGTTool tool) { + tool.used(hand, player, pos); + } else super.used(hand, player, pos); + } + @Override public boolean hasContainerItem(@NotNull ItemStack stack) { return true; @@ -378,14 +411,23 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } - protected class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; private @Nullable ToolStackHandler handler; public ToolbeltCapabilityProvider(ItemStack stack) { - slotCountSupplier = () -> (int) (ItemGTToolbelt.super.getTotalHarvestLevel(stack) * 5.4f); + slotCountSupplier = () -> { + NBTTagCompound toolTag = stack.getOrCreateSubCompound(ToolHelper.TOOL_TAG_KEY); + String string = toolTag.getString(MATERIAL_KEY); + Material material = GregTechAPI.materialManager.getMaterial(string); + if (material == null) { + toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).toString()); + } + ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); + return (int) (toolProperty == null ? 5 : toolProperty.getToolHarvestLevel() * 5.4f); + }; } @Override diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index c4f92284be8..4d0803bccb1 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -184,10 +184,18 @@ public static void registerToolSymbol(Character symbol, IGTTool tool) { } public static NBTTagCompound getToolTag(ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } return stack.getOrCreateSubCompound(TOOL_TAG_KEY); } public static NBTTagCompound getBehaviorsTag(ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); } @@ -332,6 +340,10 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa */ public static void onActionDone(@NotNull EntityPlayer player, @NotNull World world, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } IGTTool tool = (IGTTool) stack.getItem(); ToolHelper.damageItem(stack, player); if (tool.getSound() != null) { @@ -375,6 +387,10 @@ public static boolean areTools(ItemStack tool, String... toolClasses) { * @return The level of Fortune or Looting that the tool is enchanted with, or zero */ public static int getFortuneOrLootingLevel(ItemStack tool) { + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } if (tool.getItem() instanceof ItemGTSword) { return EnchantmentHelper.getEnchantmentLevel(Enchantments.LOOTING, tool); } else if (tool.getItem() instanceof IGTTool) { @@ -396,6 +412,10 @@ public static AoESymmetrical getAoEDefinition(ItemStack stack) { * AoE Block Breaking Routine. */ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlayerMP player) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } int currentDurability = getToolTag(stack).getInteger(DURABILITY_KEY); int maximumDurability = getToolTag(stack).getInteger(MAX_DURABILITY_KEY); int remainingUses = maximumDurability - currentDurability; @@ -412,7 +432,11 @@ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlaye return true; } // If the tool is an electric tool, catch the tool breaking and cancel the remaining AOE - else if (!player.getHeldItemMainhand().isItemEqualIgnoreDurability(stack)) { + ItemStack tool = player.getHeldItemMainhand(); + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } else if (!tool.isItemEqualIgnoreDurability(stack)) { return true; } } @@ -424,6 +448,10 @@ else if (!player.getHeldItemMainhand().isItemEqualIgnoreDurability(stack)) { public static Set iterateAoE(ItemStack stack, AoESymmetrical aoeDefinition, World world, EntityPlayer player, RayTraceResult rayTraceResult, QuintFunction function) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } if (aoeDefinition != AoESymmetrical.none() && rayTraceResult != null && rayTraceResult.typeOfHit == RayTraceResult.Type.BLOCK && rayTraceResult.sideHit != null) { int column = aoeDefinition.column; @@ -671,9 +699,12 @@ public static void applyHammerDropConversion(ItemStack tool, IBlockState state, } } - @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { // This is *not* a vanilla/forge convention, Forge never added "shears" to ItemShear's tool classes. + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } if (isTool(tool, ToolClasses.SHEARS) && shearBlockRoutine(player, tool, pos) == 0) { return false; } @@ -722,6 +753,10 @@ public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, B */ public static int shearBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { if (!player.isCreative()) { + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } World world = player.world; IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IShearable) { @@ -780,6 +815,10 @@ public static ItemStack getSilkTouchDrop(@NotNull IBlockState state) { } public static void playToolSound(ItemStack stack, EntityPlayer player) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } if (stack.getItem() instanceof IGTTool) { ((IGTTool) stack.getItem()).playSound(player); } diff --git a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java index 4131cf59218..150900079be 100644 --- a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java +++ b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java @@ -78,6 +78,16 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving return false; } + /** + * Not itemstack sensitive. Use the new override. + */ + @Deprecated + default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { + return EnumActionResult.PASS; + } + /** * Called when a Block is right-clicked with this Item, but before the block is activated * @@ -90,15 +100,27 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving * @param hitZ the z location of the block hit * @param hand the hand holding the item */ - default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + default EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + return onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand); + } + + /** + * Not itemstack sensitive. Use the new override. + */ + @Deprecated + @NotNull + default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { return EnumActionResult.PASS; } /** * Called when a Block is right-clicked with this Item * + * @param stack the itemstack of the tool * @param player the player clicking with the item * @param world the world in which the block is clicked * @param pos the position of the blocked clicked @@ -109,10 +131,21 @@ default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull W * @param hitZ the z location of the block hit */ @NotNull - default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + default EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { - return EnumActionResult.PASS; + return onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } + + /** + * Not itemstack sensitive. Use the new override. + */ + @NotNull + @Deprecated + default ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); } /** @@ -123,9 +156,9 @@ default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World * @param hand the hand holding the item */ @NotNull - default ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); + default ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, + @NotNull EntityPlayer player, @NotNull EnumHand hand) { + return onItemRightClick(world, player, hand); } @SideOnly(Side.CLIENT) diff --git a/src/main/java/gregtech/common/ToolEventHandlers.java b/src/main/java/gregtech/common/ToolEventHandlers.java index 62195e49791..7d5577f4320 100644 --- a/src/main/java/gregtech/common/ToolEventHandlers.java +++ b/src/main/java/gregtech/common/ToolEventHandlers.java @@ -8,6 +8,7 @@ import gregtech.api.cover.CoverDefinition; import gregtech.api.cover.CoverHolder; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.metatileentity.MetaTileEntity; @@ -165,6 +166,10 @@ public static void onHarvestDrops(@NotNull BlockEvent.HarvestDropsEvent event) { // only try once, so future water placement does not get eaten too return false; }); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } ((IGTTool) stack.getItem()).playSound(player); } } diff --git a/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java b/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java index acd60d1324a..143371982c3 100644 --- a/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java +++ b/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java @@ -33,9 +33,9 @@ public class BlockRotatingBehavior implements IToolBehavior { protected BlockRotatingBehavior() {/**/} @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing side, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing side, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { TileEntity te = world.getTileEntity(pos); // MTEs have special handling on rotation if (te instanceof IGregTechTileEntity) { diff --git a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java index 4dc960a6a3f..111bc9855ce 100644 --- a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java +++ b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java @@ -34,12 +34,11 @@ protected GrassPathBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; - ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java index d1ac7a4be93..353d0427d19 100644 --- a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java @@ -36,13 +36,12 @@ protected HarvestCropsBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { if (world.isRemote) { return EnumActionResult.PASS; } - ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); diff --git a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java index 36477d16801..fe05dabdc67 100644 --- a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java @@ -41,12 +41,11 @@ protected HoeGroundBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; - ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/PlungerBehavior.java b/src/main/java/gregtech/common/items/tool/PlungerBehavior.java index 609e429e0c0..2d6fdc3eab8 100644 --- a/src/main/java/gregtech/common/items/tool/PlungerBehavior.java +++ b/src/main/java/gregtech/common/items/tool/PlungerBehavior.java @@ -32,9 +32,9 @@ public class PlungerBehavior implements IToolBehavior { protected PlungerBehavior() {/**/} @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { IFluidHandler fluidHandler = FluidUtil.getFluidHandler(world, pos, facing); if (fluidHandler == null) { return EnumActionResult.PASS; diff --git a/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java b/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java index 19985d1459e..cac327cd442 100644 --- a/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java +++ b/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java @@ -29,9 +29,9 @@ protected RotateRailBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof BlockRailBase) { if (world.setBlockState(pos, state.withRotation(Rotation.CLOCKWISE_90))) { diff --git a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java index d9d5f86ef69..2965a1ad56d 100644 --- a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java +++ b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java @@ -37,10 +37,9 @@ protected TorchPlaceBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { - ItemStack stack = player.getHeldItem(hand); + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { NBTTagCompound behaviourTag = ToolHelper.getBehaviorsTag(stack); if (behaviourTag.getBoolean(ToolHelper.TORCH_PLACING_KEY)) { int cachedTorchSlot; From 3c14c4ff53af2c6f7e8ba70958ddee04e65e10fe Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 11:47:47 -0600 Subject: [PATCH 12/82] Prevent unexpected behavior on removal of selected tool --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index f6558f46a48..94fbb4f414d 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -100,8 +100,11 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.flex().endDefaultMode(); slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { + int finalI = i; slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group)) + .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group) + .changeListener((newItem, onlyAmountChanged, client, init) -> + handler.onContentsChanged(finalI))) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); @@ -526,6 +529,7 @@ public boolean isItemValid(int slot, @NotNull ItemStack stack) { @Override protected void onContentsChanged(int slot) { + if (this.selectedSlot != null && this.selectedSlot == slot) this.selectedSlot = null; this.updateSlot(slot); this.update(); From 31fd7613cd1f8e2722520c1a1f4ab34d2bdf60c2 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 12:50:00 -0600 Subject: [PATCH 13/82] Better toolbelt GUI handling --- .../gregtech/api/items/toolitem/IGTTool.java | 16 +++++-- .../api/items/toolitem/ItemGTToolbelt.java | 48 +++---------------- .../java/gregtech/common/items/ToolItems.java | 2 +- .../common/items/tool/OpenGUIBehavior.java | 31 ++++++++++++ 4 files changed, 52 insertions(+), 45 deletions(-) create mode 100644 src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index bca752b4cab..b071dbfca59 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -641,7 +641,10 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { ItemStack selected = toolbelt.getSelectedItem(stack); if (selected != null) stack = selected; } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + List behaviors; + if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); + else behaviors = getToolStats().getBehaviors(); + for (IToolBehavior behavior : behaviors) { if (behavior.onItemUseFirst(stack, player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -658,7 +661,11 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { ItemStack selected = toolbelt.getSelectedItem(stack); if (selected != null) stack = selected; } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + List behaviors; + if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); + else behaviors = getToolStats().getBehaviors(); + + for (IToolBehavior behavior : behaviors) { if (behavior.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -682,8 +689,11 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } + List behaviors; + if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); + else behaviors = getToolStats().getBehaviors(); - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + for (IToolBehavior behavior : behaviors) { if (behavior.onItemRightClick(stack, world, player, hand).getType() == EnumActionResult.SUCCESS) { return ActionResult.newResult(EnumActionResult.SUCCESS, original); } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 94fbb4f414d..51e583ce54f 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.GregTechAPI; +import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.OreDictUnifier; @@ -13,6 +14,7 @@ import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; @@ -70,9 +72,9 @@ public class ItemGTToolbelt extends ItemGTTool { private final ItemStack orestack; - public ItemGTToolbelt(String domain, String id, Supplier markerItem) { - super(domain, id, -1, new ToolDefinitionBuilder().cannotAttack().attackSpeed(-2.4F).build(), null, - false, new HashSet<>(), "", new ArrayList<>(), + public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { + super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), + null, false, new HashSet<>(), "", new ArrayList<>(), markerItem); this.orestack = new ItemStack(this, 1, GTValues.W); } @@ -277,44 +279,6 @@ public double getDurabilityForDisplay(@NotNull ItemStack stack) { } else return definition$getDurabilityForDisplay(stack); } - @NotNull - @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing side, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { - ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null) { - return selected.getItem().onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); - } else return definition$onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); - } - - @NotNull - @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { - ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null) { - return selected.getItem().onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); - } else return definition$onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); - } - - @Override - public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - if (player.isSneaking()) { - if (!world.isRemote) { - ItemGuiFactory.open((EntityPlayerMP) player, hand); - } - return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); - } else { - ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null) { - return selected.getItem().onItemRightClick(world, player, hand); - } else return definition$onItemRightClick(world, player, hand); - } - } - @Override @SideOnly(Side.CLIENT) public void addInformation(@NotNull ItemStack stack, @Nullable World world, @NotNull List tooltip, @@ -414,6 +378,8 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } + //TODO BEWLR for dynamic display of selected item? + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 04c6a0e7f79..5796d85c25c 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -68,7 +68,7 @@ public static List getAllTools() { public static void init() { TOOLBELT = (ItemGTToolbelt) register(new ItemGTToolbelt(GTValues.MODID, "toolbelt", - null)); + null, OpenGUIBehavior.INSTANCE)); SWORD = register(ItemGTSword.Builder.of(GTValues.MODID, "sword") .toolStats(b -> b.attacking() .attackDamage(3.0F).attackSpeed(-2.4F)) diff --git a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java new file mode 100644 index 00000000000..bc098cfea86 --- /dev/null +++ b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java @@ -0,0 +1,31 @@ +package gregtech.common.items.tool; + +import com.cleanroommc.modularui.factory.ItemGuiFactory; + +import gregtech.api.items.toolitem.behavior.IToolBehavior; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; + +public class OpenGUIBehavior implements IToolBehavior { + + public static final OpenGUIBehavior INSTANCE = new OpenGUIBehavior(); + + protected OpenGUIBehavior() {} + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, + @NotNull EntityPlayer player, @NotNull EnumHand hand) { + if (!world.isRemote) { + ItemGuiFactory.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } +} From a7c3cb51f1d17ba94e3b14b13c65cde8fe49056a Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 14:51:40 -0600 Subject: [PATCH 14/82] mui2 (pain) --- .../gregtech/api/items/toolitem/IGTTool.java | 139 +++++++++++++----- .../api/items/toolitem/ItemGTToolbelt.java | 6 + .../api/items/toolitem/ToolHelper.java | 8 + .../java/gregtech/api/mui/GTGuiTextures.java | 2 + .../gregtech/api/mui/sync/NBTSyncValue.java | 59 ++++++++ 5 files changed, 174 insertions(+), 40 deletions(-) create mode 100644 src/main/java/gregtech/api/mui/sync/NBTSyncValue.java diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index b071dbfca59..756b1c01175 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -1,5 +1,21 @@ package gregtech.api.items.toolitem; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; + +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; + +import com.cleanroommc.modularui.value.sync.SyncHandler; +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widget.sizer.Unit; +import com.cleanroommc.modularui.widgets.ButtonWidget; +import com.cleanroommc.modularui.widgets.TextWidget; + +import com.cleanroommc.modularui.widgets.layout.Column; + import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.capability.GregtechCapabilities; @@ -9,11 +25,15 @@ import gregtech.api.gui.ModularUI; import gregtech.api.gui.widgets.ClickButtonWidget; import gregtech.api.gui.widgets.DynamicLabelWidget; +import gregtech.api.gui.widgets.LabelWidget; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.gui.PlayerInventoryHolder; import gregtech.api.items.metaitem.ElectricStats; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.items.toolitem.behavior.IToolBehavior; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; +import gregtech.api.mui.sync.NBTSyncValue; import gregtech.api.recipes.ModHandler; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Material; @@ -685,7 +705,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { - PlayerInventoryHolder.openHandItemUI(player, hand); + ItemGuiFactory.open((EntityPlayerMP) player, hand); return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } @@ -929,45 +949,84 @@ default void playSound(EntityPlayer player) { } } - default ModularUI createUI(PlayerInventoryHolder holder, EntityPlayer entityPlayer) { - NBTTagCompound tag = getBehaviorsTag(holder.getCurrentItem()); - AoESymmetrical defaultDefinition = getMaxAoEDefinition(holder.getCurrentItem()); - return ModularUI.builder(GuiTextures.BORDERED_BACKGROUND, 120, 80) - .label(6, 10, "item.gt.tool.aoe.columns") - .label(49, 10, "item.gt.tool.aoe.rows") - .label(79, 10, "item.gt.tool.aoe.layers") - .widget(new ClickButtonWidget(15, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseColumn(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(15, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseColumn(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(50, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseRow(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(50, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseRow(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(85, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseLayer(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(85, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseLayer(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new DynamicLabelWidget(23, 65, () -> Integer.toString( - 1 + 2 * AoESymmetrical.getColumn(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .widget(new DynamicLabelWidget(58, 65, () -> Integer.toString( - 1 + 2 * AoESymmetrical.getRow(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .widget(new DynamicLabelWidget(93, 65, - () -> Integer.toString(1 + - AoESymmetrical.getLayer(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .build(holder, entityPlayer); + @Override + default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { + ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 120, 80); + + Supplier tag = () -> getBehaviorsTag(guiData.getUsedItemStack()); + AoESymmetrical defaultDefinition = getMaxAoEDefinition(guiData.getUsedItemStack()); + + NBTSyncValue nbtSyncer = new NBTSyncValue(tag, (nbt) -> setBehaviorsTag(guiData.getUsedItemStack(), nbt)); + guiSyncManager.syncValue("NBTSync", nbtSyncer); + + Column columns = new Column(); + columns.flex().coverChildren().startDefaultMode() + .leftRel(0.07f).bottomRel(0.5f).endDefaultMode(); + columns.child(new TextWidget(IKey.lang("item.gt.tool.aoe.columns")).paddingBottom(5)); + columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.increaseColumn(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.decreaseColumn(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + columns.child(new TextWidget(IKey.dynamic(() -> + String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))).paddingTop(5)); + panel.child(columns); + + Column rows = new Column(); + rows.flex().coverChildren().startDefaultMode() + .rightRel(0.5f).bottomRel(0.5f).endDefaultMode(); + rows.child(new TextWidget(IKey.lang("item.gt.tool.aoe.rows")).paddingBottom(5)); + rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.increaseRow(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.decreaseRow(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + rows.child(new TextWidget(IKey.dynamic(() -> + String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))).paddingTop(5)); + panel.child(rows); + + Column layers = new Column(); + layers.flex().coverChildren().startDefaultMode() + .rightRel(0.07f).bottomRel(0.5f).endDefaultMode(); + layers.child(new TextWidget(IKey.lang("item.gt.tool.aoe.layers")).paddingBottom(5)); + layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.increaseLayer(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.decreaseLayer(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + layers.child(new TextWidget(IKey.dynamic(() -> + String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))).paddingTop(5)); + panel.child(layers); + + + return panel; } Set getToolClasses(ItemStack stack); diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 51e583ce54f..d67de8697c4 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.GregTechAPI; +import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; @@ -86,6 +87,11 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem, @Override public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); + ItemStack selected = handler.getSelectedStack(); + if (selected != null && selected.getItem() instanceof ItemUIFactory factory) { + return factory.buildUI(guiData, guiSyncManager); + } + int heightBonus = (handler.getSlots() / 9) * 18; ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 4d0803bccb1..e5dfb9774e1 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -199,6 +199,14 @@ public static NBTTagCompound getBehaviorsTag(ItemStack stack) { return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); } + public static void setBehaviorsTag(ItemStack stack, NBTTagCompound tag) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } + stack.setTagInfo(BEHAVIOURS_TAG_KEY, tag); + } + public static ItemStack getAndSetToolData(IGTTool tool, Material material, int maxDurability, int harvestLevel, float toolSpeed, float attackDamage) { ItemStack stack = tool.getRaw(); diff --git a/src/main/java/gregtech/api/mui/GTGuiTextures.java b/src/main/java/gregtech/api/mui/GTGuiTextures.java index d585285efc2..c2d68451930 100644 --- a/src/main/java/gregtech/api/mui/GTGuiTextures.java +++ b/src/main/java/gregtech/api/mui/GTGuiTextures.java @@ -349,6 +349,8 @@ public static class IDs { public static final UITexture BUTTON_CROSS = fullImage("textures/gui/widget/button_cross.png"); public static final UITexture BUTTON_REDSTONE_ON = fullImage("textures/gui/widget/button_redstone_on.png"); public static final UITexture BUTTON_REDSTONE_OFF = fullImage("textures/gui/widget/button_redstone_off.png"); + public static final UITexture BUTTON_THROTTLE_PLUS = fullImage("textures/gui/widget/button_throttle_plus.png"); + public static final UITexture BUTTON_THROTTLE_MINUS = fullImage("textures/gui/widget/button_throttle_minus.png"); // PROGRESS BARS public static final UITexture PROGRESS_BAR_ARC_FURNACE = progressBar( diff --git a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java new file mode 100644 index 00000000000..4ac8c24436f --- /dev/null +++ b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java @@ -0,0 +1,59 @@ +package gregtech.api.mui.sync; + +import com.cleanroommc.modularui.value.sync.ValueSyncHandler; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; + +import java.io.IOException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class NBTSyncValue extends ValueSyncHandler { + + private final Supplier getter; + private final Consumer setter; + private NBTTagCompound cache; + + public NBTSyncValue(Supplier getter, Consumer setter) { + this.getter = getter; + this.setter = setter; + this.cache = getter.get(); + } + + @Override + public void setValue(NBTTagCompound value, boolean setSource, boolean sync) { + this.cache = value; + if (setSource && this.setter != null) { + this.setter.accept(value); + } + if (sync) { + sync(0, this::write); + } + } + + @Override + public boolean updateCacheFromSource(boolean isFirstSync) { + if (isFirstSync || !Objects.equals(this.getter.get(), this.cache)) { + setValue(this.getter.get(), false, false); + return true; + } + return false; + } + + @Override + public void write(PacketBuffer buffer) throws IOException { + buffer.writeCompoundTag(getValue()); + } + + @Override + public void read(PacketBuffer buffer) throws IOException { + setValue(buffer.readCompoundTag()); + } + + @Override + public NBTTagCompound getValue() { + return this.cache; + } +} From d426c64aba2a614a12ad6b59dc0be3279d1e5aa0 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 14:58:16 -0600 Subject: [PATCH 15/82] sp3tless --- .../gregtech/api/items/toolitem/IGTTool.java | 58 ++++++++----------- .../api/items/toolitem/ItemGTToolbelt.java | 14 ++--- .../gregtech/api/mui/sync/NBTSyncValue.java | 4 +- .../common/items/tool/OpenGUIBehavior.java | 3 +- 4 files changed, 31 insertions(+), 48 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 756b1c01175..649c1e894e6 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -1,33 +1,11 @@ package gregtech.api.items.toolitem; -import com.cleanroommc.modularui.api.drawable.IKey; -import com.cleanroommc.modularui.factory.HandGuiData; -import com.cleanroommc.modularui.factory.ItemGuiFactory; - -import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.utils.Alignment; -import com.cleanroommc.modularui.value.sync.GuiSyncManager; - -import com.cleanroommc.modularui.value.sync.SyncHandler; -import com.cleanroommc.modularui.value.sync.SyncHandlers; -import com.cleanroommc.modularui.widget.sizer.Unit; -import com.cleanroommc.modularui.widgets.ButtonWidget; -import com.cleanroommc.modularui.widgets.TextWidget; - -import com.cleanroommc.modularui.widgets.layout.Column; - import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.impl.CombinedCapabilityProvider; import gregtech.api.capability.impl.ElectricItem; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.widgets.ClickButtonWidget; -import gregtech.api.gui.widgets.DynamicLabelWidget; -import gregtech.api.gui.widgets.LabelWidget; import gregtech.api.items.gui.ItemUIFactory; -import gregtech.api.items.gui.PlayerInventoryHolder; import gregtech.api.items.metaitem.ElectricStats; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.items.toolitem.behavior.IToolBehavior; @@ -83,6 +61,14 @@ import appeng.api.implementations.items.IAEWrench; import buildcraft.api.tools.IToolWrench; import cofh.api.item.IToolHammer; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; +import com.cleanroommc.modularui.widgets.ButtonWidget; +import com.cleanroommc.modularui.widgets.TextWidget; +import com.cleanroommc.modularui.widgets.layout.Column; import com.enderio.core.common.interfaces.IOverlayRenderAware; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; @@ -964,21 +950,22 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) .leftRel(0.07f).bottomRel(0.5f).endDefaultMode(); columns.child(new TextWidget(IKey.lang("item.gt.tool.aoe.columns")).paddingBottom(5)); columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.increaseColumn(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.decreaseColumn(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); - columns.child(new TextWidget(IKey.dynamic(() -> - String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))).paddingTop(5)); + columns.child(new TextWidget( + IKey.dynamic(() -> String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))) + .paddingTop(5)); panel.child(columns); Column rows = new Column(); @@ -986,21 +973,22 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) .rightRel(0.5f).bottomRel(0.5f).endDefaultMode(); rows.child(new TextWidget(IKey.lang("item.gt.tool.aoe.rows")).paddingBottom(5)); rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.increaseRow(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.decreaseRow(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); - rows.child(new TextWidget(IKey.dynamic(() -> - String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))).paddingTop(5)); + rows.child(new TextWidget( + IKey.dynamic(() -> String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))) + .paddingTop(5)); panel.child(rows); Column layers = new Column(); @@ -1008,24 +996,24 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) .rightRel(0.07f).bottomRel(0.5f).endDefaultMode(); layers.child(new TextWidget(IKey.lang("item.gt.tool.aoe.layers")).paddingBottom(5)); layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.increaseLayer(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.decreaseLayer(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); - layers.child(new TextWidget(IKey.dynamic(() -> - String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))).paddingTop(5)); + layers.child(new TextWidget( + IKey.dynamic(() -> String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))) + .paddingTop(5)); panel.child(layers); - return panel; } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index d67de8697c4..78fab137b2e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -15,20 +15,16 @@ import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; @@ -44,7 +40,6 @@ import net.minecraftforge.items.ItemStackHandler; import com.cleanroommc.modularui.factory.HandGuiData; -import com.cleanroommc.modularui.factory.ItemGuiFactory; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.value.sync.GuiSyncManager; import com.cleanroommc.modularui.value.sync.SyncHandlers; @@ -74,7 +69,8 @@ public class ItemGTToolbelt extends ItemGTTool { private final ItemStack orestack; public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { - super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), + super(domain, id, -1, + new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), null, false, new HashSet<>(), "", new ArrayList<>(), markerItem); this.orestack = new ItemStack(this, 1, GTValues.W); @@ -111,8 +107,8 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) int finalI = i; slotGroupWidget.child(new ItemSlot() .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group) - .changeListener((newItem, onlyAmountChanged, client, init) -> - handler.onContentsChanged(finalI))) + .changeListener( + (newItem, onlyAmountChanged, client, init) -> handler.onContentsChanged(finalI))) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); @@ -384,7 +380,7 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } - //TODO BEWLR for dynamic display of selected item? + // TODO BEWLR for dynamic display of selected item? protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { diff --git a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java index 4ac8c24436f..a9f0dd6c97a 100644 --- a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java +++ b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java @@ -1,10 +1,10 @@ package gregtech.api.mui.sync; -import com.cleanroommc.modularui.value.sync.ValueSyncHandler; - import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; +import com.cleanroommc.modularui.value.sync.ValueSyncHandler; + import java.io.IOException; import java.util.Objects; import java.util.function.Consumer; diff --git a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java index bc098cfea86..0697f47ec6f 100644 --- a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java +++ b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java @@ -1,7 +1,5 @@ package gregtech.common.items.tool; -import com.cleanroommc.modularui.factory.ItemGuiFactory; - import gregtech.api.items.toolitem.behavior.IToolBehavior; import net.minecraft.entity.player.EntityPlayer; @@ -12,6 +10,7 @@ import net.minecraft.util.EnumHand; import net.minecraft.world.World; +import com.cleanroommc.modularui.factory.ItemGuiFactory; import org.jetbrains.annotations.NotNull; public class OpenGUIBehavior implements IToolBehavior { From b319b281ea8a33de5c0fc303dce13ba304bc1038 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 17:07:36 -0600 Subject: [PATCH 16/82] improve a fallback --- src/main/java/gregtech/api/items/toolitem/IGTTool.java | 4 ++++ .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 5 ----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 649c1e894e6..9e10e9b0c7e 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -910,6 +910,10 @@ default ModelResourceLocation getModelLocation() { // Sound Playing default void playCraftingSound(EntityPlayer player, ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } // player null check for things like auto-crafters if (ConfigHolder.client.toolCraftingSounds && getSound() != null && player != null) { if (canPlaySound(stack)) { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 78fab137b2e..744925c811a 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -328,11 +328,6 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { return true; } - @Override - public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { - return stack.copy(); - } - public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, @Nullable EntityPlayer entityPlayer) { return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); From 6488ebbb848c280a682d76c6fad687ab6aaff174 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 18:25:26 -0600 Subject: [PATCH 17/82] I'm dyeing --- .../java/gregtech/api/items/IDyeableItem.java | 62 ++++++++ .../api/items/toolitem/ItemGTToolbelt.java | 42 +++++- .../common/crafting/DyeableRecipes.java | 135 ++++++++++++++++++ .../loaders/recipe/GTRecipeManager.java | 3 + .../textures/items/tools/toolbelt_belt.png | Bin 192 -> 159 bytes 5 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 src/main/java/gregtech/api/items/IDyeableItem.java create mode 100644 src/main/java/gregtech/common/crafting/DyeableRecipes.java diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java new file mode 100644 index 00000000000..0497bf30fa0 --- /dev/null +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -0,0 +1,62 @@ +package gregtech.api.items; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Note - users of this interface will have to deal with cauldron dye clearing on their own. + */ +public interface IDyeableItem { + + default boolean hasColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + return nbttagcompound != null && nbttagcompound.hasKey("display", 10) && + nbttagcompound.getCompoundTag("display").hasKey("color", 3); + } + + default int getColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); + if (nbttagcompound1.hasKey("color", 3)) { + return nbttagcompound1.getInteger("color"); + } + } + return getDefaultColor(stack); + } + + default int getDefaultColor(ItemStack stack) { + return 0xFFFFFF; + } + + default void removeColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); + if (nbttagcompound1.hasKey("color")) { + nbttagcompound1.removeTag("color"); + } + } + } + + default void setColor(ItemStack stack, int color) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound == null) { + nbttagcompound = new NBTTagCompound(); + stack.setTagCompound(nbttagcompound); + } + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); + if (!nbttagcompound.hasKey("display", 10)) { + nbttagcompound.setTag("display", nbttagcompound1); + } + nbttagcompound1.setInteger("color", color); + } + + /** + * Controls whether the dyeing recipe simply removes the dyeable item from the crafting grid, + * or calls {@link net.minecraftforge.common.ForgeHooks#getContainerItem(ItemStack)} on it. + */ + default boolean shouldGetContainerItem() { + return true; + } +} diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 744925c811a..64d8c5010d3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.GregTechAPI; +import gregtech.api.items.IDyeableItem; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; @@ -14,6 +15,7 @@ import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; +import net.minecraft.block.BlockCauldron; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; @@ -25,6 +27,7 @@ import net.minecraft.item.ItemTool; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; @@ -62,7 +65,7 @@ import static gregtech.api.items.toolitem.ToolHelper.MATERIAL_KEY; -public class ItemGTToolbelt extends ItemGTTool { +public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); @@ -375,6 +378,43 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } + @Override + public @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (this.hasColor(stack)) { + IBlockState iblockstate = world.getBlockState(pos); + if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { + int water = iblockstate.getValue(BlockCauldron.LEVEL); + if (water > 0) { + this.removeColor(stack); + cauldron.setWaterLevel(world, pos, iblockstate, water - 1); + return EnumActionResult.SUCCESS; + } + } + } + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } + + @Override + public int getColor(ItemStack stack, int tintIndex) { + if (tintIndex == 0) { + return this.getColor(stack); + } + return super.getColor(stack, tintIndex); + } + + @Override + public int getDefaultColor(ItemStack stack) { + return 0xA06540; + } + + @Override + public boolean shouldGetContainerItem() { + return false; + } + // TODO BEWLR for dynamic display of selected item? protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { diff --git a/src/main/java/gregtech/common/crafting/DyeableRecipes.java b/src/main/java/gregtech/common/crafting/DyeableRecipes.java new file mode 100644 index 00000000000..6dd590ce922 --- /dev/null +++ b/src/main/java/gregtech/common/crafting/DyeableRecipes.java @@ -0,0 +1,135 @@ +package gregtech.common.crafting; + +import gregtech.api.items.IDyeableItem; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.RecipesArmorDyes; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; + +import com.google.common.collect.Lists; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public final class DyeableRecipes extends RecipesArmorDyes { + + @ApiStatus.Internal + public DyeableRecipes() { + this.setRegistryName("gt_dyeable_dyeing"); + } + + /** + * Used to check if a recipe matches current crafting inventory + */ + @Override + public boolean matches(InventoryCrafting inv, @NotNull World worldIn) { + ItemStack itemstack = ItemStack.EMPTY; + List list = Lists.newArrayList(); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { + ItemStack itemstack1 = inv.getStackInSlot(i); + + if (!itemstack1.isEmpty()) { + if (itemstack1.getItem() instanceof IDyeableItem) { + if (!itemstack.isEmpty()) { + return false; + } + + itemstack = itemstack1; + } else { + if (!net.minecraftforge.oredict.DyeUtils.isDye(itemstack1)) { + return false; + } + + list.add(itemstack1); + } + } + } + + return !itemstack.isEmpty() && !list.isEmpty(); + } + + /** + * Returns an Item that is the result of this recipe + */ + @Override + public @NotNull ItemStack getCraftingResult(InventoryCrafting inv) { + ItemStack itemstack = ItemStack.EMPTY; + int[] aint = new int[3]; + int i = 0; + int j = 0; + IDyeableItem dyeable = null; + + for (int k = 0; k < inv.getSizeInventory(); ++k) { + ItemStack itemstack1 = inv.getStackInSlot(k); + + if (!itemstack1.isEmpty()) { + if (itemstack1.getItem() instanceof IDyeableItem) { + dyeable = (IDyeableItem) itemstack1.getItem(); + + itemstack = itemstack1.copy(); + itemstack.setCount(1); + + if (dyeable.hasColor(itemstack1)) { + int l = dyeable.getColor(itemstack); + float f = (float) (l >> 16 & 255) / 255.0F; + float f1 = (float) (l >> 8 & 255) / 255.0F; + float f2 = (float) (l & 255) / 255.0F; + i = (int) ((float) i + Math.max(f, Math.max(f1, f2)) * 255.0F); + aint[0] = (int) ((float) aint[0] + f * 255.0F); + aint[1] = (int) ((float) aint[1] + f1 * 255.0F); + aint[2] = (int) ((float) aint[2] + f2 * 255.0F); + ++j; + } + } else { + if (!net.minecraftforge.oredict.DyeUtils.isDye(itemstack1)) { + return ItemStack.EMPTY; + } + + float[] afloat = net.minecraftforge.oredict.DyeUtils.colorFromStack(itemstack1).get() + .getColorComponentValues(); + int l1 = (int) (afloat[0] * 255.0F); + int i2 = (int) (afloat[1] * 255.0F); + int j2 = (int) (afloat[2] * 255.0F); + i += Math.max(l1, Math.max(i2, j2)); + aint[0] += l1; + aint[1] += i2; + aint[2] += j2; + ++j; + } + } + } + + if (dyeable == null) { + return ItemStack.EMPTY; + } else { + int i1 = aint[0] / j; + int j1 = aint[1] / j; + int k1 = aint[2] / j; + float f3 = (float) i / (float) j; + float f4 = (float) Math.max(i1, Math.max(j1, k1)); + i1 = (int) ((float) i1 * f3 / f4); + j1 = (int) ((float) j1 * f3 / f4); + k1 = (int) ((float) k1 * f3 / f4); + int k2 = (i1 << 8) + j1; + k2 = (k2 << 8) + k1; + dyeable.setColor(itemstack, k2); + return itemstack; + } + } + + public NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList nonnulllist = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + + for (int i = 0; i < nonnulllist.size(); ++i) { + ItemStack itemstack = inv.getStackInSlot(i); + if (!(itemstack.getItem() instanceof IDyeableItem item && !item.shouldGetContainerItem())) + nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack)); + } + + return nonnulllist; + } +} diff --git a/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java b/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java index e91a9bd2c7a..2b757b217c1 100644 --- a/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java +++ b/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java @@ -1,11 +1,13 @@ package gregtech.loaders.recipe; import gregtech.api.event.MaterialInfoEvent; +import gregtech.common.crafting.DyeableRecipes; import gregtech.loaders.recipe.handlers.DecompositionRecipeHandler; import gregtech.loaders.recipe.handlers.RecipeHandlerList; import gregtech.loaders.recipe.handlers.ToolRecipeHandler; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.registry.ForgeRegistries; public final class GTRecipeManager { @@ -21,6 +23,7 @@ public static void load() { MetaTileEntityLoader.init(); MetaTileEntityMachineRecipeLoader.init(); RecipeHandlerList.register(); + ForgeRegistries.RECIPES.register(new DyeableRecipes()); } public static void loadLatest() { diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png index b8e9021431ea0046ebe5743d23bac2ec3bfa687a..b703b955e156fcd5574aa175e1e92dbdcfd7ad4f 100644 GIT binary patch delta 130 zcmV-|0Db?!0iOYoBztB_L_t(IjqQ%T5x^h_g`amB#DN&W5$vcPff48!%+@JPg%=8& zG)duCaqxZs4nKjJCo|7C`pcI@1Q7|Mr%6PT&$U*x*02J`7*N&FLPW?pqxbFs>*i(v kNZ3$H2_Kl*R(trG8;uGgMEn)#zW@LL07*qoM6N<$f<$>Ywg3PC delta 164 zcmV;V09*f`0l)!}B!2;OQb$4nuFf3k0001ZNkl$hQm)jFoHGM$_Rj601|*{ znCGeWUqhIi;l|sqU?F6~k=5gLGE5Q7KxD&_(+*L7#+TSe4IO|cBua8507o(^5v=$r SxBvhE07*qoM6N<$f&c(6{6V__ From cd6e017cbd78e4d9d640fc5cf29273961735196c Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 18:36:22 -0600 Subject: [PATCH 18/82] improve passthrough --- .../java/gregtech/client/utils/ToolChargeBarRenderer.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java index de982d07450..345255d627b 100644 --- a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java +++ b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java @@ -5,6 +5,7 @@ import gregtech.api.items.metaitem.MetaItem; import gregtech.api.items.metaitem.stats.IItemDurabilityManager; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.util.GTUtility; @@ -113,6 +114,13 @@ private static void overpaintVanillaRenderBug(BufferBuilder worldrenderer, int x } public static void renderBarsTool(IGTTool tool, ItemStack stack, int xPosition, int yPosition) { + if (tool instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null && selected.getItem() instanceof IGTTool toool) { + tool = toool; + stack = selected; + } + } boolean renderedDurability = false; NBTTagCompound tag = GTUtility.getOrCreateNbtCompound(stack); if (!tag.getBoolean(ToolHelper.UNBREAKABLE_KEY)) { From bd2bf01c746f0159825b755585a0708f59919038 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 20:27:08 -0600 Subject: [PATCH 19/82] More universal solution to toolbelt crafting --- .../crafting/IToolbeltSupportingRecipe.java | 43 -------------- .../api/items/toolitem/ItemGTToolbelt.java | 23 ++++++-- .../java/gregtech/api/recipes/ModHandler.java | 2 +- .../gregtech/asm/GregTechTransformer.java | 6 ++ .../asm/hooks/OreIngredientHooks.java | 25 +++++++++ .../asm/visitors/OreIngredientVisitor.java | 52 +++++++++++++++++ .../common/crafting/FluidReplaceRecipe.java | 4 +- .../common/crafting/GTShapedOreRecipe.java | 56 +++---------------- .../common/crafting/GTShapelessOreRecipe.java | 43 ++------------ 9 files changed, 114 insertions(+), 140 deletions(-) delete mode 100644 src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java create mode 100644 src/main/java/gregtech/asm/hooks/OreIngredientHooks.java create mode 100644 src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java deleted file mode 100644 index c4d050e2082..00000000000 --- a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java +++ /dev/null @@ -1,43 +0,0 @@ -package gregtech.api.crafting; - -import gregtech.api.items.toolitem.ItemGTToolbelt; - -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.item.crafting.Ingredient; -import net.minecraft.util.NonNullList; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.common.util.RecipeMatcher; - -import org.jetbrains.annotations.NotNull; - -public interface IToolbeltSupportingRecipe extends IRecipe { - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) - return toolbelt.supportsIngredient(stack, ingredient); - else return ingredient.apply(stack); - } - - @Override - default @NotNull NonNullList getRemainingItems(InventoryCrafting inv) { - NonNullList ret = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); - for (int i = 0; i < ret.size(); i++) { - ret.set(i, inv.getStackInSlot(i)); - } - int[] matches = RecipeMatcher.findMatches(ret, this.getIngredients()); - if (matches != null) { - for (int i = 0; i < ret.size(); i++) { - ItemStack stack = ret.get(i); - Ingredient ingredient = this.getIngredients().get(matches[i]); - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - toolbelt.craftDamageTools(stack, ingredient); - } - ret.set(i, ForgeHooks.getContainerItem(stack)); - } - } else ret.replaceAll(ForgeHooks::getContainerItem); - return ret; - } -} diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 64d8c5010d3..e4c20381a25 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -69,14 +69,11 @@ public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); - private final ItemStack orestack; - public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), - null, false, new HashSet<>(), "", new ArrayList<>(), + null, false, new HashSet<>(), "toolbelt", new ArrayList<>(), markerItem); - this.orestack = new ItemStack(this, 1, GTValues.W); } public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { @@ -127,7 +124,6 @@ public static boolean isToolbeltableOredict(String oredict) { public void registerValidOredict(String oredict) { VALID_OREDICTS.add(oredict); - OreDictUnifier.registerOre(this.orestack, oredict); } @Override @@ -331,6 +327,21 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { return true; } + @Override + public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { + Ingredient nextCraftIngredient = getHandler(stack).nextCraftIngredient; + if (nextCraftIngredient != null) { + stack = stack.copy(); + this.craftDamageTools(stack, nextCraftIngredient); + return stack; + } + return super.getContainerItem(stack); + } + + public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { + getHandler(stack).nextCraftIngredient = ingredient; + } + public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, @Nullable EntityPlayer entityPlayer) { return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); @@ -470,6 +481,8 @@ protected ToolStackHandler getHandler(int minsize) { protected static class ToolStackHandler extends ItemStackHandler { + private Ingredient nextCraftIngredient; + private static final Set EMPTY = ImmutableSet.of(); private @Nullable Integer selectedSlot = null; diff --git a/src/main/java/gregtech/api/recipes/ModHandler.java b/src/main/java/gregtech/api/recipes/ModHandler.java index a96b1d9077e..1a01a2bbb39 100644 --- a/src/main/java/gregtech/api/recipes/ModHandler.java +++ b/src/main/java/gregtech/api/recipes/ModHandler.java @@ -317,7 +317,7 @@ private static boolean validateRecipeWithOutput(@NotNull String regName, @NotNul private static void addRecipe(@NotNull String regName, @NotNull ItemStack result, boolean isNBTClearing, boolean isMirrored, @NotNull Object... recipe) { - IRecipe shapedOreRecipe = GTShapedOreRecipe.create(isNBTClearing, null, result.copy(), + IRecipe shapedOreRecipe = new GTShapedOreRecipe(isNBTClearing, null, result.copy(), finalizeShapedRecipeInput(recipe)) .setMirrored(isMirrored) .setRegistryName(regName); diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index 5f9d5e1ba3f..1509098bcb1 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -196,6 +196,12 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) 0); return classWriter.toByteArray(); } + case OreIngredientVisitor.TARGET_CLASS_NAME: { + ClassReader classReader = new ClassReader(basicClass); + ClassWriter classWriter = new ClassWriter(0); + classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, OreIngredientVisitor::new), 0); + return classWriter.toByteArray(); + } } if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { ObfMapping methodMapping = EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.get(internalName); diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java new file mode 100644 index 00000000000..53e6f3dd1cd --- /dev/null +++ b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java @@ -0,0 +1,25 @@ +package gregtech.asm.hooks; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.oredict.OreIngredient; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@SuppressWarnings("unused") +public class OreIngredientHooks { + + public static boolean checkToolbelt(@Nullable ItemStack input, @NotNull OreIngredient ingredient) { + if (input.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.supportsIngredient(input, ingredient)) { + toolbelt.setOnCraftIngredient(input, ingredient); + return true; + } + } + return false; + } +} diff --git a/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java b/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java new file mode 100644 index 00000000000..8a51c12e3e6 --- /dev/null +++ b/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java @@ -0,0 +1,52 @@ +package gregtech.asm.visitors; + +import gregtech.asm.util.ObfMapping; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +public class OreIngredientVisitor extends MethodVisitor implements Opcodes { + + public static final String TARGET_CLASS_NAME = "net/minecraftforge/oredict/OreIngredient"; + public static final ObfMapping TARGET_METHOD = new ObfMapping(TARGET_CLASS_NAME, "apply", + targetSignature()); + + private static final String OWNER = "gregtech/asm/hooks/OreIngredientHooks"; + private static final String SIGNATURE = signature(); + private static final String METHOD_NAME = "checkToolbelt"; + + public OreIngredientVisitor(MethodVisitor mv) { + super(ASM5, mv); + } + + @Override + public void visitCode() { + mv.visitVarInsn(ALOAD, 1); // ItemStack + mv.visitVarInsn(ALOAD, 0); // OreIngredient + mv.visitMethodInsn(INVOKESTATIC, OWNER, METHOD_NAME, SIGNATURE, false); + Label L1 = new Label(); + mv.visitJumpInsn(IFEQ, L1); + mv.visitInsn(ICONST_1); + mv.visitInsn(IRETURN); + mv.visitLabel(L1); + mv.visitFrame(F_SAME, 0, null, 0, null); + + mv.visitCode(); + } + + // public boolean apply(@Nullable ItemStack input) + private static String targetSignature() { + return "(" + + "Lnet/minecraft/item/ItemStack;" + // ItemStack + ")Z;"; // return boolean + } + + // public static boolean extendedApply(@Nullable ItemStack input, @NotNull OreIngredient ingredient) + private static String signature() { + return "(" + + "Lnet/minecraft/item/ItemStack;" + // ItemStack + "Lnet/minecraftforge/oredict/OreIngredient;" + // OreIngredient + ")Z"; // return boolean + } +} diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index 5cfd1571d47..03c030c4be3 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -24,9 +24,7 @@ public class FluidReplaceRecipe extends GTShapedOreRecipe { public FluidReplaceRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { - super(new AtomicBoolean(false), isClearing, group, result, recipe); - // there is no possible way that we require toolbelt handling, but make sure it isn't enabled. - this.toolbeltHandling = false; + super(isClearing, group, result, recipe); } @NotNull diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 3cf67667b5d..5ff52869452 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -1,6 +1,5 @@ package gregtech.common.crafting; -import gregtech.api.crafting.IToolbeltSupportingRecipe; import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.util.GTLog; import gregtech.api.util.GTStringUtils; @@ -34,35 +33,21 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSupportingRecipe { +public class GTShapedOreRecipe extends ShapedOreRecipe { boolean isClearing; - boolean toolbeltHandling; public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); - protected GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, - @NotNull ItemStack result, Object... recipe) { - super(group, result, parseShaped(toolbeltHandling, isClearing, recipe)); + public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { + super(group, result, parseShaped(isClearing, recipe)); this.isClearing = isClearing; } - public static GTShapedOreRecipe create(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, - Object... recipe) { - AtomicBoolean toolbeltHandling = new AtomicBoolean(false); - GTShapedOreRecipe out = new GTShapedOreRecipe(toolbeltHandling, isClearing, group, result, recipe); - return out.setToolbeltHandling(toolbeltHandling.get()); - } - - private GTShapedOreRecipe setToolbeltHandling(boolean toolbeltHandling) { - this.toolbeltHandling = toolbeltHandling; - return this; - } - // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. // the only difference is calling getIngredient of this class. - public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHandling, boolean isClearing, + public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); @@ -106,7 +91,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHand for (; idx < recipe.length; idx += 2) { Character chr = (Character) recipe[idx]; Object in = recipe[idx + 1]; - Ingredient ing = getIngredient(toolbeltHandling, isClearing, in); + Ingredient ing = getIngredient(isClearing, in); if (' ' == chr) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); @@ -144,7 +129,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHand return ret; } - protected static Ingredient getIngredient(AtomicBoolean toolbeltHandling, boolean isClearing, Object obj) { + protected static Ingredient getIngredient(boolean isClearing, Object obj) { if (obj instanceof Ingredient ing) return ing; else if (obj instanceof ItemStack stk) { if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { @@ -171,8 +156,6 @@ else if (obj instanceof ItemStack stk) { else if (obj instanceof Block blk) return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); else if (obj instanceof String str) { - if (ItemGTToolbelt.isToolbeltableOredict(str)) - toolbeltHandling.set(true); return new OreIngredient(str); } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); @@ -180,37 +163,12 @@ else if (obj instanceof String str) { return null; } - @Override - protected boolean checkMatch(@NotNull InventoryCrafting inv, int startX, int startY, boolean mirror) { - if (this.toolbeltHandling) { - for (int x = 0; x < inv.getWidth(); x++) { - for (int y = 0; y < inv.getHeight(); y++) { - int subX = x - startX; - int subY = y - startY; - Ingredient target = Ingredient.EMPTY; - - if (subX >= 0 && subY >= 0 && subX < width && subY < height) { - if (mirror) { - target = input.get(width - subX - 1 + subY * width); - } else { - target = input.get(subX + subY * width); - } - } - - if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(target, inv.getStackInRowAndColumn(x, y))) - return false; - } - } - return true; - } else return super.checkMatch(inv, startX, startY, mirror); - } - @Override public @NotNull NonNullList getRemainingItems(@NotNull InventoryCrafting inv) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return IToolbeltSupportingRecipe.super.getRemainingItems(inv); + return net.minecraftforge.common.ForgeHooks.defaultRecipeGetRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index fb620ea9927..cd47529fc66 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,13 +1,12 @@ package gregtech.common.crafting; -import gregtech.api.crafting.IToolbeltSupportingRecipe; - import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; @@ -17,18 +16,16 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbeltSupportingRecipe { +public class GTShapelessOreRecipe extends ShapelessOreRecipe { boolean isClearing; - boolean toolbeltHandling; public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); this.isClearing = isClearing; - AtomicBoolean needsToolbelt = new AtomicBoolean(false); for (Object in : recipe) { - Ingredient ing = GTShapedOreRecipe.getIngredient(needsToolbelt, isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -41,38 +38,6 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull throw new RuntimeException(ret.toString()); } } - this.toolbeltHandling = needsToolbelt.get(); - } - - @Override - public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { - if (this.toolbeltHandling) { - // I can't wrap my head around the 'simple' shapeless logic, so no simple toolbelt handling. - int ingredientCount = 0; - List items = Lists.newArrayList(); - - for (int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack itemstack = inv.getStackInSlot(i); - if (!itemstack.isEmpty()) { - ++ingredientCount; - items.add(itemstack); - } - } - - if (ingredientCount != this.input.size()) - return false; - - int[] matches = RecipeMatcher.findMatches(items, this.input); - if (matches != null) { - for (int i = 0; i < items.size(); i++) { - ItemStack stack = items.get(i); - Ingredient ingredient = this.input.get(matches[i]); - if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(ingredient, stack)) return false; - } - return true; - } else return false; - - } else return super.matches(inv, world); } @Override @@ -80,7 +45,7 @@ public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return IToolbeltSupportingRecipe.super.getRemainingItems(inv); + return ForgeHooks.defaultRecipeGetRemainingItems(inv); } } } From a2d6f0c88b78d399424eac0ad3f76b4f579469e3 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 20:33:22 -0600 Subject: [PATCH 20/82] sp4tless --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 2 -- src/main/java/gregtech/api/recipes/ModHandler.java | 4 ++-- src/main/java/gregtech/asm/GregTechTransformer.java | 3 ++- src/main/java/gregtech/asm/hooks/OreIngredientHooks.java | 2 -- .../java/gregtech/common/crafting/FluidReplaceRecipe.java | 2 -- .../java/gregtech/common/crafting/GTShapedOreRecipe.java | 2 -- .../java/gregtech/common/crafting/GTShapelessOreRecipe.java | 6 ------ 7 files changed, 4 insertions(+), 17 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index e4c20381a25..5e747465fc3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,13 +1,11 @@ package gregtech.api.items.toolitem; -import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.items.IDyeableItem; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; -import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Material; import gregtech.api.unification.material.Materials; import gregtech.api.unification.material.properties.PropertyKey; diff --git a/src/main/java/gregtech/api/recipes/ModHandler.java b/src/main/java/gregtech/api/recipes/ModHandler.java index 1a01a2bbb39..10e55ea68b1 100644 --- a/src/main/java/gregtech/api/recipes/ModHandler.java +++ b/src/main/java/gregtech/api/recipes/ModHandler.java @@ -319,8 +319,8 @@ private static void addRecipe(@NotNull String regName, @NotNull ItemStack result boolean isMirrored, @NotNull Object... recipe) { IRecipe shapedOreRecipe = new GTShapedOreRecipe(isNBTClearing, null, result.copy(), finalizeShapedRecipeInput(recipe)) - .setMirrored(isMirrored) - .setRegistryName(regName); + .setMirrored(isMirrored) + .setRegistryName(regName); registerRecipe(shapedOreRecipe); } diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index 1509098bcb1..8263564746a 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -199,7 +199,8 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) case OreIngredientVisitor.TARGET_CLASS_NAME: { ClassReader classReader = new ClassReader(basicClass); ClassWriter classWriter = new ClassWriter(0); - classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, OreIngredientVisitor::new), 0); + classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, + OreIngredientVisitor::new), 0); return classWriter.toByteArray(); } } diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java index 53e6f3dd1cd..cc0a13fd4f0 100644 --- a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java +++ b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java @@ -2,9 +2,7 @@ import gregtech.api.items.toolitem.ItemGTToolbelt; - import net.minecraft.item.ItemStack; - import net.minecraftforge.oredict.OreIngredient; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index 03c030c4be3..f3addd44339 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -16,8 +16,6 @@ import org.jetbrains.annotations.NotNull; -import java.util.concurrent.atomic.AtomicBoolean; - /** * A recipe which inputs a single Fluid Container, and outputs the same Fluid Container with a new contained Fluid */ diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 5ff52869452..24940f8dae0 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -1,6 +1,5 @@ package gregtech.common.crafting; -import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.util.GTLog; import gregtech.api.util.GTStringUtils; @@ -31,7 +30,6 @@ import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; public class GTShapedOreRecipe extends ShapedOreRecipe { diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index cd47529fc66..bc062c7c15b 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -5,17 +5,11 @@ import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; -import com.google.common.collect.Lists; import org.jetbrains.annotations.NotNull; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - public class GTShapelessOreRecipe extends ShapelessOreRecipe { boolean isClearing; From d88e65812162e5c7141a5793cf1a2574edea1fa0 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Sat, 15 Jun 2024 14:40:08 -0600 Subject: [PATCH 21/82] Dynamic toolbelt render --- .../api/items/toolitem/ItemGTToolbelt.java | 2 - .../java/gregtech/client/ClientProxy.java | 10 +++ .../renderer/handler/ToolbeltRenderer.java | 60 ++++++++++++++++++ .../java/gregtech/common/items/MetaItems.java | 2 - .../java/gregtech/common/items/ToolItems.java | 11 ++++ .../textures/items/tools/toolbelt_belt.png | Bin 159 -> 160 bytes .../textures/items/tools/toolbelt_loops.png | Bin 177 -> 152 bytes 7 files changed, 81 insertions(+), 4 deletions(-) create mode 100644 src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 5e747465fc3..c6d7be7521e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -424,8 +424,6 @@ public boolean shouldGetContainerItem() { return false; } - // TODO BEWLR for dynamic display of selected item? - protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 571f617d849..3638204bfc2 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -10,6 +10,7 @@ import gregtech.api.unification.material.Materials; import gregtech.api.unification.stack.UnificationEntry; import gregtech.api.util.FluidTooltipUtil; +import gregtech.api.util.GTLog; import gregtech.api.util.IBlockOre; import gregtech.api.util.Mods; import gregtech.client.model.customtexture.CustomTextureModelHandler; @@ -50,6 +51,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.common.MinecraftForge; @@ -129,6 +131,14 @@ public static void registerModels(ModelRegistryEvent event) { ToolItems.registerModels(); } + @SubscribeEvent + @SideOnly(Side.CLIENT) + public static void registerBakedModels(ModelBakeEvent event) { + GTLog.logger.info("Registering special item models"); + MetaItems.registerBakedModels(event); + ToolItems.registerBakedModels(event); + } + @SubscribeEvent public static void addMaterialFormulaHandler(@NotNull ItemTooltipEvent event) { ItemStack itemStack = event.getItemStack(); diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java new file mode 100644 index 00000000000..0c67425daa1 --- /dev/null +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -0,0 +1,60 @@ +package gregtech.client.renderer.handler; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderItem; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.model.IModelState; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import codechicken.lib.render.item.IItemRenderer; +import codechicken.lib.util.TransformUtils; + +@SideOnly(Side.CLIENT) +public class ToolbeltRenderer implements IItemRenderer { + + private final IBakedModel toolbeltModel; + + public ToolbeltRenderer(IBakedModel toolbeltModel) { + this.toolbeltModel = toolbeltModel; + } + + @Override + public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType transformType) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + GlStateManager.pushMatrix(); + GlStateManager.translate(0.5F, 0.5F, 0.5F); + + RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); + + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) { + IBakedModel selectedModel = renderItem.getItemModelWithOverrides(selected, null, null); + renderItem.renderItem(selected, selectedModel); + } + renderItem.renderItem(stack, toolbeltModel); + + GlStateManager.popMatrix(); + } + } + + @Override + public IModelState getTransforms() { + return TransformUtils.DEFAULT_ITEM; + } + + @Override + public boolean isAmbientOcclusion() { + return false; + } + + @Override + public boolean isGui3d() { + return false; + } +} diff --git a/src/main/java/gregtech/common/items/MetaItems.java b/src/main/java/gregtech/common/items/MetaItems.java index 303588e6dc8..eaa75bc932f 100644 --- a/src/main/java/gregtech/common/items/MetaItems.java +++ b/src/main/java/gregtech/common/items/MetaItems.java @@ -19,7 +19,6 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -653,7 +652,6 @@ public static void registerColors() { } } - @SubscribeEvent @SideOnly(Side.CLIENT) public static void registerBakedModels(ModelBakeEvent event) { GTLog.logger.info("Registering special item models"); diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 5796d85c25c..561cd094a74 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -4,17 +4,22 @@ import gregtech.api.items.toolitem.*; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; +import gregtech.client.renderer.handler.ToolbeltRenderer; import gregtech.common.items.tool.*; import gregtech.core.sound.GTSoundEvents; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.entity.monster.EntityGolem; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.init.Enchantments; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; +import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import org.jetbrains.annotations.NotNull; @@ -372,6 +377,12 @@ public static void registerModels() { TOOLS.forEach(tool -> ModelLoader.setCustomModelResourceLocation(tool.get(), 0, tool.getModelLocation())); } + @SideOnly(Side.CLIENT) + public static void registerBakedModels(ModelBakeEvent event) { + ModelResourceLocation loc = TOOLBELT.getModelLocation(); + event.getModelRegistry().putObject(loc, new ToolbeltRenderer(event.getModelRegistry().getObject(loc))); + } + public static void registerColors() { TOOLS.forEach( tool -> Minecraft.getMinecraft().getItemColors().registerItemColorHandler(tool::getColor, tool.get())); diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png index b703b955e156fcd5574aa175e1e92dbdcfd7ad4f..0918698052fc7f743017c08284f0fa77cea43cae 100644 GIT binary patch delta 131 zcmV-}0DS+S0iXepBz$K{L_t(IjqQ%T4FDksg`dd{;y{ex2zJztzzB2*i(v kNZ3$H2_Kl*R(trG8;uGgMEn)#zW@LL07*qoM6N<$f;2fdmH+?% diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png index c351831679459d2785e6da182d3aa7cd938d66e3..6944f44d2ae17c028bfbf4056ff951ecbf118ea0 100644 GIT binary patch delta 123 zcmV->0EGXs0hj@hBy?X%L_t(IjbmUK1)~5BG&D5)Z)j-vPl`Mfx*{VZBZl Date: Sat, 15 Jun 2024 15:02:07 -0600 Subject: [PATCH 22/82] Fix excessive passthrough and toolbelt render and improve IDyeableItem --- .../java/gregtech/api/items/IDyeableItem.java | 31 ++++++++++++-- .../api/items/toolitem/ItemGTToolbelt.java | 40 +++++++++++-------- .../renderer/handler/ToolbeltRenderer.java | 2 +- 3 files changed, 53 insertions(+), 20 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index 0497bf30fa0..bcd2cc1f3e7 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -1,11 +1,18 @@ package gregtech.api.items; +import net.minecraft.block.BlockCauldron; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; -/** - * Note - users of this interface will have to deal with cauldron dye clearing on their own. - */ public interface IDyeableItem { default boolean hasColor(ItemStack stack) { @@ -52,6 +59,24 @@ default void setColor(ItemStack stack, int color) { nbttagcompound1.setInteger("color", color); } + default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (this.hasColor(stack)) { + IBlockState iblockstate = world.getBlockState(pos); + if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { + int water = iblockstate.getValue(BlockCauldron.LEVEL); + if (water > 0) { + this.removeColor(stack); + cauldron.setWaterLevel(world, pos, iblockstate, water - 1); + return EnumActionResult.SUCCESS; + } + } + } + return EnumActionResult.PASS; + } + /** * Controls whether the dyeing recipe simply removes the dyeable item from the crafting grid, * or calls {@link net.minecraftforge.common.ForgeHooks#getContainerItem(ItemStack)} on it. diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index c6d7be7521e..e85ccf55ee3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -383,27 +383,21 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { if (tool != null) { selectedToolDisplay = " (" + tool.getDisplayName() + ")"; } - return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), + getHandler(stack).disablePassthrough(); + String name = LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); + getHandler(stack).enablePassthrough(); + return name; } @Override public @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { - ItemStack stack = player.getHeldItem(hand); - if (this.hasColor(stack)) { - IBlockState iblockstate = world.getBlockState(pos); - if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { - int water = iblockstate.getValue(BlockCauldron.LEVEL); - if (water > 0) { - this.removeColor(stack); - cauldron.setWaterLevel(world, pos, iblockstate, water - 1); - return EnumActionResult.SUCCESS; - } - } - } - return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + EnumActionResult result = IDyeableItem.super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + if (result == EnumActionResult.PASS) + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + else return result; } @Override @@ -411,7 +405,10 @@ public int getColor(ItemStack stack, int tintIndex) { if (tintIndex == 0) { return this.getColor(stack); } - return super.getColor(stack, tintIndex); + getHandler(stack).disablePassthrough(); + int color = super.getColor(stack, tintIndex); + getHandler(stack).enablePassthrough(); + return color; } @Override @@ -488,6 +485,8 @@ protected static class ToolStackHandler extends ItemStackHandler { protected final Set toolClasses = new ObjectOpenHashSet<>(); public final Set oreDicts = new ObjectOpenHashSet<>(); + private boolean passthrough = true; + public ToolStackHandler(int size) { super(size); } @@ -511,7 +510,16 @@ public void decrementSelectedSlot() { } public @Nullable Integer getSelectedSlot() { - return selectedSlot; + if (passthrough) return selectedSlot; + else return null; + } + + public void enablePassthrough() { + this.passthrough = true; + } + + public void disablePassthrough() { + this.passthrough = false; } public @Nullable ItemStack getSelectedStack() { diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java index 0c67425daa1..cdc7d54dc0f 100644 --- a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -45,7 +45,7 @@ public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType trans @Override public IModelState getTransforms() { - return TransformUtils.DEFAULT_ITEM; + return TransformUtils.DEFAULT_TOOL; } @Override From 01587269f1d413280d364f6b90b1e6eda5a933e8 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Sat, 15 Jun 2024 15:02:51 -0600 Subject: [PATCH 23/82] Sp4tless --- src/main/java/gregtech/api/items/IDyeableItem.java | 4 ++-- src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index bcd2cc1f3e7..a79c3716749 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -60,8 +60,8 @@ default void setColor(ItemStack stack, int color) { } default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, - float hitY, float hitZ, @NotNull EnumHand hand) { + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); if (this.hasColor(stack)) { IBlockState iblockstate = world.getBlockState(pos); diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index e85ccf55ee3..3d7210d522e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -13,7 +13,6 @@ import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; -import net.minecraft.block.BlockCauldron; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; From f783a337f1dba8e869360b9c44d96370b3fcc5ec Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 18:18:43 -0600 Subject: [PATCH 24/82] Pain --- .../crafting/IToolbeltSupportingRecipe.java | 45 +++ .../api/items/toolitem/ItemGTToolbelt.java | 320 ++++++++++++++++++ .../java/gregtech/client/ClientProxy.java | 23 ++ .../common/crafting/FluidReplaceRecipe.java | 2 + .../common/crafting/GTShapedOreRecipe.java | 68 +++- .../common/crafting/GTShapelessOreRecipe.java | 93 +++-- .../java/gregtech/common/items/ToolItems.java | 9 +- src/main/java/gregtech/core/CoreModule.java | 2 + .../PacketToolbeltSelectionChange.java | 41 +++ .../resources/assets/gregtech/lang/en_us.lang | 2 + 10 files changed, 535 insertions(+), 70 deletions(-) create mode 100644 src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java create mode 100644 src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java create mode 100644 src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java new file mode 100644 index 00000000000..82e161fb167 --- /dev/null +++ b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java @@ -0,0 +1,45 @@ +package gregtech.api.crafting; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.util.NonNullList; +import net.minecraftforge.common.ForgeHooks; +import net.minecraftforge.common.util.RecipeMatcher; + +import org.jetbrains.annotations.NotNull; + +public interface IToolbeltSupportingRecipe extends IRecipe { + + ThreadLocal initNeedsToolbeltHandlingHelper = new ThreadLocal<>(); + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) + return toolbelt.supportsIngredient(stack, ingredient); + else return ingredient.apply(stack); + } + + @Override + default @NotNull NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList ret = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + for (int i = 0; i < ret.size(); i++) { + ret.set(i, inv.getStackInSlot(i)); + } + int[] matches = RecipeMatcher.findMatches(ret, this.getIngredients()); + if (matches != null) { + for (int i = 0; i < ret.size(); i++) { + ItemStack stack = ret.get(i); + Ingredient ingredient = this.getIngredients().get(matches[i]); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + toolbelt.damageTools(stack, ingredient); + } + ret.set(i, ForgeHooks.getContainerItem(stack)); + } + } else ret.replaceAll(ForgeHooks::getContainerItem); + return ret; + } +} diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java new file mode 100644 index 00000000000..416bb5f4ced --- /dev/null +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -0,0 +1,320 @@ +package gregtech.api.items.toolitem; + +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; + +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.SlotGroupWidget; + +import gregtech.api.GTValues; +import gregtech.api.GregTechAPI; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; +import gregtech.api.unification.OreDictUnifier; + +import gregtech.api.util.LocalizationUtils; + +import gregtech.core.network.packets.PacketToolbeltSelectionChange; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; + +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.common.capabilities.ICapabilityProvider; +import net.minecraftforge.common.util.INBTSerializable; +import net.minecraftforge.event.ForgeEventFactory; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.items.ItemStackHandler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; + +public class ItemGTToolbelt extends ItemGTTool { + + protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); + + private final ItemStack orestack; + + public ItemGTToolbelt(String domain, String id, Supplier markerItem) { + super(domain, id, -1, new ToolDefinitionBuilder().cannotAttack().attackSpeed(-2.4F).build(), null, + false, new HashSet<>(), "", new ArrayList<>(), + markerItem); + this.orestack = new ItemStack(this, 1, GTValues.W); + } + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + if (player.isSneaking()) { + if (!world.isRemote) { + ItemGuiFactory.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } else return definition$onItemRightClick(world, player, hand); + } + + @Override + public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { + ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 192); + + ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); + + SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); + slotGroupWidget.flex() + .coverChildren() + .startDefaultMode() + .leftRel(0.5f); + slotGroupWidget.flex().top(7); + slotGroupWidget.flex().endDefaultMode(); + slotGroupWidget.debugName("toolbelt_inventory"); + String key = "toolbelt"; + for (int i = 0; i < 27; i++) { + slotGroupWidget.child(new ItemSlot() + .slot(SyncHandlers.itemSlot(handler, i)) + .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) + .pos(i % 9 * 18, i / 9 * 18) + .debugName("slot_" + i)); + } + panel.child(slotGroupWidget); + + return panel.bindPlayerInventory(); + } + + public static boolean isToolbeltableOredict(String oredict) { + return VALID_OREDICTS.contains(oredict); + } + + public void registerValidOredict(String oredict) { + VALID_OREDICTS.add(oredict); + OreDictUnifier.registerOre(this.orestack, oredict); + } + + @Override + public int getMaxDamage(@NotNull ItemStack stack) { + return -1; + } + + @Override + public @NotNull Set getToolClasses(@NotNull ItemStack stack) { + return getHandler(stack).toolClasses; + } + + @Override + public boolean hasContainerItem(@NotNull ItemStack stack) { + return true; + } + + @Override + public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { + return stack.copy(); + } + + public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { + return getHandler(stack).checkIngredientAgainstTools(ingredient, false); + } + + public void damageTools(ItemStack stack, Ingredient ingredient) { + getHandler(stack).checkIngredientAgainstTools(ingredient, true); + } + + private ToolStackHandler getHandler(ItemStack stack) { + return (ToolStackHandler) stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); + } + + @Override + public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagCompound nbt) { + return new ToolbeltCapabilityProvider(); + } + + public void changeSelectedTool(int direction, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (direction > 0) handler.incrementSelectedSlot(); + else handler.decrementSelectedSlot(); + GregTechAPI.networkHandler.sendToServer( + new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); + } + + public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (slot == null || slot < 0 || slot >= handler.getSlots()) handler.selectedSlot = null; + else handler.selectedSlot = slot; + } + + @Override + public @NotNull String getItemStackDisplayName(@NotNull ItemStack stack) { + ItemStack tool = getHandler(stack).getSelectedStack(); + String selectedToolDisplay = ""; + if (tool != null) { + selectedToolDisplay = " (" + tool.getDisplayName() + ")"; + } + return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); + } + + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + + + private final ToolStackHandler handler = new ToolStackHandler(); + + @Override + public boolean hasCapability(@NotNull Capability capability, EnumFacing facing) { + return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY; + } + + @SuppressWarnings("unchecked") + @Override + public T getCapability(@NotNull Capability capability, EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) handler; + else return null; + } + + @Override + public NBTTagCompound serializeNBT() { + return this.handler.serializeNBT(); + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + this.handler.deserializeNBT(nbt); + } + } + + protected static class ToolStackHandler extends ItemStackHandler { + + private @Nullable Integer selectedSlot = null; + + protected final ItemTool[] tools = new ItemTool[this.getSlots()]; + protected final IGTTool[] gtTools = new IGTTool[this.getSlots()]; + protected final Set toolClasses = new ObjectOpenHashSet<>(); + public final Set oreDicts = new ObjectOpenHashSet<>(); + + public ToolStackHandler() { + super(27); + } + + public void incrementSelectedSlot() { + for (int slot = (this.selectedSlot == null ? -1 : this.selectedSlot) + 1; slot != this.getSlots(); slot++) { + if (this.getStackInSlot(slot).isEmpty()) continue; + this.selectedSlot = slot; + return; + } + this.selectedSlot = null; + } + + public void decrementSelectedSlot() { + for (int slot = (this.selectedSlot == null ? this.getSlots() : this.selectedSlot) - 1; slot != -1; slot--) { + if (this.getStackInSlot(slot).isEmpty()) continue; + this.selectedSlot = slot; + return; + } + this.selectedSlot = null; + } + + public @Nullable Integer getSelectedSlot() { + return selectedSlot; + } + + public ItemStack getSelectedStack() { + if (getSelectedSlot() == null) return null; + else return this.stacks.get(getSelectedSlot()); + } + + @Override + public boolean isItemValid(int slot, @NotNull ItemStack stack) { + return stack.getItem() instanceof ItemTool || stack.getItem() instanceof IGTTool; + } + + @Override + protected void onContentsChanged(int slot) { + this.updateSlot(slot); + this.update(); + + super.onContentsChanged(slot); + } + + @Override + public NBTTagCompound serializeNBT() { + NBTTagCompound tag = super.serializeNBT(); + if (this.selectedSlot != null) tag.setByte("SelectedSlot", this.selectedSlot.byteValue()); + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound nbt) { + super.deserializeNBT(nbt); + if (nbt.hasKey("SelectedSlot")) this.selectedSlot = (int) nbt.getByte("SelectedSlot"); + } + + @Override + protected void onLoad() { + super.onLoad(); + for (int i = 0; i < this.getSlots(); i++) { + this.updateSlot(i); + } + this.update(); + } + + protected void updateSlot(int slot) { + Item item = this.getStackInSlot(slot).getItem(); + if (item instanceof ItemTool tool) { + tools[slot] = tool; + } else { + tools[slot] = null; + } + if (item instanceof IGTTool tool) { + gtTools[slot] = tool; + } else { + gtTools[slot] = null; + } + } + + protected void update() { + this.oreDicts.clear(); + Arrays.stream(gtTools).filter(Objects::nonNull).map(igtTool -> { + Set set = new ObjectOpenHashSet<>(igtTool.getSecondaryOreDicts()); + set.add(igtTool.getOreDictName()); + return set; + }).forEach(this.oreDicts::addAll); + this.oreDicts.retainAll(VALID_OREDICTS); + + this.toolClasses.clear(); + for (int i = 0; i < this.getSlots(); i++) { + if (tools[i] != null) this.toolClasses.addAll(tools[i].getToolClasses(stacks.get(i))); + } + } + + public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraftingDamage) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (ingredient.test(stack)) { + if (doCraftingDamage && stack.getItem().hasContainerItem(stack)) { + this.setStackInSlot(i, stack.getItem().getContainerItem(stack)); + } + return true; + } + } + return false; + } + } +} diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 7fb4773d478..193a8327ab0 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -1,9 +1,12 @@ package gregtech.client; +import com.cleanroommc.modularui.utils.math.functions.limit.Min; + import gregtech.api.GTValues; import gregtech.api.fluids.GTFluidRegistration; import gregtech.api.items.metaitem.MetaOreDictItem; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.terminal.TerminalRegistry; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; @@ -34,19 +37,23 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Items; import net.minecraft.inventory.ContainerPlayer; import net.minecraft.inventory.ContainerWorkbench; import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.client.event.ModelRegistryEvent; +import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.Constants; import net.minecraftforge.event.entity.player.ItemTooltipEvent; @@ -315,4 +322,20 @@ private static boolean hasActuallyAdvancedInfo(List tooltip) { public boolean isFancyGraphics() { return Minecraft.getMinecraft().gameSettings.fancyGraphics; } + + @SubscribeEvent(priority = EventPriority.HIGH) + public static void onMouseEvent(@NotNull MouseEvent event) { + EntityPlayerSP player = Minecraft.getMinecraft().player; + if (event.getDwheel() != 0 && player.isSneaking()) { + ItemStack stack = player.getHeldItemMainhand(); + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt toolbelt) { + stack = stack.copy(); + toolbelt.changeSelectedTool(event.getDwheel(), stack); + InventoryPlayer inv = Minecraft.getMinecraft().player.inventory; + inv.mainInventory.set(inv.currentItem, stack); + event.setCanceled(true); + } + } + } } diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index f3addd44339..61733e309fd 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -23,6 +23,8 @@ public class FluidReplaceRecipe extends GTShapedOreRecipe { public FluidReplaceRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(isClearing, group, result, recipe); + // there is no possible way that we require toolbelt handling, but make sure it isn't enabled. + this.toolbeltHandling = false; } @NotNull diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index a014bd89292..7b60f40b119 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -1,5 +1,7 @@ package gregtech.common.crafting; +import gregtech.api.crafting.IToolbeltSupportingRecipe; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.util.GTLog; import gregtech.api.util.GTStringUtils; @@ -31,21 +33,26 @@ import java.util.HashMap; import java.util.Set; -public class GTShapedOreRecipe extends ShapedOreRecipe { +public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSupportingRecipe { boolean isClearing; + boolean toolbeltHandling; public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result, parseShaped(isClearing, recipe)); this.isClearing = isClearing; + this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); + initNeedsToolbeltHandlingHelper.set(false); } // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. - // the on difference is calling getIngredient of this class. + // the only difference is calling getIngredient of this class. public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { + initNeedsToolbeltHandlingHelper.set(false); + CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); int idx = 0; @@ -126,23 +133,19 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object return ret; } - // a copy of the CraftingHelper getIngredient method. - // the only difference is checking for a filled bucket and making - // it an GTFluidCraftingIngredient protected static Ingredient getIngredient(boolean isClearing, Object obj) { - if (obj instanceof Ingredient) return (Ingredient) obj; - else if (obj instanceof ItemStack) { - ItemStack ing = (ItemStack) obj; - if (ing.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { - IFluidHandlerItem handler = ing.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, + if (obj instanceof Ingredient ing) return ing; + else if (obj instanceof ItemStack stk) { + if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + IFluidHandlerItem handler = stk.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); if (handler != null) { FluidStack drained = handler.drain(Integer.MAX_VALUE, false); if (drained != null && drained.amount > 0) { - return new GTFluidCraftingIngredient(((ItemStack) obj).copy()); + return new GTFluidCraftingIngredient(stk.copy()); } if (!isClearing) { - ItemStack i = ((ItemStack) obj).copy(); + ItemStack i = (stk).copy(); try { return ingredientNBT.newInstance(i); } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { @@ -152,23 +155,52 @@ else if (obj instanceof ItemStack) { } } } - return Ingredient.fromStacks(((ItemStack) obj).copy()); - } else if (obj instanceof Item) return Ingredient.fromItem((Item) obj); - else if (obj instanceof Block) - return Ingredient.fromStacks(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); - else if (obj instanceof String) return new OreIngredient((String) obj); + return Ingredient.fromStacks(stk.copy()); + } else if (obj instanceof Item itm) return Ingredient.fromItem(itm); + else if (obj instanceof Block blk) + return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); + else if (obj instanceof String str) { + if (ItemGTToolbelt.isToolbeltableOredict(str)) + initNeedsToolbeltHandlingHelper.set(true); + return new OreIngredient(str); + } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); return null; } + @Override + protected boolean checkMatch(@NotNull InventoryCrafting inv, int startX, int startY, boolean mirror) { + if (this.toolbeltHandling) { + for (int x = 0; x < inv.getWidth(); x++) { + for (int y = 0; y < inv.getHeight(); y++) { + int subX = x - startX; + int subY = y - startY; + Ingredient target = Ingredient.EMPTY; + + if (subX >= 0 && subY >= 0 && subX < width && subY < height) { + if (mirror) { + target = input.get(width - subX - 1 + subY * width); + } else { + target = input.get(subX + subY * width); + } + } + + if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(target, inv.getStackInRowAndColumn(x, y))) + return false; + } + } + return true; + } else return super.checkMatch(inv, startX, startY, mirror); + } + @Override public @NotNull NonNullList getRemainingItems(@NotNull InventoryCrafting inv) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return super.getRemainingItems(inv); + return IToolbeltSupportingRecipe.super.getRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index 6d0ee689b32..7d39669e5f6 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,42 +1,35 @@ package gregtech.common.crafting; -import gregtech.api.util.GTLog; -import gregtech.api.util.GTStringUtils; +import com.google.common.collect.Lists; + +import gregtech.api.crafting.IToolbeltSupportingRecipe; -import net.minecraft.block.Block; import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.crafting.IngredientNBT; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fluids.capability.IFluidHandlerItem; -import net.minecraftforge.fml.relauncher.ReflectionHelper; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.OreIngredient; +import net.minecraft.world.World; +import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; -import com.google.gson.JsonElement; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; +import java.util.List; -public class GTShapelessOreRecipe extends ShapelessOreRecipe { +public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbeltSupportingRecipe { boolean isClearing; - public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, - ItemStack.class); + boolean toolbeltHandling; public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); + initNeedsToolbeltHandlingHelper.set(false); + this.isClearing = isClearing; for (Object in : recipe) { - Ingredient ing = getIngredient(isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -49,43 +42,41 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull throw new RuntimeException(ret.toString()); } } + this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); + initNeedsToolbeltHandlingHelper.set(false); } - // a copy of the CraftingHelper getIngredient method. - // the only difference is checking for a filled bucket and making - // it an GTFluidCraftingIngredient - private static Ingredient getIngredient(boolean isClearing, Object obj) { - if (obj instanceof Ingredient) return (Ingredient) obj; - else if (obj instanceof ItemStack) { - ItemStack ing = (ItemStack) obj; - if (ing.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { - IFluidHandlerItem handler = ing.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, - null); - if (handler != null) { - FluidStack drained = handler.drain(Integer.MAX_VALUE, false); - if (drained != null && drained.amount > 0) { - return new GTFluidCraftingIngredient(((ItemStack) obj).copy()); - } - if (!isClearing) { - ItemStack i = ((ItemStack) obj).copy(); - try { - return ingredientNBT.newInstance(i); - } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { - GTLog.logger.error("Failure to instantiate an IngredientNBT of item {}", - GTStringUtils.prettyPrintItemStack(i)); - } - } + @Override + public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { + if (this.toolbeltHandling) { + // I can't wrap my head around the 'simple' shapeless logic, so no simple toolbelt handling. + int ingredientCount = 0; + List items = Lists.newArrayList(); + + for (int i = 0; i < inv.getSizeInventory(); ++i) + { + ItemStack itemstack = inv.getStackInSlot(i); + if (!itemstack.isEmpty()) + { + ++ingredientCount; + items.add(itemstack); } } - return Ingredient.fromStacks(((ItemStack) obj).copy()); - } else if (obj instanceof Item) return Ingredient.fromItem((Item) obj); - else if (obj instanceof Block) - return Ingredient.fromStacks(new ItemStack((Block) obj, 1, OreDictionary.WILDCARD_VALUE)); - else if (obj instanceof String) return new OreIngredient((String) obj); - else if (obj instanceof JsonElement) - throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); - return null; + if (ingredientCount != this.input.size()) + return false; + + int[] matches = RecipeMatcher.findMatches(items, this.input); + if (matches != null) { + for (int i = 0; i < items.size(); i++) { + ItemStack stack = items.get(i); + Ingredient ingredient = this.input.get(matches[i]); + if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(ingredient, stack)) return false; + } + return true; + } else return false; + + } else return super.matches(inv, world); } @Override @@ -93,7 +84,7 @@ else if (obj instanceof JsonElement) if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return super.getRemainingItems(inv); + return IToolbeltSupportingRecipe.super.getRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 5545387ef7c..04c6a0e7f79 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -58,6 +58,7 @@ public final class ToolItems { public static IGTTool WIRECUTTER_LV; public static IGTTool WIRECUTTER_HV; public static IGTTool WIRECUTTER_IV; + public static ItemGTToolbelt TOOLBELT; private ToolItems() {/**/} @@ -66,6 +67,8 @@ public static List getAllTools() { } public static void init() { + TOOLBELT = (ItemGTToolbelt) register(new ItemGTToolbelt(GTValues.MODID, "toolbelt", + null)); SWORD = register(ItemGTSword.Builder.of(GTValues.MODID, "sword") .toolStats(b -> b.attacking() .attackDamage(3.0F).attackSpeed(-2.4F)) @@ -379,8 +382,12 @@ public static void registerOreDict() { final ItemStack stack = new ItemStack(tool.get(), 1, GTValues.W); if (tool.getOreDictName() != null) { OreDictUnifier.registerOre(stack, tool.getOreDictName()); + TOOLBELT.registerValidOredict(tool.getOreDictName()); } - tool.getSecondaryOreDicts().forEach(oreDict -> OreDictUnifier.registerOre(stack, oreDict)); + tool.getSecondaryOreDicts().forEach(oreDict -> { + OreDictUnifier.registerOre(stack, oreDict); + TOOLBELT.registerValidOredict(oreDict); + }); }); } } diff --git a/src/main/java/gregtech/core/CoreModule.java b/src/main/java/gregtech/core/CoreModule.java index f3bda89f361..c272028abfb 100644 --- a/src/main/java/gregtech/core/CoreModule.java +++ b/src/main/java/gregtech/core/CoreModule.java @@ -63,6 +63,7 @@ import gregtech.core.network.packets.PacketPluginSynced; import gregtech.core.network.packets.PacketRecoverMTE; import gregtech.core.network.packets.PacketReloadShaders; +import gregtech.core.network.packets.PacketToolbeltSelectionChange; import gregtech.core.network.packets.PacketUIClientAction; import gregtech.core.network.packets.PacketUIOpen; import gregtech.core.network.packets.PacketUIWidgetUpdate; @@ -232,6 +233,7 @@ public void registerPackets() { GregTechAPI.networkHandler.registerPacket(PacketNotifyCapeChange.class); GregTechAPI.networkHandler.registerPacket(PacketReloadShaders.class); GregTechAPI.networkHandler.registerPacket(PacketClipboardNBTUpdate.class); + GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.class); } @Override diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java new file mode 100644 index 00000000000..96b14b1c47c --- /dev/null +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -0,0 +1,41 @@ +package gregtech.core.network.packets; + +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.api.network.IPacket; +import gregtech.api.network.IServerExecutor; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.EnumHand; + +public class PacketToolbeltSelectionChange implements IPacket, IServerExecutor { + + private int slot; + + public PacketToolbeltSelectionChange() {} + + public PacketToolbeltSelectionChange(int slot) { + this.slot = slot; + } + + @Override + public void encode(PacketBuffer buf) { + buf.writeByte(slot); + } + + @Override + public void decode(PacketBuffer buf) { + this.slot = buf.readByte(); + } + + @Override + public void executeServer(NetHandlerPlayServer handler) { + ItemStack stack = handler.player.getHeldItemMainhand(); + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt toolbelt) { + toolbelt.setSelectedTool(slot, stack); + } + } +} diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index 8e9b4091db2..3974b4635c1 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1027,6 +1027,8 @@ item.gt.tool.plunger.tooltip=§8Removes Fluids from Machines item.gt.tool.wire_cutter_lv.name=%s Wire Cutter (LV) item.gt.tool.wire_cutter_hv.name=%s Wire Cutter (HV) item.gt.tool.wire_cutter_iv.name=%s Wire Cutter (IV) +item.gt.tool.toolbelt.name=%s Toolbelt%s +item.gt.tool.toolbelt.tooltip=Holds too many tools for too many jobs. item.gt.tool.tooltip.crafting_uses=§a%s Crafting Uses From 724884dd2284fc28698bcfc361122f1a7a9e4200 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 18:46:15 -0600 Subject: [PATCH 25/82] Recipe & texture --- .../recipe/handlers/ToolRecipeHandler.java | 9 +++++++++ .../gregtech/models/item/tools/toolbelt.json | 7 +++++++ .../textures/items/tools/toolbelt_belt.png | Bin 0 -> 192 bytes .../textures/items/tools/toolbelt_loops.png | Bin 0 -> 177 bytes 4 files changed, 16 insertions(+) create mode 100644 src/main/resources/assets/gregtech/models/item/tools/toolbelt.json create mode 100644 src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png create mode 100644 src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png diff --git a/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java b/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java index 1997631a38c..84e5cd91450 100644 --- a/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java +++ b/src/main/java/gregtech/loaders/recipe/handlers/ToolRecipeHandler.java @@ -19,6 +19,7 @@ import gregtech.common.items.MetaItems; import gregtech.common.items.ToolItems; +import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.ResourceLocation; @@ -215,6 +216,14 @@ private static void processTool(OrePrefix prefix, Material material, ToolPropert } } + if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING)) { + addToolRecipe(material, ToolItems.TOOLBELT, false, + "SSS", "LLL", "RSR", + 'L', Items.LEATHER, + 'S', new UnificationEntry(OrePrefix.screw, material), + 'R', new UnificationEntry(OrePrefix.ring, material)); + } + addToolRecipe(material, ToolItems.SCREWDRIVER, true, " fS", " Sh", "W ", 'S', rod, diff --git a/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json b/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json new file mode 100644 index 00000000000..25e4069ef67 --- /dev/null +++ b/src/main/resources/assets/gregtech/models/item/tools/toolbelt.json @@ -0,0 +1,7 @@ +{ + "parent": "item/handheld", + "textures": { + "layer0": "gregtech:items/tools/toolbelt_belt", + "layer1": "gregtech:items/tools/toolbelt_loops" + } +} diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png new file mode 100644 index 0000000000000000000000000000000000000000..b8e9021431ea0046ebe5743d23bac2ec3bfa687a GIT binary patch literal 192 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|Dm+~rLoEE0 zQx*sq1g)5#c!hz@L!xCx_h0sl*?Ievw0tI9Jk|}H4o|%LxWvdu@QeeHd6_S; n?%4DjZoCa@Dqck@4DLo+f@^+g?f|-h!PC{xWt~$(69WSP5ZFYA literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png new file mode 100644 index 0000000000000000000000000000000000000000..c351831679459d2785e6da182d3aa7cd938d66e3 GIT binary patch literal 177 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|GCf@!LoEE0 zQx*sq1g)5#xI^;7g$p0#MbvnCc_a3=`O3K}dNfX)D0ukV+GxqNb8|WspTB*3)*$_y zjEE(V>$Pjwc(SjpIhe&@X1OS*v5I^3>lLq=CiuR5`SL-73qNzrqr Date: Tue, 4 Jun 2024 20:59:12 -0600 Subject: [PATCH 26/82] Finalize in-world handling --- .../crafting/IToolbeltSupportingRecipe.java | 2 +- .../api/items/toolitem/ItemGTToolbelt.java | 91 +++++++++++++----- .../api/items/toolitem/ToolHelper.java | 93 ++++++++++--------- 3 files changed, 119 insertions(+), 67 deletions(-) diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java index 82e161fb167..7e55d8da228 100644 --- a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java +++ b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java @@ -35,7 +35,7 @@ static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { ItemStack stack = ret.get(i); Ingredient ingredient = this.getIngredients().get(matches[i]); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - toolbelt.damageTools(stack, ingredient); + toolbelt.craftDamageTools(stack, ingredient); } ret.set(i, ForgeHooks.getContainerItem(stack)); } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 416bb5f4ced..b9e0dc38c25 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -9,6 +9,8 @@ import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.google.common.collect.ImmutableSet; + import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; @@ -37,7 +39,6 @@ import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; -import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; @@ -64,6 +65,26 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem) this.orestack = new ItemStack(this, 1, GTValues.W); } + @Override + public int getDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.getItemDamage(); + }return super.getDamage(stack); + } + + @Override + public void setDamage(@NotNull ItemStack stack, int damage) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.setItemDamage(damage); + } else super.setDamage(stack, damage); + } + + public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { + return getHandler(stack).getSelectedStack(); + } + @Override public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, @NotNull EnumHand hand) { @@ -77,9 +98,10 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem) @Override public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { - ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 192); - ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); + int heightBonus = (handler.getSlots() / 9) * 18; + + ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); slotGroupWidget.flex() @@ -89,8 +111,7 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.flex().top(7); slotGroupWidget.flex().endDefaultMode(); slotGroupWidget.debugName("toolbelt_inventory"); - String key = "toolbelt"; - for (int i = 0; i < 27; i++) { + for (int i = 0; i < handler.getSlots(); i++) { slotGroupWidget.child(new ItemSlot() .slot(SyncHandlers.itemSlot(handler, i)) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) @@ -111,14 +132,9 @@ public void registerValidOredict(String oredict) { OreDictUnifier.registerOre(this.orestack, oredict); } - @Override - public int getMaxDamage(@NotNull ItemStack stack) { - return -1; - } - @Override public @NotNull Set getToolClasses(@NotNull ItemStack stack) { - return getHandler(stack).toolClasses; + return getHandler(stack).getToolClasses(true); } @Override @@ -135,7 +151,7 @@ public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { return getHandler(stack).checkIngredientAgainstTools(ingredient, false); } - public void damageTools(ItemStack stack, Ingredient ingredient) { + public void craftDamageTools(ItemStack stack, Ingredient ingredient) { getHandler(stack).checkIngredientAgainstTools(ingredient, true); } @@ -145,7 +161,7 @@ private ToolStackHandler getHandler(ItemStack stack) { @Override public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagCompound nbt) { - return new ToolbeltCapabilityProvider(); + return new ToolbeltCapabilityProvider(stack); } public void changeSelectedTool(int direction, ItemStack stack) { @@ -172,10 +188,15 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); } - protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + protected class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + + protected final Supplier slotCountSupplier; + private @Nullable ToolStackHandler handler; - private final ToolStackHandler handler = new ToolStackHandler(); + public ToolbeltCapabilityProvider(ItemStack stack) { + slotCountSupplier = () -> (int) (ItemGTToolbelt.super.getTotalHarvestLevel(stack) * 5.4f); + } @Override public boolean hasCapability(@NotNull Capability capability, EnumFacing facing) { @@ -185,23 +206,34 @@ public boolean hasCapability(@NotNull Capability capability, EnumFacing facin @SuppressWarnings("unchecked") @Override public T getCapability(@NotNull Capability capability, EnumFacing facing) { - if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) handler; + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) this.getHandler(0); else return null; } @Override public NBTTagCompound serializeNBT() { - return this.handler.serializeNBT(); + return this.getHandler(0).serializeNBT(); } @Override public void deserializeNBT(NBTTagCompound nbt) { - this.handler.deserializeNBT(nbt); + // make sure we can load all the slots, no matter what we're supposed to be limited to. + int minsize = nbt.hasKey("Size") ? nbt.getInteger("Size") : 0; + // .copy() prevents double damage ticks in singleplayer + this.getHandler(minsize).deserializeNBT(nbt.copy()); + } + + protected ToolStackHandler getHandler(int minsize) { + int slots = Math.max(slotCountSupplier.get(), minsize); + if (handler == null || handler.getSlots() != slots) handler = new ToolStackHandler(slots); + return handler; } } protected static class ToolStackHandler extends ItemStackHandler { + private static final Set EMPTY = ImmutableSet.of(); + private @Nullable Integer selectedSlot = null; protected final ItemTool[] tools = new ItemTool[this.getSlots()]; @@ -209,8 +241,8 @@ protected static class ToolStackHandler extends ItemStackHandler { protected final Set toolClasses = new ObjectOpenHashSet<>(); public final Set oreDicts = new ObjectOpenHashSet<>(); - public ToolStackHandler() { - super(27); + public ToolStackHandler(int size) { + super(size); } public void incrementSelectedSlot() { @@ -235,14 +267,29 @@ public void decrementSelectedSlot() { return selectedSlot; } - public ItemStack getSelectedStack() { + public @Nullable ItemStack getSelectedStack() { if (getSelectedSlot() == null) return null; else return this.stacks.get(getSelectedSlot()); } + public Set getToolClasses(boolean defaultEmpty) { + ItemStack selectedStack = getSelectedStack(); + if (selectedStack != null) { + if (selectedStack.getItem() instanceof ItemTool tool) { + return tool.getToolClasses(selectedStack); + } else if (selectedStack.getItem() instanceof IGTTool tool) { + return tool.getToolClasses(selectedStack); + } + } + if (defaultEmpty) return EMPTY; + return toolClasses; + } + @Override public boolean isItemValid(int slot, @NotNull ItemStack stack) { - return stack.getItem() instanceof ItemTool || stack.getItem() instanceof IGTTool; + Item item = stack.getItem(); + if (item instanceof ItemGTToolbelt) return false; + return item instanceof ItemTool || item instanceof IGTTool; } @Override diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 23d3145ca9b..f894664d1dd 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -254,58 +254,63 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa * @param damage how much damage the stack will take */ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBase entity, int damage) { - if (!(stack.getItem() instanceof IGTTool)) { + if (!(stack.getItem() instanceof IGTTool tool)) { if (entity != null) stack.damageItem(damage, entity); - } else { - if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { + return; + } else if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selectedStack = toolbelt.getSelectedItem(stack); + if (selectedStack != null) { + damageItem(selectedStack, entity, damage); return; } - IGTTool tool = (IGTTool) stack.getItem(); - if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { - Random random = entity == null ? GTValues.RNG : entity.getRNG(); - if (tool.isElectric()) { - int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; - IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, - null); - if (electricItem != null) { - electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); - if (electricItem.getCharge() > 0 && - random.nextInt(100) >= ConfigHolder.tools.rngDamageElectricTools) { - return; - } - } else { - throw new IllegalStateException( - "Electric tool does not have an attached electric item capability."); - } - } - int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); - int negated = 0; - for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { - if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { - negated++; + } + if (stack.getTagCompound() != null && stack.getTagCompound().getBoolean(UNBREAKABLE_KEY)) { + return; + } + if (!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { + Random random = entity == null ? GTValues.RNG : entity.getRNG(); + if (tool.isElectric()) { + int electricDamage = damage * ConfigHolder.machines.energyUsageMultiplier; + IElectricItem electricItem = stack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, + null); + if (electricItem != null) { + electricItem.discharge(electricDamage, tool.getElectricTier(), true, false, false); + if (electricItem.getCharge() > 0 && + random.nextInt(100) >= ConfigHolder.tools.rngDamageElectricTools) { + return; } + } else { + throw new IllegalStateException( + "Electric tool does not have an attached electric item capability."); } - damage -= negated; - if (damage <= 0) { - return; - } - int newDurability = stack.getItemDamage() + damage; - if (entity instanceof EntityPlayerMP) { - CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); + } + int unbreakingLevel = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, stack); + int negated = 0; + for (int k = 0; unbreakingLevel > 0 && k < damage; k++) { + if (EnchantmentDurability.negateDamage(stack, unbreakingLevel, random)) { + negated++; } - stack.setItemDamage(newDurability); - if (newDurability > stack.getMaxDamage()) { - if (entity instanceof EntityPlayer) { - StatBase stat = StatList.getObjectBreakStats(stack.getItem()); - if (stat != null) { - ((EntityPlayer) entity).addStat(stat); - } - } - if (entity != null) { - entity.renderBrokenItemStack(stack); + } + damage -= negated; + if (damage <= 0) { + return; + } + int newDurability = stack.getItemDamage() + damage; + if (entity instanceof EntityPlayerMP) { + CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger((EntityPlayerMP) entity, stack, newDurability); + } + stack.setItemDamage(newDurability); + if (newDurability > stack.getMaxDamage()) { + if (entity instanceof EntityPlayer) { + StatBase stat = StatList.getObjectBreakStats(stack.getItem()); + if (stat != null) { + ((EntityPlayer) entity).addStat(stat); } - stack.shrink(1); } + if (entity != null) { + entity.renderBrokenItemStack(stack); + } + stack.shrink(1); } } } From 0dceb77b153384faa1c657ee9caca91e26465e37 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 20:59:33 -0600 Subject: [PATCH 27/82] Spotless --- .../api/items/toolitem/ItemGTToolbelt.java | 35 ++++++++----------- .../java/gregtech/client/ClientProxy.java | 2 -- .../common/crafting/GTShapedOreRecipe.java | 3 +- .../common/crafting/GTShapelessOreRecipe.java | 9 ++--- .../PacketToolbeltSelectionChange.java | 1 - 5 files changed, 19 insertions(+), 31 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index b9e0dc38c25..e538e468aaf 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,28 +1,13 @@ package gregtech.api.items.toolitem; -import com.cleanroommc.modularui.factory.HandGuiData; -import com.cleanroommc.modularui.factory.ItemGuiFactory; -import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.value.sync.GuiSyncManager; - -import com.cleanroommc.modularui.value.sync.SyncHandlers; -import com.cleanroommc.modularui.widgets.ItemSlot; -import com.cleanroommc.modularui.widgets.SlotGroupWidget; - -import com.google.common.collect.ImmutableSet; - import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.OreDictUnifier; - import gregtech.api.util.LocalizationUtils; - import gregtech.core.network.packets.PacketToolbeltSelectionChange; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; @@ -33,7 +18,6 @@ import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; - import net.minecraft.util.EnumHand; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; @@ -42,6 +26,15 @@ import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widgets.ItemSlot; +import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.google.common.collect.ImmutableSet; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -70,7 +63,8 @@ public int getDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { selected.getItemDamage(); - }return super.getDamage(stack); + } + return super.getDamage(stack); } @Override @@ -113,8 +107,8 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i)) - .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) + .slot(SyncHandlers.itemSlot(handler, i)) + .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); } @@ -185,7 +179,8 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { if (tool != null) { selectedToolDisplay = " (" + tool.getDisplayName() + ")"; } - return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); + return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), + selectedToolDisplay); } protected class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 193a8327ab0..571f617d849 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -1,7 +1,5 @@ package gregtech.client; -import com.cleanroommc.modularui.utils.math.functions.limit.Min; - import gregtech.api.GTValues; import gregtech.api.fluids.GTFluidRegistration; import gregtech.api.items.metaitem.MetaOreDictItem; diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 7b60f40b119..aa29bf06576 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -163,8 +163,7 @@ else if (obj instanceof String str) { if (ItemGTToolbelt.isToolbeltableOredict(str)) initNeedsToolbeltHandlingHelper.set(true); return new OreIngredient(str); - } - else if (obj instanceof JsonElement) + } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); return null; diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index 7d39669e5f6..e0ceff95e51 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,7 +1,5 @@ package gregtech.common.crafting; -import com.google.common.collect.Lists; - import gregtech.api.crafting.IToolbeltSupportingRecipe; import net.minecraft.inventory.InventoryCrafting; @@ -13,6 +11,7 @@ import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; +import com.google.common.collect.Lists; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -53,11 +52,9 @@ public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { int ingredientCount = 0; List items = Lists.newArrayList(); - for (int i = 0; i < inv.getSizeInventory(); ++i) - { + for (int i = 0; i < inv.getSizeInventory(); ++i) { ItemStack itemstack = inv.getStackInSlot(i); - if (!itemstack.isEmpty()) - { + if (!itemstack.isEmpty()) { ++ingredientCount; items.add(itemstack); } diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java index 96b14b1c47c..f2978076e44 100644 --- a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -8,7 +8,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.PacketBuffer; -import net.minecraft.util.EnumHand; public class PacketToolbeltSelectionChange implements IPacket, IServerExecutor { From 247cc3116b27a8b6bf4a8932bd3b80d6e5b5997c Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 21:54:42 -0600 Subject: [PATCH 28/82] Maintenance --- .../api/items/toolitem/ItemGTToolbelt.java | 17 ++++++ .../api/items/toolitem/ToolHelper.java | 7 +++ .../MetaTileEntityMaintenanceHatch.java | 55 +++++++++---------- 3 files changed, 49 insertions(+), 30 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index e538e468aaf..24b27bad50f 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -141,6 +141,11 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { return stack.copy(); } + public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, + @Nullable EntityPlayer entityPlayer) { + return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); + } + public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { return getHandler(stack).checkIngredientAgainstTools(ingredient, false); } @@ -346,6 +351,18 @@ protected void update() { } } + public boolean checkMaintenanceAgainstTools(String toolClass, boolean doCraftingDamage, + @Nullable EntityPlayer entityPlayer) { + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (ToolHelper.isTool(stack, toolClass)) { + if (doCraftingDamage) ToolHelper.damageItemWhenCrafting(stack, entityPlayer); + return true; + } + } + return false; + } + public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraftingDamage) { for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index f894664d1dd..c4f92284be8 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -220,6 +220,13 @@ public static ItemStack getAndSetToolData(IGTTool tool, Material material, int m * @param entity entity that has damaged this stack */ public static void damageItemWhenCrafting(@NotNull ItemStack stack, @Nullable EntityLivingBase entity) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selectedStack = toolbelt.getSelectedItem(stack); + if (selectedStack != null) { + damageItemWhenCrafting(selectedStack, entity); + return; + } + } int damage = 2; if (stack.getItem() instanceof IGTTool) { damage = ((IGTTool) stack.getItem()).getToolStats().getToolDamagePerCraft(stack); diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index dda660e024f..8437b2674ce 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -9,6 +9,7 @@ import gregtech.api.gui.widgets.ClickButtonWidget; import gregtech.api.gui.widgets.SlotWidget; import gregtech.api.items.itemhandlers.GTItemStackHandler; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.metatileentity.MetaTileEntity; @@ -50,6 +51,7 @@ import java.math.BigDecimal; import java.math.RoundingMode; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -260,24 +262,12 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { if (((problems >> index) & 1) == 0) { proceed = true; switch (index) { - case 0: - toolsToMatch.set(0, ToolClasses.WRENCH); - break; - case 1: - toolsToMatch.set(1, ToolClasses.SCREWDRIVER); - break; - case 2: - toolsToMatch.set(2, ToolClasses.SOFT_MALLET); - break; - case 3: - toolsToMatch.set(3, ToolClasses.HARD_HAMMER); - break; - case 4: - toolsToMatch.set(4, ToolClasses.WIRE_CUTTER); - break; - case 5: - toolsToMatch.set(5, ToolClasses.CROWBAR); - break; + case 0 -> toolsToMatch.set(0, ToolClasses.WRENCH); + case 1 -> toolsToMatch.set(1, ToolClasses.SCREWDRIVER); + case 2 -> toolsToMatch.set(2, ToolClasses.SOFT_MALLET); + case 3 -> toolsToMatch.set(3, ToolClasses.HARD_HAMMER); + case 4 -> toolsToMatch.set(4, ToolClasses.WIRE_CUTTER); + case 5 -> toolsToMatch.set(5, ToolClasses.CROWBAR); } } } @@ -285,37 +275,42 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { return; } + mainfor: for (int i = 0; i < toolsToMatch.size(); i++) { String toolToMatch = toolsToMatch.get(i); if (toolToMatch != null) { // Try to use the item in the player's "hand" (under the cursor) ItemStack heldItem = entityPlayer.inventory.getItemStack(); - if (ToolHelper.isTool(heldItem, toolToMatch)) { + if (heldItem.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.damageAgainstMaintenanceProblem(heldItem, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(i); + setTaped(false); + continue; + } + } else if (ToolHelper.isTool(heldItem, toolToMatch)) { fixProblemWithTool(i, heldItem, entityPlayer); if (toolsToMatch.stream().allMatch(Objects::isNull)) { return; } + continue; } // Then try all the remaining inventory slots for (ItemStack itemStack : entityPlayer.inventory.mainInventory) { - if (ToolHelper.isTool(itemStack, toolToMatch)) { - fixProblemWithTool(i, itemStack, entityPlayer); - - if (toolsToMatch.stream().allMatch(Objects::isNull)) { - return; + if (itemStack.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.damageAgainstMaintenanceProblem(itemStack, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(i); + setTaped(false); + continue mainfor; } - } - } + } else if (ToolHelper.isTool(itemStack, toolToMatch)) { + fixProblemWithTool(i, itemStack, entityPlayer); - for (ItemStack stack : entityPlayer.inventory.mainInventory) { - if (ToolHelper.isTool(stack, toolToMatch)) { - ((IMaintenance) this.getController()).setMaintenanceFixed(i); - ToolHelper.damageItemWhenCrafting(stack, entityPlayer); if (toolsToMatch.stream().allMatch(Objects::isNull)) { return; } + continue mainfor; } } } From d062ae88d45f1b8dc1a7706cb0334038b8330081 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 22:06:27 -0600 Subject: [PATCH 29/82] Shift-click --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 24b27bad50f..52548b54033 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,5 +1,7 @@ package gregtech.api.items.toolitem; +import com.cleanroommc.modularui.widgets.slot.SlotGroup; + import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; @@ -97,6 +99,9 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); + SlotGroup group = new SlotGroup("toolbelt_inventory", 9); + guiSyncManager.registerSlotGroup(group); + SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); slotGroupWidget.flex() .coverChildren() @@ -107,7 +112,7 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i)) + .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group)) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); From deeb74e1a8d6a4110b79404ba6851f1d17a2c8ff Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 22:07:26 -0600 Subject: [PATCH 30/82] Spotless, once more --- src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 3 +-- .../multi/multiblockpart/MetaTileEntityMaintenanceHatch.java | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 52548b54033..c958357eadc 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,7 +1,5 @@ package gregtech.api.items.toolitem; -import com.cleanroommc.modularui.widgets.slot.SlotGroup; - import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.mui.GTGuiTextures; @@ -35,6 +33,7 @@ import com.cleanroommc.modularui.value.sync.SyncHandlers; import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.cleanroommc.modularui.widgets.slot.SlotGroup; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index 8437b2674ce..c28ddc32860 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -51,7 +51,6 @@ import java.math.BigDecimal; import java.math.RoundingMode; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; From 2e81c34471c0a7311a509ebfb8e8c9ea9730826d Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 22:32:47 -0600 Subject: [PATCH 31/82] Passthrough methods --- .../api/items/toolitem/ItemGTToolbelt.java | 244 +++++++++++++++--- 1 file changed, 215 insertions(+), 29 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index c958357eadc..c3d8668c511 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -8,8 +8,13 @@ import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.util.ITooltipFlag; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; @@ -19,10 +24,14 @@ import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; @@ -35,6 +44,7 @@ import com.cleanroommc.modularui.widgets.SlotGroupWidget; import com.cleanroommc.modularui.widgets.slot.SlotGroup; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multimap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -42,6 +52,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; @@ -59,38 +70,10 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem) this.orestack = new ItemStack(this, 1, GTValues.W); } - @Override - public int getDamage(@NotNull ItemStack stack) { - ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { - selected.getItemDamage(); - } - return super.getDamage(stack); - } - - @Override - public void setDamage(@NotNull ItemStack stack, int damage) { - ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { - selected.setItemDamage(damage); - } else super.setDamage(stack, damage); - } - public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { return getHandler(stack).getSelectedStack(); } - @Override - public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - if (player.isSneaking()) { - if (!world.isRemote) { - ItemGuiFactory.open((EntityPlayerMP) player, hand); - } - return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); - } else return definition$onItemRightClick(world, player, hand); - } - @Override public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); @@ -131,10 +114,213 @@ public void registerValidOredict(String oredict) { } @Override - public @NotNull Set getToolClasses(@NotNull ItemStack stack) { + public float getDestroySpeed(@NotNull ItemStack stack, @NotNull IBlockState state) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getDestroySpeed(selected, state); + } else return definition$getDestroySpeed(stack, state); + } + + @Override + public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase target, + @NotNull EntityLivingBase attacker) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().hitEntity(selected, target, attacker); + } else return definition$hitEntity(stack, target, attacker); + } + + @Override + public boolean onBlockStartBreak(@NotNull ItemStack itemstack, @NotNull BlockPos pos, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(itemstack).getSelectedStack(); + if (selected != null) { + return selected.getItem().onBlockStartBreak(selected, pos, player); + } else return definition$onBlockStartBreak(itemstack, pos, player); + } + + @Override + public boolean onBlockDestroyed(@NotNull ItemStack stack, @NotNull World worldIn, @NotNull IBlockState state, + @NotNull BlockPos pos, @NotNull EntityLivingBase entityLiving) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().onBlockDestroyed(selected, worldIn, state, pos, entityLiving); + } else return definition$onBlockDestroyed(stack, worldIn, state, pos, entityLiving); + } + + @Override + public boolean getIsRepairable(@NotNull ItemStack toRepair, @NotNull ItemStack repair) { + // I think this lets repairs go through to the selected tool, in combination with the setDamage passthroughs? + // Idk testing required. + ItemStack selected = getHandler(toRepair).getSelectedStack(); + if (selected != null) { + return selected.getItem().getIsRepairable(selected, repair); + } else return definition$getIsRepairable(toRepair, repair); + } + + @NotNull + @Override + public Multimap getAttributeModifiers(@NotNull EntityEquipmentSlot slot, + @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getAttributeModifiers(slot, selected); + } else return definition$getAttributeModifiers(slot, stack); + } + + @Override + public int getHarvestLevel(@NotNull ItemStack stack, @NotNull String toolClass, @Nullable EntityPlayer player, + @Nullable IBlockState blockState) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getHarvestLevel(stack, toolClass, player, blockState); + } else return super.getHarvestLevel(stack, toolClass, player, blockState); + } + + @NotNull + @Override + public Set getToolClasses(@NotNull ItemStack stack) { return getHandler(stack).getToolClasses(true); } + @Override + public boolean canDisableShield(@NotNull ItemStack stack, @NotNull ItemStack shield, + @NotNull EntityLivingBase entity, @NotNull EntityLivingBase attacker) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().canDisableShield(selected, shield, entity, attacker); + } else return definition$canDisableShield(stack, shield, entity, attacker); + } + + @Override + public boolean doesSneakBypassUse(@NotNull ItemStack stack, @NotNull IBlockAccess world, @NotNull BlockPos pos, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().doesSneakBypassUse(selected, world, pos, player); + } else return definition$doesSneakBypassUse(stack, world, pos, player); + } + + @Override + public boolean onEntitySwing(@NotNull EntityLivingBase entityLiving, @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().onEntitySwing(entityLiving, selected); + } else return definition$onEntitySwing(entityLiving, stack); + } + + @Override + public boolean canDestroyBlockInCreative(@NotNull World world, @NotNull BlockPos pos, @NotNull ItemStack stack, + @NotNull EntityPlayer player) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().canDestroyBlockInCreative(world, pos, selected, player); + } else return definition$canDestroyBlockInCreative(world, pos, stack, player); + } + + @Override + public boolean shouldCauseReequipAnimation(@NotNull ItemStack oldStack, @NotNull ItemStack newStack, + boolean slotChanged) { + return false; + } + + @Override + public boolean isDamaged(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().isDamaged(selected); + } else return definition$isDamaged(stack); + } + + @Override + public int getDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.getItemDamage(); + } + return super.getDamage(stack); + } + + @Override + public int getMaxDamage(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getMaxDamage(selected); + } else return definition$getMaxDamage(stack); + } + + @Override + public void setDamage(@NotNull ItemStack stack, int damage) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.setItemDamage(damage); + } else super.setDamage(stack, damage); + } + + @Override + public double getDurabilityForDisplay(@NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().getDurabilityForDisplay(selected); + } else return definition$getDurabilityForDisplay(stack); + } + + @NotNull + @Override + public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing side, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null) { + return selected.getItem().onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } else return definition$onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } + + @NotNull + @Override + public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null) { + return selected.getItem().onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } else return definition$onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + if (player.isSneaking()) { + if (!world.isRemote) { + ItemGuiFactory.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } else { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null) { + return selected.getItem().onItemRightClick(world, player, hand); + } else return definition$onItemRightClick(world, player, hand); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void addInformation(@NotNull ItemStack stack, @Nullable World world, @NotNull List tooltip, + @NotNull ITooltipFlag flag) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + selected.getItem().addInformation(selected, world, tooltip, flag); + } else definition$addInformation(stack, world, tooltip, flag); + } + + @Override + public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected != null) { + return selected.getItem().canHarvestBlock(state, selected); + } else return ToolHelper.isToolEffective(state, getToolClasses(stack), getTotalHarvestLevel(stack)); + } + @Override public boolean hasContainerItem(@NotNull ItemStack stack) { return true; From e922f65ad22a6145162c6dba70a5d7dd321a5a3f Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 23:15:17 -0600 Subject: [PATCH 32/82] Less cringe --- .../crafting/IToolbeltSupportingRecipe.java | 2 -- .../java/gregtech/api/recipes/ModHandler.java | 6 ++-- .../common/crafting/GTShapedOreRecipe.java | 31 +++++++++++++------ .../common/crafting/GTShapelessOreRecipe.java | 9 +++--- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java index 7e55d8da228..c4d050e2082 100644 --- a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java +++ b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java @@ -14,8 +14,6 @@ public interface IToolbeltSupportingRecipe extends IRecipe { - ThreadLocal initNeedsToolbeltHandlingHelper = new ThreadLocal<>(); - @SuppressWarnings("BooleanMethodIsAlwaysInverted") static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) diff --git a/src/main/java/gregtech/api/recipes/ModHandler.java b/src/main/java/gregtech/api/recipes/ModHandler.java index 10e55ea68b1..a96b1d9077e 100644 --- a/src/main/java/gregtech/api/recipes/ModHandler.java +++ b/src/main/java/gregtech/api/recipes/ModHandler.java @@ -317,10 +317,10 @@ private static boolean validateRecipeWithOutput(@NotNull String regName, @NotNul private static void addRecipe(@NotNull String regName, @NotNull ItemStack result, boolean isNBTClearing, boolean isMirrored, @NotNull Object... recipe) { - IRecipe shapedOreRecipe = new GTShapedOreRecipe(isNBTClearing, null, result.copy(), + IRecipe shapedOreRecipe = GTShapedOreRecipe.create(isNBTClearing, null, result.copy(), finalizeShapedRecipeInput(recipe)) - .setMirrored(isMirrored) - .setRegistryName(regName); + .setMirrored(isMirrored) + .setRegistryName(regName); registerRecipe(shapedOreRecipe); } diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index aa29bf06576..c7b4f67bab5 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -32,6 +32,7 @@ import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSupportingRecipe { @@ -40,19 +41,29 @@ public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSuppo public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); - public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { - super(group, result, parseShaped(isClearing, recipe)); + private GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, + @NotNull ItemStack result, Object... recipe) { + super(group, result, parseShaped(toolbeltHandling, isClearing, recipe)); this.isClearing = isClearing; - this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); - initNeedsToolbeltHandlingHelper.set(false); + } + + public static GTShapedOreRecipe create(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, + Object... recipe) { + AtomicBoolean toolbeltHandling = new AtomicBoolean(false); + GTShapedOreRecipe out = new GTShapedOreRecipe(toolbeltHandling, isClearing, group, result, recipe); + return out.setToolbeltHandling(toolbeltHandling.get()); + } + + private GTShapedOreRecipe setToolbeltHandling(boolean toolbeltHandling) { + this.toolbeltHandling = toolbeltHandling; + return this; } // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. // the only difference is calling getIngredient of this class. - public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { - initNeedsToolbeltHandlingHelper.set(false); - + public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHandling, boolean isClearing, + Object... recipe) { CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); int idx = 0; @@ -95,7 +106,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object for (; idx < recipe.length; idx += 2) { Character chr = (Character) recipe[idx]; Object in = recipe[idx + 1]; - Ingredient ing = getIngredient(isClearing, in); + Ingredient ing = getIngredient(toolbeltHandling, isClearing, in); if (' ' == chr) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); @@ -133,7 +144,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object return ret; } - protected static Ingredient getIngredient(boolean isClearing, Object obj) { + protected static Ingredient getIngredient(AtomicBoolean toolbeltHandling, boolean isClearing, Object obj) { if (obj instanceof Ingredient ing) return ing; else if (obj instanceof ItemStack stk) { if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { @@ -161,7 +172,7 @@ else if (obj instanceof Block blk) return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); else if (obj instanceof String str) { if (ItemGTToolbelt.isToolbeltableOredict(str)) - initNeedsToolbeltHandlingHelper.set(true); + toolbeltHandling.set(true); return new OreIngredient(str); } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index e0ceff95e51..fb620ea9927 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -15,6 +15,7 @@ import org.jetbrains.annotations.NotNull; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbeltSupportingRecipe { @@ -24,11 +25,10 @@ public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbel public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); - initNeedsToolbeltHandlingHelper.set(false); - this.isClearing = isClearing; + AtomicBoolean needsToolbelt = new AtomicBoolean(false); for (Object in : recipe) { - Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(needsToolbelt, isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -41,8 +41,7 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull throw new RuntimeException(ret.toString()); } } - this.toolbeltHandling = initNeedsToolbeltHandlingHelper.get(); - initNeedsToolbeltHandlingHelper.set(false); + this.toolbeltHandling = needsToolbelt.get(); } @Override From d85110e6b4150b00b7810f1666747eac47dfec90 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Tue, 4 Jun 2024 23:42:34 -0600 Subject: [PATCH 33/82] Oops --- .../java/gregtech/common/crafting/FluidReplaceRecipe.java | 4 +++- src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index 61733e309fd..5cfd1571d47 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -16,13 +16,15 @@ import org.jetbrains.annotations.NotNull; +import java.util.concurrent.atomic.AtomicBoolean; + /** * A recipe which inputs a single Fluid Container, and outputs the same Fluid Container with a new contained Fluid */ public class FluidReplaceRecipe extends GTShapedOreRecipe { public FluidReplaceRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { - super(isClearing, group, result, recipe); + super(new AtomicBoolean(false), isClearing, group, result, recipe); // there is no possible way that we require toolbelt handling, but make sure it isn't enabled. this.toolbeltHandling = false; } diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index c7b4f67bab5..3cf67667b5d 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -41,8 +41,8 @@ public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSuppo public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); - private GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, - @NotNull ItemStack result, Object... recipe) { + protected GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, + @NotNull ItemStack result, Object... recipe) { super(group, result, parseShaped(toolbeltHandling, isClearing, recipe)); this.isClearing = isClearing; } From edbe78f97663bcb3460d56d1da81b35f2d2690ed Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 11:02:10 -0600 Subject: [PATCH 34/82] Passthrough / toolbelt detection improvements --- .../gregtech/api/items/toolitem/IGTTool.java | 28 ++++++++-- .../api/items/toolitem/ItemGTToolbelt.java | 56 ++++++++++++++++--- .../api/items/toolitem/ToolHelper.java | 43 +++++++++++++- .../toolitem/behavior/IToolBehavior.java | 49 +++++++++++++--- .../gregtech/common/ToolEventHandlers.java | 5 ++ .../items/tool/BlockRotatingBehavior.java | 6 +- .../common/items/tool/GrassPathBehavior.java | 7 +-- .../items/tool/HarvestCropsBehavior.java | 7 +-- .../common/items/tool/HoeGroundBehavior.java | 7 +-- .../common/items/tool/PlungerBehavior.java | 6 +- .../common/items/tool/RotateRailBehavior.java | 6 +- .../common/items/tool/TorchPlaceBehavior.java | 7 +-- 12 files changed, 179 insertions(+), 48 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 94ae45effb9..bca752b4cab 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -636,8 +636,13 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand) == + if (behavior.onItemUseFirst(stack, player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } @@ -648,8 +653,14 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + ItemStack stack = player.getHeldItem(hand); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { + if (behavior.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ) == + EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } } @@ -659,20 +670,25 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default ActionResult definition$onItemRightClick(World world, EntityPlayer player, EnumHand hand) { ItemStack stack = player.getHeldItem(hand); + ItemStack original = stack; + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { PlayerInventoryHolder.openHandItemUI(player, hand); - return ActionResult.newResult(EnumActionResult.SUCCESS, stack); + return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } for (IToolBehavior behavior : getToolStats().getBehaviors()) { - if (behavior.onItemRightClick(world, player, hand).getType() == EnumActionResult.SUCCESS) { - return ActionResult.newResult(EnumActionResult.SUCCESS, stack); + if (behavior.onItemRightClick(stack, world, player, hand).getType() == EnumActionResult.SUCCESS) { + return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } - return ActionResult.newResult(EnumActionResult.PASS, stack); + return ActionResult.newResult(EnumActionResult.PASS, original); } default void definition$getSubItems(@NotNull NonNullList items) { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index c3d8668c511..f6558f46a48 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -5,6 +5,10 @@ import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.OreDictUnifier; +import gregtech.api.unification.material.Material; +import gregtech.api.unification.material.Materials; +import gregtech.api.unification.material.properties.PropertyKey; +import gregtech.api.unification.material.properties.ToolProperty; import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; @@ -25,6 +29,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; @@ -57,6 +62,8 @@ import java.util.Set; import java.util.function.Supplier; +import static gregtech.api.items.toolitem.ToolHelper.MATERIAL_KEY; + public class ItemGTToolbelt extends ItemGTTool { protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); @@ -236,9 +243,8 @@ public boolean isDamaged(@NotNull ItemStack stack) { public int getDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { - selected.getItemDamage(); - } - return super.getDamage(stack); + return selected.getItem().getDamage(selected); + } else return super.getDamage(stack); } @Override @@ -253,7 +259,7 @@ public int getMaxDamage(@NotNull ItemStack stack) { public void setDamage(@NotNull ItemStack stack, int damage) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { - selected.setItemDamage(damage); + selected.getItem().setDamage(selected, damage); } else super.setDamage(stack, damage); } @@ -261,7 +267,10 @@ public void setDamage(@NotNull ItemStack stack, int damage) { public double getDurabilityForDisplay(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (selected != null) { - return selected.getItem().getDurabilityForDisplay(selected); + double dis = selected.getItem().getDurabilityForDisplay(selected); + // vanillaesque tools need to be inverted + if (!(selected.getItem() instanceof IGTTool)) dis = 1 - dis; + return dis; } else return definition$getDurabilityForDisplay(stack); } @@ -321,6 +330,30 @@ public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack st } else return ToolHelper.isToolEffective(state, getToolClasses(stack), getTotalHarvestLevel(stack)); } + @Override + public void wrenchUsed(EntityPlayer player, EnumHand hand, ItemStack wrench, RayTraceResult rayTrace) { + ItemStack selected = getHandler(wrench).getSelectedStack(); + if (selected != null && selected.getItem() instanceof IGTTool tool) { + tool.wrenchUsed(player, hand, selected, rayTrace); + } else super.wrenchUsed(player, hand, wrench, rayTrace); + } + + @Override + public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { + ItemStack selected = getHandler(item).getSelectedStack(); + if (selected != null && selected.getItem() instanceof IGTTool tool) { + tool.toolUsed(selected, user, pos); + } else super.toolUsed(item, user, pos); + } + + @Override + public void used(@NotNull EnumHand hand, @NotNull EntityPlayer player, @NotNull BlockPos pos) { + ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); + if (selected != null && selected.getItem() instanceof IGTTool tool) { + tool.used(hand, player, pos); + } else super.used(hand, player, pos); + } + @Override public boolean hasContainerItem(@NotNull ItemStack stack) { return true; @@ -378,14 +411,23 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } - protected class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; private @Nullable ToolStackHandler handler; public ToolbeltCapabilityProvider(ItemStack stack) { - slotCountSupplier = () -> (int) (ItemGTToolbelt.super.getTotalHarvestLevel(stack) * 5.4f); + slotCountSupplier = () -> { + NBTTagCompound toolTag = stack.getOrCreateSubCompound(ToolHelper.TOOL_TAG_KEY); + String string = toolTag.getString(MATERIAL_KEY); + Material material = GregTechAPI.materialManager.getMaterial(string); + if (material == null) { + toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).toString()); + } + ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); + return (int) (toolProperty == null ? 5 : toolProperty.getToolHarvestLevel() * 5.4f); + }; } @Override diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index c4f92284be8..4d0803bccb1 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -184,10 +184,18 @@ public static void registerToolSymbol(Character symbol, IGTTool tool) { } public static NBTTagCompound getToolTag(ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } return stack.getOrCreateSubCompound(TOOL_TAG_KEY); } public static NBTTagCompound getBehaviorsTag(ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); } @@ -332,6 +340,10 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa */ public static void onActionDone(@NotNull EntityPlayer player, @NotNull World world, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } IGTTool tool = (IGTTool) stack.getItem(); ToolHelper.damageItem(stack, player); if (tool.getSound() != null) { @@ -375,6 +387,10 @@ public static boolean areTools(ItemStack tool, String... toolClasses) { * @return The level of Fortune or Looting that the tool is enchanted with, or zero */ public static int getFortuneOrLootingLevel(ItemStack tool) { + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } if (tool.getItem() instanceof ItemGTSword) { return EnchantmentHelper.getEnchantmentLevel(Enchantments.LOOTING, tool); } else if (tool.getItem() instanceof IGTTool) { @@ -396,6 +412,10 @@ public static AoESymmetrical getAoEDefinition(ItemStack stack) { * AoE Block Breaking Routine. */ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlayerMP player) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } int currentDurability = getToolTag(stack).getInteger(DURABILITY_KEY); int maximumDurability = getToolTag(stack).getInteger(MAX_DURABILITY_KEY); int remainingUses = maximumDurability - currentDurability; @@ -412,7 +432,11 @@ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlaye return true; } // If the tool is an electric tool, catch the tool breaking and cancel the remaining AOE - else if (!player.getHeldItemMainhand().isItemEqualIgnoreDurability(stack)) { + ItemStack tool = player.getHeldItemMainhand(); + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } else if (!tool.isItemEqualIgnoreDurability(stack)) { return true; } } @@ -424,6 +448,10 @@ else if (!player.getHeldItemMainhand().isItemEqualIgnoreDurability(stack)) { public static Set iterateAoE(ItemStack stack, AoESymmetrical aoeDefinition, World world, EntityPlayer player, RayTraceResult rayTraceResult, QuintFunction function) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } if (aoeDefinition != AoESymmetrical.none() && rayTraceResult != null && rayTraceResult.typeOfHit == RayTraceResult.Type.BLOCK && rayTraceResult.sideHit != null) { int column = aoeDefinition.column; @@ -671,9 +699,12 @@ public static void applyHammerDropConversion(ItemStack tool, IBlockState state, } } - @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { // This is *not* a vanilla/forge convention, Forge never added "shears" to ItemShear's tool classes. + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } if (isTool(tool, ToolClasses.SHEARS) && shearBlockRoutine(player, tool, pos) == 0) { return false; } @@ -722,6 +753,10 @@ public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, B */ public static int shearBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { if (!player.isCreative()) { + if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(tool); + if (selected != null) tool = selected; + } World world = player.world; IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IShearable) { @@ -780,6 +815,10 @@ public static ItemStack getSilkTouchDrop(@NotNull IBlockState state) { } public static void playToolSound(ItemStack stack, EntityPlayer player) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } if (stack.getItem() instanceof IGTTool) { ((IGTTool) stack.getItem()).playSound(player); } diff --git a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java index 4131cf59218..150900079be 100644 --- a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java +++ b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java @@ -78,6 +78,16 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving return false; } + /** + * Not itemstack sensitive. Use the new override. + */ + @Deprecated + default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { + return EnumActionResult.PASS; + } + /** * Called when a Block is right-clicked with this Item, but before the block is activated * @@ -90,15 +100,27 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving * @param hitZ the z location of the block hit * @param hand the hand holding the item */ - default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + default EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + return onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand); + } + + /** + * Not itemstack sensitive. Use the new override. + */ + @Deprecated + @NotNull + default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { return EnumActionResult.PASS; } /** * Called when a Block is right-clicked with this Item * + * @param stack the itemstack of the tool * @param player the player clicking with the item * @param world the world in which the block is clicked * @param pos the position of the blocked clicked @@ -109,10 +131,21 @@ default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull W * @param hitZ the z location of the block hit */ @NotNull - default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + default EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { - return EnumActionResult.PASS; + return onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } + + /** + * Not itemstack sensitive. Use the new override. + */ + @NotNull + @Deprecated + default ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { + return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); } /** @@ -123,9 +156,9 @@ default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World * @param hand the hand holding the item */ @NotNull - default ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); + default ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, + @NotNull EntityPlayer player, @NotNull EnumHand hand) { + return onItemRightClick(world, player, hand); } @SideOnly(Side.CLIENT) diff --git a/src/main/java/gregtech/common/ToolEventHandlers.java b/src/main/java/gregtech/common/ToolEventHandlers.java index 62195e49791..7d5577f4320 100644 --- a/src/main/java/gregtech/common/ToolEventHandlers.java +++ b/src/main/java/gregtech/common/ToolEventHandlers.java @@ -8,6 +8,7 @@ import gregtech.api.cover.CoverDefinition; import gregtech.api.cover.CoverHolder; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.metatileentity.MetaTileEntity; @@ -165,6 +166,10 @@ public static void onHarvestDrops(@NotNull BlockEvent.HarvestDropsEvent event) { // only try once, so future water placement does not get eaten too return false; }); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } ((IGTTool) stack.getItem()).playSound(player); } } diff --git a/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java b/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java index acd60d1324a..143371982c3 100644 --- a/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java +++ b/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java @@ -33,9 +33,9 @@ public class BlockRotatingBehavior implements IToolBehavior { protected BlockRotatingBehavior() {/**/} @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing side, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing side, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { TileEntity te = world.getTileEntity(pos); // MTEs have special handling on rotation if (te instanceof IGregTechTileEntity) { diff --git a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java index 4dc960a6a3f..111bc9855ce 100644 --- a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java +++ b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java @@ -34,12 +34,11 @@ protected GrassPathBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; - ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java index d1ac7a4be93..353d0427d19 100644 --- a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java @@ -36,13 +36,12 @@ protected HarvestCropsBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { if (world.isRemote) { return EnumActionResult.PASS; } - ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); diff --git a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java index 36477d16801..fe05dabdc67 100644 --- a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java @@ -41,12 +41,11 @@ protected HoeGroundBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; - ItemStack stack = player.getHeldItem(hand); AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/PlungerBehavior.java b/src/main/java/gregtech/common/items/tool/PlungerBehavior.java index 609e429e0c0..2d6fdc3eab8 100644 --- a/src/main/java/gregtech/common/items/tool/PlungerBehavior.java +++ b/src/main/java/gregtech/common/items/tool/PlungerBehavior.java @@ -32,9 +32,9 @@ public class PlungerBehavior implements IToolBehavior { protected PlungerBehavior() {/**/} @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { IFluidHandler fluidHandler = FluidUtil.getFluidHandler(world, pos, facing); if (fluidHandler == null) { return EnumActionResult.PASS; diff --git a/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java b/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java index 19985d1459e..cac327cd442 100644 --- a/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java +++ b/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java @@ -29,9 +29,9 @@ protected RotateRailBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, + @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof BlockRailBase) { if (world.setBlockState(pos, state.withRotation(Rotation.CLOCKWISE_90))) { diff --git a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java index d9d5f86ef69..2965a1ad56d 100644 --- a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java +++ b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java @@ -37,10 +37,9 @@ protected TorchPlaceBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { - ItemStack stack = player.getHeldItem(hand); + public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, + float hitX, float hitY, float hitZ) { NBTTagCompound behaviourTag = ToolHelper.getBehaviorsTag(stack); if (behaviourTag.getBoolean(ToolHelper.TORCH_PLACING_KEY)) { int cachedTorchSlot; From 002074f3a7eb780bacf3e0e92f7615f774ef4f72 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 11:47:47 -0600 Subject: [PATCH 35/82] Prevent unexpected behavior on removal of selected tool --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index f6558f46a48..94fbb4f414d 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -100,8 +100,11 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) slotGroupWidget.flex().endDefaultMode(); slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { + int finalI = i; slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group)) + .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group) + .changeListener((newItem, onlyAmountChanged, client, init) -> + handler.onContentsChanged(finalI))) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); @@ -526,6 +529,7 @@ public boolean isItemValid(int slot, @NotNull ItemStack stack) { @Override protected void onContentsChanged(int slot) { + if (this.selectedSlot != null && this.selectedSlot == slot) this.selectedSlot = null; this.updateSlot(slot); this.update(); From 6d2716d3a3829d8fa7f42ca19ac2d50422a22942 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 12:50:00 -0600 Subject: [PATCH 36/82] Better toolbelt GUI handling --- .../gregtech/api/items/toolitem/IGTTool.java | 16 +++++-- .../api/items/toolitem/ItemGTToolbelt.java | 48 +++---------------- .../java/gregtech/common/items/ToolItems.java | 2 +- .../common/items/tool/OpenGUIBehavior.java | 31 ++++++++++++ 4 files changed, 52 insertions(+), 45 deletions(-) create mode 100644 src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index bca752b4cab..b071dbfca59 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -641,7 +641,10 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { ItemStack selected = toolbelt.getSelectedItem(stack); if (selected != null) stack = selected; } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + List behaviors; + if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); + else behaviors = getToolStats().getBehaviors(); + for (IToolBehavior behavior : behaviors) { if (behavior.onItemUseFirst(stack, player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -658,7 +661,11 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { ItemStack selected = toolbelt.getSelectedItem(stack); if (selected != null) stack = selected; } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + List behaviors; + if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); + else behaviors = getToolStats().getBehaviors(); + + for (IToolBehavior behavior : behaviors) { if (behavior.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -682,8 +689,11 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } + List behaviors; + if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); + else behaviors = getToolStats().getBehaviors(); - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + for (IToolBehavior behavior : behaviors) { if (behavior.onItemRightClick(stack, world, player, hand).getType() == EnumActionResult.SUCCESS) { return ActionResult.newResult(EnumActionResult.SUCCESS, original); } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 94fbb4f414d..51e583ce54f 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.GregTechAPI; +import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.OreDictUnifier; @@ -13,6 +14,7 @@ import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; @@ -70,9 +72,9 @@ public class ItemGTToolbelt extends ItemGTTool { private final ItemStack orestack; - public ItemGTToolbelt(String domain, String id, Supplier markerItem) { - super(domain, id, -1, new ToolDefinitionBuilder().cannotAttack().attackSpeed(-2.4F).build(), null, - false, new HashSet<>(), "", new ArrayList<>(), + public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { + super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), + null, false, new HashSet<>(), "", new ArrayList<>(), markerItem); this.orestack = new ItemStack(this, 1, GTValues.W); } @@ -277,44 +279,6 @@ public double getDurabilityForDisplay(@NotNull ItemStack stack) { } else return definition$getDurabilityForDisplay(stack); } - @NotNull - @Override - public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing side, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { - ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null) { - return selected.getItem().onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); - } else return definition$onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); - } - - @NotNull - @Override - public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { - ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null) { - return selected.getItem().onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); - } else return definition$onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); - } - - @Override - public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - if (player.isSneaking()) { - if (!world.isRemote) { - ItemGuiFactory.open((EntityPlayerMP) player, hand); - } - return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); - } else { - ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null) { - return selected.getItem().onItemRightClick(world, player, hand); - } else return definition$onItemRightClick(world, player, hand); - } - } - @Override @SideOnly(Side.CLIENT) public void addInformation(@NotNull ItemStack stack, @Nullable World world, @NotNull List tooltip, @@ -414,6 +378,8 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } + //TODO BEWLR for dynamic display of selected item? + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 04c6a0e7f79..5796d85c25c 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -68,7 +68,7 @@ public static List getAllTools() { public static void init() { TOOLBELT = (ItemGTToolbelt) register(new ItemGTToolbelt(GTValues.MODID, "toolbelt", - null)); + null, OpenGUIBehavior.INSTANCE)); SWORD = register(ItemGTSword.Builder.of(GTValues.MODID, "sword") .toolStats(b -> b.attacking() .attackDamage(3.0F).attackSpeed(-2.4F)) diff --git a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java new file mode 100644 index 00000000000..bc098cfea86 --- /dev/null +++ b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java @@ -0,0 +1,31 @@ +package gregtech.common.items.tool; + +import com.cleanroommc.modularui.factory.ItemGuiFactory; + +import gregtech.api.items.toolitem.behavior.IToolBehavior; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; + +public class OpenGUIBehavior implements IToolBehavior { + + public static final OpenGUIBehavior INSTANCE = new OpenGUIBehavior(); + + protected OpenGUIBehavior() {} + + @Override + public @NotNull ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, + @NotNull EntityPlayer player, @NotNull EnumHand hand) { + if (!world.isRemote) { + ItemGuiFactory.open((EntityPlayerMP) player, hand); + } + return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); + } +} From 86c5b20cbbda9044c5926c7b68bc1c5075eb896c Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 14:51:40 -0600 Subject: [PATCH 37/82] mui2 (pain) --- .../gregtech/api/items/toolitem/IGTTool.java | 139 +++++++++++++----- .../api/items/toolitem/ItemGTToolbelt.java | 6 + .../api/items/toolitem/ToolHelper.java | 8 + .../java/gregtech/api/mui/GTGuiTextures.java | 2 + .../gregtech/api/mui/sync/NBTSyncValue.java | 59 ++++++++ 5 files changed, 174 insertions(+), 40 deletions(-) create mode 100644 src/main/java/gregtech/api/mui/sync/NBTSyncValue.java diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index b071dbfca59..756b1c01175 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -1,5 +1,21 @@ package gregtech.api.items.toolitem; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; + +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; + +import com.cleanroommc.modularui.value.sync.SyncHandler; +import com.cleanroommc.modularui.value.sync.SyncHandlers; +import com.cleanroommc.modularui.widget.sizer.Unit; +import com.cleanroommc.modularui.widgets.ButtonWidget; +import com.cleanroommc.modularui.widgets.TextWidget; + +import com.cleanroommc.modularui.widgets.layout.Column; + import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.capability.GregtechCapabilities; @@ -9,11 +25,15 @@ import gregtech.api.gui.ModularUI; import gregtech.api.gui.widgets.ClickButtonWidget; import gregtech.api.gui.widgets.DynamicLabelWidget; +import gregtech.api.gui.widgets.LabelWidget; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.gui.PlayerInventoryHolder; import gregtech.api.items.metaitem.ElectricStats; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.items.toolitem.behavior.IToolBehavior; +import gregtech.api.mui.GTGuiTextures; +import gregtech.api.mui.GTGuis; +import gregtech.api.mui.sync.NBTSyncValue; import gregtech.api.recipes.ModHandler; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Material; @@ -685,7 +705,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { - PlayerInventoryHolder.openHandItemUI(player, hand); + ItemGuiFactory.open((EntityPlayerMP) player, hand); return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } @@ -929,45 +949,84 @@ default void playSound(EntityPlayer player) { } } - default ModularUI createUI(PlayerInventoryHolder holder, EntityPlayer entityPlayer) { - NBTTagCompound tag = getBehaviorsTag(holder.getCurrentItem()); - AoESymmetrical defaultDefinition = getMaxAoEDefinition(holder.getCurrentItem()); - return ModularUI.builder(GuiTextures.BORDERED_BACKGROUND, 120, 80) - .label(6, 10, "item.gt.tool.aoe.columns") - .label(49, 10, "item.gt.tool.aoe.rows") - .label(79, 10, "item.gt.tool.aoe.layers") - .widget(new ClickButtonWidget(15, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseColumn(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(15, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseColumn(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(50, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseRow(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(50, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseRow(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(85, 24, 20, 20, "+", data -> { - AoESymmetrical.increaseLayer(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new ClickButtonWidget(85, 44, 20, 20, "-", data -> { - AoESymmetrical.decreaseLayer(tag, defaultDefinition); - holder.markAsDirty(); - })) - .widget(new DynamicLabelWidget(23, 65, () -> Integer.toString( - 1 + 2 * AoESymmetrical.getColumn(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .widget(new DynamicLabelWidget(58, 65, () -> Integer.toString( - 1 + 2 * AoESymmetrical.getRow(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .widget(new DynamicLabelWidget(93, 65, - () -> Integer.toString(1 + - AoESymmetrical.getLayer(getBehaviorsTag(holder.getCurrentItem()), defaultDefinition)))) - .build(holder, entityPlayer); + @Override + default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { + ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 120, 80); + + Supplier tag = () -> getBehaviorsTag(guiData.getUsedItemStack()); + AoESymmetrical defaultDefinition = getMaxAoEDefinition(guiData.getUsedItemStack()); + + NBTSyncValue nbtSyncer = new NBTSyncValue(tag, (nbt) -> setBehaviorsTag(guiData.getUsedItemStack(), nbt)); + guiSyncManager.syncValue("NBTSync", nbtSyncer); + + Column columns = new Column(); + columns.flex().coverChildren().startDefaultMode() + .leftRel(0.07f).bottomRel(0.5f).endDefaultMode(); + columns.child(new TextWidget(IKey.lang("item.gt.tool.aoe.columns")).paddingBottom(5)); + columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.increaseColumn(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.decreaseColumn(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + columns.child(new TextWidget(IKey.dynamic(() -> + String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))).paddingTop(5)); + panel.child(columns); + + Column rows = new Column(); + rows.flex().coverChildren().startDefaultMode() + .rightRel(0.5f).bottomRel(0.5f).endDefaultMode(); + rows.child(new TextWidget(IKey.lang("item.gt.tool.aoe.rows")).paddingBottom(5)); + rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.increaseRow(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.decreaseRow(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + rows.child(new TextWidget(IKey.dynamic(() -> + String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))).paddingTop(5)); + panel.child(rows); + + Column layers = new Column(); + layers.flex().coverChildren().startDefaultMode() + .rightRel(0.07f).bottomRel(0.5f).endDefaultMode(); + layers.child(new TextWidget(IKey.lang("item.gt.tool.aoe.layers")).paddingBottom(5)); + layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.increaseLayer(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) + .disableHoverBackground().onMousePressed( data -> { + NBTTagCompound nbt = tag.get(); + AoESymmetrical.decreaseLayer(nbt, defaultDefinition); + nbtSyncer.setValue(nbt, true); + return true; + })); + layers.child(new TextWidget(IKey.dynamic(() -> + String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))).paddingTop(5)); + panel.child(layers); + + + return panel; } Set getToolClasses(ItemStack stack); diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 51e583ce54f..d67de8697c4 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.GregTechAPI; +import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; @@ -86,6 +87,11 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem, @Override public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); + ItemStack selected = handler.getSelectedStack(); + if (selected != null && selected.getItem() instanceof ItemUIFactory factory) { + return factory.buildUI(guiData, guiSyncManager); + } + int heightBonus = (handler.getSlots() / 9) * 18; ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 4d0803bccb1..e5dfb9774e1 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -199,6 +199,14 @@ public static NBTTagCompound getBehaviorsTag(ItemStack stack) { return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); } + public static void setBehaviorsTag(ItemStack stack, NBTTagCompound tag) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } + stack.setTagInfo(BEHAVIOURS_TAG_KEY, tag); + } + public static ItemStack getAndSetToolData(IGTTool tool, Material material, int maxDurability, int harvestLevel, float toolSpeed, float attackDamage) { ItemStack stack = tool.getRaw(); diff --git a/src/main/java/gregtech/api/mui/GTGuiTextures.java b/src/main/java/gregtech/api/mui/GTGuiTextures.java index f17affee609..140333f39bb 100644 --- a/src/main/java/gregtech/api/mui/GTGuiTextures.java +++ b/src/main/java/gregtech/api/mui/GTGuiTextures.java @@ -351,6 +351,8 @@ public static class IDs { public static final UITexture BUTTON_CROSS = fullImage("textures/gui/widget/button_cross.png"); public static final UITexture BUTTON_REDSTONE_ON = fullImage("textures/gui/widget/button_redstone_on.png"); public static final UITexture BUTTON_REDSTONE_OFF = fullImage("textures/gui/widget/button_redstone_off.png"); + public static final UITexture BUTTON_THROTTLE_PLUS = fullImage("textures/gui/widget/button_throttle_plus.png"); + public static final UITexture BUTTON_THROTTLE_MINUS = fullImage("textures/gui/widget/button_throttle_minus.png"); // PROGRESS BARS public static final UITexture PROGRESS_BAR_ARC_FURNACE = progressBar( diff --git a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java new file mode 100644 index 00000000000..4ac8c24436f --- /dev/null +++ b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java @@ -0,0 +1,59 @@ +package gregtech.api.mui.sync; + +import com.cleanroommc.modularui.value.sync.ValueSyncHandler; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.PacketBuffer; + +import java.io.IOException; +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Supplier; + +public class NBTSyncValue extends ValueSyncHandler { + + private final Supplier getter; + private final Consumer setter; + private NBTTagCompound cache; + + public NBTSyncValue(Supplier getter, Consumer setter) { + this.getter = getter; + this.setter = setter; + this.cache = getter.get(); + } + + @Override + public void setValue(NBTTagCompound value, boolean setSource, boolean sync) { + this.cache = value; + if (setSource && this.setter != null) { + this.setter.accept(value); + } + if (sync) { + sync(0, this::write); + } + } + + @Override + public boolean updateCacheFromSource(boolean isFirstSync) { + if (isFirstSync || !Objects.equals(this.getter.get(), this.cache)) { + setValue(this.getter.get(), false, false); + return true; + } + return false; + } + + @Override + public void write(PacketBuffer buffer) throws IOException { + buffer.writeCompoundTag(getValue()); + } + + @Override + public void read(PacketBuffer buffer) throws IOException { + setValue(buffer.readCompoundTag()); + } + + @Override + public NBTTagCompound getValue() { + return this.cache; + } +} From 1d69ba1f48aef76f51fb188d3fae68db9bd1e194 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 14:58:16 -0600 Subject: [PATCH 38/82] sp3tless --- .../gregtech/api/items/toolitem/IGTTool.java | 58 ++++++++----------- .../api/items/toolitem/ItemGTToolbelt.java | 14 ++--- .../gregtech/api/mui/sync/NBTSyncValue.java | 4 +- .../common/items/tool/OpenGUIBehavior.java | 3 +- 4 files changed, 31 insertions(+), 48 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 756b1c01175..649c1e894e6 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -1,33 +1,11 @@ package gregtech.api.items.toolitem; -import com.cleanroommc.modularui.api.drawable.IKey; -import com.cleanroommc.modularui.factory.HandGuiData; -import com.cleanroommc.modularui.factory.ItemGuiFactory; - -import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.utils.Alignment; -import com.cleanroommc.modularui.value.sync.GuiSyncManager; - -import com.cleanroommc.modularui.value.sync.SyncHandler; -import com.cleanroommc.modularui.value.sync.SyncHandlers; -import com.cleanroommc.modularui.widget.sizer.Unit; -import com.cleanroommc.modularui.widgets.ButtonWidget; -import com.cleanroommc.modularui.widgets.TextWidget; - -import com.cleanroommc.modularui.widgets.layout.Column; - import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.impl.CombinedCapabilityProvider; import gregtech.api.capability.impl.ElectricItem; -import gregtech.api.gui.GuiTextures; -import gregtech.api.gui.ModularUI; -import gregtech.api.gui.widgets.ClickButtonWidget; -import gregtech.api.gui.widgets.DynamicLabelWidget; -import gregtech.api.gui.widgets.LabelWidget; import gregtech.api.items.gui.ItemUIFactory; -import gregtech.api.items.gui.PlayerInventoryHolder; import gregtech.api.items.metaitem.ElectricStats; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.items.toolitem.behavior.IToolBehavior; @@ -83,6 +61,14 @@ import appeng.api.implementations.items.IAEWrench; import buildcraft.api.tools.IToolWrench; import cofh.api.item.IToolHammer; +import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.factory.HandGuiData; +import com.cleanroommc.modularui.factory.ItemGuiFactory; +import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.value.sync.GuiSyncManager; +import com.cleanroommc.modularui.widgets.ButtonWidget; +import com.cleanroommc.modularui.widgets.TextWidget; +import com.cleanroommc.modularui.widgets.layout.Column; import com.enderio.core.common.interfaces.IOverlayRenderAware; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; @@ -964,21 +950,22 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) .leftRel(0.07f).bottomRel(0.5f).endDefaultMode(); columns.child(new TextWidget(IKey.lang("item.gt.tool.aoe.columns")).paddingBottom(5)); columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.increaseColumn(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.decreaseColumn(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); - columns.child(new TextWidget(IKey.dynamic(() -> - String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))).paddingTop(5)); + columns.child(new TextWidget( + IKey.dynamic(() -> String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))) + .paddingTop(5)); panel.child(columns); Column rows = new Column(); @@ -986,21 +973,22 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) .rightRel(0.5f).bottomRel(0.5f).endDefaultMode(); rows.child(new TextWidget(IKey.lang("item.gt.tool.aoe.rows")).paddingBottom(5)); rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.increaseRow(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.decreaseRow(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); - rows.child(new TextWidget(IKey.dynamic(() -> - String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))).paddingTop(5)); + rows.child(new TextWidget( + IKey.dynamic(() -> String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))) + .paddingTop(5)); panel.child(rows); Column layers = new Column(); @@ -1008,24 +996,24 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) .rightRel(0.07f).bottomRel(0.5f).endDefaultMode(); layers.child(new TextWidget(IKey.lang("item.gt.tool.aoe.layers")).paddingBottom(5)); layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.increaseLayer(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed( data -> { + .disableHoverBackground().onMousePressed(data -> { NBTTagCompound nbt = tag.get(); AoESymmetrical.decreaseLayer(nbt, defaultDefinition); nbtSyncer.setValue(nbt, true); return true; })); - layers.child(new TextWidget(IKey.dynamic(() -> - String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))).paddingTop(5)); + layers.child(new TextWidget( + IKey.dynamic(() -> String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))) + .paddingTop(5)); panel.child(layers); - return panel; } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index d67de8697c4..78fab137b2e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -15,20 +15,16 @@ import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; @@ -44,7 +40,6 @@ import net.minecraftforge.items.ItemStackHandler; import com.cleanroommc.modularui.factory.HandGuiData; -import com.cleanroommc.modularui.factory.ItemGuiFactory; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.value.sync.GuiSyncManager; import com.cleanroommc.modularui.value.sync.SyncHandlers; @@ -74,7 +69,8 @@ public class ItemGTToolbelt extends ItemGTTool { private final ItemStack orestack; public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { - super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), + super(domain, id, -1, + new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), null, false, new HashSet<>(), "", new ArrayList<>(), markerItem); this.orestack = new ItemStack(this, 1, GTValues.W); @@ -111,8 +107,8 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) int finalI = i; slotGroupWidget.child(new ItemSlot() .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group) - .changeListener((newItem, onlyAmountChanged, client, init) -> - handler.onContentsChanged(finalI))) + .changeListener( + (newItem, onlyAmountChanged, client, init) -> handler.onContentsChanged(finalI))) .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) .pos(i % 9 * 18, i / 9 * 18) .debugName("slot_" + i)); @@ -384,7 +380,7 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } - //TODO BEWLR for dynamic display of selected item? + // TODO BEWLR for dynamic display of selected item? protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { diff --git a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java index 4ac8c24436f..a9f0dd6c97a 100644 --- a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java +++ b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java @@ -1,10 +1,10 @@ package gregtech.api.mui.sync; -import com.cleanroommc.modularui.value.sync.ValueSyncHandler; - import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; +import com.cleanroommc.modularui.value.sync.ValueSyncHandler; + import java.io.IOException; import java.util.Objects; import java.util.function.Consumer; diff --git a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java index bc098cfea86..0697f47ec6f 100644 --- a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java +++ b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java @@ -1,7 +1,5 @@ package gregtech.common.items.tool; -import com.cleanroommc.modularui.factory.ItemGuiFactory; - import gregtech.api.items.toolitem.behavior.IToolBehavior; import net.minecraft.entity.player.EntityPlayer; @@ -12,6 +10,7 @@ import net.minecraft.util.EnumHand; import net.minecraft.world.World; +import com.cleanroommc.modularui.factory.ItemGuiFactory; import org.jetbrains.annotations.NotNull; public class OpenGUIBehavior implements IToolBehavior { From 48f543f997bef3dabae21d931446c5e85fee2907 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 17:07:36 -0600 Subject: [PATCH 39/82] improve a fallback --- src/main/java/gregtech/api/items/toolitem/IGTTool.java | 4 ++++ .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 5 ----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 649c1e894e6..9e10e9b0c7e 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -910,6 +910,10 @@ default ModelResourceLocation getModelLocation() { // Sound Playing default void playCraftingSound(EntityPlayer player, ItemStack stack) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) stack = selected; + } // player null check for things like auto-crafters if (ConfigHolder.client.toolCraftingSounds && getSound() != null && player != null) { if (canPlaySound(stack)) { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 78fab137b2e..744925c811a 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -328,11 +328,6 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { return true; } - @Override - public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { - return stack.copy(); - } - public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, @Nullable EntityPlayer entityPlayer) { return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); From 05f423d10b0c757058a9a08538ae41aa5d9d40d1 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 18:25:26 -0600 Subject: [PATCH 40/82] I'm dyeing --- .../java/gregtech/api/items/IDyeableItem.java | 62 ++++++++ .../api/items/toolitem/ItemGTToolbelt.java | 42 +++++- .../common/crafting/DyeableRecipes.java | 135 ++++++++++++++++++ .../loaders/recipe/GTRecipeManager.java | 3 + .../textures/items/tools/toolbelt_belt.png | Bin 192 -> 159 bytes 5 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 src/main/java/gregtech/api/items/IDyeableItem.java create mode 100644 src/main/java/gregtech/common/crafting/DyeableRecipes.java diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java new file mode 100644 index 00000000000..0497bf30fa0 --- /dev/null +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -0,0 +1,62 @@ +package gregtech.api.items; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Note - users of this interface will have to deal with cauldron dye clearing on their own. + */ +public interface IDyeableItem { + + default boolean hasColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + return nbttagcompound != null && nbttagcompound.hasKey("display", 10) && + nbttagcompound.getCompoundTag("display").hasKey("color", 3); + } + + default int getColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); + if (nbttagcompound1.hasKey("color", 3)) { + return nbttagcompound1.getInteger("color"); + } + } + return getDefaultColor(stack); + } + + default int getDefaultColor(ItemStack stack) { + return 0xFFFFFF; + } + + default void removeColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); + if (nbttagcompound1.hasKey("color")) { + nbttagcompound1.removeTag("color"); + } + } + } + + default void setColor(ItemStack stack, int color) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + if (nbttagcompound == null) { + nbttagcompound = new NBTTagCompound(); + stack.setTagCompound(nbttagcompound); + } + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); + if (!nbttagcompound.hasKey("display", 10)) { + nbttagcompound.setTag("display", nbttagcompound1); + } + nbttagcompound1.setInteger("color", color); + } + + /** + * Controls whether the dyeing recipe simply removes the dyeable item from the crafting grid, + * or calls {@link net.minecraftforge.common.ForgeHooks#getContainerItem(ItemStack)} on it. + */ + default boolean shouldGetContainerItem() { + return true; + } +} diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 744925c811a..64d8c5010d3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -2,6 +2,7 @@ import gregtech.api.GTValues; import gregtech.api.GregTechAPI; +import gregtech.api.items.IDyeableItem; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; @@ -14,6 +15,7 @@ import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; +import net.minecraft.block.BlockCauldron; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; @@ -25,6 +27,7 @@ import net.minecraft.item.ItemTool; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; @@ -62,7 +65,7 @@ import static gregtech.api.items.toolitem.ToolHelper.MATERIAL_KEY; -public class ItemGTToolbelt extends ItemGTTool { +public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); @@ -375,6 +378,43 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { selectedToolDisplay); } + @Override + public @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (this.hasColor(stack)) { + IBlockState iblockstate = world.getBlockState(pos); + if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { + int water = iblockstate.getValue(BlockCauldron.LEVEL); + if (water > 0) { + this.removeColor(stack); + cauldron.setWaterLevel(world, pos, iblockstate, water - 1); + return EnumActionResult.SUCCESS; + } + } + } + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + } + + @Override + public int getColor(ItemStack stack, int tintIndex) { + if (tintIndex == 0) { + return this.getColor(stack); + } + return super.getColor(stack, tintIndex); + } + + @Override + public int getDefaultColor(ItemStack stack) { + return 0xA06540; + } + + @Override + public boolean shouldGetContainerItem() { + return false; + } + // TODO BEWLR for dynamic display of selected item? protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { diff --git a/src/main/java/gregtech/common/crafting/DyeableRecipes.java b/src/main/java/gregtech/common/crafting/DyeableRecipes.java new file mode 100644 index 00000000000..6dd590ce922 --- /dev/null +++ b/src/main/java/gregtech/common/crafting/DyeableRecipes.java @@ -0,0 +1,135 @@ +package gregtech.common.crafting; + +import gregtech.api.items.IDyeableItem; + +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.RecipesArmorDyes; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; + +import com.google.common.collect.Lists; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public final class DyeableRecipes extends RecipesArmorDyes { + + @ApiStatus.Internal + public DyeableRecipes() { + this.setRegistryName("gt_dyeable_dyeing"); + } + + /** + * Used to check if a recipe matches current crafting inventory + */ + @Override + public boolean matches(InventoryCrafting inv, @NotNull World worldIn) { + ItemStack itemstack = ItemStack.EMPTY; + List list = Lists.newArrayList(); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { + ItemStack itemstack1 = inv.getStackInSlot(i); + + if (!itemstack1.isEmpty()) { + if (itemstack1.getItem() instanceof IDyeableItem) { + if (!itemstack.isEmpty()) { + return false; + } + + itemstack = itemstack1; + } else { + if (!net.minecraftforge.oredict.DyeUtils.isDye(itemstack1)) { + return false; + } + + list.add(itemstack1); + } + } + } + + return !itemstack.isEmpty() && !list.isEmpty(); + } + + /** + * Returns an Item that is the result of this recipe + */ + @Override + public @NotNull ItemStack getCraftingResult(InventoryCrafting inv) { + ItemStack itemstack = ItemStack.EMPTY; + int[] aint = new int[3]; + int i = 0; + int j = 0; + IDyeableItem dyeable = null; + + for (int k = 0; k < inv.getSizeInventory(); ++k) { + ItemStack itemstack1 = inv.getStackInSlot(k); + + if (!itemstack1.isEmpty()) { + if (itemstack1.getItem() instanceof IDyeableItem) { + dyeable = (IDyeableItem) itemstack1.getItem(); + + itemstack = itemstack1.copy(); + itemstack.setCount(1); + + if (dyeable.hasColor(itemstack1)) { + int l = dyeable.getColor(itemstack); + float f = (float) (l >> 16 & 255) / 255.0F; + float f1 = (float) (l >> 8 & 255) / 255.0F; + float f2 = (float) (l & 255) / 255.0F; + i = (int) ((float) i + Math.max(f, Math.max(f1, f2)) * 255.0F); + aint[0] = (int) ((float) aint[0] + f * 255.0F); + aint[1] = (int) ((float) aint[1] + f1 * 255.0F); + aint[2] = (int) ((float) aint[2] + f2 * 255.0F); + ++j; + } + } else { + if (!net.minecraftforge.oredict.DyeUtils.isDye(itemstack1)) { + return ItemStack.EMPTY; + } + + float[] afloat = net.minecraftforge.oredict.DyeUtils.colorFromStack(itemstack1).get() + .getColorComponentValues(); + int l1 = (int) (afloat[0] * 255.0F); + int i2 = (int) (afloat[1] * 255.0F); + int j2 = (int) (afloat[2] * 255.0F); + i += Math.max(l1, Math.max(i2, j2)); + aint[0] += l1; + aint[1] += i2; + aint[2] += j2; + ++j; + } + } + } + + if (dyeable == null) { + return ItemStack.EMPTY; + } else { + int i1 = aint[0] / j; + int j1 = aint[1] / j; + int k1 = aint[2] / j; + float f3 = (float) i / (float) j; + float f4 = (float) Math.max(i1, Math.max(j1, k1)); + i1 = (int) ((float) i1 * f3 / f4); + j1 = (int) ((float) j1 * f3 / f4); + k1 = (int) ((float) k1 * f3 / f4); + int k2 = (i1 << 8) + j1; + k2 = (k2 << 8) + k1; + dyeable.setColor(itemstack, k2); + return itemstack; + } + } + + public NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList nonnulllist = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + + for (int i = 0; i < nonnulllist.size(); ++i) { + ItemStack itemstack = inv.getStackInSlot(i); + if (!(itemstack.getItem() instanceof IDyeableItem item && !item.shouldGetContainerItem())) + nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack)); + } + + return nonnulllist; + } +} diff --git a/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java b/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java index e91a9bd2c7a..2b757b217c1 100644 --- a/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java +++ b/src/main/java/gregtech/loaders/recipe/GTRecipeManager.java @@ -1,11 +1,13 @@ package gregtech.loaders.recipe; import gregtech.api.event.MaterialInfoEvent; +import gregtech.common.crafting.DyeableRecipes; import gregtech.loaders.recipe.handlers.DecompositionRecipeHandler; import gregtech.loaders.recipe.handlers.RecipeHandlerList; import gregtech.loaders.recipe.handlers.ToolRecipeHandler; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.registry.ForgeRegistries; public final class GTRecipeManager { @@ -21,6 +23,7 @@ public static void load() { MetaTileEntityLoader.init(); MetaTileEntityMachineRecipeLoader.init(); RecipeHandlerList.register(); + ForgeRegistries.RECIPES.register(new DyeableRecipes()); } public static void loadLatest() { diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png index b8e9021431ea0046ebe5743d23bac2ec3bfa687a..b703b955e156fcd5574aa175e1e92dbdcfd7ad4f 100644 GIT binary patch delta 130 zcmV-|0Db?!0iOYoBztB_L_t(IjqQ%T5x^h_g`amB#DN&W5$vcPff48!%+@JPg%=8& zG)duCaqxZs4nKjJCo|7C`pcI@1Q7|Mr%6PT&$U*x*02J`7*N&FLPW?pqxbFs>*i(v kNZ3$H2_Kl*R(trG8;uGgMEn)#zW@LL07*qoM6N<$f<$>Ywg3PC delta 164 zcmV;V09*f`0l)!}B!2;OQb$4nuFf3k0001ZNkl$hQm)jFoHGM$_Rj601|*{ znCGeWUqhIi;l|sqU?F6~k=5gLGE5Q7KxD&_(+*L7#+TSe4IO|cBua8507o(^5v=$r SxBvhE07*qoM6N<$f&c(6{6V__ From 93e17bab32a1fa1d2ba2c73180c9ae46c0ec3022 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 18:36:22 -0600 Subject: [PATCH 41/82] improve passthrough --- .../java/gregtech/client/utils/ToolChargeBarRenderer.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java index de982d07450..345255d627b 100644 --- a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java +++ b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java @@ -5,6 +5,7 @@ import gregtech.api.items.metaitem.MetaItem; import gregtech.api.items.metaitem.stats.IItemDurabilityManager; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.util.GTUtility; @@ -113,6 +114,13 @@ private static void overpaintVanillaRenderBug(BufferBuilder worldrenderer, int x } public static void renderBarsTool(IGTTool tool, ItemStack stack, int xPosition, int yPosition) { + if (tool instanceof ItemGTToolbelt toolbelt) { + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null && selected.getItem() instanceof IGTTool toool) { + tool = toool; + stack = selected; + } + } boolean renderedDurability = false; NBTTagCompound tag = GTUtility.getOrCreateNbtCompound(stack); if (!tag.getBoolean(ToolHelper.UNBREAKABLE_KEY)) { From d7d29f4cac818726dfba323c67041ed94d8d6952 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 20:27:08 -0600 Subject: [PATCH 42/82] More universal solution to toolbelt crafting --- .../crafting/IToolbeltSupportingRecipe.java | 43 -------------- .../api/items/toolitem/ItemGTToolbelt.java | 23 ++++++-- .../java/gregtech/api/recipes/ModHandler.java | 2 +- .../gregtech/asm/GregTechTransformer.java | 14 +++++ .../asm/hooks/OreIngredientHooks.java | 25 +++++++++ .../asm/visitors/OreIngredientVisitor.java | 52 +++++++++++++++++ .../common/crafting/FluidReplaceRecipe.java | 4 +- .../common/crafting/GTShapedOreRecipe.java | 56 +++---------------- .../common/crafting/GTShapelessOreRecipe.java | 43 ++------------ 9 files changed, 122 insertions(+), 140 deletions(-) delete mode 100644 src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java create mode 100644 src/main/java/gregtech/asm/hooks/OreIngredientHooks.java create mode 100644 src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java diff --git a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java b/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java deleted file mode 100644 index c4d050e2082..00000000000 --- a/src/main/java/gregtech/api/crafting/IToolbeltSupportingRecipe.java +++ /dev/null @@ -1,43 +0,0 @@ -package gregtech.api.crafting; - -import gregtech.api.items.toolitem.ItemGTToolbelt; - -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.item.crafting.Ingredient; -import net.minecraft.util.NonNullList; -import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.common.util.RecipeMatcher; - -import org.jetbrains.annotations.NotNull; - -public interface IToolbeltSupportingRecipe extends IRecipe { - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - static boolean toolbeltIngredientCheck(Ingredient ingredient, ItemStack stack) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) - return toolbelt.supportsIngredient(stack, ingredient); - else return ingredient.apply(stack); - } - - @Override - default @NotNull NonNullList getRemainingItems(InventoryCrafting inv) { - NonNullList ret = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); - for (int i = 0; i < ret.size(); i++) { - ret.set(i, inv.getStackInSlot(i)); - } - int[] matches = RecipeMatcher.findMatches(ret, this.getIngredients()); - if (matches != null) { - for (int i = 0; i < ret.size(); i++) { - ItemStack stack = ret.get(i); - Ingredient ingredient = this.getIngredients().get(matches[i]); - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - toolbelt.craftDamageTools(stack, ingredient); - } - ret.set(i, ForgeHooks.getContainerItem(stack)); - } - } else ret.replaceAll(ForgeHooks::getContainerItem); - return ret; - } -} diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 64d8c5010d3..e4c20381a25 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -69,14 +69,11 @@ public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); - private final ItemStack orestack; - public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), - null, false, new HashSet<>(), "", new ArrayList<>(), + null, false, new HashSet<>(), "toolbelt", new ArrayList<>(), markerItem); - this.orestack = new ItemStack(this, 1, GTValues.W); } public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { @@ -127,7 +124,6 @@ public static boolean isToolbeltableOredict(String oredict) { public void registerValidOredict(String oredict) { VALID_OREDICTS.add(oredict); - OreDictUnifier.registerOre(this.orestack, oredict); } @Override @@ -331,6 +327,21 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { return true; } + @Override + public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { + Ingredient nextCraftIngredient = getHandler(stack).nextCraftIngredient; + if (nextCraftIngredient != null) { + stack = stack.copy(); + this.craftDamageTools(stack, nextCraftIngredient); + return stack; + } + return super.getContainerItem(stack); + } + + public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { + getHandler(stack).nextCraftIngredient = ingredient; + } + public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, @Nullable EntityPlayer entityPlayer) { return getHandler(stack).checkMaintenanceAgainstTools(toolClass, true, entityPlayer); @@ -470,6 +481,8 @@ protected ToolStackHandler getHandler(int minsize) { protected static class ToolStackHandler extends ItemStackHandler { + private Ingredient nextCraftIngredient; + private static final Set EMPTY = ImmutableSet.of(); private @Nullable Integer selectedSlot = null; diff --git a/src/main/java/gregtech/api/recipes/ModHandler.java b/src/main/java/gregtech/api/recipes/ModHandler.java index a96b1d9077e..1a01a2bbb39 100644 --- a/src/main/java/gregtech/api/recipes/ModHandler.java +++ b/src/main/java/gregtech/api/recipes/ModHandler.java @@ -317,7 +317,7 @@ private static boolean validateRecipeWithOutput(@NotNull String regName, @NotNul private static void addRecipe(@NotNull String regName, @NotNull ItemStack result, boolean isNBTClearing, boolean isMirrored, @NotNull Object... recipe) { - IRecipe shapedOreRecipe = GTShapedOreRecipe.create(isNBTClearing, null, result.copy(), + IRecipe shapedOreRecipe = new GTShapedOreRecipe(isNBTClearing, null, result.copy(), finalizeShapedRecipeInput(recipe)) .setMirrored(isMirrored) .setRegistryName(regName); diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index 9a13badeaf5..1714fd602a4 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -1,7 +1,15 @@ package gregtech.asm; +import gregtech.asm.util.ObfMapping; +import gregtech.asm.util.TargetClassVisitor; +import gregtech.asm.visitors.*; +import gregtech.common.ConfigHolder; + import net.minecraft.launchwrapper.IClassTransformer; +import net.minecraft.launchwrapper.Launch; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; public class GregTechTransformer implements IClassTransformer, Opcodes { @@ -222,6 +230,12 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) // 0); // return classWriter.toByteArray(); // } + case OreIngredientVisitor.TARGET_CLASS_NAME: { + ClassReader classReader = new ClassReader(basicClass); + ClassWriter classWriter = new ClassWriter(0); + classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, OreIngredientVisitor::new), 0); + return classWriter.toByteArray(); + } } /* * if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java new file mode 100644 index 00000000000..53e6f3dd1cd --- /dev/null +++ b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java @@ -0,0 +1,25 @@ +package gregtech.asm.hooks; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + + +import net.minecraft.item.ItemStack; + +import net.minecraftforge.oredict.OreIngredient; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@SuppressWarnings("unused") +public class OreIngredientHooks { + + public static boolean checkToolbelt(@Nullable ItemStack input, @NotNull OreIngredient ingredient) { + if (input.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.supportsIngredient(input, ingredient)) { + toolbelt.setOnCraftIngredient(input, ingredient); + return true; + } + } + return false; + } +} diff --git a/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java b/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java new file mode 100644 index 00000000000..8a51c12e3e6 --- /dev/null +++ b/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java @@ -0,0 +1,52 @@ +package gregtech.asm.visitors; + +import gregtech.asm.util.ObfMapping; + +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +public class OreIngredientVisitor extends MethodVisitor implements Opcodes { + + public static final String TARGET_CLASS_NAME = "net/minecraftforge/oredict/OreIngredient"; + public static final ObfMapping TARGET_METHOD = new ObfMapping(TARGET_CLASS_NAME, "apply", + targetSignature()); + + private static final String OWNER = "gregtech/asm/hooks/OreIngredientHooks"; + private static final String SIGNATURE = signature(); + private static final String METHOD_NAME = "checkToolbelt"; + + public OreIngredientVisitor(MethodVisitor mv) { + super(ASM5, mv); + } + + @Override + public void visitCode() { + mv.visitVarInsn(ALOAD, 1); // ItemStack + mv.visitVarInsn(ALOAD, 0); // OreIngredient + mv.visitMethodInsn(INVOKESTATIC, OWNER, METHOD_NAME, SIGNATURE, false); + Label L1 = new Label(); + mv.visitJumpInsn(IFEQ, L1); + mv.visitInsn(ICONST_1); + mv.visitInsn(IRETURN); + mv.visitLabel(L1); + mv.visitFrame(F_SAME, 0, null, 0, null); + + mv.visitCode(); + } + + // public boolean apply(@Nullable ItemStack input) + private static String targetSignature() { + return "(" + + "Lnet/minecraft/item/ItemStack;" + // ItemStack + ")Z;"; // return boolean + } + + // public static boolean extendedApply(@Nullable ItemStack input, @NotNull OreIngredient ingredient) + private static String signature() { + return "(" + + "Lnet/minecraft/item/ItemStack;" + // ItemStack + "Lnet/minecraftforge/oredict/OreIngredient;" + // OreIngredient + ")Z"; // return boolean + } +} diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index 5cfd1571d47..03c030c4be3 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -24,9 +24,7 @@ public class FluidReplaceRecipe extends GTShapedOreRecipe { public FluidReplaceRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { - super(new AtomicBoolean(false), isClearing, group, result, recipe); - // there is no possible way that we require toolbelt handling, but make sure it isn't enabled. - this.toolbeltHandling = false; + super(isClearing, group, result, recipe); } @NotNull diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 3cf67667b5d..5ff52869452 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -1,6 +1,5 @@ package gregtech.common.crafting; -import gregtech.api.crafting.IToolbeltSupportingRecipe; import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.util.GTLog; import gregtech.api.util.GTStringUtils; @@ -34,35 +33,21 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -public class GTShapedOreRecipe extends ShapedOreRecipe implements IToolbeltSupportingRecipe { +public class GTShapedOreRecipe extends ShapedOreRecipe { boolean isClearing; - boolean toolbeltHandling; public static Constructor ingredientNBT = ReflectionHelper.findConstructor(IngredientNBT.class, ItemStack.class); - protected GTShapedOreRecipe(AtomicBoolean toolbeltHandling, boolean isClearing, ResourceLocation group, - @NotNull ItemStack result, Object... recipe) { - super(group, result, parseShaped(toolbeltHandling, isClearing, recipe)); + public GTShapedOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { + super(group, result, parseShaped(isClearing, recipe)); this.isClearing = isClearing; } - public static GTShapedOreRecipe create(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, - Object... recipe) { - AtomicBoolean toolbeltHandling = new AtomicBoolean(false); - GTShapedOreRecipe out = new GTShapedOreRecipe(toolbeltHandling, isClearing, group, result, recipe); - return out.setToolbeltHandling(toolbeltHandling.get()); - } - - private GTShapedOreRecipe setToolbeltHandling(boolean toolbeltHandling) { - this.toolbeltHandling = toolbeltHandling; - return this; - } - // a copy of the CraftingHelper.ShapedPrimer.parseShaped method. // the only difference is calling getIngredient of this class. - public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHandling, boolean isClearing, + public static CraftingHelper.ShapedPrimer parseShaped(boolean isClearing, Object... recipe) { CraftingHelper.ShapedPrimer ret = new CraftingHelper.ShapedPrimer(); StringBuilder shape = new StringBuilder(); @@ -106,7 +91,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHand for (; idx < recipe.length; idx += 2) { Character chr = (Character) recipe[idx]; Object in = recipe[idx + 1]; - Ingredient ing = getIngredient(toolbeltHandling, isClearing, in); + Ingredient ing = getIngredient(isClearing, in); if (' ' == chr) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); @@ -144,7 +129,7 @@ public static CraftingHelper.ShapedPrimer parseShaped(AtomicBoolean toolbeltHand return ret; } - protected static Ingredient getIngredient(AtomicBoolean toolbeltHandling, boolean isClearing, Object obj) { + protected static Ingredient getIngredient(boolean isClearing, Object obj) { if (obj instanceof Ingredient ing) return ing; else if (obj instanceof ItemStack stk) { if (stk.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { @@ -171,8 +156,6 @@ else if (obj instanceof ItemStack stk) { else if (obj instanceof Block blk) return Ingredient.fromStacks(new ItemStack(blk, 1, OreDictionary.WILDCARD_VALUE)); else if (obj instanceof String str) { - if (ItemGTToolbelt.isToolbeltableOredict(str)) - toolbeltHandling.set(true); return new OreIngredient(str); } else if (obj instanceof JsonElement) throw new IllegalArgumentException("JsonObjects must use getIngredient(JsonObject, JsonContext)"); @@ -180,37 +163,12 @@ else if (obj instanceof String str) { return null; } - @Override - protected boolean checkMatch(@NotNull InventoryCrafting inv, int startX, int startY, boolean mirror) { - if (this.toolbeltHandling) { - for (int x = 0; x < inv.getWidth(); x++) { - for (int y = 0; y < inv.getHeight(); y++) { - int subX = x - startX; - int subY = y - startY; - Ingredient target = Ingredient.EMPTY; - - if (subX >= 0 && subY >= 0 && subX < width && subY < height) { - if (mirror) { - target = input.get(width - subX - 1 + subY * width); - } else { - target = input.get(subX + subY * width); - } - } - - if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(target, inv.getStackInRowAndColumn(x, y))) - return false; - } - } - return true; - } else return super.checkMatch(inv, startX, startY, mirror); - } - @Override public @NotNull NonNullList getRemainingItems(@NotNull InventoryCrafting inv) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return IToolbeltSupportingRecipe.super.getRemainingItems(inv); + return net.minecraftforge.common.ForgeHooks.defaultRecipeGetRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index fb620ea9927..cd47529fc66 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -1,13 +1,12 @@ package gregtech.common.crafting; -import gregtech.api.crafting.IToolbeltSupportingRecipe; - import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; @@ -17,18 +16,16 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -public class GTShapelessOreRecipe extends ShapelessOreRecipe implements IToolbeltSupportingRecipe { +public class GTShapelessOreRecipe extends ShapelessOreRecipe { boolean isClearing; - boolean toolbeltHandling; public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull ItemStack result, Object... recipe) { super(group, result); this.isClearing = isClearing; - AtomicBoolean needsToolbelt = new AtomicBoolean(false); for (Object in : recipe) { - Ingredient ing = GTShapedOreRecipe.getIngredient(needsToolbelt, isClearing, in); + Ingredient ing = GTShapedOreRecipe.getIngredient(isClearing, in); if (ing != null) { input.add(ing); this.isSimple = this.isSimple && ing.isSimple(); @@ -41,38 +38,6 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull throw new RuntimeException(ret.toString()); } } - this.toolbeltHandling = needsToolbelt.get(); - } - - @Override - public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { - if (this.toolbeltHandling) { - // I can't wrap my head around the 'simple' shapeless logic, so no simple toolbelt handling. - int ingredientCount = 0; - List items = Lists.newArrayList(); - - for (int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack itemstack = inv.getStackInSlot(i); - if (!itemstack.isEmpty()) { - ++ingredientCount; - items.add(itemstack); - } - } - - if (ingredientCount != this.input.size()) - return false; - - int[] matches = RecipeMatcher.findMatches(items, this.input); - if (matches != null) { - for (int i = 0; i < items.size(); i++) { - ItemStack stack = items.get(i); - Ingredient ingredient = this.input.get(matches[i]); - if (!IToolbeltSupportingRecipe.toolbeltIngredientCheck(ingredient, stack)) return false; - } - return true; - } else return false; - - } else return super.matches(inv, world); } @Override @@ -80,7 +45,7 @@ public boolean matches(@NotNull InventoryCrafting inv, @NotNull World world) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return IToolbeltSupportingRecipe.super.getRemainingItems(inv); + return ForgeHooks.defaultRecipeGetRemainingItems(inv); } } } From f9eeb270937f015290de7dd1d9ad6e9e2b8db853 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Wed, 5 Jun 2024 20:33:22 -0600 Subject: [PATCH 43/82] sp4tless --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 2 -- src/main/java/gregtech/api/recipes/ModHandler.java | 4 ++-- src/main/java/gregtech/asm/GregTechTransformer.java | 3 ++- src/main/java/gregtech/asm/hooks/OreIngredientHooks.java | 2 -- .../java/gregtech/common/crafting/FluidReplaceRecipe.java | 2 -- .../java/gregtech/common/crafting/GTShapedOreRecipe.java | 2 -- .../java/gregtech/common/crafting/GTShapelessOreRecipe.java | 6 ------ 7 files changed, 4 insertions(+), 17 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index e4c20381a25..5e747465fc3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -1,13 +1,11 @@ package gregtech.api.items.toolitem; -import gregtech.api.GTValues; import gregtech.api.GregTechAPI; import gregtech.api.items.IDyeableItem; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; -import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Material; import gregtech.api.unification.material.Materials; import gregtech.api.unification.material.properties.PropertyKey; diff --git a/src/main/java/gregtech/api/recipes/ModHandler.java b/src/main/java/gregtech/api/recipes/ModHandler.java index 1a01a2bbb39..10e55ea68b1 100644 --- a/src/main/java/gregtech/api/recipes/ModHandler.java +++ b/src/main/java/gregtech/api/recipes/ModHandler.java @@ -319,8 +319,8 @@ private static void addRecipe(@NotNull String regName, @NotNull ItemStack result boolean isMirrored, @NotNull Object... recipe) { IRecipe shapedOreRecipe = new GTShapedOreRecipe(isNBTClearing, null, result.copy(), finalizeShapedRecipeInput(recipe)) - .setMirrored(isMirrored) - .setRegistryName(regName); + .setMirrored(isMirrored) + .setRegistryName(regName); registerRecipe(shapedOreRecipe); } diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index 1714fd602a4..abd2493fe07 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -233,7 +233,8 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) case OreIngredientVisitor.TARGET_CLASS_NAME: { ClassReader classReader = new ClassReader(basicClass); ClassWriter classWriter = new ClassWriter(0); - classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, OreIngredientVisitor::new), 0); + classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, + OreIngredientVisitor::new), 0); return classWriter.toByteArray(); } } diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java index 53e6f3dd1cd..cc0a13fd4f0 100644 --- a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java +++ b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java @@ -2,9 +2,7 @@ import gregtech.api.items.toolitem.ItemGTToolbelt; - import net.minecraft.item.ItemStack; - import net.minecraftforge.oredict.OreIngredient; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java index 03c030c4be3..f3addd44339 100644 --- a/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java +++ b/src/main/java/gregtech/common/crafting/FluidReplaceRecipe.java @@ -16,8 +16,6 @@ import org.jetbrains.annotations.NotNull; -import java.util.concurrent.atomic.AtomicBoolean; - /** * A recipe which inputs a single Fluid Container, and outputs the same Fluid Container with a new contained Fluid */ diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 5ff52869452..24940f8dae0 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -1,6 +1,5 @@ package gregtech.common.crafting; -import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.util.GTLog; import gregtech.api.util.GTStringUtils; @@ -31,7 +30,6 @@ import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; public class GTShapedOreRecipe extends ShapedOreRecipe { diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index cd47529fc66..bc062c7c15b 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -5,17 +5,11 @@ import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; -import net.minecraftforge.common.util.RecipeMatcher; import net.minecraftforge.oredict.ShapelessOreRecipe; -import com.google.common.collect.Lists; import org.jetbrains.annotations.NotNull; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - public class GTShapelessOreRecipe extends ShapelessOreRecipe { boolean isClearing; From 0da1cf91e622b56f85adc544b1740cb678695e19 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Sat, 15 Jun 2024 14:40:08 -0600 Subject: [PATCH 44/82] Dynamic toolbelt render --- .../api/items/toolitem/ItemGTToolbelt.java | 2 - .../java/gregtech/client/ClientProxy.java | 10 +++ .../renderer/handler/ToolbeltRenderer.java | 60 ++++++++++++++++++ .../java/gregtech/common/items/MetaItems.java | 2 - .../java/gregtech/common/items/ToolItems.java | 11 ++++ .../textures/items/tools/toolbelt_belt.png | Bin 159 -> 160 bytes .../textures/items/tools/toolbelt_loops.png | Bin 177 -> 152 bytes 7 files changed, 81 insertions(+), 4 deletions(-) create mode 100644 src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 5e747465fc3..c6d7be7521e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -424,8 +424,6 @@ public boolean shouldGetContainerItem() { return false; } - // TODO BEWLR for dynamic display of selected item? - protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 571f617d849..3638204bfc2 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -10,6 +10,7 @@ import gregtech.api.unification.material.Materials; import gregtech.api.unification.stack.UnificationEntry; import gregtech.api.util.FluidTooltipUtil; +import gregtech.api.util.GTLog; import gregtech.api.util.IBlockOre; import gregtech.api.util.Mods; import gregtech.client.model.customtexture.CustomTextureModelHandler; @@ -50,6 +51,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.common.MinecraftForge; @@ -129,6 +131,14 @@ public static void registerModels(ModelRegistryEvent event) { ToolItems.registerModels(); } + @SubscribeEvent + @SideOnly(Side.CLIENT) + public static void registerBakedModels(ModelBakeEvent event) { + GTLog.logger.info("Registering special item models"); + MetaItems.registerBakedModels(event); + ToolItems.registerBakedModels(event); + } + @SubscribeEvent public static void addMaterialFormulaHandler(@NotNull ItemTooltipEvent event) { ItemStack itemStack = event.getItemStack(); diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java new file mode 100644 index 00000000000..0c67425daa1 --- /dev/null +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -0,0 +1,60 @@ +package gregtech.client.renderer.handler; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderItem; +import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.model.IModelState; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import codechicken.lib.render.item.IItemRenderer; +import codechicken.lib.util.TransformUtils; + +@SideOnly(Side.CLIENT) +public class ToolbeltRenderer implements IItemRenderer { + + private final IBakedModel toolbeltModel; + + public ToolbeltRenderer(IBakedModel toolbeltModel) { + this.toolbeltModel = toolbeltModel; + } + + @Override + public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType transformType) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + GlStateManager.pushMatrix(); + GlStateManager.translate(0.5F, 0.5F, 0.5F); + + RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); + + ItemStack selected = toolbelt.getSelectedItem(stack); + if (selected != null) { + IBakedModel selectedModel = renderItem.getItemModelWithOverrides(selected, null, null); + renderItem.renderItem(selected, selectedModel); + } + renderItem.renderItem(stack, toolbeltModel); + + GlStateManager.popMatrix(); + } + } + + @Override + public IModelState getTransforms() { + return TransformUtils.DEFAULT_ITEM; + } + + @Override + public boolean isAmbientOcclusion() { + return false; + } + + @Override + public boolean isGui3d() { + return false; + } +} diff --git a/src/main/java/gregtech/common/items/MetaItems.java b/src/main/java/gregtech/common/items/MetaItems.java index 303588e6dc8..eaa75bc932f 100644 --- a/src/main/java/gregtech/common/items/MetaItems.java +++ b/src/main/java/gregtech/common/items/MetaItems.java @@ -19,7 +19,6 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -653,7 +652,6 @@ public static void registerColors() { } } - @SubscribeEvent @SideOnly(Side.CLIENT) public static void registerBakedModels(ModelBakeEvent event) { GTLog.logger.info("Registering special item models"); diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 5796d85c25c..561cd094a74 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -4,17 +4,22 @@ import gregtech.api.items.toolitem.*; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; +import gregtech.client.renderer.handler.ToolbeltRenderer; import gregtech.common.items.tool.*; import gregtech.core.sound.GTSoundEvents; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.entity.monster.EntityGolem; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.init.Enchantments; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; +import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; import org.jetbrains.annotations.NotNull; @@ -372,6 +377,12 @@ public static void registerModels() { TOOLS.forEach(tool -> ModelLoader.setCustomModelResourceLocation(tool.get(), 0, tool.getModelLocation())); } + @SideOnly(Side.CLIENT) + public static void registerBakedModels(ModelBakeEvent event) { + ModelResourceLocation loc = TOOLBELT.getModelLocation(); + event.getModelRegistry().putObject(loc, new ToolbeltRenderer(event.getModelRegistry().getObject(loc))); + } + public static void registerColors() { TOOLS.forEach( tool -> Minecraft.getMinecraft().getItemColors().registerItemColorHandler(tool::getColor, tool.get())); diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_belt.png index b703b955e156fcd5574aa175e1e92dbdcfd7ad4f..0918698052fc7f743017c08284f0fa77cea43cae 100644 GIT binary patch delta 131 zcmV-}0DS+S0iXepBz$K{L_t(IjqQ%T4FDksg`dd{;y{ex2zJztzzB2*i(v kNZ3$H2_Kl*R(trG8;uGgMEn)#zW@LL07*qoM6N<$f;2fdmH+?% diff --git a/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png b/src/main/resources/assets/gregtech/textures/items/tools/toolbelt_loops.png index c351831679459d2785e6da182d3aa7cd938d66e3..6944f44d2ae17c028bfbf4056ff951ecbf118ea0 100644 GIT binary patch delta 123 zcmV->0EGXs0hj@hBy?X%L_t(IjbmUK1)~5BG&D5)Z)j-vPl`Mfx*{VZBZl Date: Sat, 15 Jun 2024 15:02:07 -0600 Subject: [PATCH 45/82] Fix excessive passthrough and toolbelt render and improve IDyeableItem --- .../java/gregtech/api/items/IDyeableItem.java | 31 ++++++++++++-- .../api/items/toolitem/ItemGTToolbelt.java | 40 +++++++++++-------- .../renderer/handler/ToolbeltRenderer.java | 2 +- 3 files changed, 53 insertions(+), 20 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index 0497bf30fa0..bcd2cc1f3e7 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -1,11 +1,18 @@ package gregtech.api.items; +import net.minecraft.block.BlockCauldron; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; + +import org.jetbrains.annotations.NotNull; -/** - * Note - users of this interface will have to deal with cauldron dye clearing on their own. - */ public interface IDyeableItem { default boolean hasColor(ItemStack stack) { @@ -52,6 +59,24 @@ default void setColor(ItemStack stack, int color) { nbttagcompound1.setInteger("color", color); } + default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { + ItemStack stack = player.getHeldItem(hand); + if (this.hasColor(stack)) { + IBlockState iblockstate = world.getBlockState(pos); + if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { + int water = iblockstate.getValue(BlockCauldron.LEVEL); + if (water > 0) { + this.removeColor(stack); + cauldron.setWaterLevel(world, pos, iblockstate, water - 1); + return EnumActionResult.SUCCESS; + } + } + } + return EnumActionResult.PASS; + } + /** * Controls whether the dyeing recipe simply removes the dyeable item from the crafting grid, * or calls {@link net.minecraftforge.common.ForgeHooks#getContainerItem(ItemStack)} on it. diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index c6d7be7521e..e85ccf55ee3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -383,27 +383,21 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { if (tool != null) { selectedToolDisplay = " (" + tool.getDisplayName() + ")"; } - return LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), + getHandler(stack).disablePassthrough(); + String name = LocalizationUtils.format(getTranslationKey(), getToolMaterial(stack).getLocalizedName(), selectedToolDisplay); + getHandler(stack).enablePassthrough(); + return name; } @Override public @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { - ItemStack stack = player.getHeldItem(hand); - if (this.hasColor(stack)) { - IBlockState iblockstate = world.getBlockState(pos); - if (iblockstate.getBlock() instanceof BlockCauldron cauldron) { - int water = iblockstate.getValue(BlockCauldron.LEVEL); - if (water > 0) { - this.removeColor(stack); - cauldron.setWaterLevel(world, pos, iblockstate, water - 1); - return EnumActionResult.SUCCESS; - } - } - } - return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + EnumActionResult result = IDyeableItem.super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + if (result == EnumActionResult.PASS) + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); + else return result; } @Override @@ -411,7 +405,10 @@ public int getColor(ItemStack stack, int tintIndex) { if (tintIndex == 0) { return this.getColor(stack); } - return super.getColor(stack, tintIndex); + getHandler(stack).disablePassthrough(); + int color = super.getColor(stack, tintIndex); + getHandler(stack).enablePassthrough(); + return color; } @Override @@ -488,6 +485,8 @@ protected static class ToolStackHandler extends ItemStackHandler { protected final Set toolClasses = new ObjectOpenHashSet<>(); public final Set oreDicts = new ObjectOpenHashSet<>(); + private boolean passthrough = true; + public ToolStackHandler(int size) { super(size); } @@ -511,7 +510,16 @@ public void decrementSelectedSlot() { } public @Nullable Integer getSelectedSlot() { - return selectedSlot; + if (passthrough) return selectedSlot; + else return null; + } + + public void enablePassthrough() { + this.passthrough = true; + } + + public void disablePassthrough() { + this.passthrough = false; } public @Nullable ItemStack getSelectedStack() { diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java index 0c67425daa1..cdc7d54dc0f 100644 --- a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -45,7 +45,7 @@ public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType trans @Override public IModelState getTransforms() { - return TransformUtils.DEFAULT_ITEM; + return TransformUtils.DEFAULT_TOOL; } @Override From 64a7b67f276715ebe7ad8e083cf21a7b71788927 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Sat, 15 Jun 2024 15:02:51 -0600 Subject: [PATCH 46/82] Sp4tless --- src/main/java/gregtech/api/items/IDyeableItem.java | 4 ++-- src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index bcd2cc1f3e7..a79c3716749 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -60,8 +60,8 @@ default void setColor(ItemStack stack, int color) { } default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, - float hitY, float hitZ, @NotNull EnumHand hand) { + @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, + float hitY, float hitZ, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); if (this.hasColor(stack)) { IBlockState iblockstate = world.getBlockState(pos); diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index e85ccf55ee3..3d7210d522e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -13,7 +13,6 @@ import gregtech.api.util.LocalizationUtils; import gregtech.core.network.packets.PacketToolbeltSelectionChange; -import net.minecraft.block.BlockCauldron; import net.minecraft.block.state.IBlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; From 57e8438c8a61f968c6f6afdda4ee0f0529bf9d89 Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Thu, 27 Jun 2024 19:52:06 -0700 Subject: [PATCH 47/82] convert asm to mixin --- .../gregtech/asm/GregTechTransformer.java | 19 +++++++--------- .../mixins/forge/OreIngredientMixin.java | 22 +++++++++++++++++++ src/main/resources/mixins.gregtech.forge.json | 3 ++- 3 files changed, 32 insertions(+), 12 deletions(-) create mode 100644 src/main/java/gregtech/mixins/forge/OreIngredientMixin.java diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index abd2493fe07..1b94ad0fa47 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -1,12 +1,9 @@ package gregtech.asm; -import gregtech.asm.util.ObfMapping; import gregtech.asm.util.TargetClassVisitor; -import gregtech.asm.visitors.*; -import gregtech.common.ConfigHolder; +import gregtech.asm.visitors.OreIngredientVisitor; import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraft.launchwrapper.Launch; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; @@ -230,13 +227,13 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) // 0); // return classWriter.toByteArray(); // } - case OreIngredientVisitor.TARGET_CLASS_NAME: { - ClassReader classReader = new ClassReader(basicClass); - ClassWriter classWriter = new ClassWriter(0); - classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, - OreIngredientVisitor::new), 0); - return classWriter.toByteArray(); - } +// case OreIngredientVisitor.TARGET_CLASS_NAME: { +// ClassReader classReader = new ClassReader(basicClass); +// ClassWriter classWriter = new ClassWriter(0); +// classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, +// OreIngredientVisitor::new), 0); +// return classWriter.toByteArray(); +// } } /* * if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { diff --git a/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java new file mode 100644 index 00000000000..c01d9c6ffd4 --- /dev/null +++ b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java @@ -0,0 +1,22 @@ +package gregtech.mixins.forge; + +import gregtech.asm.hooks.OreIngredientHooks; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreIngredient; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(OreIngredient.class) +public abstract class OreIngredientMixin { + + @Inject(method = "apply(Lnet/minecraft/item/ItemStack;)Z", at = @At("HEAD"), cancellable = true) + private void checkToolbelt(ItemStack input, CallbackInfoReturnable cir) { + if (OreIngredientHooks.checkToolbelt(input, (OreIngredient) (Object) this)) { + cir.setReturnValue(true); + } + } +} diff --git a/src/main/resources/mixins.gregtech.forge.json b/src/main/resources/mixins.gregtech.forge.json index 81605c0c9dc..57f68b178ac 100644 --- a/src/main/resources/mixins.gregtech.forge.json +++ b/src/main/resources/mixins.gregtech.forge.json @@ -4,8 +4,9 @@ "target": "@env(DEFAULT)", "minVersion": "0.8", "compatibilityLevel": "JAVA_8", - "mixins" : [ + "mixins": [ "ModelLoaderRegistryMixin", + "OreIngredientMixin", "SpecialArmorPropertiesMixin" ], "client": [], From 76bd2817bfa8bfe29a962f1c95040eb41cd2d20d Mon Sep 17 00:00:00 2001 From: M-W-K Date: Thu, 27 Jun 2024 21:04:25 -0600 Subject: [PATCH 48/82] fix an oops in the merge process --- .../gregtech/asm/GregTechTransformer.java | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/main/java/gregtech/asm/GregTechTransformer.java b/src/main/java/gregtech/asm/GregTechTransformer.java index 4d9b2a64ac5..c3b906dd4ae 100644 --- a/src/main/java/gregtech/asm/GregTechTransformer.java +++ b/src/main/java/gregtech/asm/GregTechTransformer.java @@ -1,12 +1,7 @@ package gregtech.asm; -import gregtech.asm.util.TargetClassVisitor; -import gregtech.asm.visitors.OreIngredientVisitor; - import net.minecraft.launchwrapper.IClassTransformer; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; public class GregTechTransformer implements IClassTransformer, Opcodes { @@ -227,23 +222,24 @@ public byte[] transform(String name, String transformedName, byte[] basicClass) // 0); // return classWriter.toByteArray(); // } -// case OreIngredientVisitor.TARGET_CLASS_NAME: { -// ClassReader classReader = new ClassReader(basicClass); -// ClassWriter classWriter = new ClassWriter(0); -// classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, -// OreIngredientVisitor::new), 0); -// return classWriter.toByteArray(); -// } - /* - * if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { - * ObfMapping methodMapping = EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.get(internalName); - * ClassReader classReader = new ClassReader(basicClass); - * ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - * classReader.accept(new TargetClassVisitor(classWriter, methodMapping, - * mv -> new EnchantmentCanApplyVisitor(mv, methodMapping)), ClassReader.EXPAND_FRAMES); - * return classWriter.toByteArray(); - * } - */ + // case OreIngredientVisitor.TARGET_CLASS_NAME: { + // ClassReader classReader = new ClassReader(basicClass); + // ClassWriter classWriter = new ClassWriter(0); + // classReader.accept(new TargetClassVisitor(classWriter, OreIngredientVisitor.TARGET_METHOD, + // OreIngredientVisitor::new), 0); + // return classWriter.toByteArray(); + // } + /* + * if (EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.containsKey(internalName)) { + * ObfMapping methodMapping = EnchantmentCanApplyVisitor.CLASS_TO_MAPPING_MAP.get(internalName); + * ClassReader classReader = new ClassReader(basicClass); + * ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + * classReader.accept(new TargetClassVisitor(classWriter, methodMapping, + * mv -> new EnchantmentCanApplyVisitor(mv, methodMapping)), ClassReader.EXPAND_FRAMES); + * return classWriter.toByteArray(); + * } + */ + } return basicClass; } } From 002d7724f37b2c6164e684c0df4532f700385eac Mon Sep 17 00:00:00 2001 From: M-W-K Date: Fri, 28 Jun 2024 08:48:29 -0600 Subject: [PATCH 49/82] toolbelt JEI complete --- .../api/items/toolitem/ItemGTToolbelt.java | 39 +++++++++++++++++++ .../asm/hooks/OreIngredientHooks.java | 2 + .../mixins/forge/OreIngredientMixin.java | 3 +- .../gregtech/mixins/jei/StackHelperMixin.java | 23 +++++++++++ src/main/resources/mixins.gregtech.jei.json | 19 ++++----- 5 files changed, 76 insertions(+), 10 deletions(-) create mode 100644 src/main/java/gregtech/mixins/jei/StackHelperMixin.java diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 3d7210d522e..3491c65fbe8 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -49,6 +49,10 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.OreIngredient; + import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -348,6 +352,10 @@ public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { return getHandler(stack).checkIngredientAgainstTools(ingredient, false); } + public boolean supportsTool(ItemStack stack, ItemStack tool) { + return getHandler(stack).checkToolAgainstTools(tool, false); + } + public void craftDamageTools(ItemStack stack, Ingredient ingredient) { getHandler(stack).checkIngredientAgainstTools(ingredient, true); } @@ -420,6 +428,23 @@ public boolean shouldGetContainerItem() { return false; } + public static boolean checkIngredientAgainstToolbelt(@NotNull ItemStack input, @NotNull OreIngredient ingredient) { + if (input.getItem() instanceof ItemGTToolbelt toolbelt) { + if (toolbelt.supportsIngredient(input, ingredient)) { + toolbelt.setOnCraftIngredient(input, ingredient); + return true; + } + } + return false; + } + + public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @NotNull ItemStack tool) { + if (toolbelt.getItem() instanceof ItemGTToolbelt belt) { + return belt.supportsTool(toolbelt, tool); + } + return false; + } + protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { protected final Supplier slotCountSupplier; @@ -630,5 +655,19 @@ public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraf } return false; } + + public boolean checkToolAgainstTools(ItemStack tool, boolean doCraftingDamage) { + if (!this.isItemValid(0, tool)) return false; + for (int i = 0; i < this.getSlots(); i++) { + ItemStack stack = this.getStackInSlot(i); + if (OreDictionary.itemMatches(stack, tool, false)) { + if (doCraftingDamage && stack.getItem().hasContainerItem(stack)) { + this.setStackInSlot(i, stack.getItem().getContainerItem(stack)); + } + return true; + } + } + return false; + } } } diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java index cc0a13fd4f0..5096e98fa9e 100644 --- a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java +++ b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java @@ -2,6 +2,8 @@ import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.api.unification.OreDictUnifier; + import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreIngredient; diff --git a/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java index c01d9c6ffd4..c20bf4a2ad0 100644 --- a/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java +++ b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java @@ -1,5 +1,6 @@ package gregtech.mixins.forge; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.asm.hooks.OreIngredientHooks; import net.minecraft.item.ItemStack; @@ -15,7 +16,7 @@ public abstract class OreIngredientMixin { @Inject(method = "apply(Lnet/minecraft/item/ItemStack;)Z", at = @At("HEAD"), cancellable = true) private void checkToolbelt(ItemStack input, CallbackInfoReturnable cir) { - if (OreIngredientHooks.checkToolbelt(input, (OreIngredient) (Object) this)) { + if (ItemGTToolbelt.checkIngredientAgainstToolbelt(input, (OreIngredient) (Object) this)) { cir.setReturnValue(true); } } diff --git a/src/main/java/gregtech/mixins/jei/StackHelperMixin.java b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java new file mode 100644 index 00000000000..4fd843f9ee8 --- /dev/null +++ b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java @@ -0,0 +1,23 @@ +package gregtech.mixins.jei; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import mezz.jei.startup.StackHelper; + +import net.minecraft.item.ItemStack; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(StackHelper.class) +public class StackHelperMixin { + + @Inject(method = "isEquivalent", at = @At(value = "RETURN", ordinal = 2), cancellable = true) + private void toolbeltIsEquivalent(ItemStack lhs, ItemStack rhs, CallbackInfoReturnable cir) { + if (ItemGTToolbelt.checkToolAgainstToolbelt(rhs, lhs)) { + cir.setReturnValue(true); + } + } +} diff --git a/src/main/resources/mixins.gregtech.jei.json b/src/main/resources/mixins.gregtech.jei.json index 2520843c7d6..d3a1804b6a3 100644 --- a/src/main/resources/mixins.gregtech.jei.json +++ b/src/main/resources/mixins.gregtech.jei.json @@ -1,12 +1,13 @@ { - "package" : "gregtech.mixins.jei", - "refmap" : "mixins.gregtech.refmap.json", - "target" : "@env(DEFAULT)", - "minVersion" : "0.8", - "compatibilityLevel" : "JAVA_8", - "mixins" : [ - "JEITooltipMixin" + "package": "gregtech.mixins.jei", + "refmap": "mixins.gregtech.refmap.json", + "target": "@env(DEFAULT)", + "minVersion": "0.8", + "compatibilityLevel": "JAVA_8", + "mixins": [ + "JEITooltipMixin", + "StackHelperMixin" ], - "client" : [], - "server" : [] + "client": [], + "server": [] } From b0ccde355dcfbdae1a5de71b7d8d37e3480faa73 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Fri, 28 Jun 2024 09:38:49 -0600 Subject: [PATCH 50/82] improve JEI shift-complete behavior --- .../api/items/toolitem/ItemGTToolbelt.java | 5 +- .../api/items/toolitem/ToolHelper.java | 8 + ...BasicRecipeTransferHandlerServerMixin.java | 137 ++++++++++++++++++ .../gregtech/mixins/jei/StackHelperMixin.java | 2 +- src/main/resources/mixins.gregtech.jei.json | 1 + 5 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 3491c65fbe8..20238c38ea4 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -439,7 +439,7 @@ public static boolean checkIngredientAgainstToolbelt(@NotNull ItemStack input, @ } public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @NotNull ItemStack tool) { - if (toolbelt.getItem() instanceof ItemGTToolbelt belt) { + if (toolbelt.getItem() instanceof ItemGTToolbelt belt && ToolHelper.isTool(tool)) { return belt.supportsTool(toolbelt, tool); } return false; @@ -568,7 +568,7 @@ public Set getToolClasses(boolean defaultEmpty) { public boolean isItemValid(int slot, @NotNull ItemStack stack) { Item item = stack.getItem(); if (item instanceof ItemGTToolbelt) return false; - return item instanceof ItemTool || item instanceof IGTTool; + return ToolHelper.isTool(stack); } @Override @@ -657,7 +657,6 @@ public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraf } public boolean checkToolAgainstTools(ItemStack tool, boolean doCraftingDamage) { - if (!this.isItemValid(0, tool)) return false; for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); if (OreDictionary.itemMatches(stack, tool, false)) { diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index e5dfb9774e1..151a53f0a5e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -29,6 +29,7 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Enchantments; import net.minecraft.item.ItemStack; +import net.minecraft.item.ItemTool; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.play.server.SPacketBlockChange; import net.minecraft.stats.StatBase; @@ -378,6 +379,13 @@ public static boolean isTool(ItemStack tool, String... toolClasses) { return false; } + /** + * @return if the itemstack should be considered a tool + */ + public static boolean isTool(ItemStack tool) { + return tool.getItem() instanceof ItemTool || tool.getItem() instanceof IGTTool; + } + /** * Return if all the specified tool classes exists in the tool */ diff --git a/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java new file mode 100644 index 00000000000..a6764bc6fe6 --- /dev/null +++ b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java @@ -0,0 +1,137 @@ +package gregtech.mixins.jei; + +import gregtech.api.items.toolitem.ToolHelper; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import mezz.jei.transfer.BasicRecipeTransferHandlerServer; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Mixin(BasicRecipeTransferHandlerServer.class) +public class BasicRecipeTransferHandlerServerMixin { + + /** + * @author M_W_K + * @reason The modification required to make tools only be needed once on a max-transfer event is best done through + * an overwrite, due to being spread out throughout the method. + */ + @Overwrite(remap = false) + private static Map removeItemsFromInventory( + EntityPlayer player, + Container container, + Map required, + List craftingSlots, + List inventorySlots, + boolean transferAsCompleteSets, + boolean maxTransfer) { + List> orderedRequired = new ObjectArrayList<>(required.entrySet()); + + // This map becomes populated with the resulting items to transfer and is returned by this method. + final Map result = new HashMap<>(orderedRequired.size()); + + loopSets: + while (true) { // for each set + + // This map holds the original contents of a slot we have removed items from. This is used if we don't + // have enough items to complete a whole set, we can roll back the items that were removed. + Map originalSlotContents = null; + + if (transferAsCompleteSets) { + // We only need to create a new map for each set iteration if we're transferring as complete sets. + originalSlotContents = new HashMap<>(); + } + + // This map holds items found for each set iteration. Its contents are added to the result map + // after each complete set iteration. If we are transferring as complete sets, this allows + // us to simply ignore the map's contents when a complete set isn't found. + final Map foundItemsInSet = new HashMap<>(orderedRequired.size()); + + // This flag is set to false if at least one item is found during the set iteration. It is used + // to determine if iteration should continue and prevents an infinite loop if not transferring + // as complete sets. + boolean noItemsFound = true; + + for (int i = 0; i < orderedRequired.size(); i++) { + Map.Entry entry = orderedRequired.get(i); + if (entry == null) continue; // null entries are set for tool stacks that have been satisfied + + final ItemStack requiredStack = entry.getValue().copy(); + + // Locate a slot that has what we need. + final Slot slot = getSlotWithStack(container, requiredStack, craftingSlots, inventorySlots); + + boolean itemFound = (slot != null) && !slot.getStack().isEmpty() && slot.canTakeStack(player); + ItemStack resultItemStack = result.get(entry.getKey()); + boolean resultItemStackLimitReached = (resultItemStack != null) && (resultItemStack.getCount() == resultItemStack.getMaxStackSize()); + + if (!itemFound || resultItemStackLimitReached) { + // We can't find any more items to fulfill the requirements or the maximum stack size for this item + // has been reached. + + if (transferAsCompleteSets) { + // Since the full set requirement wasn't satisfied, we need to roll back any + // slot changes we've made during this set iteration. + for (Map.Entry slotEntry : originalSlotContents.entrySet()) { + ItemStack stack = slotEntry.getValue(); + slotEntry.getKey().putStack(stack); + } + break loopSets; + } + + } else { // the item was found and the stack limit has not been reached + + // Keep a copy of the slot's original contents in case we need to roll back. + if (originalSlotContents != null && !originalSlotContents.containsKey(slot)) { + originalSlotContents.put(slot, slot.getStack().copy()); + } + + // Reduce the size of the found slot. + ItemStack removedItemStack = slot.decrStackSize(1); + foundItemsInSet.put(entry.getKey(), removedItemStack); + + // mark tool stacks as 'permanently' satisfied + if (ToolHelper.isTool(removedItemStack)) orderedRequired.set(i, null); + + noItemsFound = false; + } + } + + // Merge the contents of the temporary map with the result map. + for (Map.Entry entry : foundItemsInSet.entrySet()) { + ItemStack resultItemStack = result.get(entry.getKey()); + + if (resultItemStack == null) { + result.put(entry.getKey(), entry.getValue()); + + } else { + resultItemStack.grow(1); + } + } + + if (!maxTransfer || noItemsFound) { + // If max transfer is not requested by the player this will exit the loop after trying one set. + // If no items were found during this iteration, we're done. + break; + } + } + + return result; + } + + @Shadow(remap = false) + private static Slot getSlotWithStack(Container container, ItemStack requiredStack, List craftingSlots, + List inventorySlots) { + return null; + } +} diff --git a/src/main/java/gregtech/mixins/jei/StackHelperMixin.java b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java index 4fd843f9ee8..7926250221a 100644 --- a/src/main/java/gregtech/mixins/jei/StackHelperMixin.java +++ b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java @@ -14,7 +14,7 @@ @Mixin(StackHelper.class) public class StackHelperMixin { - @Inject(method = "isEquivalent", at = @At(value = "RETURN", ordinal = 2), cancellable = true) + @Inject(method = "isEquivalent", at = @At(value = "RETURN", ordinal = 2), cancellable = true, remap = false) private void toolbeltIsEquivalent(ItemStack lhs, ItemStack rhs, CallbackInfoReturnable cir) { if (ItemGTToolbelt.checkToolAgainstToolbelt(rhs, lhs)) { cir.setReturnValue(true); diff --git a/src/main/resources/mixins.gregtech.jei.json b/src/main/resources/mixins.gregtech.jei.json index d3a1804b6a3..3e7545b737d 100644 --- a/src/main/resources/mixins.gregtech.jei.json +++ b/src/main/resources/mixins.gregtech.jei.json @@ -5,6 +5,7 @@ "minVersion": "0.8", "compatibilityLevel": "JAVA_8", "mixins": [ + "BasicRecipeTransferHandlerServerMixin", "JEITooltipMixin", "StackHelperMixin" ], From 647285cbdf2ed7bda09e286e30bae0be6ddcd6d3 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Fri, 28 Jun 2024 09:39:58 -0600 Subject: [PATCH 51/82] sp6tless --- .../api/items/toolitem/ItemGTToolbelt.java | 6 ++--- .../asm/hooks/OreIngredientHooks.java | 2 -- .../mixins/forge/OreIngredientMixin.java | 1 - ...BasicRecipeTransferHandlerServerMixin.java | 24 +++++++++---------- .../gregtech/mixins/jei/StackHelperMixin.java | 3 +-- 5 files changed, 15 insertions(+), 21 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 20238c38ea4..05525e2d7bf 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -38,6 +38,8 @@ import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.OreIngredient; import com.cleanroommc.modularui.factory.HandGuiData; import com.cleanroommc.modularui.screen.ModularPanel; @@ -49,10 +51,6 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; - -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.OreIngredient; - import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java index 5096e98fa9e..cc0a13fd4f0 100644 --- a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java +++ b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java @@ -2,8 +2,6 @@ import gregtech.api.items.toolitem.ItemGTToolbelt; -import gregtech.api.unification.OreDictUnifier; - import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreIngredient; diff --git a/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java index c20bf4a2ad0..b9a3641343c 100644 --- a/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java +++ b/src/main/java/gregtech/mixins/forge/OreIngredientMixin.java @@ -1,7 +1,6 @@ package gregtech.mixins.forge; import gregtech.api.items.toolitem.ItemGTToolbelt; -import gregtech.asm.hooks.OreIngredientHooks; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreIngredient; diff --git a/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java index a6764bc6fe6..85c6748a829 100644 --- a/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java +++ b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java @@ -2,14 +2,13 @@ import gregtech.api.items.toolitem.ToolHelper; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import mezz.jei.transfer.BasicRecipeTransferHandlerServer; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import mezz.jei.transfer.BasicRecipeTransferHandlerServer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; @@ -24,17 +23,17 @@ public class BasicRecipeTransferHandlerServerMixin { /** * @author M_W_K * @reason The modification required to make tools only be needed once on a max-transfer event is best done through - * an overwrite, due to being spread out throughout the method. + * an overwrite, due to being spread out throughout the method. */ @Overwrite(remap = false) private static Map removeItemsFromInventory( - EntityPlayer player, - Container container, - Map required, - List craftingSlots, - List inventorySlots, - boolean transferAsCompleteSets, - boolean maxTransfer) { + EntityPlayer player, + Container container, + Map required, + List craftingSlots, + List inventorySlots, + boolean transferAsCompleteSets, + boolean maxTransfer) { List> orderedRequired = new ObjectArrayList<>(required.entrySet()); // This map becomes populated with the resulting items to transfer and is returned by this method. @@ -73,7 +72,8 @@ private static Map removeItemsFromInventory( boolean itemFound = (slot != null) && !slot.getStack().isEmpty() && slot.canTakeStack(player); ItemStack resultItemStack = result.get(entry.getKey()); - boolean resultItemStackLimitReached = (resultItemStack != null) && (resultItemStack.getCount() == resultItemStack.getMaxStackSize()); + boolean resultItemStackLimitReached = (resultItemStack != null) && + (resultItemStack.getCount() == resultItemStack.getMaxStackSize()); if (!itemFound || resultItemStackLimitReached) { // We can't find any more items to fulfill the requirements or the maximum stack size for this item diff --git a/src/main/java/gregtech/mixins/jei/StackHelperMixin.java b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java index 7926250221a..16906220c90 100644 --- a/src/main/java/gregtech/mixins/jei/StackHelperMixin.java +++ b/src/main/java/gregtech/mixins/jei/StackHelperMixin.java @@ -2,10 +2,9 @@ import gregtech.api.items.toolitem.ItemGTToolbelt; -import mezz.jei.startup.StackHelper; - import net.minecraft.item.ItemStack; +import mezz.jei.startup.StackHelper; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; From b9fdd95bd91354686a9c8c444eaa9660a7578278 Mon Sep 17 00:00:00 2001 From: M-W-K Date: Fri, 28 Jun 2024 11:01:11 -0600 Subject: [PATCH 52/82] sound --- .../packets/PacketToolbeltSelectionChange.java | 8 +++++++- .../java/gregtech/core/sound/GTSoundEvents.java | 2 ++ .../resources/assets/gregtech/lang/en_us.lang | 3 +++ src/main/resources/assets/gregtech/sounds.json | 10 ++++++++++ .../resources/assets/gregtech/sounds/click.ogg | Bin 0 -> 4205 bytes 5 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 src/main/resources/assets/gregtech/sounds/click.ogg diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java index f2978076e44..7d7853e9271 100644 --- a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -3,11 +3,14 @@ import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.network.IPacket; import gregtech.api.network.IServerExecutor; +import gregtech.core.sound.GTSoundEvents; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.PacketBuffer; +import net.minecraft.util.SoundCategory; public class PacketToolbeltSelectionChange implements IPacket, IServerExecutor { @@ -31,9 +34,12 @@ public void decode(PacketBuffer buf) { @Override public void executeServer(NetHandlerPlayServer handler) { - ItemStack stack = handler.player.getHeldItemMainhand(); + EntityPlayerMP player = handler.player; + ItemStack stack = player.getHeldItemMainhand(); Item item = stack.getItem(); if (item instanceof ItemGTToolbelt toolbelt) { + player.getServerWorld().playSound(null, player.posX, player.posY, player.posZ, GTSoundEvents.CLICK, + SoundCategory.PLAYERS, 2F, 1F); toolbelt.setSelectedTool(slot, stack); } } diff --git a/src/main/java/gregtech/core/sound/GTSoundEvents.java b/src/main/java/gregtech/core/sound/GTSoundEvents.java index 53fd8067972..80f5caccd3b 100644 --- a/src/main/java/gregtech/core/sound/GTSoundEvents.java +++ b/src/main/java/gregtech/core/sound/GTSoundEvents.java @@ -57,6 +57,7 @@ public class GTSoundEvents { // Misc public static SoundEvent DEFAULT_ALARM; + public static SoundEvent CLICK; public static void register() { FORGE_HAMMER = soundManager.registerSound("tick.forge_hammer"); @@ -102,5 +103,6 @@ public static void register() { BREAKDOWN_MECHANICAL = soundManager.registerSound("maintenance.mechanical"); DEFAULT_ALARM = soundManager.registerSound("alarm"); + CLICK = soundManager.registerSound("click"); } } diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index 3974b4635c1..e4fd8493795 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -6090,6 +6090,9 @@ gregtech.subtitle.entity.portal_opening=Portal opens gregtech.subtitle.entity.portal_closing=Portal closes gregtech.subtitle.maintenance.electrical=Electrical breakdown gregtech.subtitle.maintenance.mechanical=Mechanical breakdown +gregtech.subtitle.alarm=Alarm Whines +gregtech.subtitle.click=Something Clicks + # Debug messaging gregtech.debug.f3_h.enabled=GregTech has modified the debug info! For Developers: enable the misc:debug config option in the GregTech config file to see more diff --git a/src/main/resources/assets/gregtech/sounds.json b/src/main/resources/assets/gregtech/sounds.json index 10977e9cf2d..b5bd3bcdcc0 100644 --- a/src/main/resources/assets/gregtech/sounds.json +++ b/src/main/resources/assets/gregtech/sounds.json @@ -397,5 +397,15 @@ "stream" : false } ] + }, + "click" : { + "subtitle" : "gregtech.subtitle.click", + "category" : "block", + "sounds" : [ + { + "name" : "gregtech:click", + "stream" : false + } + ] } } diff --git a/src/main/resources/assets/gregtech/sounds/click.ogg b/src/main/resources/assets/gregtech/sounds/click.ogg new file mode 100644 index 0000000000000000000000000000000000000000..bed708e967680877fc9d01994027fffcf283a5b8 GIT binary patch literal 4205 zcmahsd0bP+);Gu!0cn7UfI;DzNP?gQ6D2M!2_O)Nz=g{anujbAX&O{wtoW4{NkEK1 zF@`{6=np7SQSdb=QEZ`D0TB>cWD^lBLU5@|tp@9}eshER`u=+Jn>+X1v(B73XXf1S zw6rM51bWvT>KYtTa6@q0Sg-?Txa#f`^}xvNM&Rxfu{s0Fk9vmStXUr0$zj%^mxozGT9Hgdna$)X0@6H<%D^`I@5<;JI zmZmZHIn3K2GJ{Jb=FCn<=@urKfjQ#>UfRt(=`8hNV3$i>X{n2$5(uiSCd;bHmN@4I zOQ;iqaDI{aE4v9-j}WeE30Bxe@n&EnAS~bumem9o-wT!#+EAwv4dGF*LN48D%!g|J}da5$sM#a`LT-3ph zS@L7DCWc-u>b*LnruG7;S{-k#0(^RPTV=fEJmjv;>Qi~3xZSCCEcQ62lP8!x7a2-``l+5X1y0WOVq3f{j)o26dSOl(%mrIecs_FkRR494-W^w zACe2)@*Oj~C?_g&*&ekgs|$U)JAa|QJS0XK zs}v^a#N%cBaYOdx-#X92xI{Z}kjPh1}GG$Uodl8dK&<-`y< zDP5kHr9Anq>i)Oid7Lt`Ksb~IZL;J0WVQQbC-)W47RYyet2|k&TGe&@(Zw?l|5vv% z1~?Id_7HdT6mvvp;iFqh8ud?MH4MJr3FHe1$eBg`brjK{O}NTz#6usD;;iLx@JN(>AhH;VQgV<+{&kvgEE<_`K!$Yu zgqPW|O7X;6&KUX$sABNR(+MZaKBz)QqLJ}+fJ%?t!;3`t@j&xlUi=6WJDd$P4@Ggt z79)rf85`mwN^#;IWFm$)HiEL;%^TXA%kJ) zgoXkl5l(EQFiI>;un!zrj0`CQqr^Zi;ppG*#BpyV>lf&ZaZ-wJ?KunA%^AZ8y zNZ#G7jEN=RMIzz}1uqeZEy+k+f3qcH)4zl%;~zKtYlU@C%MYHs@pTtlIOXDr*`@w> z*XPp)&k2FPi9Ni;GV#QYhZiHF5ne2R%z(tc%m$OV`!ajd5g9Q6m*)>DE0PS^n#We9 zh%OJzKwmE8#eFq3`|lQ?J>mo)tL z?qRxgfJ@diMz9apYMc`U^eu(VPW4ea!(F2=5_%XO6%ufSf`g9hNokK`xRWHsYzsGy zoE=8eIQn~NOBKn0Fv|VBsl8l8*0jsnpOZ9k31JMKqo^1)?rt=$X@p@xsR#zD_%>`0 zpo-0=f>{AoHY_$!6~zX#N?t`7ierDK1*$@+!x8XdKnP`1fvODc^e}UWSB+f?nbhHs za;Cn~*`G3Re8?fCz8N)6>X5UGP~$~S;5gi>omO${n%YMN!loB0QD1E%H!7?NomG=r zyy$VWqz|mTJ%U|W-^fiUWE^~FT-FFw3A8T(0jLUP({+x5V){!J_cR~~KGV*qL{F$Q zqfr9-c}D@T!3C;jhEqWGv%m%%4=WW1K;E06d2i~*rkYnV3#j@U8kRbvR>-J&*BY2Q zLy*EgdRK)UMj_ZzQzM53RSFpXtRCdO37YpyX(R^=khUbK#1h)Ji_rc1rbrqxw%7CO z^MHOD$SfBl24tVGdmbYePZ)U+F^^{mh@^u61_8bqNC8az%k05uBSx2(NJC-)M#-Oy zWxSZXE=5j8OtR-K!%`)Z1(*fd$lIuINc~*>G|l zU4Ki0`{f)yp#ZJu+LMren)qNivvd6;UrC3y-8%ufp$`eo9mmn@PX z=nKgLC?L0JZ5^>%Zp zj{{rvj!yxHfD)A83qsYA>F$I$Bz?bd$+8?{{Q5x^M^h3tZss7va4CvbMo}Y{7K*+jS09x2)9sV4A1t zL5otzmbw@st|Z?x@ylxuyxDHH$LUV)>c<;!EL<+G?N`V$xb@P)^_!mMyWhHFT2T#K zpg$B4*!_@uWfg1oy5pT9naxxpUQO7$(@L>lDj(9dt*-s*htqWc)< zZ0z(p>tXXlYcG95c2=Z?{-{`OTP)|s^c=AiXZ^v6TAw3{CZ^Mp8N7pLq^8( z&3|Cb{leE)x7pANpY9g zzoo%%O#NH_ZLe&f=8vv@W$?;>FqdrEXc8gV{L{x7(MJz`S7dqca#c*wv3l9>Y##ph zC)=`|tTruQ-WOJW;LYy0ccH8I3@^U9ob;GKc3%(8-C6K4+H&4Jb5oXqcC`QZsmqw< zt&@@1M~p(KW$(Rmt1ZDFQN*Vlgnuqqv5y3-X~^kdDZ>&?FXM9G%;?Lu#^YzX+Op-3R|zZgG=*NVWR1+lDKM_^~cKzm3}Z+`ZTHn~BC_ ze{tM(`_4(HOrOTPIE@qum5@&zTWOnCsobKBAY__&~c~ia3Y_dyg&oo)O=(zr05E2Y+Jk_2TDVtA35Jpr>9u zjQygz=J0sMssjstCj9nb&~BnDrTeR8JvSd#8`7}2+x%q-i;@OIbvT=cXI?bO&+%7a zK9jEwZT@qAeuVOni*CV*)~mnWl5|`-m_y3jI?X-Ac$N9YocqOJX8D3kO{umO^wX`X z=Yw%F!8BEliQ_Vs^2VIO8WA_c+FN>OOZnnJ!ZRIku_d|fk Date: Sun, 30 Jun 2024 08:52:20 -0600 Subject: [PATCH 53/82] Alternate mixin --- ...BasicRecipeTransferHandlerServerMixin.java | 172 ++++++------------ 1 file changed, 57 insertions(+), 115 deletions(-) diff --git a/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java index 85c6748a829..cbd4a6c140d 100644 --- a/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java +++ b/src/main/java/gregtech/mixins/jei/BasicRecipeTransferHandlerServerMixin.java @@ -2,136 +2,78 @@ import gregtech.api.items.toolitem.ToolHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import com.llamalad7.mixinextras.injector.ModifyExpressionValue; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import com.llamalad7.mixinextras.sugar.Share; +import com.llamalad7.mixinextras.sugar.ref.LocalRef; +import it.unimi.dsi.fastutil.ints.IntArrayList; import mezz.jei.transfer.BasicRecipeTransferHandlerServer; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import java.util.HashMap; -import java.util.List; +import java.util.Iterator; import java.util.Map; -@Mixin(BasicRecipeTransferHandlerServer.class) +@Mixin(value = BasicRecipeTransferHandlerServer.class, remap = false) public class BasicRecipeTransferHandlerServerMixin { /** - * @author M_W_K - * @reason The modification required to make tools only be needed once on a max-transfer event is best done through - * an overwrite, due to being spread out throughout the method. + * @reason create the list used to indicate what slots contain tools, and thus should be ignored on the 2nd+ checks */ - @Overwrite(remap = false) - private static Map removeItemsFromInventory( - EntityPlayer player, - Container container, - Map required, - List craftingSlots, - List inventorySlots, - boolean transferAsCompleteSets, - boolean maxTransfer) { - List> orderedRequired = new ObjectArrayList<>(required.entrySet()); - - // This map becomes populated with the resulting items to transfer and is returned by this method. - final Map result = new HashMap<>(orderedRequired.size()); - - loopSets: - while (true) { // for each set - - // This map holds the original contents of a slot we have removed items from. This is used if we don't - // have enough items to complete a whole set, we can roll back the items that were removed. - Map originalSlotContents = null; - - if (transferAsCompleteSets) { - // We only need to create a new map for each set iteration if we're transferring as complete sets. - originalSlotContents = new HashMap<>(); - } - - // This map holds items found for each set iteration. Its contents are added to the result map - // after each complete set iteration. If we are transferring as complete sets, this allows - // us to simply ignore the map's contents when a complete set isn't found. - final Map foundItemsInSet = new HashMap<>(orderedRequired.size()); - - // This flag is set to false if at least one item is found during the set iteration. It is used - // to determine if iteration should continue and prevents an infinite loop if not transferring - // as complete sets. - boolean noItemsFound = true; - - for (int i = 0; i < orderedRequired.size(); i++) { - Map.Entry entry = orderedRequired.get(i); - if (entry == null) continue; // null entries are set for tool stacks that have been satisfied - - final ItemStack requiredStack = entry.getValue().copy(); - - // Locate a slot that has what we need. - final Slot slot = getSlotWithStack(container, requiredStack, craftingSlots, inventorySlots); - - boolean itemFound = (slot != null) && !slot.getStack().isEmpty() && slot.canTakeStack(player); - ItemStack resultItemStack = result.get(entry.getKey()); - boolean resultItemStackLimitReached = (resultItemStack != null) && - (resultItemStack.getCount() == resultItemStack.getMaxStackSize()); - - if (!itemFound || resultItemStackLimitReached) { - // We can't find any more items to fulfill the requirements or the maximum stack size for this item - // has been reached. - - if (transferAsCompleteSets) { - // Since the full set requirement wasn't satisfied, we need to roll back any - // slot changes we've made during this set iteration. - for (Map.Entry slotEntry : originalSlotContents.entrySet()) { - ItemStack stack = slotEntry.getValue(); - slotEntry.getKey().putStack(stack); - } - break loopSets; - } - - } else { // the item was found and the stack limit has not been reached - - // Keep a copy of the slot's original contents in case we need to roll back. - if (originalSlotContents != null && !originalSlotContents.containsKey(slot)) { - originalSlotContents.put(slot, slot.getStack().copy()); - } - - // Reduce the size of the found slot. - ItemStack removedItemStack = slot.decrStackSize(1); - foundItemsInSet.put(entry.getKey(), removedItemStack); - - // mark tool stacks as 'permanently' satisfied - if (ToolHelper.isTool(removedItemStack)) orderedRequired.set(i, null); - - noItemsFound = false; - } - } - - // Merge the contents of the temporary map with the result map. - for (Map.Entry entry : foundItemsInSet.entrySet()) { - ItemStack resultItemStack = result.get(entry.getKey()); - - if (resultItemStack == null) { - result.put(entry.getKey(), entry.getValue()); + @Inject(method = "removeItemsFromInventory", at = @At("HEAD")) + private static void gregtechCEu$initCompletedList(CallbackInfoReturnable> cir, + @Share("completed") LocalRef completed) { + completed.set(new IntArrayList()); + } - } else { - resultItemStack.grow(1); - } - } + /** + * @reason add the index of the entry to the list of skipped locations on the 2nd+ checks + */ + @Inject(method = "removeItemsFromInventory", + at = @At(value = "INVOKE", + target = "Ljava/util/Map;put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", + ordinal = 1)) + private static void gregtechCEu$markItemStackAsCompleted(CallbackInfoReturnable> cir, + @Local(ordinal = 0) Map.Entry entry, + @Local(ordinal = 2) ItemStack removedItemStack, + @Share("completed") LocalRef completed) { + // mark tool stacks as 'permanently' satisfied + if (removedItemStack != null && ToolHelper.isTool(removedItemStack)) completed.get().add(entry.getKey()); + } - if (!maxTransfer || noItemsFound) { - // If max transfer is not requested by the player this will exit the loop after trying one set. - // If no items were found during this iteration, we're done. - break; - } + /** + * @reason if the given location is marked as completed, skip processing this slot and check the next slot + */ + @ModifyExpressionValue(method = "removeItemsFromInventory", + at = @At(value = "INVOKE", target = "Ljava/util/Iterator;hasNext()Z", ordinal = 0)) + private static boolean gregtechCEu$skipCompletedStacks(boolean original, + @Local(ordinal = 0) Iterator> iterator, + @Share("completed") LocalRef completed, + @Share("iterator_next") LocalRef> next) { + if (!original) return false; + next.set(iterator.next()); + while (completed.get().contains(next.get().getKey())) { + if (!iterator.hasNext()) return false; + next.set(iterator.next()); } - - return result; + return true; } - @Shadow(remap = false) - private static Slot getSlotWithStack(Container container, ItemStack requiredStack, List craftingSlots, - List inventorySlots) { - return null; + /** + * @reason use the next variable that respects the completed status + */ + @WrapOperation(method = "removeItemsFromInventory", + at = @At(value = "INVOKE", target = "Ljava/util/Iterator;next()Ljava/lang/Object;", ordinal = 0)) + private static Object gregtechCEu$useCorrectIteratorNext(Iterator> instance, + Operation> original, + @Share("completed") LocalRef completed, + @Share("iterator_next") LocalRef> next) { + return next.get() == null ? original.call(instance) : next.get(); } } From 56283636aa4cbcfaa99680f442abf74b3f1dd74c Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Wed, 16 Oct 2024 13:52:49 -0600 Subject: [PATCH 54/82] Merge with master --- .../java/gregtech/api/items/toolitem/IGTTool.java | 13 +++++-------- .../gregtech/api/items/toolitem/ItemGTToolbelt.java | 11 +++-------- src/main/java/gregtech/client/ClientProxy.java | 1 - 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 9e10e9b0c7e..2ed025f154e 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -65,7 +65,7 @@ import com.cleanroommc.modularui.factory.HandGuiData; import com.cleanroommc.modularui.factory.ItemGuiFactory; import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.value.sync.GuiSyncManager; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widgets.ButtonWidget; import com.cleanroommc.modularui.widgets.TextWidget; import com.cleanroommc.modularui.widgets.layout.Column; @@ -940,7 +940,7 @@ default void playSound(EntityPlayer player) { } @Override - default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { + default ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 120, 80); Supplier tag = () -> getBehaviorsTag(guiData.getUsedItemStack()); @@ -950,8 +950,7 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) guiSyncManager.syncValue("NBTSync", nbtSyncer); Column columns = new Column(); - columns.flex().coverChildren().startDefaultMode() - .leftRel(0.07f).bottomRel(0.5f).endDefaultMode(); + columns.flex().coverChildren().leftRel(0.07f).bottomRel(0.5f); columns.child(new TextWidget(IKey.lang("item.gt.tool.aoe.columns")).paddingBottom(5)); columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) .disableHoverBackground().onMousePressed(data -> { @@ -973,8 +972,7 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) panel.child(columns); Column rows = new Column(); - rows.flex().coverChildren().startDefaultMode() - .rightRel(0.5f).bottomRel(0.5f).endDefaultMode(); + rows.flex().coverChildren().rightRel(0.5f).bottomRel(0.5f); rows.child(new TextWidget(IKey.lang("item.gt.tool.aoe.rows")).paddingBottom(5)); rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) .disableHoverBackground().onMousePressed(data -> { @@ -996,8 +994,7 @@ default ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) panel.child(rows); Column layers = new Column(); - layers.flex().coverChildren().startDefaultMode() - .rightRel(0.07f).bottomRel(0.5f).endDefaultMode(); + layers.flex().coverChildren().rightRel(0.07f).bottomRel(0.5f); layers.child(new TextWidget(IKey.lang("item.gt.tool.aoe.layers")).paddingBottom(5)); layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) .disableHoverBackground().onMousePressed(data -> { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 05525e2d7bf..3ad95e8e9b3 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -43,7 +43,7 @@ import com.cleanroommc.modularui.factory.HandGuiData; import com.cleanroommc.modularui.screen.ModularPanel; -import com.cleanroommc.modularui.value.sync.GuiSyncManager; +import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.value.sync.SyncHandlers; import com.cleanroommc.modularui.widgets.ItemSlot; import com.cleanroommc.modularui.widgets.SlotGroupWidget; @@ -80,7 +80,7 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem, } @Override - public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) { + public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); ItemStack selected = handler.getSelectedStack(); if (selected != null && selected.getItem() instanceof ItemUIFactory factory) { @@ -95,12 +95,7 @@ public ModularPanel buildUI(HandGuiData guiData, GuiSyncManager guiSyncManager) guiSyncManager.registerSlotGroup(group); SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); - slotGroupWidget.flex() - .coverChildren() - .startDefaultMode() - .leftRel(0.5f); - slotGroupWidget.flex().top(7); - slotGroupWidget.flex().endDefaultMode(); + slotGroupWidget.flex().coverChildren().leftRel(0.5f).top(7); slotGroupWidget.debugName("toolbelt_inventory"); for (int i = 0; i < handler.getSlots(); i++) { int finalI = i; diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index f19c08c69f7..7d038b827c8 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -5,7 +5,6 @@ import gregtech.api.items.metaitem.MetaOreDictItem; import gregtech.api.items.toolitem.IGTTool; import gregtech.api.items.toolitem.ItemGTToolbelt; -import gregtech.api.terminal.TerminalRegistry; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; import gregtech.api.unification.stack.UnificationEntry; From 03c55bc89e0a85e8aa0756e38595eab7a0ae06fc Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Thu, 7 Nov 2024 18:42:26 -0700 Subject: [PATCH 55/82] Fixes and change to JEI behavior --- .../api/items/toolitem/ItemGTToolbelt.java | 91 +++++++++++++------ .../api/items/toolitem/ToolHelper.java | 17 ++++ .../items/behaviors/ColorSprayBehaviour.java | 25 +++++ 3 files changed, 107 insertions(+), 26 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 3ad95e8e9b3..ef625fb6b69 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -11,6 +11,7 @@ import gregtech.api.unification.material.properties.PropertyKey; import gregtech.api.unification.material.properties.ToolProperty; import gregtech.api.util.LocalizationUtils; +import gregtech.common.items.behaviors.ColorSprayBehaviour; import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; @@ -269,7 +270,7 @@ public double getDurabilityForDisplay(@NotNull ItemStack stack) { if (selected != null) { double dis = selected.getItem().getDurabilityForDisplay(selected); // vanillaesque tools need to be inverted - if (!(selected.getItem() instanceof IGTTool)) dis = 1 - dis; + if (selected.getItem() instanceof ItemTool) dis = 1 - dis; return dis; } else return definition$getDurabilityForDisplay(stack); } @@ -323,17 +324,18 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { @Override public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { - Ingredient nextCraftIngredient = getHandler(stack).nextCraftIngredient; - if (nextCraftIngredient != null) { + if (getHandler(stack).dealCraftDamageToSelected()) { stack = stack.copy(); - this.craftDamageTools(stack, nextCraftIngredient); return stack; } return super.getContainerItem(stack); } public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { - getHandler(stack).nextCraftIngredient = ingredient; + Integer match = getHandler(stack).checkIngredientAgainstTools(ingredient); + if (match != null) { + setSelectedTool(match, stack); + } } public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass, @@ -342,15 +344,11 @@ public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass } public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { - return getHandler(stack).checkIngredientAgainstTools(ingredient, false); + return getHandler(stack).checkIngredientAgainstTools(ingredient) != null; } public boolean supportsTool(ItemStack stack, ItemStack tool) { - return getHandler(stack).checkToolAgainstTools(tool, false); - } - - public void craftDamageTools(ItemStack stack, Ingredient ingredient) { - getHandler(stack).checkIngredientAgainstTools(ingredient, true); + return getHandler(stack).checkToolAgainstTools(tool) != null; } private ToolStackHandler getHandler(ItemStack stack) { @@ -400,6 +398,23 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { else return result; } + @Override + public @NotNull EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, + @NotNull BlockPos pos, @NotNull EnumHand hand, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { + ToolStackHandler handler = getHandler(player.getHeldItem(hand)); + ItemStack selected = handler.getSelectedStack(); + if (selected != null) { + ColorSprayBehaviour spray = ColorSprayBehaviour.getBehavior(selected); + if (spray != null) { + EnumActionResult result = spray.useFromToolbelt(player, world, pos, hand, facing, hitX, hitY, hitZ, + selected); + if (result != EnumActionResult.PASS) return result; + } + } + return super.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); + } + @Override public int getColor(ItemStack stack, int tintIndex) { if (tintIndex == 0) { @@ -432,7 +447,7 @@ public static boolean checkIngredientAgainstToolbelt(@NotNull ItemStack input, @ } public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @NotNull ItemStack tool) { - if (toolbelt.getItem() instanceof ItemGTToolbelt belt && ToolHelper.isTool(tool)) { + if (toolbelt.getItem() instanceof ItemGTToolbelt belt && ToolHelper.isUtilityItem(tool)) { return belt.supportsTool(toolbelt, tool); } return false; @@ -450,7 +465,7 @@ public ToolbeltCapabilityProvider(ItemStack stack) { String string = toolTag.getString(MATERIAL_KEY); Material material = GregTechAPI.materialManager.getMaterial(string); if (material == null) { - toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).toString()); + toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).getRegistryName()); } ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); return (int) (toolProperty == null ? 5 : toolProperty.getToolHarvestLevel() * 5.4f); @@ -489,6 +504,22 @@ protected ToolStackHandler getHandler(int minsize) { } } + @Override + public NBTTagCompound getNBTShareTag(ItemStack stack) { + NBTTagCompound tag = new NBTTagCompound(); + if (stack.getTagCompound() != null) { + tag.setTag("NBT", stack.getTagCompound()); + } + tag.setTag("Cap", getHandler(stack).serializeNBT()); + return tag; + } + + @Override + public void readNBTShareTag(ItemStack stack, NBTTagCompound nbt) { + // cap syncing is handled separately, we only need it on the share tag so that changes are detected properly. + stack.setTagCompound(nbt == null ? null : (nbt.hasKey("NBT") ? nbt.getCompoundTag("NBT") : null)); + } + protected static class ToolStackHandler extends ItemStackHandler { private Ingredient nextCraftIngredient; @@ -561,7 +592,7 @@ public Set getToolClasses(boolean defaultEmpty) { public boolean isItemValid(int slot, @NotNull ItemStack stack) { Item item = stack.getItem(); if (item instanceof ItemGTToolbelt) return false; - return ToolHelper.isTool(stack); + return ToolHelper.isUtilityItem(stack); } @Override @@ -636,30 +667,38 @@ public boolean checkMaintenanceAgainstTools(String toolClass, boolean doCrafting return false; } - public boolean checkIngredientAgainstTools(Ingredient ingredient, boolean doCraftingDamage) { + @Nullable + public Integer checkIngredientAgainstTools(Ingredient ingredient) { for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); if (ingredient.test(stack)) { - if (doCraftingDamage && stack.getItem().hasContainerItem(stack)) { - this.setStackInSlot(i, stack.getItem().getContainerItem(stack)); - } - return true; + return i; } } - return false; + return null; } - public boolean checkToolAgainstTools(ItemStack tool, boolean doCraftingDamage) { + public void dealCraftDamageToSlot(int slot) { + ItemStack stack = this.getStackInSlot(slot); + this.setStackInSlot(slot, stack.getItem().getContainerItem(stack)); + } + + public boolean dealCraftDamageToSelected() { + if (selectedSlot != null) { + dealCraftDamageToSlot(selectedSlot); + return true; + } else return false; + } + + @Nullable + public Integer checkToolAgainstTools(ItemStack tool) { for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); if (OreDictionary.itemMatches(stack, tool, false)) { - if (doCraftingDamage && stack.getItem().hasContainerItem(stack)) { - this.setStackInSlot(i, stack.getItem().getContainerItem(stack)); - } - return true; + return i; } } - return false; + return null; } } } diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 454157b2fb9..b79d980dc6b 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -3,6 +3,7 @@ import gregtech.api.GTValues; import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.IElectricItem; +import gregtech.api.items.metaitem.MetaItem; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; @@ -15,6 +16,7 @@ import gregtech.api.util.function.QuintFunction; import gregtech.common.ConfigHolder; import gregtech.common.items.MetaItems; +import gregtech.common.items.behaviors.ColorSprayBehaviour; import gregtech.tools.enchants.EnchantmentHardHammer; import net.minecraft.advancements.CriteriaTriggers; @@ -389,6 +391,13 @@ public static boolean isTool(ItemStack tool, String... toolClasses) { return false; } + /** + * @return if the itemstack should be considered a utility item and thus can be put into toolbelts. + */ + public static boolean isUtilityItem(ItemStack utility) { + return isTool(utility) || isSpraycan(utility); + } + /** * @return if the itemstack should be considered a tool */ @@ -396,6 +405,14 @@ public static boolean isTool(ItemStack tool) { return tool.getItem() instanceof ItemTool || tool.getItem() instanceof IGTTool; } + /** + * @return if the itemstack should be considered a spraycan + */ + public static boolean isSpraycan(ItemStack spraycan) { + return spraycan.getItem() instanceof MetaItemmeta && + meta.getBehaviours(spraycan).stream().anyMatch(b -> b instanceof ColorSprayBehaviour); + } + /** * Return if all the specified tool classes exists in the tool */ diff --git a/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java b/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java index a52777f70d6..72d164afd19 100644 --- a/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java +++ b/src/main/java/gregtech/common/items/behaviors/ColorSprayBehaviour.java @@ -1,5 +1,7 @@ package gregtech.common.items.behaviors; +import gregtech.api.items.metaitem.MetaItem; +import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.items.metaitem.stats.IItemDurabilityManager; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; @@ -68,6 +70,29 @@ public ActionResult onItemUse(EntityPlayer player, World world, Block return ActionResult.newResult(EnumActionResult.SUCCESS, player.getHeldItem(hand)); } + @Nullable + public static ColorSprayBehaviour getBehavior(ItemStack spraycan) { + if (!(spraycan.getItem() instanceof MetaItemmeta)) return null; + for (IItemBehaviour behaviour : meta.getBehaviours(spraycan)) { + if (behaviour instanceof ColorSprayBehaviour spray) return spray; + } + return null; + } + + public EnumActionResult useFromToolbelt(EntityPlayer player, World world, BlockPos pos, EnumHand hand, + EnumFacing facing, float hitX, float hitY, float hitZ, ItemStack spraycan) { + if (!player.canPlayerEdit(pos, facing, spraycan)) { + return EnumActionResult.FAIL; + } + if (!tryPaintBlock(player, world, pos, facing)) { + return EnumActionResult.PASS; + } + useItemDurability(player, hand, spraycan, empty.copy()); + world.playSound(null, player.posX, player.posY, player.posZ, GTSoundEvents.SPRAY_CAN_TOOL, + SoundCategory.PLAYERS, 1.0f, 1.0f); + return EnumActionResult.SUCCESS; + } + private boolean tryPaintBlock(EntityPlayer player, World world, BlockPos pos, EnumFacing side) { IBlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); From f3740498ab6d730b9d5fbe3887739ebbe806db0c Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Thu, 7 Nov 2024 19:47:36 -0700 Subject: [PATCH 56/82] Allow toolbelt to fix maintenance in-world and prevent merge crafting --- .../gregtech/api/items/toolitem/ItemGTToolbelt.java | 12 ++++++++++-- .../MetaTileEntityMaintenanceHatch.java | 2 +- .../mixins/minecraft/RecipeRepairItemMixin.java | 4 +++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index ef625fb6b69..f4158d3d2ef 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -4,6 +4,7 @@ import gregtech.api.items.IDyeableItem; import gregtech.api.items.gui.ItemUIFactory; import gregtech.api.items.toolitem.behavior.IToolBehavior; +import gregtech.api.metatileentity.MetaTileEntityHolder; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.material.Material; @@ -12,6 +13,7 @@ import gregtech.api.unification.material.properties.ToolProperty; import gregtech.api.util.LocalizationUtils; import gregtech.common.items.behaviors.ColorSprayBehaviour; +import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMaintenanceHatch; import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; @@ -393,9 +395,15 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { @NotNull BlockPos pos, @NotNull EnumFacing side, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { EnumActionResult result = IDyeableItem.super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); - if (result == EnumActionResult.PASS) + if (result == EnumActionResult.PASS) { + ToolStackHandler handler = getHandler(player.getHeldItem(hand)); + if (handler.getSelectedSlot() == null && world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && + holder.getMetaTileEntity() instanceof MetaTileEntityMaintenanceHatch maintenance) { + maintenance.fixMaintenanceProblems(player); + return EnumActionResult.SUCCESS; + } return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); - else return result; + } else return result; } @Override diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index ea8dcbc1fa5..583f032a4f3 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -197,7 +197,7 @@ public void update() { * * @param entityPlayer the player performing the fixing */ - private void fixMaintenanceProblems(@Nullable EntityPlayer entityPlayer) { + public void fixMaintenanceProblems(@Nullable EntityPlayer entityPlayer) { if (!(this.getController() instanceof IMaintenance)) return; diff --git a/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java b/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java index 5cd275b6cf8..dd76f8d959c 100644 --- a/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java +++ b/src/main/java/gregtech/mixins/minecraft/RecipeRepairItemMixin.java @@ -1,6 +1,7 @@ package gregtech.mixins.minecraft; import gregtech.api.items.toolitem.IGTTool; +import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolHelper; import net.minecraft.inventory.InventoryCrafting; @@ -36,7 +37,8 @@ public class RecipeRepairItemMixin { ItemStack itemstack1 = list.get(0); if (itemstack.getItem() instanceof IGTTool first && itemstack1.getItem() instanceof IGTTool second) { - if (first.isElectric() || second.isElectric()) { + if (first.isElectric() || second.isElectric() || + first instanceof ItemGTToolbelt || second instanceof ItemGTToolbelt) { cir.setReturnValue(false); } else { cir.setReturnValue(first.getToolMaterial(itemstack) == second.getToolMaterial(itemstack1)); From a862a1d330fe5a65c0f6f1523db9c92d4710395e Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Thu, 7 Nov 2024 20:51:37 -0700 Subject: [PATCH 57/82] Tweaks and rebalance slot counts --- src/main/java/gregtech/api/items/toolitem/IGTTool.java | 6 +++--- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 2 +- src/main/resources/assets/gregtech/lang/en_us.lang | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 2ed025f154e..97304fe8068 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -649,7 +649,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); - else behaviors = getToolStats().getBehaviors(); + else return EnumActionResult.PASS; for (IToolBehavior behavior : behaviors) { if (behavior.onItemUseFirst(stack, player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { @@ -669,7 +669,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); - else behaviors = getToolStats().getBehaviors(); + else return EnumActionResult.PASS; for (IToolBehavior behavior : behaviors) { if (behavior.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ) == @@ -697,7 +697,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); - else behaviors = getToolStats().getBehaviors(); + else return ActionResult.newResult(EnumActionResult.PASS, original); for (IToolBehavior behavior : behaviors) { if (behavior.onItemRightClick(stack, world, player, hand).getType() == EnumActionResult.SUCCESS) { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index f4158d3d2ef..0f080ef760a 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -476,7 +476,7 @@ public ToolbeltCapabilityProvider(ItemStack stack) { toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).getRegistryName()); } ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); - return (int) (toolProperty == null ? 5 : toolProperty.getToolHarvestLevel() * 5.4f); + return Math.min(8, 3 + (toolProperty == null ? 0 : toolProperty.getToolHarvestLevel())); }; } diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index c57ce185f41..c2985695e21 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1036,7 +1036,7 @@ item.gt.tool.wire_cutter_lv.name=%s Wire Cutter (LV) item.gt.tool.wire_cutter_hv.name=%s Wire Cutter (HV) item.gt.tool.wire_cutter_iv.name=%s Wire Cutter (IV) item.gt.tool.toolbelt.name=%s Toolbelt%s -item.gt.tool.toolbelt.tooltip=Holds too many tools for too many jobs. +item.gt.tool.toolbelt.tooltip=Can trigger maintenance repair by clicking on a maintenance hatch item.gt.tool.tooltip.crafting_uses=§a%s Crafting Uses From e836de93ce80b1b4a137987066e58363c6cf387d Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 13:20:59 -0700 Subject: [PATCH 58/82] Behold, RENDERING --- .../gregtech/api/items/toolitem/IGTTool.java | 8 +-- .../api/items/toolitem/ItemGTToolbelt.java | 23 ++++-- .../api/items/toolitem/ToolHelper.java | 26 +++---- .../java/gregtech/client/ClientProxy.java | 71 ++++++++++++++++++- .../renderer/handler/ToolbeltRenderer.java | 2 +- .../client/utils/ToolChargeBarRenderer.java | 2 +- .../java/gregtech/common/ConfigHolder.java | 19 +++++ .../gregtech/common/ToolEventHandlers.java | 2 +- .../mixins/minecraft/MinecraftMixin.java | 23 ++++++ src/main/resources/gregtech_at.cfg | 7 ++ 10 files changed, 156 insertions(+), 27 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 97304fe8068..83ecfcb9bf1 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -644,7 +644,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { float hitY, float hitZ, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } List behaviors; @@ -664,7 +664,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { EnumFacing facing, float hitX, float hitY, float hitZ) { ItemStack stack = player.getHeldItem(hand); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } List behaviors; @@ -685,7 +685,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { ItemStack stack = player.getHeldItem(hand); ItemStack original = stack; if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } if (!world.isRemote) { @@ -911,7 +911,7 @@ default ModelResourceLocation getModelLocation() { // Sound Playing default void playCraftingSound(EntityPlayer player, ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } // player null check for things like auto-crafters diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 0f080ef760a..6ac0ea1df20 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -78,8 +78,22 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem, markerItem); } - public @Nullable ItemStack getSelectedItem(@NotNull ItemStack stack) { - return getHandler(stack).getSelectedStack(); + public @Nullable Integer getSelectedSlot(@NotNull ItemStack toolbelt) { + return getHandler(toolbelt).getSelectedSlot(); + } + + public int getSlotCount(@NotNull ItemStack toolbelt) { + return getHandler(toolbelt).getSlots(); + } + + public @Nullable ItemStack getSelectedTool(@NotNull ItemStack toolbelt) { + return getHandler(toolbelt).getSelectedStack(); + } + + public @Nullable ItemStack getToolInSlot(@NotNull ItemStack toolbelt, int slot) { + ToolStackHandler handler = getHandler(toolbelt); + if (slot < 0 || slot >= handler.getSlots()) return null; + return handler.getStackInSlot(slot); } @Override @@ -372,7 +386,8 @@ public void changeSelectedTool(int direction, ItemStack stack) { public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { ToolStackHandler handler = getHandler(stack); - if (slot == null || slot < 0 || slot >= handler.getSlots()) handler.selectedSlot = null; + if (slot == null || slot < 0 || slot >= handler.getSlots() || handler.getStackInSlot(slot).isEmpty()) + handler.selectedSlot = null; else handler.selectedSlot = slot; } @@ -476,7 +491,7 @@ public ToolbeltCapabilityProvider(ItemStack stack) { toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).getRegistryName()); } ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); - return Math.min(8, 3 + (toolProperty == null ? 0 : toolProperty.getToolHarvestLevel())); + return Math.min(8, 2 + (toolProperty == null ? 0 : toolProperty.getToolHarvestLevel())); }; } diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index b79d980dc6b..8036dbdef44 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -198,7 +198,7 @@ public static void registerToolSymbol(Character symbol, IGTTool tool) { public static NBTTagCompound getToolTag(ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } return stack.getOrCreateSubCompound(TOOL_TAG_KEY); @@ -206,7 +206,7 @@ public static NBTTagCompound getToolTag(ItemStack stack) { public static NBTTagCompound getBehaviorsTag(ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); @@ -214,7 +214,7 @@ public static NBTTagCompound getBehaviorsTag(ItemStack stack) { public static void setBehaviorsTag(ItemStack stack, NBTTagCompound tag) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } stack.setTagInfo(BEHAVIOURS_TAG_KEY, tag); @@ -250,7 +250,7 @@ public static ItemStack getAndSetToolData(IGTTool tool, Material material, int m */ public static void damageItemWhenCrafting(@NotNull ItemStack stack, @Nullable EntityLivingBase entity) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selectedStack = toolbelt.getSelectedItem(stack); + ItemStack selectedStack = toolbelt.getSelectedTool(stack); if (selectedStack != null) { damageItemWhenCrafting(selectedStack, entity); return; @@ -294,7 +294,7 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa if (entity != null) stack.damageItem(damage, entity); return; } else if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selectedStack = toolbelt.getSelectedItem(stack); + ItemStack selectedStack = toolbelt.getSelectedTool(stack); if (selectedStack != null) { damageItem(selectedStack, entity, damage); return; @@ -362,7 +362,7 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa public static void onActionDone(@NotNull EntityPlayer player, @NotNull World world, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } IGTTool tool = (IGTTool) stack.getItem(); @@ -431,7 +431,7 @@ public static boolean areTools(ItemStack tool, String... toolClasses) { */ public static int getFortuneOrLootingLevel(ItemStack tool) { if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(tool); + ItemStack selected = toolbelt.getSelectedTool(tool); if (selected != null) tool = selected; } if (tool.getItem() instanceof ItemGTSword) { @@ -456,7 +456,7 @@ public static AoESymmetrical getAoEDefinition(ItemStack stack) { */ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlayerMP player) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } int currentDurability = getToolTag(stack).getInteger(DURABILITY_KEY); @@ -477,7 +477,7 @@ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlaye // If the tool is an electric tool, catch the tool breaking and cancel the remaining AOE ItemStack tool = player.getHeldItemMainhand(); if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(tool); + ItemStack selected = toolbelt.getSelectedTool(tool); if (selected != null) tool = selected; } else if (!tool.isItemEqualIgnoreDurability(stack)) { return true; @@ -492,7 +492,7 @@ public static Set iterateAoE(ItemStack stack, AoESymmetrical aoeDefini EntityPlayer player, RayTraceResult rayTraceResult, QuintFunction function) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } if (aoeDefinition != AoESymmetrical.none() && rayTraceResult != null && @@ -745,7 +745,7 @@ public static void applyHammerDropConversion(ItemStack tool, IBlockState state, public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { // This is *not* a vanilla/forge convention, Forge never added "shears" to ItemShear's tool classes. if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(tool); + ItemStack selected = toolbelt.getSelectedTool(tool); if (selected != null) tool = selected; } if (isTool(tool, ToolClasses.SHEARS) && shearBlockRoutine(player, tool, pos) == 0) { @@ -797,7 +797,7 @@ public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, B public static int shearBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { if (!player.isCreative()) { if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(tool); + ItemStack selected = toolbelt.getSelectedTool(tool); if (selected != null) tool = selected; } World world = player.world; @@ -859,7 +859,7 @@ public static ItemStack getSilkTouchDrop(@NotNull IBlockState state) { public static void playToolSound(ItemStack stack, EntityPlayer player) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } if (stack.getItem() instanceof IGTTool) { diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 7d038b827c8..a009eeee4a9 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -36,6 +36,10 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.gui.GuiIngame; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.entity.player.EntityPlayer; @@ -45,14 +49,15 @@ import net.minecraft.inventory.ContainerWorkbench; import net.minecraft.inventory.InventoryCraftResult; import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.client.GuiIngameForge; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.MouseEvent; +import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.Constants; import net.minecraftforge.event.entity.player.ItemTooltipEvent; @@ -331,11 +336,11 @@ public boolean isFancyGraphics() { @SubscribeEvent(priority = EventPriority.HIGH) public static void onMouseEvent(@NotNull MouseEvent event) { + if (!ConfigHolder.client.toolbeltConfig.enableToolbeltScrollingCapture) return; EntityPlayerSP player = Minecraft.getMinecraft().player; if (event.getDwheel() != 0 && player.isSneaking()) { ItemStack stack = player.getHeldItemMainhand(); - Item item = stack.getItem(); - if (item instanceof ItemGTToolbelt toolbelt) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { stack = stack.copy(); toolbelt.changeSelectedTool(event.getDwheel(), stack); InventoryPlayer inv = Minecraft.getMinecraft().player.inventory; @@ -344,4 +349,64 @@ public static void onMouseEvent(@NotNull MouseEvent event) { } } } + + @SubscribeEvent + public static void onRenderGameOverlayPostEvent(RenderGameOverlayEvent.Post event) { + if (!ConfigHolder.client.toolbeltConfig.enableToolbeltHotbarDisplay) return; + if (event.getType() == RenderGameOverlayEvent.ElementType.HOTBAR) { + if (Minecraft.getMinecraft().ingameGUI instanceof GuiIngameForge gui) { + ItemStack stack = Minecraft.getMinecraft().player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + renderToolbeltHotbar(gui, stack, toolbelt, event.getResolution(), event.getPartialTicks()); + } + } + } + } + + private static void renderToolbeltHotbar(GuiIngameForge gui, ItemStack stack, ItemGTToolbelt toolbelt, + ScaledResolution sr, float partialTicks) { + Minecraft mc = Minecraft.getMinecraft(); + int offset = 31; + int slots = Math.min(9, toolbelt.getSlotCount(stack)); + GuiIngameForge.left_height += offset - 6; + if (slots > 4) { + GuiIngameForge.right_height += offset - 6; + } + if (mc.getRenderViewEntity() instanceof EntityPlayer entityplayer) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + mc.getTextureManager().bindTexture(GuiIngame.WIDGETS_TEX_PATH); + int i = sr.getScaledWidth() / 2; + float f = gui.zLevel; + gui.zLevel = -90.0F; + // draw the left side of the hotbar + gui.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22 - offset, 0, 0, slots * 20 - 18, 22); + // draw the endpiece to the hotbar + gui.drawTexturedModalRect(i - 91 + slots * 20 - 18, sr.getScaledHeight() - 22 - offset, 162, 0, 20, 22); + Integer selected = toolbelt.getSelectedSlot(stack); + if (selected != null) { + gui.drawTexturedModalRect(i - 91 - 1 + selected * 20, sr.getScaledHeight() - 22 - 1 - offset, 0, 22, 24, + 22); + } + + gui.zLevel = f; + GlStateManager.enableRescaleNormal(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, + GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO); + RenderHelper.enableGUIStandardItemLighting(); + + for (int l = 0; l < slots; ++l) { + ItemStack stack1 = toolbelt.getToolInSlot(stack, l); + if (stack1 == null) continue; + int i1 = i - 90 + l * 20 + 2; + int j1 = sr.getScaledHeight() - 16 - 3 - offset; + gui.renderHotbarItem(i1, j1, partialTicks, entityplayer, stack1); + } + + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + GlStateManager.disableBlend(); + } + } } diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java index cdc7d54dc0f..821a0f5c4c3 100644 --- a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -32,7 +32,7 @@ public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType trans RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) { IBakedModel selectedModel = renderItem.getItemModelWithOverrides(selected, null, null); renderItem.renderItem(selected, selectedModel); diff --git a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java index 345255d627b..0b89f162452 100644 --- a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java +++ b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java @@ -115,7 +115,7 @@ private static void overpaintVanillaRenderBug(BufferBuilder worldrenderer, int x public static void renderBarsTool(IGTTool tool, ItemStack stack, int xPosition, int yPosition) { if (tool instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null && selected.getItem() instanceof IGTTool toool) { tool = toool; stack = selected; diff --git a/src/main/java/gregtech/common/ConfigHolder.java b/src/main/java/gregtech/common/ConfigHolder.java index 7127a2ab688..5ecec7ab1b0 100644 --- a/src/main/java/gregtech/common/ConfigHolder.java +++ b/src/main/java/gregtech/common/ConfigHolder.java @@ -381,6 +381,9 @@ public static class ClientOptions { @Config.Name("Shader Options") public ShaderOptions shader = new ShaderOptions(); + @Config.Name("Toolbelt Config") + public ToolbeltConfig toolbeltConfig = new ToolbeltConfig(); + @Config.Comment({ "Terminal root path.", "Default: {.../config}/gregtech/terminal" }) @Config.RequiresMcRestart public String terminalRootPath = "gregtech/terminal"; @@ -554,6 +557,22 @@ public static class ShaderOptions { @Config.RangeDouble(min = 0) public double step = 1; } + + public static class ToolbeltConfig { + + @Config.Comment({ "Enable the capturing of hotbar scroll while sneaking by a selected toolbelt.", + "Default: true" }) + public boolean enableToolbeltScrollingCapture = true; + + @Config.Comment({ "Enable the capturing of hotbar keypresses while sneaking by a selected toolbelt.", + "Default: true" }) + public boolean enableToolbeltKeypressCapture = true; + + @Config.Comment({ + "Enable the display of a second hotbar representing the toolbelt's inventory when one is selected.", + "Default: true" }) + public boolean enableToolbeltHotbarDisplay = true; + } } public static class FusionBloom { diff --git a/src/main/java/gregtech/common/ToolEventHandlers.java b/src/main/java/gregtech/common/ToolEventHandlers.java index 7d5577f4320..ad03995d64c 100644 --- a/src/main/java/gregtech/common/ToolEventHandlers.java +++ b/src/main/java/gregtech/common/ToolEventHandlers.java @@ -167,7 +167,7 @@ public static void onHarvestDrops(@NotNull BlockEvent.HarvestDropsEvent event) { return false; }); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedItem(stack); + ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } ((IGTTool) stack.getItem()).playSound(player); diff --git a/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java b/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java index 31ada3545f0..27212596a90 100644 --- a/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java +++ b/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java @@ -1,12 +1,19 @@ package gregtech.mixins.minecraft; +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.common.ConfigHolder; + import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextComponentTranslation; import org.lwjgl.input.Keyboard; +import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Minecraft.class) @@ -19,4 +26,20 @@ public void addGregTechDebugMessage(int auxKey, CallbackInfoReturnable .printChatMessage(new TextComponentTranslation("gregtech.debug.f3_h.enabled")); } } + + @Redirect(method = "processKeyBinds", + at = @At(value = "FIELD", + target = "Lnet/minecraft/entity/player/InventoryPlayer;currentItem:I", + opcode = Opcodes.PUTFIELD)) + public void interceptHotbarKeybindsForToolbelt(InventoryPlayer inventoryPlayer, int i) { + if (!ConfigHolder.client.toolbeltConfig.enableToolbeltKeypressCapture) return; + if (inventoryPlayer.player.isSneaking()) { + ItemStack stack = inventoryPlayer.player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + toolbelt.setSelectedTool(i, stack); + return; + } + } + inventoryPlayer.currentItem = i; + } } diff --git a/src/main/resources/gregtech_at.cfg b/src/main/resources/gregtech_at.cfg index 76892c9fc05..b1286b391a8 100644 --- a/src/main/resources/gregtech_at.cfg +++ b/src/main/resources/gregtech_at.cfg @@ -84,3 +84,10 @@ public net.minecraft.entity.item.EntityItem field_145804_b # pickupDelay # Explosion public net.minecraft.world.Explosion field_77283_e # exploder + +# GuiIngame +public net.minecraft.client.gui.GuiIngame field_110330_c # WIDGETS_TEX_PATH +public net.minecraft.client.gui.GuiIngame func_184044_a(IIFLnet/minecraft/entity/player/EntityPlayer;Lnet/minecraft/item/ItemStack;)V # renderHotbarItem + +# Gui +public net.minecraft.client.gui.Gui field_73735_i # zLevel From 566ed93697ac0d2e693dbb534420bae71c838410 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 18:32:54 -0700 Subject: [PATCH 59/82] Sync moment --- .../api/items/toolitem/ItemGTToolbelt.java | 41 ++++++++++++++++--- .../java/gregtech/client/ClientProxy.java | 2 +- .../MetaTileEntityMaintenanceHatch.java | 26 +++++++++++- .../mixins/minecraft/MinecraftMixin.java | 2 +- .../resources/assets/gregtech/lang/en_us.lang | 5 ++- 5 files changed, 67 insertions(+), 9 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 6ac0ea1df20..9c9fa94d870 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -12,11 +12,14 @@ import gregtech.api.unification.material.properties.PropertyKey; import gregtech.api.unification.material.properties.ToolProperty; import gregtech.api.util.LocalizationUtils; +import gregtech.api.util.TextFormattingUtil; +import gregtech.client.utils.TooltipHelper; import gregtech.common.items.behaviors.ColorSprayBehaviour; import gregtech.common.metatileentities.multi.multiblockpart.MetaTileEntityMaintenanceHatch; import gregtech.core.network.packets.PacketToolbeltSelectionChange; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.resources.I18n; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; @@ -295,10 +298,26 @@ public double getDurabilityForDisplay(@NotNull ItemStack stack) { @SideOnly(Side.CLIENT) public void addInformation(@NotNull ItemStack stack, @Nullable World world, @NotNull List tooltip, @NotNull ITooltipFlag flag) { - ItemStack selected = getHandler(stack).getSelectedStack(); + ToolStackHandler handler = getHandler(stack); + ItemStack selected = handler.getSelectedStack(); if (selected != null) { selected.getItem().addInformation(selected, world, tooltip, flag); - } else definition$addInformation(stack, world, tooltip, flag); + } else { + int damageRemaining = this.getTotalMaxDurability(stack) - stack.getItemDamage() + 1; + tooltip.add(I18n.format("item.gt.tool.tooltip.general_uses", + TextFormattingUtil.formatNumbers(damageRemaining))); + tooltip.add(I18n.format("item.gt.tool.toolbelt.size", + TextFormattingUtil.formatNumbers(handler.getSlots()))); + tooltip.add(""); + if (TooltipHelper.isShiftDown()) { + tooltip.add(I18n.format("item.gt.tool.toolbelt.tooltip")); + tooltip.add(""); + tooltip.add(I18n.format("item.gt.tool.toolbelt.paint")); + tooltip.add(""); + tooltip.add(I18n.format("item.gt.tool.toolbelt.maintenance")); + } else tooltip.add(I18n.format("gregtech.tooltip.hold_shift")); + + } } @Override @@ -376,7 +395,8 @@ public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagComp return new ToolbeltCapabilityProvider(stack); } - public void changeSelectedTool(int direction, ItemStack stack) { + @SideOnly(Side.CLIENT) + public void changeSelectedToolMousewheel(int direction, ItemStack stack) { ToolStackHandler handler = getHandler(stack); if (direction > 0) handler.incrementSelectedSlot(); else handler.decrementSelectedSlot(); @@ -384,6 +404,16 @@ public void changeSelectedTool(int direction, ItemStack stack) { new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); } + @SideOnly(Side.CLIENT) + public void changeSelectedToolHotkey(int slot, ItemStack stack) { + ToolStackHandler handler = getHandler(stack); + if (slot < 0 || slot >= handler.getSlots() || handler.getStackInSlot(slot).isEmpty()) + handler.selectedSlot = null; + else handler.selectedSlot = slot; + GregTechAPI.networkHandler.sendToServer( + new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); + } + public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { ToolStackHandler handler = getHandler(stack); if (slot == null || slot < 0 || slot >= handler.getSlots() || handler.getStackInSlot(slot).isEmpty()) @@ -411,10 +441,11 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { float hitY, float hitZ, @NotNull EnumHand hand) { EnumActionResult result = IDyeableItem.super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); if (result == EnumActionResult.PASS) { - ToolStackHandler handler = getHandler(player.getHeldItem(hand)); + ItemStack stack = player.getHeldItem(hand); + ToolStackHandler handler = getHandler(stack); if (handler.getSelectedSlot() == null && world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && holder.getMetaTileEntity() instanceof MetaTileEntityMaintenanceHatch maintenance) { - maintenance.fixMaintenanceProblems(player); + maintenance.fixMaintenanceProblemsWithToolbelt(player, this, stack); return EnumActionResult.SUCCESS; } return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index a009eeee4a9..b3c77efe22b 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -342,7 +342,7 @@ public static void onMouseEvent(@NotNull MouseEvent event) { ItemStack stack = player.getHeldItemMainhand(); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { stack = stack.copy(); - toolbelt.changeSelectedTool(event.getDwheel(), stack); + toolbelt.changeSelectedToolMousewheel(event.getDwheel(), stack); InventoryPlayer inv = Minecraft.getMinecraft().player.inventory; inv.mainInventory.set(inv.currentItem, stack); event.setCanceled(true); diff --git a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java index 583f032a4f3..6c8e3cd2e97 100644 --- a/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java +++ b/src/main/java/gregtech/common/metatileentities/multi/multiblockpart/MetaTileEntityMaintenanceHatch.java @@ -46,6 +46,7 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.IVertexOperation; import codechicken.lib.vec.Matrix4; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -197,7 +198,7 @@ public void update() { * * @param entityPlayer the player performing the fixing */ - public void fixMaintenanceProblems(@Nullable EntityPlayer entityPlayer) { + private void fixMaintenanceProblems(@Nullable EntityPlayer entityPlayer) { if (!(this.getController() instanceof IMaintenance)) return; @@ -316,6 +317,29 @@ private void fixProblemsWithTools(byte problems, EntityPlayer entityPlayer) { } } + @ApiStatus.Internal + public void fixMaintenanceProblemsWithToolbelt(@NotNull EntityPlayer entityPlayer, ItemGTToolbelt toolbelt, + ItemStack toolbeltStack) { + byte problems = ((IMaintenance) this.getController()).getMaintenanceProblems(); + for (byte index = 0; index < 6; index++) { + if (((problems >> index) & 1) == 0) { + String toolToMatch = switch (index) { + case 0 -> ToolClasses.WRENCH; + case 1 -> ToolClasses.SCREWDRIVER; + case 2 -> ToolClasses.SOFT_MALLET; + case 3 -> ToolClasses.HARD_HAMMER; + case 4 -> ToolClasses.WIRE_CUTTER; + case 5 -> ToolClasses.CROWBAR; + default -> null; + }; + if (toolbelt.damageAgainstMaintenanceProblem(toolbeltStack, toolToMatch, entityPlayer)) { + ((IMaintenance) getController()).setMaintenanceFixed(index); + setTaped(false); + } + } + } + } + private void fixProblemWithTool(int problemIndex, ItemStack stack, EntityPlayer player) { ((IMaintenance) getController()).setMaintenanceFixed(problemIndex); ToolHelper.damageItemWhenCrafting(stack, player); diff --git a/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java b/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java index 27212596a90..0bba8ad4f03 100644 --- a/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java +++ b/src/main/java/gregtech/mixins/minecraft/MinecraftMixin.java @@ -36,7 +36,7 @@ public void interceptHotbarKeybindsForToolbelt(InventoryPlayer inventoryPlayer, if (inventoryPlayer.player.isSneaking()) { ItemStack stack = inventoryPlayer.player.getHeldItemMainhand(); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - toolbelt.setSelectedTool(i, stack); + toolbelt.changeSelectedToolHotkey(i, stack); return; } } diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index c2985695e21..d9d4f92bc08 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1036,7 +1036,10 @@ item.gt.tool.wire_cutter_lv.name=%s Wire Cutter (LV) item.gt.tool.wire_cutter_hv.name=%s Wire Cutter (HV) item.gt.tool.wire_cutter_iv.name=%s Wire Cutter (IV) item.gt.tool.toolbelt.name=%s Toolbelt%s -item.gt.tool.toolbelt.tooltip=Can trigger maintenance repair by clicking on a maintenance hatch +item.gt.tool.toolbelt.size=§a%s Tool Slots +item.gt.tool.toolbelt.tooltip=Holds GT or vanilla-esque tools that can be manually selected for in-world use, automatically selected for crafting, or stored for maintenance repair. +item.gt.tool.toolbelt.paint=Also supports Spray Cans. +item.gt.tool.toolbelt.maintenance=Repairs maintenance problems with only inserted tools upon interacting with a maintenance hatch in-world. item.gt.tool.tooltip.crafting_uses=§a%s Crafting Uses From c6c0276ed691308136a3feac49d4037f3a329f9f Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 18:57:55 -0700 Subject: [PATCH 60/82] Hide durability until damaged --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 8 +++++--- src/main/java/gregtech/client/ClientProxy.java | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 9c9fa94d870..21869671845 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -303,9 +303,11 @@ public void addInformation(@NotNull ItemStack stack, @Nullable World world, @Not if (selected != null) { selected.getItem().addInformation(selected, world, tooltip, flag); } else { - int damageRemaining = this.getTotalMaxDurability(stack) - stack.getItemDamage() + 1; - tooltip.add(I18n.format("item.gt.tool.tooltip.general_uses", - TextFormattingUtil.formatNumbers(damageRemaining))); + if (stack.getItemDamage() > 0) { + int damageRemaining = this.getTotalMaxDurability(stack) - stack.getItemDamage() + 1; + tooltip.add(I18n.format("item.gt.tool.tooltip.general_uses", + TextFormattingUtil.formatNumbers(damageRemaining))); + } tooltip.add(I18n.format("item.gt.tool.toolbelt.size", TextFormattingUtil.formatNumbers(handler.getSlots()))); tooltip.add(""); diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index e663186f297..52d9ac3b949 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -36,12 +36,12 @@ import net.minecraft.block.Block; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiIngame; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.entity.player.EntityPlayer; From 860db4ecc625f0cae2f71a20dc36bd4bc4fce1f1 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 19:11:27 -0700 Subject: [PATCH 61/82] Minor Tweaks --- src/main/java/gregtech/api/items/IDyeableItem.java | 10 ++++++---- .../gregtech/api/items/toolitem/ItemGTToolbelt.java | 2 ++ src/main/resources/assets/gregtech/lang/en_us.lang | 1 + 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index a79c3716749..96efd043cf3 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -11,21 +11,23 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants; + import org.jetbrains.annotations.NotNull; public interface IDyeableItem { default boolean hasColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - return nbttagcompound != null && nbttagcompound.hasKey("display", 10) && - nbttagcompound.getCompoundTag("display").hasKey("color", 3); + return nbttagcompound != null && nbttagcompound.hasKey("display", Constants.NBT.TAG_COMPOUND) && + nbttagcompound.getCompoundTag("display").hasKey("color", Constants.NBT.TAG_INT); } default int getColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); if (nbttagcompound != null) { NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (nbttagcompound1.hasKey("color", 3)) { + if (nbttagcompound1.hasKey("color", Constants.NBT.TAG_INT)) { return nbttagcompound1.getInteger("color"); } } @@ -53,7 +55,7 @@ default void setColor(ItemStack stack, int color) { stack.setTagCompound(nbttagcompound); } NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (!nbttagcompound.hasKey("display", 10)) { + if (!nbttagcompound.hasKey("display", Constants.NBT.TAG_COMPOUND)) { nbttagcompound.setTag("display", nbttagcompound1); } nbttagcompound1.setInteger("color", color); diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 21869671845..b2de750cadc 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -316,6 +316,8 @@ public void addInformation(@NotNull ItemStack stack, @Nullable World world, @Not tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.paint")); tooltip.add(""); + tooltip.add(I18n.format("item.gt.tool.toolbelt.dye")); + tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.maintenance")); } else tooltip.add(I18n.format("gregtech.tooltip.hold_shift")); diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index 9532babc3e5..ca09a422d30 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1046,6 +1046,7 @@ item.gt.tool.toolbelt.name=%s Toolbelt%s item.gt.tool.toolbelt.size=§a%s Tool Slots item.gt.tool.toolbelt.tooltip=Holds GT or vanilla-esque tools that can be manually selected for in-world use, automatically selected for crafting, or stored for maintenance repair. item.gt.tool.toolbelt.paint=Also supports Spray Cans. +item.gt.tool.toolbelt.dye=Can be dyed like leather equipment. item.gt.tool.toolbelt.maintenance=Repairs maintenance problems with only inserted tools upon interacting with a maintenance hatch in-world. From a23249b1528f4b14bd3e52528dfb41defff4b568 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 19:11:27 -0700 Subject: [PATCH 62/82] spotless --- src/main/java/gregtech/api/items/IDyeableItem.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index 96efd043cf3..5e9596435fc 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -10,6 +10,7 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.Constants; From 38f59026b47362f8e0768cffc14612a621d383f3 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 19:14:30 -0700 Subject: [PATCH 63/82] actually spotless --- src/main/java/gregtech/api/items/IDyeableItem.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index 5e9596435fc..7823b65d09f 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -12,8 +12,6 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.Constants; -import net.minecraftforge.common.util.Constants; - import org.jetbrains.annotations.NotNull; public interface IDyeableItem { From ee1a9ea74ffb96259f359f710de69f4dd6ba1e9c Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 8 Nov 2024 20:48:34 -0700 Subject: [PATCH 64/82] Fixes --- .../gregtech/api/items/toolitem/IGTTool.java | 20 ++----- .../api/items/toolitem/ItemGTToolbelt.java | 14 +++-- .../api/items/toolitem/ToolHelper.java | 52 +++++------------- .../toolitem/behavior/IToolBehavior.java | 35 +----------- .../java/gregtech/client/ClientProxy.java | 17 +++--- .../common/crafting/DyeableRecipes.java | 13 +++-- .../assets/gregtech/sounds/click.ogg | Bin 4205 -> 3865 bytes 7 files changed, 47 insertions(+), 104 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 83ecfcb9bf1..f3044abd90c 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -643,10 +643,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); else return EnumActionResult.PASS; @@ -663,10 +660,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { ItemStack stack = player.getHeldItem(hand); - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); else return EnumActionResult.PASS; @@ -684,10 +678,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default ActionResult definition$onItemRightClick(World world, EntityPlayer player, EnumHand hand) { ItemStack stack = player.getHeldItem(hand); ItemStack original = stack; - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { @@ -910,10 +901,7 @@ default ModelResourceLocation getModelLocation() { // Sound Playing default void playCraftingSound(EntityPlayer player, ItemStack stack) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); // player null check for things like auto-crafters if (ConfigHolder.client.toolCraftingSounds && getSound() != null && player != null) { if (canPlaySound(stack)) { diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index b2de750cadc..1ce60b70e75 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -89,13 +89,16 @@ public int getSlotCount(@NotNull ItemStack toolbelt) { return getHandler(toolbelt).getSlots(); } + // nullable to differentiate between "no tool selected" and "no tool in selected slot" which is theoretically + // possible public @Nullable ItemStack getSelectedTool(@NotNull ItemStack toolbelt) { return getHandler(toolbelt).getSelectedStack(); } - public @Nullable ItemStack getToolInSlot(@NotNull ItemStack toolbelt, int slot) { + @NotNull + public ItemStack getToolInSlot(@NotNull ItemStack toolbelt, int slot) { ToolStackHandler handler = getHandler(toolbelt); - if (slot < 0 || slot >= handler.getSlots()) return null; + if (slot < 0 || slot >= handler.getSlots()) return ItemStack.EMPTY; return handler.getStackInSlot(slot); } @@ -315,7 +318,6 @@ public void addInformation(@NotNull ItemStack stack, @Nullable World world, @Not tooltip.add(I18n.format("item.gt.tool.toolbelt.tooltip")); tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.paint")); - tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.dye")); tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.maintenance")); @@ -402,7 +404,7 @@ public ICapabilityProvider initCapabilities(@NotNull ItemStack stack, NBTTagComp @SideOnly(Side.CLIENT) public void changeSelectedToolMousewheel(int direction, ItemStack stack) { ToolStackHandler handler = getHandler(stack); - if (direction > 0) handler.incrementSelectedSlot(); + if (direction < 0) handler.incrementSelectedSlot(); else handler.decrementSelectedSlot(); GregTechAPI.networkHandler.sendToServer( new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); @@ -535,10 +537,10 @@ public boolean hasCapability(@NotNull Capability capability, EnumFacing facin return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY; } - @SuppressWarnings("unchecked") @Override public T getCapability(@NotNull Capability capability, EnumFacing facing) { - if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) this.getHandler(0); + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) + return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(this.getHandler(0)); else return null; } diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 8036dbdef44..cfde5af013d 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -197,26 +197,25 @@ public static void registerToolSymbol(Character symbol, IGTTool tool) { } public static NBTTagCompound getToolTag(ItemStack stack) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); return stack.getOrCreateSubCompound(TOOL_TAG_KEY); } - public static NBTTagCompound getBehaviorsTag(ItemStack stack) { + public static ItemStack toolbeltPassthrough(ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { ItemStack selected = toolbelt.getSelectedTool(stack); if (selected != null) stack = selected; } + return stack; + } + + public static NBTTagCompound getBehaviorsTag(ItemStack stack) { + stack = toolbeltPassthrough(stack); return stack.getOrCreateSubCompound(BEHAVIOURS_TAG_KEY); } public static void setBehaviorsTag(ItemStack stack, NBTTagCompound tag) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); stack.setTagInfo(BEHAVIOURS_TAG_KEY, tag); } @@ -361,10 +360,7 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa */ public static void onActionDone(@NotNull EntityPlayer player, @NotNull World world, @NotNull EnumHand hand) { ItemStack stack = player.getHeldItem(hand); - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); IGTTool tool = (IGTTool) stack.getItem(); ToolHelper.damageItem(stack, player); if (tool.getSound() != null) { @@ -430,10 +426,7 @@ public static boolean areTools(ItemStack tool, String... toolClasses) { * @return The level of Fortune or Looting that the tool is enchanted with, or zero */ public static int getFortuneOrLootingLevel(ItemStack tool) { - if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(tool); - if (selected != null) tool = selected; - } + tool = toolbeltPassthrough(tool); if (tool.getItem() instanceof ItemGTSword) { return EnchantmentHelper.getEnchantmentLevel(Enchantments.LOOTING, tool); } else if (tool.getItem() instanceof IGTTool) { @@ -455,10 +448,7 @@ public static AoESymmetrical getAoEDefinition(ItemStack stack) { * AoE Block Breaking Routine. */ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlayerMP player) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); int currentDurability = getToolTag(stack).getInteger(DURABILITY_KEY); int maximumDurability = getToolTag(stack).getInteger(MAX_DURABILITY_KEY); int remainingUses = maximumDurability - currentDurability; @@ -491,10 +481,7 @@ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlaye public static Set iterateAoE(ItemStack stack, AoESymmetrical aoeDefinition, World world, EntityPlayer player, RayTraceResult rayTraceResult, QuintFunction function) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); if (aoeDefinition != AoESymmetrical.none() && rayTraceResult != null && rayTraceResult.typeOfHit == RayTraceResult.Type.BLOCK && rayTraceResult.sideHit != null) { int column = aoeDefinition.column; @@ -744,10 +731,7 @@ public static void applyHammerDropConversion(ItemStack tool, IBlockState state, public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { // This is *not* a vanilla/forge convention, Forge never added "shears" to ItemShear's tool classes. - if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(tool); - if (selected != null) tool = selected; - } + tool = toolbeltPassthrough(tool); if (isTool(tool, ToolClasses.SHEARS) && shearBlockRoutine(player, tool, pos) == 0) { return false; } @@ -796,10 +780,7 @@ public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, B */ public static int shearBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { if (!player.isCreative()) { - if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(tool); - if (selected != null) tool = selected; - } + tool = toolbeltPassthrough(tool); World world = player.world; IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof IShearable) { @@ -858,10 +839,7 @@ public static ItemStack getSilkTouchDrop(@NotNull IBlockState state) { } public static void playToolSound(ItemStack stack, EntityPlayer player) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = toolbeltPassthrough(stack); if (stack.getItem() instanceof IGTTool) { ((IGTTool) stack.getItem()).playSound(player); } diff --git a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java index 150900079be..88b249d4327 100644 --- a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java +++ b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java @@ -78,16 +78,6 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving return false; } - /** - * Not itemstack sensitive. Use the new override. - */ - @Deprecated - default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, - @NotNull EnumHand hand) { - return EnumActionResult.PASS; - } - /** * Called when a Block is right-clicked with this Item, but before the block is activated * @@ -103,17 +93,6 @@ default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull W default EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { - return onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand); - } - - /** - * Not itemstack sensitive. Use the new override. - */ - @Deprecated - @NotNull - default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, - @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, - float hitZ) { return EnumActionResult.PASS; } @@ -135,17 +114,7 @@ default EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlay @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { - return onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ); - } - - /** - * Not itemstack sensitive. Use the new override. - */ - @NotNull - @Deprecated - default ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, - @NotNull EnumHand hand) { - return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); + return EnumActionResult.PASS; } /** @@ -158,7 +127,7 @@ default ActionResult onItemRightClick(@NotNull World world, @NotNull @NotNull default ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, @NotNull EntityPlayer player, @NotNull EnumHand hand) { - return onItemRightClick(world, player, hand); + return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); } @SideOnly(Side.CLIENT) diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index 52d9ac3b949..fa04b3d864f 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -391,6 +391,10 @@ private static void renderToolbeltHotbar(GuiIngameForge gui, ItemStack stack, It int i = sr.getScaledWidth() / 2; float f = gui.zLevel; gui.zLevel = -90.0F; + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, + GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, + GlStateManager.DestFactor.ZERO); // draw the left side of the hotbar gui.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22 - offset, 0, 0, slots * 20 - 18, 22); // draw the endpiece to the hotbar @@ -398,25 +402,22 @@ private static void renderToolbeltHotbar(GuiIngameForge gui, ItemStack stack, It Integer selected = toolbelt.getSelectedSlot(stack); if (selected != null) { gui.drawTexturedModalRect(i - 91 - 1 + selected * 20, sr.getScaledHeight() - 22 - 1 - offset, 0, 22, 24, - 22); + 24); } - - gui.zLevel = f; + gui.zLevel = -80f; GlStateManager.enableRescaleNormal(); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, - GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, - GlStateManager.DestFactor.ZERO); RenderHelper.enableGUIStandardItemLighting(); for (int l = 0; l < slots; ++l) { ItemStack stack1 = toolbelt.getToolInSlot(stack, l); - if (stack1 == null) continue; + if (stack1.isEmpty()) continue; int i1 = i - 90 + l * 20 + 2; int j1 = sr.getScaledHeight() - 16 - 3 - offset; gui.renderHotbarItem(i1, j1, partialTicks, entityplayer, stack1); } + gui.zLevel = f; + RenderHelper.disableStandardItemLighting(); GlStateManager.disableRescaleNormal(); GlStateManager.disableBlend(); diff --git a/src/main/java/gregtech/common/crafting/DyeableRecipes.java b/src/main/java/gregtech/common/crafting/DyeableRecipes.java index 6dd590ce922..bcc9eabb183 100644 --- a/src/main/java/gregtech/common/crafting/DyeableRecipes.java +++ b/src/main/java/gregtech/common/crafting/DyeableRecipes.java @@ -8,12 +8,16 @@ import net.minecraft.util.NonNullList; import net.minecraft.world.World; -import com.google.common.collect.Lists; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.List; +/** + * Composed almost entirely of code taken from {@link RecipesArmorDyes} and modified to apply to {@link IDyeableItem} + * instead of just leather armor. Thus, will be difficult to parse. + */ public final class DyeableRecipes extends RecipesArmorDyes { @ApiStatus.Internal @@ -27,7 +31,7 @@ public DyeableRecipes() { @Override public boolean matches(InventoryCrafting inv, @NotNull World worldIn) { ItemStack itemstack = ItemStack.EMPTY; - List list = Lists.newArrayList(); + List list = new ObjectArrayList<>(); for (int i = 0; i < inv.getSizeInventory(); ++i) { ItemStack itemstack1 = inv.getStackInSlot(i); @@ -121,8 +125,9 @@ public boolean matches(InventoryCrafting inv, @NotNull World worldIn) { } } - public NonNullList getRemainingItems(InventoryCrafting inv) { - NonNullList nonnulllist = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + @Override + public @NotNull NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList nonnulllist = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); for (int i = 0; i < nonnulllist.size(); ++i) { ItemStack itemstack = inv.getStackInSlot(i); diff --git a/src/main/resources/assets/gregtech/sounds/click.ogg b/src/main/resources/assets/gregtech/sounds/click.ogg index bed708e967680877fc9d01994027fffcf283a5b8..c523d784b79751545fd5a94d3c846372b8f05d79 100644 GIT binary patch literal 3865 zcmcf^YgiLk_6AV`Dn=SHV6=%%G=qXf#Tt|r0!kPQ#Q_oHI{^`aDg;|CwxuRmn_wD~ zfekcJkPH|#tyrU`Uu}If2`{5X9`I}t+_^xuo(x~XEr{+X@NKfezCDM^)z_$pHptl%P&g+oDy*JXdJJ& zP%*NKF?!@ZU7DQ3K#2%(q^zjXcBMYPV-mkQ;y{zM3-e5sUgEb1lJ~~D<2)Q?sxwb3 z?R@o;VFjWWSh*`R%hIBK7F7#pWl!la51=7lK~HJ05Fow8XDri;N3fw~7)|#oJ5^iS z#sSF61?V6Rm55Io%e)eRuJc|a%HEEnv7Ca?vavK5H_h(`&AB@6WZwv#pV&WC)9n4w zb7Eh(>TQ|}Ot~Z9c=PinAp=59%_8kzMWL+7V^hRb!B5&yfIBiBKTWjZ1B3r{5J^{M+J-_x`hwY|BFk?H1*6Mm=%?lOGw8 z+(3k_2?>{SCnisodXsIG`YWtTsO-%;lEmcix}EUj)r#9AE?^f)+hdggMw*&$JJPEA5T}i|U;uOj#{` z?d(H`w5_&7hqlzW7XEn;XyzYA zC>Wuso>FdVDc4gZ>?tRy-4b(F|MM`EbZWY*Q_>(tBwwSs=9dk$7$fai6{lqg`4MQDLce7gz7M{N03KM z_gTmcd%Eu`W#jRwSUeab!h0P7BQH4rpK*Fm;LGX-izGRrhNVLG* zpwfz&6O}A!FjkdG9I}{tlhSNzBavov8Hwr|6%ikdZ4V=&Fjp?2jkabh3!?{niG9&- z%j)XWdq_pJtzRxb>~!U-ba6j+Nbm-7ARe<*16$JV{hy{4Mq39Ih0*Q-#Rbf5nTOe{ zY8A6=t}BY}IEPsUtk}wnn7gs)h|^#a zX#e*SBRtl)F*oJ$vPIHOoF^+46mY>q^Bf3FkA_9s9sn zt1m3+u&6INAGTJ+F75wR-Q!@^saWyD)64I4?jX0s*oW50ZzK#v?z$jhek{L*xvysF zP7gM|dGvG;U)~L@)LQYwdR1(^Pmygu3kn(>;ms9ua37C6)0Kmw_siIwTZFgJaBQ4Jj32E2`5v%xa@}CPfl*rqBUit5XtlJyuPa zJW6;x3@@~iy>b!dsFhb^j__p6Rz=8XQO9fLhs2H?W^}WEn){u#e;jrSOl!_ zK}I9!JtQ+JwI09TWHk~+l$Aa2x)q|Yi`POx$WUQfAQiBptON3DM{A!vTIc{)?PM6u zDtuWwgbW@fhCPbJ*X!jvF(5F^ZN!W1uKLx*lHWGRx3u@yDvR2$_YwOr2OykoGV2Y; z0}DikBb!F#uHFhsa}fj?XfAY_<+^qVOOfz|e{&A3I1#R#(0n`>SXslAup4K!-sX@4 zqP0(9cRb*(elCFuFVeMNhX{`wysAu>OhPF3D>(NXq!FU|c|yd3+Qm7~QL-W_3mj23 zsq&_ES|IV`5E@b$rpl1w(fQsanaz=j<91g#o@R4|k3~qd4NBM1q%1{gr9YYY4=^qs z(=1+!`FQi)A{Xs!x5bo+K{#j5g>cEluUk|sJeW@sIL_A)zzPm*0DXX`%om0Sfj~<} z1X5b&dHEp?l$Q|LS_YOEiKxhB)eY{PiW|<$krgG*CrNytZ9ret?d-o=n4WNw3j!?y zffgNQg^XVnjIKc<2MNq7Z$uS`uI1y1YPz&*q1=ORGy+NuARrixQ0_G>e3+IGqsjr% zOcL=v9>|9^fVdb%LPZXtb5$|>6Uzp{!Api3lnD2u4dbNVv_kvF9tktL|4OWzOOgs5 zoC-qcT-uW)!`w}aM3{q9e5XM}%5{<;6QPUqT~&iA>($>anyl zHKPy;NfJ>C@P!aA7FdG`Jhfj<;NQY|#e*S%;7tE8l_aF#E^yqVA^s86CBY~YjY#pP zVRQgu6z$+gbdR9lFE@W;kN|XQ3K#LhiY*(3-yYdE|CB!-;9}RrR_SpjMjD8N<^y^u zhFJ+bWTMiW_8k{W5oD(>36rvt(kT9RZ&Hx3%0LA3YxMEMA~KVR5|X_V5v5_{I96kj z%53E%ArjWm#5Dvi6V|ZskOpfu9%8d*6U>HkgLJ0QYJ{nYgtZijJ=u8bYfWg$$YqO#?l6!c6HT1>anFj}H5>9a7jG-y zv8xhz(~XICAtacdn36JIH7R^DCn9nRcj~mqd3^ehjK3u&Ci>qz7!woy|BnLiLtN2~ z{(nSYFlT)7)78;Mn^xxV$DMZS^JCB;%43ifyNZnOFDSotp4hQIXN>cuf=_=L{IKM( zT5{cdA@kk1wO=?NfBNXIpDsnpZ|!qa2kvKmHs|WEM?S1Ldd0eWx{dYp;y1VnttAuJ z#J+u47+$raxh;YG`5!mgA$KkH4=-;*_us2Kc5l>VwC@a`kti9tLp|K5&Mz3b{0|6Bl9$qnLH zR=qdtiRZh}tOwP#nLW=^-X-ttohg0kFSl+_V%(4E3VLZWgUK7q()FKcPCIYkZ`$D8 z{9WZd?-Df^o{zb=?CXu214Ibi3D^&k8&^zzr7)YS9B zX)V5&4-DPylz;e27`gxUuy82ED-$@(xLQS literal 4205 zcmahsd0bP+);Gu!0cn7UfI;DzNP?gQ6D2M!2_O)Nz=g{anujbAX&O{wtoW4{NkEK1 zF@`{6=np7SQSdb=QEZ`D0TB>cWD^lBLU5@|tp@9}eshER`u=+Jn>+X1v(B73XXf1S zw6rM51bWvT>KYtTa6@q0Sg-?Txa#f`^}xvNM&Rxfu{s0Fk9vmStXUr0$zj%^mxozGT9Hgdna$)X0@6H<%D^`I@5<;JI zmZmZHIn3K2GJ{Jb=FCn<=@urKfjQ#>UfRt(=`8hNV3$i>X{n2$5(uiSCd;bHmN@4I zOQ;iqaDI{aE4v9-j}WeE30Bxe@n&EnAS~bumem9o-wT!#+EAwv4dGF*LN48D%!g|J}da5$sM#a`LT-3ph zS@L7DCWc-u>b*LnruG7;S{-k#0(^RPTV=fEJmjv;>Qi~3xZSCCEcQ62lP8!x7a2-``l+5X1y0WOVq3f{j)o26dSOl(%mrIecs_FkRR494-W^w zACe2)@*Oj~C?_g&*&ekgs|$U)JAa|QJS0XK zs}v^a#N%cBaYOdx-#X92xI{Z}kjPh1}GG$Uodl8dK&<-`y< zDP5kHr9Anq>i)Oid7Lt`Ksb~IZL;J0WVQQbC-)W47RYyet2|k&TGe&@(Zw?l|5vv% z1~?Id_7HdT6mvvp;iFqh8ud?MH4MJr3FHe1$eBg`brjK{O}NTz#6usD;;iLx@JN(>AhH;VQgV<+{&kvgEE<_`K!$Yu zgqPW|O7X;6&KUX$sABNR(+MZaKBz)QqLJ}+fJ%?t!;3`t@j&xlUi=6WJDd$P4@Ggt z79)rf85`mwN^#;IWFm$)HiEL;%^TXA%kJ) zgoXkl5l(EQFiI>;un!zrj0`CQqr^Zi;ppG*#BpyV>lf&ZaZ-wJ?KunA%^AZ8y zNZ#G7jEN=RMIzz}1uqeZEy+k+f3qcH)4zl%;~zKtYlU@C%MYHs@pTtlIOXDr*`@w> z*XPp)&k2FPi9Ni;GV#QYhZiHF5ne2R%z(tc%m$OV`!ajd5g9Q6m*)>DE0PS^n#We9 zh%OJzKwmE8#eFq3`|lQ?J>mo)tL z?qRxgfJ@diMz9apYMc`U^eu(VPW4ea!(F2=5_%XO6%ufSf`g9hNokK`xRWHsYzsGy zoE=8eIQn~NOBKn0Fv|VBsl8l8*0jsnpOZ9k31JMKqo^1)?rt=$X@p@xsR#zD_%>`0 zpo-0=f>{AoHY_$!6~zX#N?t`7ierDK1*$@+!x8XdKnP`1fvODc^e}UWSB+f?nbhHs za;Cn~*`G3Re8?fCz8N)6>X5UGP~$~S;5gi>omO${n%YMN!loB0QD1E%H!7?NomG=r zyy$VWqz|mTJ%U|W-^fiUWE^~FT-FFw3A8T(0jLUP({+x5V){!J_cR~~KGV*qL{F$Q zqfr9-c}D@T!3C;jhEqWGv%m%%4=WW1K;E06d2i~*rkYnV3#j@U8kRbvR>-J&*BY2Q zLy*EgdRK)UMj_ZzQzM53RSFpXtRCdO37YpyX(R^=khUbK#1h)Ji_rc1rbrqxw%7CO z^MHOD$SfBl24tVGdmbYePZ)U+F^^{mh@^u61_8bqNC8az%k05uBSx2(NJC-)M#-Oy zWxSZXE=5j8OtR-K!%`)Z1(*fd$lIuINc~*>G|l zU4Ki0`{f)yp#ZJu+LMren)qNivvd6;UrC3y-8%ufp$`eo9mmn@PX z=nKgLC?L0JZ5^>%Zp zj{{rvj!yxHfD)A83qsYA>F$I$Bz?bd$+8?{{Q5x^M^h3tZss7va4CvbMo}Y{7K*+jS09x2)9sV4A1t zL5otzmbw@st|Z?x@ylxuyxDHH$LUV)>c<;!EL<+G?N`V$xb@P)^_!mMyWhHFT2T#K zpg$B4*!_@uWfg1oy5pT9naxxpUQO7$(@L>lDj(9dt*-s*htqWc)< zZ0z(p>tXXlYcG95c2=Z?{-{`OTP)|s^c=AiXZ^v6TAw3{CZ^Mp8N7pLq^8( z&3|Cb{leE)x7pANpY9g zzoo%%O#NH_ZLe&f=8vv@W$?;>FqdrEXc8gV{L{x7(MJz`S7dqca#c*wv3l9>Y##ph zC)=`|tTruQ-WOJW;LYy0ccH8I3@^U9ob;GKc3%(8-C6K4+H&4Jb5oXqcC`QZsmqw< zt&@@1M~p(KW$(Rmt1ZDFQN*Vlgnuqqv5y3-X~^kdDZ>&?FXM9G%;?Lu#^YzX+Op-3R|zZgG=*NVWR1+lDKM_^~cKzm3}Z+`ZTHn~BC_ ze{tM(`_4(HOrOTPIE@qum5@&zTWOnCsobKBAY__&~c~ia3Y_dyg&oo)O=(zr05E2Y+Jk_2TDVtA35Jpr>9u zjQygz=J0sMssjstCj9nb&~BnDrTeR8JvSd#8`7}2+x%q-i;@OIbvT=cXI?bO&+%7a zK9jEwZT@qAeuVOni*CV*)~mnWl5|`-m_y3jI?X-Ac$N9YocqOJX8D3kO{umO^wX`X z=Yw%F!8BEliQ_Vs^2VIO8WA_c+FN>OOZnnJ!ZRIku_d|fk Date: Sat, 9 Nov 2024 00:05:17 -0700 Subject: [PATCH 65/82] rework `buildUI()` (it bothered me) fix button texture yeet NBTSyncValue.java --- .../gregtech/api/items/toolitem/IGTTool.java | 151 +++++++++--------- .../items/toolitem/aoe/AoESymmetrical.java | 73 +++------ .../gregtech/api/mui/sync/NBTSyncValue.java | 59 ------- 3 files changed, 101 insertions(+), 182 deletions(-) delete mode 100644 src/main/java/gregtech/api/mui/sync/NBTSyncValue.java diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index f3044abd90c..65647a4278e 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -11,7 +11,6 @@ import gregtech.api.items.toolitem.behavior.IToolBehavior; import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; -import gregtech.api.mui.sync.NBTSyncValue; import gregtech.api.recipes.ModHandler; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Material; @@ -61,14 +60,20 @@ import appeng.api.implementations.items.IAEWrench; import buildcraft.api.tools.IToolWrench; import cofh.api.item.IToolHammer; +import com.cleanroommc.modularui.api.drawable.IDrawable; import com.cleanroommc.modularui.api.drawable.IKey; +import com.cleanroommc.modularui.api.widget.IWidget; +import com.cleanroommc.modularui.api.widget.Interactable; import com.cleanroommc.modularui.factory.HandGuiData; import com.cleanroommc.modularui.factory.ItemGuiFactory; import com.cleanroommc.modularui.screen.ModularPanel; +import com.cleanroommc.modularui.utils.Alignment; +import com.cleanroommc.modularui.value.sync.IntSyncValue; import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.widgets.ButtonWidget; import com.cleanroommc.modularui.widgets.TextWidget; import com.cleanroommc.modularui.widgets.layout.Column; +import com.cleanroommc.modularui.widgets.layout.Row; import com.enderio.core.common.interfaces.IOverlayRenderAware; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; @@ -927,83 +932,79 @@ default void playSound(EntityPlayer player) { } } + IDrawable PLUS = IKey.str("+").asIcon().marginLeft(1); + IDrawable MINUS = IKey.str("-").asIcon().marginLeft(1); + @Override - default ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { - ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 120, 80); - - Supplier tag = () -> getBehaviorsTag(guiData.getUsedItemStack()); - AoESymmetrical defaultDefinition = getMaxAoEDefinition(guiData.getUsedItemStack()); - - NBTSyncValue nbtSyncer = new NBTSyncValue(tag, (nbt) -> setBehaviorsTag(guiData.getUsedItemStack(), nbt)); - guiSyncManager.syncValue("NBTSync", nbtSyncer); - - Column columns = new Column(); - columns.flex().coverChildren().leftRel(0.07f).bottomRel(0.5f); - columns.child(new TextWidget(IKey.lang("item.gt.tool.aoe.columns")).paddingBottom(5)); - columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed(data -> { - NBTTagCompound nbt = tag.get(); - AoESymmetrical.increaseColumn(nbt, defaultDefinition); - nbtSyncer.setValue(nbt, true); - return true; - })); - columns.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed(data -> { - NBTTagCompound nbt = tag.get(); - AoESymmetrical.decreaseColumn(nbt, defaultDefinition); - nbtSyncer.setValue(nbt, true); - return true; - })); - columns.child(new TextWidget( - IKey.dynamic(() -> String.valueOf(1 + 2 * AoESymmetrical.getColumn(tag.get(), defaultDefinition)))) - .paddingTop(5)); - panel.child(columns); - - Column rows = new Column(); - rows.flex().coverChildren().rightRel(0.5f).bottomRel(0.5f); - rows.child(new TextWidget(IKey.lang("item.gt.tool.aoe.rows")).paddingBottom(5)); - rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed(data -> { - NBTTagCompound nbt = tag.get(); - AoESymmetrical.increaseRow(nbt, defaultDefinition); - nbtSyncer.setValue(nbt, true); + default ModularPanel buildUI(HandGuiData guiData, PanelSyncManager manager) { + final var usedStack = guiData.getUsedItemStack(); + final var behaviorsTag = getBehaviorsTag(usedStack); + final var defaultDefinition = getMaxAoEDefinition(usedStack); + + var columnValue = new IntSyncValue( + () -> AoESymmetrical.getColumn(behaviorsTag, defaultDefinition), + i -> AoESymmetrical.setColumn(behaviorsTag, i, defaultDefinition)); + var rowValue = new IntSyncValue( + () -> AoESymmetrical.getRow(behaviorsTag, defaultDefinition), + i -> AoESymmetrical.setRow(behaviorsTag, i, defaultDefinition)); + var layerValue = new IntSyncValue( + () -> AoESymmetrical.getLayer(behaviorsTag, defaultDefinition), + i -> AoESymmetrical.setLayer(behaviorsTag, i, defaultDefinition)); + + manager.syncValue("row_value", rowValue); + manager.syncValue("column_value", columnValue); + manager.syncValue("layer_value", layerValue); + + return GTGuis.createPanel(usedStack.getTranslationKey(), 120, 80) + .child(new Row() + .widthRel(1f) + .margin(4, 0) + .alignY(0.5f) + .coverChildrenHeight() + .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) + .child(createColumn(columnValue, "columns", true)) + .child(createColumn(rowValue, "rows", true)) + .child(createColumn(layerValue, "layers", false))); + } + + default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldDouble) { + final var display = IKey.dynamic( + () -> String.valueOf(1 + (shouldDouble ? 2 * syncValue.getIntValue() : syncValue.getIntValue()))); + + IWidget increaseButton = new ButtonWidget<>() + .size(9, 18) + .background(GTGuiTextures.MC_BUTTON) + .overlay(PLUS) + .disableHoverBackground() + .onMousePressed(data -> { + syncValue.setIntValue(syncValue.getIntValue() + 1, true, true); + Interactable.playButtonClickSound(); return true; - })); - rows.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed(data -> { - NBTTagCompound nbt = tag.get(); - AoESymmetrical.decreaseRow(nbt, defaultDefinition); - nbtSyncer.setValue(nbt, true); + }); + + IWidget decreaseButton = new ButtonWidget<>() + .size(9, 18) + .background(GTGuiTextures.MC_BUTTON) + .overlay(MINUS) + .disableHoverBackground() + .onMousePressed(data -> { + syncValue.setIntValue(syncValue.getIntValue() - 1, true, true); + Interactable.playButtonClickSound(); return true; - })); - rows.child(new TextWidget( - IKey.dynamic(() -> String.valueOf(1 + 2 * AoESymmetrical.getRow(tag.get(), defaultDefinition)))) - .paddingTop(5)); - panel.child(rows); - - Column layers = new Column(); - layers.flex().coverChildren().rightRel(0.07f).bottomRel(0.5f); - layers.child(new TextWidget(IKey.lang("item.gt.tool.aoe.layers")).paddingBottom(5)); - layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_PLUS).size(9, 18) - .disableHoverBackground().onMousePressed(data -> { - NBTTagCompound nbt = tag.get(); - AoESymmetrical.increaseLayer(nbt, defaultDefinition); - nbtSyncer.setValue(nbt, true); - return true; - })); - layers.child(new ButtonWidget<>().background(GTGuiTextures.BUTTON_THROTTLE_MINUS).size(9, 18) - .disableHoverBackground().onMousePressed(data -> { - NBTTagCompound nbt = tag.get(); - AoESymmetrical.decreaseLayer(nbt, defaultDefinition); - nbtSyncer.setValue(nbt, true); - return true; - })); - layers.child(new TextWidget( - IKey.dynamic(() -> String.valueOf(1 + AoESymmetrical.getLayer(tag.get(), defaultDefinition)))) - .paddingTop(5)); - panel.child(layers); - - return panel; + }); + + return new Column() + .coverChildren() + .child(new TextWidget(IKey.lang("item.gt.tool.aoe." + lang)) + .marginBottom(5)) + .child(new Row() + .coverChildren() + .marginBottom(5) + .child(increaseButton) + .child(decreaseButton)) + .child(new TextWidget(display) + .alignment(Alignment.Center) + .widthRel(1f)); } Set getToolClasses(ItemStack stack); diff --git a/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java b/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java index a1dfc249012..48a8a0b2b37 100644 --- a/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java +++ b/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java @@ -3,6 +3,7 @@ import gregtech.api.items.toolitem.ToolHelper; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.MathHelper; import net.minecraftforge.common.util.Constants; import com.google.common.base.Preconditions; @@ -73,70 +74,46 @@ public static int getLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) return defaultDefinition.layer; } + public static void setColumn(NBTTagCompound tag, int i, AoESymmetrical defaultDefinition) { + tag.setInteger(ToolHelper.AOE_COLUMN_KEY, MathHelper.clamp(i, 0, defaultDefinition.column)); + } + + public static void setRow(NBTTagCompound tag, int i, AoESymmetrical defaultDefinition) { + tag.setInteger(ToolHelper.AOE_ROW_KEY, MathHelper.clamp(i, 0, defaultDefinition.row)); + } + + public static void setLayer(NBTTagCompound tag, int i, AoESymmetrical defaultDefinition) { + tag.setInteger(ToolHelper.AOE_LAYER_KEY, MathHelper.clamp(i, 0, defaultDefinition.layer)); + } + public static void increaseColumn(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_COLUMN_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, defaultDefinition.column); - } else { - int currentColumn = tag.getInteger(ToolHelper.AOE_COLUMN_KEY); - if (currentColumn < defaultDefinition.column) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, currentColumn + 1); - } - } + int currentColumn = getColumn(tag, defaultDefinition); + setColumn(tag, currentColumn + 1, defaultDefinition); } public static void increaseRow(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_ROW_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, defaultDefinition.row); - } else { - int currentRow = tag.getInteger(ToolHelper.AOE_ROW_KEY); - if (currentRow < defaultDefinition.row) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, currentRow + 1); - } - } + int currentRow = getRow(tag, defaultDefinition); + setRow(tag, currentRow + 1, defaultDefinition); } public static void increaseLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_LAYER_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, defaultDefinition.layer); - } else { - int currentLayer = tag.getInteger(ToolHelper.AOE_LAYER_KEY); - if (currentLayer < defaultDefinition.layer) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, currentLayer + 1); - } - } + int currentLayer = getLayer(tag, defaultDefinition); + setLayer(tag, currentLayer + 1, defaultDefinition); } public static void decreaseColumn(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_COLUMN_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, defaultDefinition.column); - } else { - int currentColumn = tag.getInteger(ToolHelper.AOE_COLUMN_KEY); - if (currentColumn > 0) { - tag.setInteger(ToolHelper.AOE_COLUMN_KEY, currentColumn - 1); - } - } + int currentColumn = getColumn(tag, defaultDefinition); + setColumn(tag, currentColumn - 1, defaultDefinition); } public static void decreaseRow(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_ROW_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, defaultDefinition.row); - } else { - int currentRow = tag.getInteger(ToolHelper.AOE_ROW_KEY); - if (currentRow > 0) { - tag.setInteger(ToolHelper.AOE_ROW_KEY, currentRow - 1); - } - } + int currentRow = getRow(tag, defaultDefinition); + setRow(tag, currentRow + 1, defaultDefinition); } public static void decreaseLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) { - if (!tag.hasKey(ToolHelper.AOE_LAYER_KEY, Constants.NBT.TAG_INT)) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, defaultDefinition.layer); - } else { - int currentLayer = tag.getInteger(ToolHelper.AOE_LAYER_KEY); - if (currentLayer > 0) { - tag.setInteger(ToolHelper.AOE_LAYER_KEY, currentLayer - 1); - } - } + int currentLayer = getLayer(tag, defaultDefinition); + setLayer(tag, currentLayer + 1, defaultDefinition); } public static AoESymmetrical none() { diff --git a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java b/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java deleted file mode 100644 index a9f0dd6c97a..00000000000 --- a/src/main/java/gregtech/api/mui/sync/NBTSyncValue.java +++ /dev/null @@ -1,59 +0,0 @@ -package gregtech.api.mui.sync; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; - -import com.cleanroommc.modularui.value.sync.ValueSyncHandler; - -import java.io.IOException; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.Supplier; - -public class NBTSyncValue extends ValueSyncHandler { - - private final Supplier getter; - private final Consumer setter; - private NBTTagCompound cache; - - public NBTSyncValue(Supplier getter, Consumer setter) { - this.getter = getter; - this.setter = setter; - this.cache = getter.get(); - } - - @Override - public void setValue(NBTTagCompound value, boolean setSource, boolean sync) { - this.cache = value; - if (setSource && this.setter != null) { - this.setter.accept(value); - } - if (sync) { - sync(0, this::write); - } - } - - @Override - public boolean updateCacheFromSource(boolean isFirstSync) { - if (isFirstSync || !Objects.equals(this.getter.get(), this.cache)) { - setValue(this.getter.get(), false, false); - return true; - } - return false; - } - - @Override - public void write(PacketBuffer buffer) throws IOException { - buffer.writeCompoundTag(getValue()); - } - - @Override - public void read(PacketBuffer buffer) throws IOException { - setValue(buffer.readCompoundTag()); - } - - @Override - public NBTTagCompound getValue() { - return this.cache; - } -} From 2b197feafe08845d256ab2f92cc07202f039d15f Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Sat, 9 Nov 2024 13:13:29 -0700 Subject: [PATCH 66/82] rework toolbelt's `buildUI()` (it looked at me wrong) --- .../api/items/toolitem/ItemGTToolbelt.java | 44 ++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 1ce60b70e75..406541fec55 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -52,7 +52,7 @@ import com.cleanroommc.modularui.value.sync.PanelSyncManager; import com.cleanroommc.modularui.value.sync.SyncHandlers; import com.cleanroommc.modularui.widgets.ItemSlot; -import com.cleanroommc.modularui.widgets.SlotGroupWidget; +import com.cleanroommc.modularui.widgets.layout.Grid; import com.cleanroommc.modularui.widgets.slot.SlotGroup; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; @@ -104,35 +104,39 @@ public ItemStack getToolInSlot(@NotNull ItemStack toolbelt, int slot) { @Override public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { - ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); - ItemStack selected = handler.getSelectedStack(); + final var usedStack = guiData.getUsedItemStack(); + final var handler = getHandler(usedStack); + final var selected = handler.getSelectedStack(); if (selected != null && selected.getItem() instanceof ItemUIFactory factory) { return factory.buildUI(guiData, guiSyncManager); } int heightBonus = (handler.getSlots() / 9) * 18; - ModularPanel panel = GTGuis.createPanel(guiData.getUsedItemStack().getDisplayName(), 176, 120 + heightBonus); - SlotGroup group = new SlotGroup("toolbelt_inventory", 9); guiSyncManager.registerSlotGroup(group); - SlotGroupWidget slotGroupWidget = new SlotGroupWidget(); - slotGroupWidget.flex().coverChildren().leftRel(0.5f).top(7); - slotGroupWidget.debugName("toolbelt_inventory"); + List slots = new ArrayList<>(); for (int i = 0; i < handler.getSlots(); i++) { - int finalI = i; - slotGroupWidget.child(new ItemSlot() - .slot(SyncHandlers.itemSlot(handler, i).slotGroup(group) - .changeListener( - (newItem, onlyAmountChanged, client, init) -> handler.onContentsChanged(finalI))) - .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) - .pos(i % 9 * 18, i / 9 * 18) - .debugName("slot_" + i)); - } - panel.child(slotGroupWidget); - - return panel.bindPlayerInventory(); + slots.add(new ItemSlot()); + } + + return GTGuis.createPanel(usedStack.getTranslationKey(), 176, 120 + heightBonus) + .child(new Grid() + .margin(0) + .leftRel(0.5f) + .top(7) + .coverChildren() + .mapTo(group.getRowSize(), slots, (index, value) -> value + .slot(SyncHandlers.itemSlot(handler, index) + .slotGroup(group) + .changeListener( + (newItem, onlyAmountChanged, client, init) -> handler + .onContentsChanged(index))) + .background(GTGuiTextures.SLOT, GTGuiTextures.TOOL_SLOT_OVERLAY) + .debugName("slot_" + index)) + .debugName("toolbelt_inventory")) + .bindPlayerInventory(); } public static boolean isToolbeltableOredict(String oredict) { From f91468a854625d4050f41bee6f6d92f175358ad1 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Sat, 9 Nov 2024 15:21:51 -0700 Subject: [PATCH 67/82] Refactor --- .../api/items/toolitem/ItemGTToolbelt.java | 144 +++++++++--------- .../api/items/toolitem/ToolHelper.java | 21 +-- .../java/gregtech/client/ClientProxy.java | 4 +- .../renderer/handler/ToolbeltRenderer.java | 2 +- .../client/utils/ToolChargeBarRenderer.java | 2 +- .../gregtech/common/ToolEventHandlers.java | 6 +- .../resources/assets/gregtech/lang/en_us.lang | 2 + 7 files changed, 90 insertions(+), 91 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 1ce60b70e75..6d66afe1e77 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -59,6 +59,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Range; import java.util.ArrayList; import java.util.Arrays; @@ -66,6 +67,7 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.function.IntSupplier; import java.util.function.Supplier; import static gregtech.api.items.toolitem.ToolHelper.MATERIAL_KEY; @@ -81,7 +83,7 @@ public ItemGTToolbelt(String domain, String id, Supplier markerItem, markerItem); } - public @Nullable Integer getSelectedSlot(@NotNull ItemStack toolbelt) { + public int getSelectedSlot(@NotNull ItemStack toolbelt) { return getHandler(toolbelt).getSelectedSlot(); } @@ -91,7 +93,7 @@ public int getSlotCount(@NotNull ItemStack toolbelt) { // nullable to differentiate between "no tool selected" and "no tool in selected slot" which is theoretically // possible - public @Nullable ItemStack getSelectedTool(@NotNull ItemStack toolbelt) { + public @NotNull ItemStack getSelectedTool(@NotNull ItemStack toolbelt) { return getHandler(toolbelt).getSelectedStack(); } @@ -106,7 +108,7 @@ public ItemStack getToolInSlot(@NotNull ItemStack toolbelt, int slot) { public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager) { ToolStackHandler handler = getHandler(guiData.getUsedItemStack()); ItemStack selected = handler.getSelectedStack(); - if (selected != null && selected.getItem() instanceof ItemUIFactory factory) { + if (!selected.isEmpty() && selected.getItem() instanceof ItemUIFactory factory) { return factory.buildUI(guiData, guiSyncManager); } @@ -146,7 +148,7 @@ public void registerValidOredict(String oredict) { @Override public float getDestroySpeed(@NotNull ItemStack stack, @NotNull IBlockState state) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().getDestroySpeed(selected, state); } else return definition$getDestroySpeed(stack, state); } @@ -155,7 +157,7 @@ public float getDestroySpeed(@NotNull ItemStack stack, @NotNull IBlockState stat public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase target, @NotNull EntityLivingBase attacker) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().hitEntity(selected, target, attacker); } else return definition$hitEntity(stack, target, attacker); } @@ -164,7 +166,7 @@ public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase tar public boolean onBlockStartBreak(@NotNull ItemStack itemstack, @NotNull BlockPos pos, @NotNull EntityPlayer player) { ItemStack selected = getHandler(itemstack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().onBlockStartBreak(selected, pos, player); } else return definition$onBlockStartBreak(itemstack, pos, player); } @@ -173,17 +175,15 @@ public boolean onBlockStartBreak(@NotNull ItemStack itemstack, @NotNull BlockPos public boolean onBlockDestroyed(@NotNull ItemStack stack, @NotNull World worldIn, @NotNull IBlockState state, @NotNull BlockPos pos, @NotNull EntityLivingBase entityLiving) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().onBlockDestroyed(selected, worldIn, state, pos, entityLiving); } else return definition$onBlockDestroyed(stack, worldIn, state, pos, entityLiving); } @Override public boolean getIsRepairable(@NotNull ItemStack toRepair, @NotNull ItemStack repair) { - // I think this lets repairs go through to the selected tool, in combination with the setDamage passthroughs? - // Idk testing required. ItemStack selected = getHandler(toRepair).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().getIsRepairable(selected, repair); } else return definition$getIsRepairable(toRepair, repair); } @@ -193,7 +193,7 @@ public boolean getIsRepairable(@NotNull ItemStack toRepair, @NotNull ItemStack r public Multimap getAttributeModifiers(@NotNull EntityEquipmentSlot slot, @NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().getAttributeModifiers(slot, selected); } else return definition$getAttributeModifiers(slot, stack); } @@ -202,7 +202,7 @@ public Multimap getAttributeModifiers(@NotNull Entity public int getHarvestLevel(@NotNull ItemStack stack, @NotNull String toolClass, @Nullable EntityPlayer player, @Nullable IBlockState blockState) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().getHarvestLevel(stack, toolClass, player, blockState); } else return super.getHarvestLevel(stack, toolClass, player, blockState); } @@ -217,7 +217,7 @@ public Set getToolClasses(@NotNull ItemStack stack) { public boolean canDisableShield(@NotNull ItemStack stack, @NotNull ItemStack shield, @NotNull EntityLivingBase entity, @NotNull EntityLivingBase attacker) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().canDisableShield(selected, shield, entity, attacker); } else return definition$canDisableShield(stack, shield, entity, attacker); } @@ -226,7 +226,7 @@ public boolean canDisableShield(@NotNull ItemStack stack, @NotNull ItemStack shi public boolean doesSneakBypassUse(@NotNull ItemStack stack, @NotNull IBlockAccess world, @NotNull BlockPos pos, @NotNull EntityPlayer player) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().doesSneakBypassUse(selected, world, pos, player); } else return definition$doesSneakBypassUse(stack, world, pos, player); } @@ -234,7 +234,7 @@ public boolean doesSneakBypassUse(@NotNull ItemStack stack, @NotNull IBlockAcces @Override public boolean onEntitySwing(@NotNull EntityLivingBase entityLiving, @NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().onEntitySwing(entityLiving, selected); } else return definition$onEntitySwing(entityLiving, stack); } @@ -243,7 +243,7 @@ public boolean onEntitySwing(@NotNull EntityLivingBase entityLiving, @NotNull It public boolean canDestroyBlockInCreative(@NotNull World world, @NotNull BlockPos pos, @NotNull ItemStack stack, @NotNull EntityPlayer player) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().canDestroyBlockInCreative(world, pos, selected, player); } else return definition$canDestroyBlockInCreative(world, pos, stack, player); } @@ -257,7 +257,7 @@ public boolean shouldCauseReequipAnimation(@NotNull ItemStack oldStack, @NotNull @Override public boolean isDamaged(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().isDamaged(selected); } else return definition$isDamaged(stack); } @@ -265,7 +265,7 @@ public boolean isDamaged(@NotNull ItemStack stack) { @Override public int getDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().getDamage(selected); } else return super.getDamage(stack); } @@ -273,7 +273,7 @@ public int getDamage(@NotNull ItemStack stack) { @Override public int getMaxDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().getMaxDamage(selected); } else return definition$getMaxDamage(stack); } @@ -281,7 +281,7 @@ public int getMaxDamage(@NotNull ItemStack stack) { @Override public void setDamage(@NotNull ItemStack stack, int damage) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { selected.getItem().setDamage(selected, damage); } else super.setDamage(stack, damage); } @@ -289,7 +289,7 @@ public void setDamage(@NotNull ItemStack stack, int damage) { @Override public double getDurabilityForDisplay(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { double dis = selected.getItem().getDurabilityForDisplay(selected); // vanillaesque tools need to be inverted if (selected.getItem() instanceof ItemTool) dis = 1 - dis; @@ -303,7 +303,7 @@ public void addInformation(@NotNull ItemStack stack, @Nullable World world, @Not @NotNull ITooltipFlag flag) { ToolStackHandler handler = getHandler(stack); ItemStack selected = handler.getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { selected.getItem().addInformation(selected, world, tooltip, flag); } else { if (stack.getItemDamage() > 0) { @@ -322,14 +322,23 @@ public void addInformation(@NotNull ItemStack stack, @Nullable World world, @Not tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.maintenance")); } else tooltip.add(I18n.format("gregtech.tooltip.hold_shift")); - } + if (TooltipHelper.isCtrlDown()) { + tooltip.add(""); + for (int i = 0; i < handler.getSlots(); i++) { + ItemStack tool = handler.getStackInSlot(i); + String name = tool.isEmpty() ? "x" : tool.getDisplayName(); + tooltip.add(I18n.format( + handler.selectedSlot == i ? "item.gt.tool.toolbelt.selected" : "item.gt.tool.toolbelt.tool", + i + 1, name)); + } + } else tooltip.add(I18n.format("gregtech.tooltip.hold_ctrl")); } @Override public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { return selected.getItem().canHarvestBlock(state, selected); } else return ToolHelper.isToolEffective(state, getToolClasses(stack), getTotalHarvestLevel(stack)); } @@ -337,7 +346,7 @@ public boolean canHarvestBlock(@NotNull IBlockState state, @NotNull ItemStack st @Override public void wrenchUsed(EntityPlayer player, EnumHand hand, ItemStack wrench, RayTraceResult rayTrace) { ItemStack selected = getHandler(wrench).getSelectedStack(); - if (selected != null && selected.getItem() instanceof IGTTool tool) { + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool tool) { tool.wrenchUsed(player, hand, selected, rayTrace); } else super.wrenchUsed(player, hand, wrench, rayTrace); } @@ -345,7 +354,7 @@ public void wrenchUsed(EntityPlayer player, EnumHand hand, ItemStack wrench, Ray @Override public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { ItemStack selected = getHandler(item).getSelectedStack(); - if (selected != null && selected.getItem() instanceof IGTTool tool) { + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool tool) { tool.toolUsed(selected, user, pos); } else super.toolUsed(item, user, pos); } @@ -353,7 +362,7 @@ public void toolUsed(ItemStack item, EntityLivingBase user, BlockPos pos) { @Override public void used(@NotNull EnumHand hand, @NotNull EntityPlayer player, @NotNull BlockPos pos) { ItemStack selected = getHandler(player.getHeldItem(hand)).getSelectedStack(); - if (selected != null && selected.getItem() instanceof IGTTool tool) { + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool tool) { tool.used(hand, player, pos); } else super.used(hand, player, pos); } @@ -373,8 +382,8 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { } public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { - Integer match = getHandler(stack).checkIngredientAgainstTools(ingredient); - if (match != null) { + int match = getHandler(stack).checkIngredientAgainstTools(ingredient); + if (match != -1) { setSelectedTool(match, stack); } } @@ -385,11 +394,11 @@ public boolean damageAgainstMaintenanceProblem(ItemStack stack, String toolClass } public boolean supportsIngredient(ItemStack stack, Ingredient ingredient) { - return getHandler(stack).checkIngredientAgainstTools(ingredient) != null; + return getHandler(stack).checkIngredientAgainstTools(ingredient) != -1; } public boolean supportsTool(ItemStack stack, ItemStack tool) { - return getHandler(stack).checkToolAgainstTools(tool) != null; + return getHandler(stack).checkToolAgainstTools(tool) != -1; } private ToolStackHandler getHandler(ItemStack stack) { @@ -407,23 +416,22 @@ public void changeSelectedToolMousewheel(int direction, ItemStack stack) { if (direction < 0) handler.incrementSelectedSlot(); else handler.decrementSelectedSlot(); GregTechAPI.networkHandler.sendToServer( - new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); + new PacketToolbeltSelectionChange(handler.selectedSlot)); } @SideOnly(Side.CLIENT) public void changeSelectedToolHotkey(int slot, ItemStack stack) { ToolStackHandler handler = getHandler(stack); - if (slot < 0 || slot >= handler.getSlots() || handler.getStackInSlot(slot).isEmpty()) - handler.selectedSlot = null; + if (slot < 0 || slot >= handler.getSlots()) handler.selectedSlot = -1; else handler.selectedSlot = slot; GregTechAPI.networkHandler.sendToServer( - new PacketToolbeltSelectionChange(handler.selectedSlot == null ? -1 : handler.selectedSlot)); + new PacketToolbeltSelectionChange(handler.selectedSlot)); } - public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { + public void setSelectedTool(int slot, ItemStack stack) { ToolStackHandler handler = getHandler(stack); - if (slot == null || slot < 0 || slot >= handler.getSlots() || handler.getStackInSlot(slot).isEmpty()) - handler.selectedSlot = null; + if (slot < 0 || slot >= handler.getSlots()) + handler.selectedSlot = -1; else handler.selectedSlot = slot; } @@ -431,7 +439,7 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { public @NotNull String getItemStackDisplayName(@NotNull ItemStack stack) { ItemStack tool = getHandler(stack).getSelectedStack(); String selectedToolDisplay = ""; - if (tool != null) { + if (!tool.isEmpty()) { selectedToolDisplay = " (" + tool.getDisplayName() + ")"; } getHandler(stack).disablePassthrough(); @@ -449,7 +457,7 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { if (result == EnumActionResult.PASS) { ItemStack stack = player.getHeldItem(hand); ToolStackHandler handler = getHandler(stack); - if (handler.getSelectedSlot() == null && world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && + if (handler.getSelectedSlot() == -1 && world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && holder.getMetaTileEntity() instanceof MetaTileEntityMaintenanceHatch maintenance) { maintenance.fixMaintenanceProblemsWithToolbelt(player, this, stack); return EnumActionResult.SUCCESS; @@ -464,7 +472,7 @@ public void setSelectedTool(@Nullable Integer slot, ItemStack stack) { @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { ToolStackHandler handler = getHandler(player.getHeldItem(hand)); ItemStack selected = handler.getSelectedStack(); - if (selected != null) { + if (!selected.isEmpty()) { ColorSprayBehaviour spray = ColorSprayBehaviour.getBehavior(selected); if (spray != null) { EnumActionResult result = spray.useFromToolbelt(player, world, pos, hand, facing, hitX, hitY, hitZ, @@ -515,7 +523,7 @@ public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @Not protected static class ToolbeltCapabilityProvider implements ICapabilityProvider, INBTSerializable { - protected final Supplier slotCountSupplier; + protected final IntSupplier slotCountSupplier; private @Nullable ToolStackHandler handler; @@ -558,7 +566,7 @@ public void deserializeNBT(NBTTagCompound nbt) { } protected ToolStackHandler getHandler(int minsize) { - int slots = Math.max(slotCountSupplier.get(), minsize); + int slots = Math.max(slotCountSupplier.getAsInt(), minsize); if (handler == null || handler.getSlots() != slots) handler = new ToolStackHandler(slots); return handler; } @@ -582,11 +590,9 @@ public void readNBTShareTag(ItemStack stack, NBTTagCompound nbt) { protected static class ToolStackHandler extends ItemStackHandler { - private Ingredient nextCraftIngredient; - private static final Set EMPTY = ImmutableSet.of(); - private @Nullable Integer selectedSlot = null; + private @Range(from = -1, to = 128) int selectedSlot = -1; protected final ItemTool[] tools = new ItemTool[this.getSlots()]; protected final IGTTool[] gtTools = new IGTTool[this.getSlots()]; @@ -600,26 +606,20 @@ public ToolStackHandler(int size) { } public void incrementSelectedSlot() { - for (int slot = (this.selectedSlot == null ? -1 : this.selectedSlot) + 1; slot != this.getSlots(); slot++) { - if (this.getStackInSlot(slot).isEmpty()) continue; - this.selectedSlot = slot; - return; - } - this.selectedSlot = null; + if ((this.selectedSlot += 1) >= this.getSlots()) this.selectedSlot = -1; } public void decrementSelectedSlot() { - for (int slot = (this.selectedSlot == null ? this.getSlots() : this.selectedSlot) - 1; slot != -1; slot--) { - if (this.getStackInSlot(slot).isEmpty()) continue; - this.selectedSlot = slot; - return; - } - this.selectedSlot = null; + if ((this.selectedSlot -= 1) < -1) this.selectedSlot = this.getSlots() - 1; } - public @Nullable Integer getSelectedSlot() { + public int getSelectedSlot() { if (passthrough) return selectedSlot; - else return null; + else return -1; + } + + public void setSelectedSlot(int selectedSlot) { + this.selectedSlot = Math.min(getSlots() - 1, Math.max(selectedSlot, -1)); } public void enablePassthrough() { @@ -630,14 +630,14 @@ public void disablePassthrough() { this.passthrough = false; } - public @Nullable ItemStack getSelectedStack() { - if (getSelectedSlot() == null) return null; + public @NotNull ItemStack getSelectedStack() { + if (getSelectedSlot() == -1) return ItemStack.EMPTY; else return this.stacks.get(getSelectedSlot()); } public Set getToolClasses(boolean defaultEmpty) { ItemStack selectedStack = getSelectedStack(); - if (selectedStack != null) { + if (!selectedStack.isEmpty()) { if (selectedStack.getItem() instanceof ItemTool tool) { return tool.getToolClasses(selectedStack); } else if (selectedStack.getItem() instanceof IGTTool tool) { @@ -657,7 +657,7 @@ public boolean isItemValid(int slot, @NotNull ItemStack stack) { @Override protected void onContentsChanged(int slot) { - if (this.selectedSlot != null && this.selectedSlot == slot) this.selectedSlot = null; + if (this.selectedSlot == slot) this.selectedSlot = -1; this.updateSlot(slot); this.update(); @@ -667,14 +667,14 @@ protected void onContentsChanged(int slot) { @Override public NBTTagCompound serializeNBT() { NBTTagCompound tag = super.serializeNBT(); - if (this.selectedSlot != null) tag.setByte("SelectedSlot", this.selectedSlot.byteValue()); + if (this.selectedSlot != -1) tag.setByte("SelectedSlot", (byte) this.selectedSlot); return tag; } @Override public void deserializeNBT(NBTTagCompound nbt) { super.deserializeNBT(nbt); - if (nbt.hasKey("SelectedSlot")) this.selectedSlot = (int) nbt.getByte("SelectedSlot"); + if (nbt.hasKey("SelectedSlot")) this.selectedSlot = nbt.getByte("SelectedSlot"); } @Override @@ -727,15 +727,14 @@ public boolean checkMaintenanceAgainstTools(String toolClass, boolean doCrafting return false; } - @Nullable - public Integer checkIngredientAgainstTools(Ingredient ingredient) { + public int checkIngredientAgainstTools(Ingredient ingredient) { for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); if (ingredient.test(stack)) { return i; } } - return null; + return -1; } public void dealCraftDamageToSlot(int slot) { @@ -744,21 +743,20 @@ public void dealCraftDamageToSlot(int slot) { } public boolean dealCraftDamageToSelected() { - if (selectedSlot != null) { + if (selectedSlot != -1) { dealCraftDamageToSlot(selectedSlot); return true; } else return false; } - @Nullable - public Integer checkToolAgainstTools(ItemStack tool) { + public int checkToolAgainstTools(ItemStack tool) { for (int i = 0; i < this.getSlots(); i++) { ItemStack stack = this.getStackInSlot(i); if (OreDictionary.itemMatches(stack, tool, false)) { return i; } } - return null; + return -1; } } } diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index cfde5af013d..0596a473008 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -4,6 +4,7 @@ import gregtech.api.capability.GregtechCapabilities; import gregtech.api.capability.IElectricItem; import gregtech.api.items.metaitem.MetaItem; +import gregtech.api.items.metaitem.stats.IItemBehaviour; import gregtech.api.items.toolitem.aoe.AoESymmetrical; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; @@ -204,7 +205,7 @@ public static NBTTagCompound getToolTag(ItemStack stack) { public static ItemStack toolbeltPassthrough(ItemStack stack) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; + if (!selected.isEmpty()) stack = selected; } return stack; } @@ -250,7 +251,7 @@ public static ItemStack getAndSetToolData(IGTTool tool, Material material, int m public static void damageItemWhenCrafting(@NotNull ItemStack stack, @Nullable EntityLivingBase entity) { if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { ItemStack selectedStack = toolbelt.getSelectedTool(stack); - if (selectedStack != null) { + if (!selectedStack.isEmpty()) { damageItemWhenCrafting(selectedStack, entity); return; } @@ -294,7 +295,7 @@ public static void damageItem(@NotNull ItemStack stack, @Nullable EntityLivingBa return; } else if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { ItemStack selectedStack = toolbelt.getSelectedTool(stack); - if (selectedStack != null) { + if (!selectedStack.isEmpty()) { damageItem(selectedStack, entity, damage); return; } @@ -405,8 +406,12 @@ public static boolean isTool(ItemStack tool) { * @return if the itemstack should be considered a spraycan */ public static boolean isSpraycan(ItemStack spraycan) { - return spraycan.getItem() instanceof MetaItemmeta && - meta.getBehaviours(spraycan).stream().anyMatch(b -> b instanceof ColorSprayBehaviour); + if (spraycan.getItem() instanceof MetaItemmeta) { + for (IItemBehaviour behaviour : meta.getBehaviours(spraycan)) { + if (behaviour instanceof ColorSprayBehaviour) return true; + } + } + return false; } /** @@ -466,10 +471,8 @@ public static boolean areaOfEffectBlockBreakRoutine(ItemStack stack, EntityPlaye } // If the tool is an electric tool, catch the tool breaking and cancel the remaining AOE ItemStack tool = player.getHeldItemMainhand(); - if (tool.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(tool); - if (selected != null) tool = selected; - } else if (!tool.isItemEqualIgnoreDurability(stack)) { + tool = toolbeltPassthrough(tool); + if (!tool.isItemEqualIgnoreDurability(stack)) { return true; } } diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index fa04b3d864f..a0fec925635 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -399,8 +399,8 @@ private static void renderToolbeltHotbar(GuiIngameForge gui, ItemStack stack, It gui.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22 - offset, 0, 0, slots * 20 - 18, 22); // draw the endpiece to the hotbar gui.drawTexturedModalRect(i - 91 + slots * 20 - 18, sr.getScaledHeight() - 22 - offset, 162, 0, 20, 22); - Integer selected = toolbelt.getSelectedSlot(stack); - if (selected != null) { + int selected = toolbelt.getSelectedSlot(stack); + if (selected != -1) { gui.drawTexturedModalRect(i - 91 - 1 + selected * 20, sr.getScaledHeight() - 22 - 1 - offset, 0, 22, 24, 24); } diff --git a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java index 821a0f5c4c3..bdeacb59ff8 100644 --- a/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java +++ b/src/main/java/gregtech/client/renderer/handler/ToolbeltRenderer.java @@ -33,7 +33,7 @@ public void renderItem(ItemStack stack, ItemCameraTransforms.TransformType trans RenderItem renderItem = Minecraft.getMinecraft().getRenderItem(); ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) { + if (!selected.isEmpty()) { IBakedModel selectedModel = renderItem.getItemModelWithOverrides(selected, null, null); renderItem.renderItem(selected, selectedModel); } diff --git a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java index 0b89f162452..c8ffd11b817 100644 --- a/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java +++ b/src/main/java/gregtech/client/utils/ToolChargeBarRenderer.java @@ -116,7 +116,7 @@ private static void overpaintVanillaRenderBug(BufferBuilder worldrenderer, int x public static void renderBarsTool(IGTTool tool, ItemStack stack, int xPosition, int yPosition) { if (tool instanceof ItemGTToolbelt toolbelt) { ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null && selected.getItem() instanceof IGTTool toool) { + if (!selected.isEmpty() && selected.getItem() instanceof IGTTool toool) { tool = toool; stack = selected; } diff --git a/src/main/java/gregtech/common/ToolEventHandlers.java b/src/main/java/gregtech/common/ToolEventHandlers.java index ad03995d64c..e503b539547 100644 --- a/src/main/java/gregtech/common/ToolEventHandlers.java +++ b/src/main/java/gregtech/common/ToolEventHandlers.java @@ -8,7 +8,6 @@ import gregtech.api.cover.CoverDefinition; import gregtech.api.cover.CoverHolder; import gregtech.api.items.toolitem.IGTTool; -import gregtech.api.items.toolitem.ItemGTToolbelt; import gregtech.api.items.toolitem.ToolClasses; import gregtech.api.items.toolitem.ToolHelper; import gregtech.api.metatileentity.MetaTileEntity; @@ -166,10 +165,7 @@ public static void onHarvestDrops(@NotNull BlockEvent.HarvestDropsEvent event) { // only try once, so future water placement does not get eaten too return false; }); - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { - ItemStack selected = toolbelt.getSelectedTool(stack); - if (selected != null) stack = selected; - } + stack = ToolHelper.toolbeltPassthrough(stack); ((IGTTool) stack.getItem()).playSound(player); } } diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index ca09a422d30..5e27ffbbb98 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1048,6 +1048,8 @@ item.gt.tool.toolbelt.tooltip=Holds GT or vanilla-esque tools that can be manual item.gt.tool.toolbelt.paint=Also supports Spray Cans. item.gt.tool.toolbelt.dye=Can be dyed like leather equipment. item.gt.tool.toolbelt.maintenance=Repairs maintenance problems with only inserted tools upon interacting with a maintenance hatch in-world. +item.gt.tool.toolbelt.tool=§aSlot %s: §f%s +item.gt.tool.toolbelt.selected=- §aSlot %s: §f%s item.gt.tool.tooltip.crafting_uses=§a%s Crafting Uses From f2100bdd26d5f84794c9633c50246bccb7c4fda5 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 22 Nov 2024 11:25:28 -0700 Subject: [PATCH 68/82] Minor change --- src/main/java/gregtech/api/items/toolitem/ToolHelper.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 0596a473008..03032e099b8 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -734,7 +734,6 @@ public static void applyHammerDropConversion(ItemStack tool, IBlockState state, public static boolean breakBlockRoutine(EntityPlayerMP player, ItemStack tool, BlockPos pos) { // This is *not* a vanilla/forge convention, Forge never added "shears" to ItemShear's tool classes. - tool = toolbeltPassthrough(tool); if (isTool(tool, ToolClasses.SHEARS) && shearBlockRoutine(player, tool, pos) == 0) { return false; } From 9ad32594e8937da4e1605d4aff92ea9cbc745cea Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Sun, 24 Nov 2024 08:32:45 -0700 Subject: [PATCH 69/82] Address review --- .../java/gregtech/api/items/IDyeableItem.java | 23 +++----- .../gregtech/api/items/toolitem/IGTTool.java | 12 ++--- .../api/items/toolitem/ItemGTToolbelt.java | 1 - .../toolitem/behavior/IToolBehavior.java | 27 ++++++---- .../asm/hooks/OreIngredientHooks.java | 23 -------- .../asm/visitors/OreIngredientVisitor.java | 52 ------------------- .../java/gregtech/common/items/ToolItems.java | 3 ++ .../items/tool/BlockRotatingBehavior.java | 6 +-- .../common/items/tool/GrassPathBehavior.java | 8 +-- .../items/tool/HarvestCropsBehavior.java | 8 +-- .../common/items/tool/HoeGroundBehavior.java | 8 +-- .../common/items/tool/OpenGUIBehavior.java | 4 +- .../common/items/tool/PlungerBehavior.java | 6 +-- .../common/items/tool/RotateRailBehavior.java | 6 +-- .../common/items/tool/TorchPlaceBehavior.java | 8 +-- .../jei/JustEnoughItemsModule.java | 18 ++++--- .../resources/assets/gregtech/lang/en_us.lang | 2 +- 17 files changed, 74 insertions(+), 141 deletions(-) delete mode 100644 src/main/java/gregtech/asm/hooks/OreIngredientHooks.java delete mode 100644 src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index 7823b65d09f..6fc5aac04ed 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -18,17 +18,13 @@ public interface IDyeableItem { default boolean hasColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - return nbttagcompound != null && nbttagcompound.hasKey("display", Constants.NBT.TAG_COMPOUND) && - nbttagcompound.getCompoundTag("display").hasKey("color", Constants.NBT.TAG_INT); + return nbttagcompound != null && nbttagcompound.hasKey("color", Constants.NBT.TAG_INT); } default int getColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - if (nbttagcompound != null) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (nbttagcompound1.hasKey("color", Constants.NBT.TAG_INT)) { - return nbttagcompound1.getInteger("color"); - } + if (nbttagcompound != null && nbttagcompound.hasKey("color", Constants.NBT.TAG_INT)) { + return nbttagcompound.getInteger("color"); } return getDefaultColor(stack); } @@ -39,11 +35,8 @@ default int getDefaultColor(ItemStack stack) { default void removeColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - if (nbttagcompound != null) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (nbttagcompound1.hasKey("color")) { - nbttagcompound1.removeTag("color"); - } + if (nbttagcompound != null && nbttagcompound.hasKey("color")) { + nbttagcompound.removeTag("color"); } } @@ -53,11 +46,7 @@ default void setColor(ItemStack stack, int color) { nbttagcompound = new NBTTagCompound(); stack.setTagCompound(nbttagcompound); } - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (!nbttagcompound.hasKey("display", Constants.NBT.TAG_COMPOUND)) { - nbttagcompound.setTag("display", nbttagcompound1); - } - nbttagcompound1.setInteger("color", color); + nbttagcompound.setInteger("color", color); } default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 65647a4278e..550599b473d 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -647,13 +647,12 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { - ItemStack stack = player.getHeldItem(hand); - stack = toolbeltPassthrough(stack); + ItemStack stack = toolbeltPassthrough(player.getHeldItem(hand)); List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); else return EnumActionResult.PASS; for (IToolBehavior behavior : behaviors) { - if (behavior.onItemUseFirst(stack, player, world, pos, facing, hitX, hitY, hitZ, hand) == + if (behavior.onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } @@ -664,14 +663,13 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { - ItemStack stack = player.getHeldItem(hand); - stack = toolbeltPassthrough(stack); + ItemStack stack = toolbeltPassthrough(player.getHeldItem(hand)); List behaviors; if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); else return EnumActionResult.PASS; for (IToolBehavior behavior : behaviors) { - if (behavior.onItemUse(stack, player, world, pos, hand, facing, hitX, hitY, hitZ) == + if (behavior.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; } @@ -696,7 +694,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { else return ActionResult.newResult(EnumActionResult.PASS, original); for (IToolBehavior behavior : behaviors) { - if (behavior.onItemRightClick(stack, world, player, hand).getType() == EnumActionResult.SUCCESS) { + if (behavior.onItemRightClick(world, player, hand).getType() == EnumActionResult.SUCCESS) { return ActionResult.newResult(EnumActionResult.SUCCESS, original); } } diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 1d81519db7d..70547e6eaf4 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -322,7 +322,6 @@ public void addInformation(@NotNull ItemStack stack, @Nullable World world, @Not tooltip.add(I18n.format("item.gt.tool.toolbelt.tooltip")); tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.paint")); - tooltip.add(I18n.format("item.gt.tool.toolbelt.dye")); tooltip.add(""); tooltip.add(I18n.format("item.gt.tool.toolbelt.maintenance")); } else tooltip.add(I18n.format("gregtech.tooltip.hold_shift")); diff --git a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java index 88b249d4327..77dd5679b68 100644 --- a/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java +++ b/src/main/java/gregtech/api/items/toolitem/behavior/IToolBehavior.java @@ -79,7 +79,10 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving } /** - * Called when a Block is right-clicked with this Item, but before the block is activated + * Called when a Block is right-clicked with this Item, but before the block is activated. + * If actions not going through {@link gregtech.api.items.toolitem.ToolHelper} are performed, such as + * {@link ItemStack#shrink(int)}, don't forget to perform toolbelt passthrough via + * {@link gregtech.api.items.toolitem.ToolHelper#toolbeltPassthrough(ItemStack)} * * @param player the player clicking with the item * @param world the world in which the block is clicked @@ -90,16 +93,18 @@ default boolean canDisableShield(ItemStack stack, ItemStack shield, EntityLiving * @param hitZ the z location of the block hit * @param hand the hand holding the item */ - default EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, - @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + default EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { return EnumActionResult.PASS; } /** - * Called when a Block is right-clicked with this Item + * Called when a Block is right-clicked with this Item. + * If actions not going through {@link gregtech.api.items.toolitem.ToolHelper} are performed, such as + * {@link ItemStack#shrink(int)}, don't forget to perform toolbelt passthrough via + * {@link gregtech.api.items.toolitem.ToolHelper#toolbeltPassthrough(ItemStack)} * - * @param stack the itemstack of the tool * @param player the player clicking with the item * @param world the world in which the block is clicked * @param pos the position of the blocked clicked @@ -110,8 +115,7 @@ default EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull Entit * @param hitZ the z location of the block hit */ @NotNull - default EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, + default EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ) { return EnumActionResult.PASS; @@ -119,14 +123,17 @@ default EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlay /** * Called when the equipped item is right-clicked. + * If actions not going through {@link gregtech.api.items.toolitem.ToolHelper} are performed, such as + * {@link ItemStack#shrink(int)}, don't forget to perform toolbelt passthrough via + * {@link gregtech.api.items.toolitem.ToolHelper#toolbeltPassthrough(ItemStack)} * * @param world the world in which the click happened * @param player the player clicking the item * @param hand the hand holding the item */ @NotNull - default ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, - @NotNull EntityPlayer player, @NotNull EnumHand hand) { + default ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand)); } diff --git a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java b/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java deleted file mode 100644 index cc0a13fd4f0..00000000000 --- a/src/main/java/gregtech/asm/hooks/OreIngredientHooks.java +++ /dev/null @@ -1,23 +0,0 @@ -package gregtech.asm.hooks; - -import gregtech.api.items.toolitem.ItemGTToolbelt; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreIngredient; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -@SuppressWarnings("unused") -public class OreIngredientHooks { - - public static boolean checkToolbelt(@Nullable ItemStack input, @NotNull OreIngredient ingredient) { - if (input.getItem() instanceof ItemGTToolbelt toolbelt) { - if (toolbelt.supportsIngredient(input, ingredient)) { - toolbelt.setOnCraftIngredient(input, ingredient); - return true; - } - } - return false; - } -} diff --git a/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java b/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java deleted file mode 100644 index 8a51c12e3e6..00000000000 --- a/src/main/java/gregtech/asm/visitors/OreIngredientVisitor.java +++ /dev/null @@ -1,52 +0,0 @@ -package gregtech.asm.visitors; - -import gregtech.asm.util.ObfMapping; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -public class OreIngredientVisitor extends MethodVisitor implements Opcodes { - - public static final String TARGET_CLASS_NAME = "net/minecraftforge/oredict/OreIngredient"; - public static final ObfMapping TARGET_METHOD = new ObfMapping(TARGET_CLASS_NAME, "apply", - targetSignature()); - - private static final String OWNER = "gregtech/asm/hooks/OreIngredientHooks"; - private static final String SIGNATURE = signature(); - private static final String METHOD_NAME = "checkToolbelt"; - - public OreIngredientVisitor(MethodVisitor mv) { - super(ASM5, mv); - } - - @Override - public void visitCode() { - mv.visitVarInsn(ALOAD, 1); // ItemStack - mv.visitVarInsn(ALOAD, 0); // OreIngredient - mv.visitMethodInsn(INVOKESTATIC, OWNER, METHOD_NAME, SIGNATURE, false); - Label L1 = new Label(); - mv.visitJumpInsn(IFEQ, L1); - mv.visitInsn(ICONST_1); - mv.visitInsn(IRETURN); - mv.visitLabel(L1); - mv.visitFrame(F_SAME, 0, null, 0, null); - - mv.visitCode(); - } - - // public boolean apply(@Nullable ItemStack input) - private static String targetSignature() { - return "(" + - "Lnet/minecraft/item/ItemStack;" + // ItemStack - ")Z;"; // return boolean - } - - // public static boolean extendedApply(@Nullable ItemStack input, @NotNull OreIngredient ingredient) - private static String signature() { - return "(" + - "Lnet/minecraft/item/ItemStack;" + // ItemStack - "Lnet/minecraftforge/oredict/OreIngredient;" + // OreIngredient - ")Z"; // return boolean - } -} diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 561cd094a74..524056915f5 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -8,6 +8,8 @@ import gregtech.common.items.tool.*; import gregtech.core.sound.GTSoundEvents; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.enchantment.EnumEnchantmentType; @@ -21,6 +23,7 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java b/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java index 143371982c3..acd60d1324a 100644 --- a/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java +++ b/src/main/java/gregtech/common/items/tool/BlockRotatingBehavior.java @@ -33,9 +33,9 @@ public class BlockRotatingBehavior implements IToolBehavior { protected BlockRotatingBehavior() {/**/} @Override - public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, - @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing side, - float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing side, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { TileEntity te = world.getTileEntity(pos); // MTEs have special handling on rotation if (te instanceof IGregTechTileEntity) { diff --git a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java index 111bc9855ce..cdb694fbb44 100644 --- a/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java +++ b/src/main/java/gregtech/common/items/tool/GrassPathBehavior.java @@ -34,11 +34,13 @@ protected GrassPathBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; + ItemStack stack = player.getHeldItem(hand); + AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java index 353d0427d19..519b275192e 100644 --- a/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HarvestCropsBehavior.java @@ -36,13 +36,15 @@ protected HarvestCropsBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { if (world.isRemote) { return EnumActionResult.PASS; } + ItemStack stack = player.getHeldItem(hand); + AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java index fe05dabdc67..9fef46e5e5d 100644 --- a/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java +++ b/src/main/java/gregtech/common/items/tool/HoeGroundBehavior.java @@ -41,11 +41,13 @@ protected HoeGroundBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { if (facing == EnumFacing.DOWN) return EnumActionResult.PASS; + ItemStack stack = player.getHeldItem(hand); + AoESymmetrical aoeDefinition = ToolHelper.getAoEDefinition(stack); Set blocks; diff --git a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java index 0697f47ec6f..4d0a43d71b0 100644 --- a/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java +++ b/src/main/java/gregtech/common/items/tool/OpenGUIBehavior.java @@ -20,8 +20,8 @@ public class OpenGUIBehavior implements IToolBehavior { protected OpenGUIBehavior() {} @Override - public @NotNull ActionResult onItemRightClick(@NotNull ItemStack stack, @NotNull World world, - @NotNull EntityPlayer player, @NotNull EnumHand hand) { + public @NotNull ActionResult onItemRightClick(@NotNull World world, @NotNull EntityPlayer player, + @NotNull EnumHand hand) { if (!world.isRemote) { ItemGuiFactory.open((EntityPlayerMP) player, hand); } diff --git a/src/main/java/gregtech/common/items/tool/PlungerBehavior.java b/src/main/java/gregtech/common/items/tool/PlungerBehavior.java index 2d6fdc3eab8..609e429e0c0 100644 --- a/src/main/java/gregtech/common/items/tool/PlungerBehavior.java +++ b/src/main/java/gregtech/common/items/tool/PlungerBehavior.java @@ -32,9 +32,9 @@ public class PlungerBehavior implements IToolBehavior { protected PlungerBehavior() {/**/} @Override - public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, - @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { IFluidHandler fluidHandler = FluidUtil.getFluidHandler(world, pos, facing); if (fluidHandler == null) { return EnumActionResult.PASS; diff --git a/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java b/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java index cac327cd442..19985d1459e 100644 --- a/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java +++ b/src/main/java/gregtech/common/items/tool/RotateRailBehavior.java @@ -29,9 +29,9 @@ protected RotateRailBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUseFirst(@NotNull ItemStack stack, @NotNull EntityPlayer player, - @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { + public EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, + @NotNull EnumHand hand) { IBlockState state = world.getBlockState(pos); if (state.getBlock() instanceof BlockRailBase) { if (world.setBlockState(pos, state.withRotation(Rotation.CLOCKWISE_90))) { diff --git a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java index 2965a1ad56d..8edee2b537b 100644 --- a/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java +++ b/src/main/java/gregtech/common/items/tool/TorchPlaceBehavior.java @@ -37,10 +37,10 @@ protected TorchPlaceBehavior() {/**/} @NotNull @Override - public EnumActionResult onItemUse(@NotNull ItemStack stack, @NotNull EntityPlayer player, @NotNull World world, - @NotNull BlockPos pos, @NotNull EnumHand hand, @NotNull EnumFacing facing, - float hitX, float hitY, float hitZ) { - NBTTagCompound behaviourTag = ToolHelper.getBehaviorsTag(stack); + public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, + @NotNull EnumHand hand, @NotNull EnumFacing facing, float hitX, float hitY, + float hitZ) { + NBTTagCompound behaviourTag = ToolHelper.getBehaviorsTag(player.getHeldItem(hand)); if (behaviourTag.getBoolean(ToolHelper.TORCH_PLACING_KEY)) { int cachedTorchSlot; ItemStack slotStack; diff --git a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java index 5ce3cff1cb9..1e4a95df60b 100644 --- a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java +++ b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java @@ -29,6 +29,7 @@ import gregtech.common.blocks.MetaBlocks; import gregtech.common.gui.widget.craftingstation.CraftingSlotWidget; import gregtech.common.items.MetaItems; +import gregtech.common.items.ToolItems; import gregtech.common.metatileentities.MetaTileEntities; import gregtech.integration.IntegrationSubmodule; import gregtech.integration.jei.basic.GTFluidVeinCategory; @@ -84,6 +85,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static gregtech.api.unification.material.info.MaterialFlags.GENERATE_BOLT_SCREW; +import static gregtech.api.unification.material.info.MaterialFlags.GENERATE_RING; + @JEIPlugin @GregTechModule( moduleID = GregTechModules.MODULE_JEI, @@ -237,11 +241,19 @@ public void register(IModRegistry registry) { } List oreByproductList = new ArrayList<>(); + List materialTreeList = new ArrayList<>(); for (Material material : GregTechAPI.materialManager.getRegisteredMaterials()) { if (material.hasProperty(PropertyKey.ORE)) { oreByproductList.add(new OreByProduct(material)); } + if (material.hasProperty(PropertyKey.DUST)) { + materialTreeList.add(new MaterialTree(material)); + } + if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING)) { + registry.addIngredientInfo(ToolItems.TOOLBELT.get(material), VanillaTypes.ITEM, "item.gt.tool.toolbelt.tooltip", "item.gt.tool.toolbelt.paint", "item.gt.tool.toolbelt.dye", "item.gt.tool.toolbelt.maintenance"); + } } + String oreByProductId = GTValues.MODID + ":" + "ore_by_product"; registry.addRecipes(oreByproductList, oreByProductId); MetaTileEntity[][] machineLists = { @@ -259,12 +271,6 @@ public void register(IModRegistry registry) { } // Material Tree - List materialTreeList = new ArrayList<>(); - for (Material material : GregTechAPI.materialManager.getRegisteredMaterials()) { - if (material.hasProperty(PropertyKey.DUST)) { - materialTreeList.add(new MaterialTree(material)); - } - } registry.addRecipes(materialTreeList, GTValues.MODID + ":" + "material_tree"); // Ore Veins diff --git a/src/main/resources/assets/gregtech/lang/en_us.lang b/src/main/resources/assets/gregtech/lang/en_us.lang index 5e27ffbbb98..ea8f15425cc 100644 --- a/src/main/resources/assets/gregtech/lang/en_us.lang +++ b/src/main/resources/assets/gregtech/lang/en_us.lang @@ -1046,7 +1046,7 @@ item.gt.tool.toolbelt.name=%s Toolbelt%s item.gt.tool.toolbelt.size=§a%s Tool Slots item.gt.tool.toolbelt.tooltip=Holds GT or vanilla-esque tools that can be manually selected for in-world use, automatically selected for crafting, or stored for maintenance repair. item.gt.tool.toolbelt.paint=Also supports Spray Cans. -item.gt.tool.toolbelt.dye=Can be dyed like leather equipment. +item.gt.tool.toolbelt.dye=Can be dyed like leather equipment, and the dye can be removed via water cauldron, also like leather equipment. item.gt.tool.toolbelt.maintenance=Repairs maintenance problems with only inserted tools upon interacting with a maintenance hatch in-world. item.gt.tool.toolbelt.tool=§aSlot %s: §f%s item.gt.tool.toolbelt.selected=- §aSlot %s: §f%s From 531f8688820a6c415b83a626603b2fb4c012eee9 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Mon, 25 Nov 2024 17:52:35 -0700 Subject: [PATCH 70/82] spotless --- src/main/java/gregtech/common/items/ToolItems.java | 3 --- .../java/gregtech/integration/jei/JustEnoughItemsModule.java | 4 +++- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 524056915f5..561cd094a74 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -8,8 +8,6 @@ import gregtech.common.items.tool.*; import gregtech.core.sound.GTSoundEvents; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; - import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.enchantment.EnumEnchantmentType; @@ -23,7 +21,6 @@ import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; diff --git a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java index 1e4a95df60b..bcdc2fbc3ad 100644 --- a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java +++ b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java @@ -250,7 +250,9 @@ public void register(IModRegistry registry) { materialTreeList.add(new MaterialTree(material)); } if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING)) { - registry.addIngredientInfo(ToolItems.TOOLBELT.get(material), VanillaTypes.ITEM, "item.gt.tool.toolbelt.tooltip", "item.gt.tool.toolbelt.paint", "item.gt.tool.toolbelt.dye", "item.gt.tool.toolbelt.maintenance"); + registry.addIngredientInfo(ToolItems.TOOLBELT.get(material), VanillaTypes.ITEM, + "item.gt.tool.toolbelt.tooltip", "item.gt.tool.toolbelt.paint", "item.gt.tool.toolbelt.dye", + "item.gt.tool.toolbelt.maintenance"); } } From f46d4d6d910154a74a5c25e1b6790d93e2b5c5d1 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:22:22 -0700 Subject: [PATCH 71/82] mixin to relocate tool highlight text --- .../mixins/forge/GuiIngameForgeMixin.java | 31 +++++++++++++++++++ src/main/resources/mixins.gregtech.forge.json | 1 + 2 files changed, 32 insertions(+) create mode 100644 src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java diff --git a/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java new file mode 100644 index 00000000000..b7dac3bb0d1 --- /dev/null +++ b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java @@ -0,0 +1,31 @@ +package gregtech.mixins.forge; + +import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.common.ConfigHolder; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiIngame; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraftforge.client.GuiIngameForge; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(GuiIngameForge.class) +public class GuiIngameForgeMixin extends GuiIngame { + + private GuiIngameForgeMixin(Minecraft mcIn) { + super(mcIn); + } + + @Redirect(method = "renderToolHighlight", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/gui/ScaledResolution;getScaledHeight()I")) + private int shiftToolHighlightText(ScaledResolution res) { + if (ConfigHolder.client.toolbeltConfig.enableToolbeltHotbarDisplay && + highlightingItemStack.getItem() instanceof ItemGTToolbelt) + return res.getScaledHeight() - 31 + 6; + else return res.getScaledHeight(); + } +} diff --git a/src/main/resources/mixins.gregtech.forge.json b/src/main/resources/mixins.gregtech.forge.json index 57f68b178ac..61138099624 100644 --- a/src/main/resources/mixins.gregtech.forge.json +++ b/src/main/resources/mixins.gregtech.forge.json @@ -5,6 +5,7 @@ "minVersion": "0.8", "compatibilityLevel": "JAVA_8", "mixins": [ + "GuiIngameForgeMixin", "ModelLoaderRegistryMixin", "OreIngredientMixin", "SpecialArmorPropertiesMixin" From b1d9262557969a20960fb5066344ea3193a9761d Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Tue, 26 Nov 2024 17:18:47 -0700 Subject: [PATCH 72/82] WrapOperation-ify --- .../integration/jei/JustEnoughItemsModule.java | 3 ++- .../mixins/forge/GuiIngameForgeMixin.java | 15 ++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java index bcdc2fbc3ad..5a182dbadde 100644 --- a/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java +++ b/src/main/java/gregtech/integration/jei/JustEnoughItemsModule.java @@ -249,7 +249,8 @@ public void register(IModRegistry registry) { if (material.hasProperty(PropertyKey.DUST)) { materialTreeList.add(new MaterialTree(material)); } - if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING)) { + if (material.hasFlag(GENERATE_BOLT_SCREW) && material.hasFlag(GENERATE_RING) && + material.hasProperty(PropertyKey.TOOL)) { registry.addIngredientInfo(ToolItems.TOOLBELT.get(material), VanillaTypes.ITEM, "item.gt.tool.toolbelt.tooltip", "item.gt.tool.toolbelt.paint", "item.gt.tool.toolbelt.dye", "item.gt.tool.toolbelt.maintenance"); diff --git a/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java index b7dac3bb0d1..5d31f07f152 100644 --- a/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java +++ b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java @@ -8,9 +8,10 @@ import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.client.GuiIngameForge; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(GuiIngameForge.class) public class GuiIngameForgeMixin extends GuiIngame { @@ -19,13 +20,13 @@ private GuiIngameForgeMixin(Minecraft mcIn) { super(mcIn); } - @Redirect(method = "renderToolHighlight", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/gui/ScaledResolution;getScaledHeight()I")) - private int shiftToolHighlightText(ScaledResolution res) { + @WrapOperation(method = "renderToolHighlight", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/gui/ScaledResolution;getScaledHeight()I")) + private int shiftToolHighlightText(ScaledResolution resolution, Operation op) { if (ConfigHolder.client.toolbeltConfig.enableToolbeltHotbarDisplay && highlightingItemStack.getItem() instanceof ItemGTToolbelt) - return res.getScaledHeight() - 31 + 6; - else return res.getScaledHeight(); + return op.call(resolution) - 31 + 6; + else return op.call(resolution); } } From a1ae9d2b2fb688f7425cafbe0ef38eb16ca8b4da Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Tue, 26 Nov 2024 22:08:07 -0700 Subject: [PATCH 73/82] address review --- .../gregtech/api/items/toolitem/IGTTool.java | 49 ++++++++----------- .../api/items/toolitem/ItemGTHoe.java | 2 +- .../api/items/toolitem/ItemGTToolbelt.java | 15 ++++-- .../mixins/forge/GuiIngameForgeMixin.java | 16 +++--- 4 files changed, 39 insertions(+), 43 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index 550599b473d..f9acab239f5 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -218,7 +218,7 @@ default ItemStack get(Material material) { // Set behaviours NBTTagCompound behaviourTag = getBehaviorsTag(stack); - getToolStats().getBehaviors().forEach(behavior -> behavior.addBehaviorNBT(stack, behaviourTag)); + getBehaviors(stack).forEach(behavior -> behavior.addBehaviorNBT(stack, behaviourTag)); if (aoeDefinition != AoESymmetrical.none()) { behaviourTag.setInteger(MAX_AOE_COLUMN_KEY, aoeDefinition.column); @@ -420,14 +420,14 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } default boolean definition$hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { - getToolStats().getBehaviors().forEach(behavior -> behavior.hitEntity(stack, target, attacker)); + getBehaviors(stack).forEach(behavior -> behavior.hitEntity(stack, target, attacker)); damageItem(stack, attacker, getToolStats().getToolDamagePerAttack(stack)); return true; } default boolean definition$onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) { if (player.world.isRemote) return false; - getToolStats().getBehaviors().forEach(behavior -> behavior.onBlockStartBreak(stack, pos, player)); + getBehaviors(stack).forEach(behavior -> behavior.onBlockStartBreak(stack, pos, player)); if (!player.isSneaking()) { EntityPlayerMP playerMP = (EntityPlayerMP) player; @@ -469,7 +469,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default boolean definition$onBlockDestroyed(ItemStack stack, World worldIn, IBlockState state, BlockPos pos, EntityLivingBase entityLiving) { if (!worldIn.isRemote) { - getToolStats().getBehaviors() + getBehaviors(stack) .forEach(behavior -> behavior.onBlockDestroyed(stack, worldIn, state, pos, entityLiving)); if ((double) state.getBlockHardness(worldIn, pos) != 0.0D) { @@ -533,7 +533,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default boolean definition$canDisableShield(ItemStack stack, ItemStack shield, EntityLivingBase entity, EntityLivingBase attacker) { - return getToolStats().getBehaviors().stream() + return getBehaviors(stack).stream() .anyMatch(behavior -> behavior.canDisableShield(stack, shield, entity, attacker)); } @@ -581,7 +581,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { } default boolean definition$onEntitySwing(EntityLivingBase entityLiving, ItemStack stack) { - getToolStats().getBehaviors().forEach(behavior -> behavior.onEntitySwing(entityLiving, stack)); + getBehaviors(stack).forEach(behavior -> behavior.onEntitySwing(entityLiving, stack)); return false; } @@ -633,7 +633,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { if (isElectric()) { providers.add(ElectricStats.createElectricItem(0L, getElectricTier()).createProvider(stack)); } - for (IToolBehavior behavior : getToolStats().getBehaviors()) { + for (IToolBehavior behavior : getBehaviors(stack)) { ICapabilityProvider behaviorProvider = behavior.createProvider(stack, nbt); if (behaviorProvider != null) { providers.add(behaviorProvider); @@ -644,14 +644,15 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { return new CombinedCapabilityProvider(providers); } + @NotNull + default List getBehaviors(ItemStack stack) { + return getToolStats().getBehaviors(); + } + default EnumActionResult definition$onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, @NotNull BlockPos pos, @NotNull EnumFacing facing, float hitX, float hitY, float hitZ, @NotNull EnumHand hand) { - ItemStack stack = toolbeltPassthrough(player.getHeldItem(hand)); - List behaviors; - if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); - else return EnumActionResult.PASS; - for (IToolBehavior behavior : behaviors) { + for (IToolBehavior behavior : getBehaviors(player.getHeldItem(hand))) { if (behavior.onItemUseFirst(player, world, pos, facing, hitX, hitY, hitZ, hand) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -663,12 +664,7 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default EnumActionResult definition$onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { - ItemStack stack = toolbeltPassthrough(player.getHeldItem(hand)); - List behaviors; - if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); - else return EnumActionResult.PASS; - - for (IToolBehavior behavior : behaviors) { + for (IToolBehavior behavior : getBehaviors(player.getHeldItem(hand))) { if (behavior.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ) == EnumActionResult.SUCCESS) { return EnumActionResult.SUCCESS; @@ -680,25 +676,20 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { default ActionResult definition$onItemRightClick(World world, EntityPlayer player, EnumHand hand) { ItemStack stack = player.getHeldItem(hand); - ItemStack original = stack; - stack = toolbeltPassthrough(stack); if (!world.isRemote) { // TODO: relocate to keybind action when keybind PR happens if (player.isSneaking() && getMaxAoEDefinition(stack) != AoESymmetrical.none()) { ItemGuiFactory.open((EntityPlayerMP) player, hand); - return ActionResult.newResult(EnumActionResult.SUCCESS, original); + return ActionResult.newResult(EnumActionResult.SUCCESS, stack); } } - List behaviors; - if (stack.getItem() instanceof IGTTool tool) behaviors = tool.getToolStats().getBehaviors(); - else return ActionResult.newResult(EnumActionResult.PASS, original); - for (IToolBehavior behavior : behaviors) { + for (IToolBehavior behavior : getBehaviors(stack)) { if (behavior.onItemRightClick(world, player, hand).getType() == EnumActionResult.SUCCESS) { - return ActionResult.newResult(EnumActionResult.SUCCESS, original); + return ActionResult.newResult(EnumActionResult.SUCCESS, stack); } } - return ActionResult.newResult(EnumActionResult.PASS, original); + return ActionResult.newResult(EnumActionResult.PASS, stack); } default void definition$getSubItems(@NotNull NonNullList items) { @@ -788,10 +779,10 @@ default AoESymmetrical getAoEDefinition(ItemStack stack) { tooltip.add(I18n.format("item.gt.tool.behavior.relocate_mining")); } - if (!addedBehaviorNewLine && !toolStats.getBehaviors().isEmpty()) { + if (!addedBehaviorNewLine && !getBehaviors(stack).isEmpty()) { tooltip.add(""); } - toolStats.getBehaviors().forEach(behavior -> behavior.addInformation(stack, world, tooltip, flag)); + getBehaviors(stack).forEach(behavior -> behavior.addInformation(stack, world, tooltip, flag)); // unique tooltip String uniqueTooltip = "item.gt.tool." + getToolId() + ".tooltip"; diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java b/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java index 13e14e8e574..1dd69871cb4 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTHoe.java @@ -314,7 +314,7 @@ public EnumActionResult onItemUse(@NotNull EntityPlayer player, @NotNull World w @Override public boolean hitEntity(@NotNull ItemStack stack, @NotNull EntityLivingBase target, @NotNull EntityLivingBase attacker) { - getToolStats().getBehaviors().forEach(behavior -> behavior.hitEntity(stack, target, attacker)); + getBehaviors(stack).forEach(behavior -> behavior.hitEntity(stack, target, attacker)); // damage by 1, as this is what vanilla does ToolHelper.damageItem(stack, attacker, 1); return true; diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 70547e6eaf4..2e59f5dc440 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -63,6 +63,7 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -91,8 +92,6 @@ public int getSlotCount(@NotNull ItemStack toolbelt) { return getHandler(toolbelt).getSlots(); } - // nullable to differentiate between "no tool selected" and "no tool in selected slot" which is theoretically - // possible public @NotNull ItemStack getSelectedTool(@NotNull ItemStack toolbelt) { return getHandler(toolbelt).getSelectedStack(); } @@ -141,6 +140,15 @@ public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager .bindPlayerInventory(); } + @Override + public @NotNull List getBehaviors(ItemStack stack) { + ItemStack selected = getHandler(stack).getSelectedStack(); + if (selected.isEmpty()) return super.getBehaviors(stack); + else if (selected.getItem() instanceof IGTTool tool) { + return tool.getBehaviors(selected); + } else return Collections.emptyList(); + } + public static boolean isToolbeltableOredict(String oredict) { return VALID_OREDICTS.contains(oredict); } @@ -378,8 +386,7 @@ public boolean hasContainerItem(@NotNull ItemStack stack) { @Override public @NotNull ItemStack getContainerItem(@NotNull ItemStack stack) { if (getHandler(stack).dealCraftDamageToSelected()) { - stack = stack.copy(); - return stack; + return stack.copy(); } return super.getContainerItem(stack); } diff --git a/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java index 5d31f07f152..b34c7b1d416 100644 --- a/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java +++ b/src/main/java/gregtech/mixins/forge/GuiIngameForgeMixin.java @@ -5,11 +5,9 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiIngame; -import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.client.GuiIngameForge; -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -20,13 +18,13 @@ private GuiIngameForgeMixin(Minecraft mcIn) { super(mcIn); } - @WrapOperation(method = "renderToolHighlight", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/gui/ScaledResolution;getScaledHeight()I")) - private int shiftToolHighlightText(ScaledResolution resolution, Operation op) { + @ModifyExpressionValue(method = "renderToolHighlight", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/gui/ScaledResolution;getScaledHeight()I")) + private int shiftToolHighlightText(int y) { if (ConfigHolder.client.toolbeltConfig.enableToolbeltHotbarDisplay && highlightingItemStack.getItem() instanceof ItemGTToolbelt) - return op.call(resolution) - 31 + 6; - else return op.call(resolution); + return y - 31 + 6; + else return y; } } From 2fd02a46483826e69fbc96a79a6390d9168bec48 Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Fri, 29 Nov 2024 16:14:51 -0700 Subject: [PATCH 74/82] fix my side of reviews --- src/main/java/gregtech/api/items/toolitem/IGTTool.java | 8 ++------ .../gregtech/api/items/toolitem/aoe/AoESymmetrical.java | 4 ++-- src/main/java/gregtech/api/mui/GTGuiTextures.java | 5 +++++ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index f9acab239f5..b1920e3b492 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -60,7 +60,6 @@ import appeng.api.implementations.items.IAEWrench; import buildcraft.api.tools.IToolWrench; import cofh.api.item.IToolHammer; -import com.cleanroommc.modularui.api.drawable.IDrawable; import com.cleanroommc.modularui.api.drawable.IKey; import com.cleanroommc.modularui.api.widget.IWidget; import com.cleanroommc.modularui.api.widget.Interactable; @@ -921,9 +920,6 @@ default void playSound(EntityPlayer player) { } } - IDrawable PLUS = IKey.str("+").asIcon().marginLeft(1); - IDrawable MINUS = IKey.str("-").asIcon().marginLeft(1); - @Override default ModularPanel buildUI(HandGuiData guiData, PanelSyncManager manager) { final var usedStack = guiData.getUsedItemStack(); @@ -963,7 +959,7 @@ default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldD IWidget increaseButton = new ButtonWidget<>() .size(9, 18) .background(GTGuiTextures.MC_BUTTON) - .overlay(PLUS) + .overlay(GTGuiTextures.PLUS) .disableHoverBackground() .onMousePressed(data -> { syncValue.setIntValue(syncValue.getIntValue() + 1, true, true); @@ -974,7 +970,7 @@ default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldD IWidget decreaseButton = new ButtonWidget<>() .size(9, 18) .background(GTGuiTextures.MC_BUTTON) - .overlay(MINUS) + .overlay(GTGuiTextures.MINUS) .disableHoverBackground() .onMousePressed(data -> { syncValue.setIntValue(syncValue.getIntValue() - 1, true, true); diff --git a/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java b/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java index 48a8a0b2b37..8f3276f6212 100644 --- a/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java +++ b/src/main/java/gregtech/api/items/toolitem/aoe/AoESymmetrical.java @@ -108,12 +108,12 @@ public static void decreaseColumn(NBTTagCompound tag, AoESymmetrical defaultDefi public static void decreaseRow(NBTTagCompound tag, AoESymmetrical defaultDefinition) { int currentRow = getRow(tag, defaultDefinition); - setRow(tag, currentRow + 1, defaultDefinition); + setRow(tag, currentRow - 1, defaultDefinition); } public static void decreaseLayer(NBTTagCompound tag, AoESymmetrical defaultDefinition) { int currentLayer = getLayer(tag, defaultDefinition); - setLayer(tag, currentLayer + 1, defaultDefinition); + setLayer(tag, currentLayer - 1, defaultDefinition); } public static AoESymmetrical none() { diff --git a/src/main/java/gregtech/api/mui/GTGuiTextures.java b/src/main/java/gregtech/api/mui/GTGuiTextures.java index 8a1b26c2a07..e2abb861c4b 100644 --- a/src/main/java/gregtech/api/mui/GTGuiTextures.java +++ b/src/main/java/gregtech/api/mui/GTGuiTextures.java @@ -2,6 +2,8 @@ import gregtech.api.GTValues; +import com.cleanroommc.modularui.api.drawable.IDrawable; +import com.cleanroommc.modularui.api.drawable.IKey; import com.cleanroommc.modularui.drawable.UITexture; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -176,6 +178,9 @@ public static class IDs { public static final UITexture OREDICT_WAITING = fullImage("textures/gui/widget/ore_filter/waiting.png"); public static final UITexture OREDICT_WARN = fullImage("textures/gui/widget/ore_filter/warn.png"); + public static final IDrawable PLUS = IKey.str("+").asIcon().marginLeft(1); + public static final IDrawable MINUS = IKey.str("-").asIcon().marginLeft(1); + public static final UITexture[] MANUAL_IO_OVERLAY_IN = slice("textures/gui/overlay/manual_io_overlay_in.png", 18, 18 * 3, 18, 18, true); public static final UITexture[] MANUAL_IO_OVERLAY_OUT = slice("textures/gui/overlay/manual_io_overlay_out.png", From c37e0c70e5c7e93f41f1812aed89b9304a21f0ab Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Fri, 29 Nov 2024 16:31:07 -0700 Subject: [PATCH 75/82] fix aoe size flickering --- .../java/gregtech/api/items/toolitem/IGTTool.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/IGTTool.java b/src/main/java/gregtech/api/items/toolitem/IGTTool.java index b1920e3b492..3701560d080 100644 --- a/src/main/java/gregtech/api/items/toolitem/IGTTool.java +++ b/src/main/java/gregtech/api/items/toolitem/IGTTool.java @@ -947,12 +947,12 @@ default ModularPanel buildUI(HandGuiData guiData, PanelSyncManager manager) { .alignY(0.5f) .coverChildrenHeight() .mainAxisAlignment(Alignment.MainAxis.SPACE_BETWEEN) - .child(createColumn(columnValue, "columns", true)) - .child(createColumn(rowValue, "rows", true)) - .child(createColumn(layerValue, "layers", false))); + .child(createColumn(columnValue, "columns", true, defaultDefinition.column)) + .child(createColumn(rowValue, "rows", true, defaultDefinition.row)) + .child(createColumn(layerValue, "layers", false, defaultDefinition.layer))); } - default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldDouble) { + default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldDouble, int max) { final var display = IKey.dynamic( () -> String.valueOf(1 + (shouldDouble ? 2 * syncValue.getIntValue() : syncValue.getIntValue()))); @@ -962,7 +962,8 @@ default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldD .overlay(GTGuiTextures.PLUS) .disableHoverBackground() .onMousePressed(data -> { - syncValue.setIntValue(syncValue.getIntValue() + 1, true, true); + int val = syncValue.getIntValue(); + if (val < max) syncValue.setIntValue(++val); Interactable.playButtonClickSound(); return true; }); @@ -973,7 +974,8 @@ default Column createColumn(IntSyncValue syncValue, String lang, boolean shouldD .overlay(GTGuiTextures.MINUS) .disableHoverBackground() .onMousePressed(data -> { - syncValue.setIntValue(syncValue.getIntValue() - 1, true, true); + int val = syncValue.getIntValue(); + if (val > 0) syncValue.setIntValue(--val); Interactable.playButtonClickSound(); return true; }); From 33bd4f8f5df8d1f1d94ff6ddb138fddad417e0a2 Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Fri, 29 Nov 2024 17:06:45 -0700 Subject: [PATCH 76/82] add ui title --- .../java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 2e59f5dc440..6b1a6f25d72 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -47,6 +47,7 @@ import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreIngredient; +import com.cleanroommc.modularui.api.drawable.IKey; import com.cleanroommc.modularui.factory.HandGuiData; import com.cleanroommc.modularui.screen.ModularPanel; import com.cleanroommc.modularui.value.sync.PanelSyncManager; @@ -122,11 +123,14 @@ public ModularPanel buildUI(HandGuiData guiData, PanelSyncManager guiSyncManager slots.add(new ItemSlot()); } - return GTGuis.createPanel(usedStack.getTranslationKey(), 176, 120 + heightBonus) + return GTGuis.createPanel(usedStack.getTranslationKey(), 176, 120 + heightBonus + 12) + .child(IKey.str(usedStack.getDisplayName()).asWidget() + .pos(5, 5) + .height(12)) .child(new Grid() .margin(0) .leftRel(0.5f) - .top(7) + .top(7 + 12) .coverChildren() .mapTo(group.getRowSize(), slots, (index, value) -> value .slot(SyncHandlers.itemSlot(handler, index) From 65b9ff8cfa8497ea8ba33679c390666300e6b030 Mon Sep 17 00:00:00 2001 From: M-W-K <31022105+M-W-K@users.noreply.github.com> Date: Fri, 29 Nov 2024 17:38:46 -0700 Subject: [PATCH 77/82] address review --- .../java/gregtech/api/items/IDyeableItem.java | 14 ++++--- .../api/items/toolitem/ItemGTToolbelt.java | 41 ++++++------------- .../java/gregtech/client/ClientProxy.java | 2 + .../common/crafting/DyeableRecipes.java | 2 + .../common/crafting/GTShapedOreRecipe.java | 2 +- .../common/crafting/GTShapelessOreRecipe.java | 3 +- .../java/gregtech/common/items/ToolItems.java | 2 - 7 files changed, 26 insertions(+), 40 deletions(-) diff --git a/src/main/java/gregtech/api/items/IDyeableItem.java b/src/main/java/gregtech/api/items/IDyeableItem.java index 6fc5aac04ed..fe5625480e8 100644 --- a/src/main/java/gregtech/api/items/IDyeableItem.java +++ b/src/main/java/gregtech/api/items/IDyeableItem.java @@ -16,15 +16,17 @@ public interface IDyeableItem { + String COLOR_KEY = "gt_color"; + default boolean hasColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - return nbttagcompound != null && nbttagcompound.hasKey("color", Constants.NBT.TAG_INT); + return nbttagcompound != null && nbttagcompound.hasKey(COLOR_KEY, Constants.NBT.TAG_INT); } default int getColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - if (nbttagcompound != null && nbttagcompound.hasKey("color", Constants.NBT.TAG_INT)) { - return nbttagcompound.getInteger("color"); + if (nbttagcompound != null && nbttagcompound.hasKey(COLOR_KEY, Constants.NBT.TAG_INT)) { + return nbttagcompound.getInteger(COLOR_KEY); } return getDefaultColor(stack); } @@ -35,8 +37,8 @@ default int getDefaultColor(ItemStack stack) { default void removeColor(ItemStack stack) { NBTTagCompound nbttagcompound = stack.getTagCompound(); - if (nbttagcompound != null && nbttagcompound.hasKey("color")) { - nbttagcompound.removeTag("color"); + if (nbttagcompound != null && nbttagcompound.hasKey(COLOR_KEY)) { + nbttagcompound.removeTag(COLOR_KEY); } } @@ -46,7 +48,7 @@ default void setColor(ItemStack stack, int color) { nbttagcompound = new NBTTagCompound(); stack.setTagCompound(nbttagcompound); } - nbttagcompound.setInteger("color", color); + nbttagcompound.setInteger(COLOR_KEY, color); } default @NotNull EnumActionResult onItemUseFirst(@NotNull EntityPlayer player, @NotNull World world, diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 6b1a6f25d72..f44065b5a61 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -58,16 +58,15 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Range; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; -import java.util.Objects; import java.util.Set; import java.util.function.IntSupplier; import java.util.function.Supplier; @@ -76,8 +75,6 @@ public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { - protected final static Set VALID_OREDICTS = new ObjectOpenHashSet<>(); - public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), @@ -153,14 +150,6 @@ else if (selected.getItem() instanceof IGTTool tool) { } else return Collections.emptyList(); } - public static boolean isToolbeltableOredict(String oredict) { - return VALID_OREDICTS.contains(oredict); - } - - public void registerValidOredict(String oredict) { - VALID_OREDICTS.add(oredict); - } - @Override public float getDestroySpeed(@NotNull ItemStack stack, @NotNull IBlockState state) { ItemStack selected = getHandler(stack).getSelectedStack(); @@ -220,7 +209,7 @@ public int getHarvestLevel(@NotNull ItemStack stack, @NotNull String toolClass, ItemStack selected = getHandler(stack).getSelectedStack(); if (!selected.isEmpty()) { return selected.getItem().getHarvestLevel(stack, toolClass, player, blockState); - } else return super.getHarvestLevel(stack, toolClass, player, blockState); + } else return definition$getHarvestLevel(stack, toolClass, player, blockState); } @NotNull @@ -283,7 +272,7 @@ public int getDamage(@NotNull ItemStack stack) { ItemStack selected = getHandler(stack).getSelectedStack(); if (!selected.isEmpty()) { return selected.getItem().getDamage(selected); - } else return super.getDamage(stack); + } else return definition$getDamage(stack); } @Override @@ -299,7 +288,7 @@ public void setDamage(@NotNull ItemStack stack, int damage) { ItemStack selected = getHandler(stack).getSelectedStack(); if (!selected.isEmpty()) { selected.getItem().setDamage(selected, damage); - } else super.setDamage(stack, damage); + } else definition$setDamage(stack, damage); } @Override @@ -442,6 +431,10 @@ public void changeSelectedToolHotkey(int slot, ItemStack stack) { new PacketToolbeltSelectionChange(handler.selectedSlot)); } + /** + * For use by {@link PacketToolbeltSelectionChange} only! + */ + @ApiStatus.Internal public void setSelectedTool(int slot, ItemStack stack) { ToolStackHandler handler = getHandler(stack); if (slot < 0 || slot >= handler.getSlots()) @@ -471,7 +464,8 @@ public void setSelectedTool(int slot, ItemStack stack) { if (result == EnumActionResult.PASS) { ItemStack stack = player.getHeldItem(hand); ToolStackHandler handler = getHandler(stack); - if (handler.getSelectedSlot() == -1 && world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && + if (handler.getSelectedStack().isEmpty() && + world.getTileEntity(pos) instanceof MetaTileEntityHolder holder && holder.getMetaTileEntity() instanceof MetaTileEntityMaintenanceHatch maintenance) { maintenance.fixMaintenanceProblemsWithToolbelt(player, this, stack); return EnumActionResult.SUCCESS; @@ -573,10 +567,8 @@ public NBTTagCompound serializeNBT() { @Override public void deserializeNBT(NBTTagCompound nbt) { - // make sure we can load all the slots, no matter what we're supposed to be limited to. - int minsize = nbt.hasKey("Size") ? nbt.getInteger("Size") : 0; // .copy() prevents double damage ticks in singleplayer - this.getHandler(minsize).deserializeNBT(nbt.copy()); + this.getHandler(slotCountSupplier.getAsInt()).deserializeNBT(nbt.copy()); } protected ToolStackHandler getHandler(int minsize) { @@ -611,7 +603,6 @@ protected static class ToolStackHandler extends ItemStackHandler { protected final ItemTool[] tools = new ItemTool[this.getSlots()]; protected final IGTTool[] gtTools = new IGTTool[this.getSlots()]; protected final Set toolClasses = new ObjectOpenHashSet<>(); - public final Set oreDicts = new ObjectOpenHashSet<>(); private boolean passthrough = true; @@ -646,7 +637,7 @@ public void disablePassthrough() { public @NotNull ItemStack getSelectedStack() { if (getSelectedSlot() == -1) return ItemStack.EMPTY; - else return this.stacks.get(getSelectedSlot()); + else return this.getStackInSlot(getSelectedSlot()); } public Set getToolClasses(boolean defaultEmpty) { @@ -715,14 +706,6 @@ protected void updateSlot(int slot) { } protected void update() { - this.oreDicts.clear(); - Arrays.stream(gtTools).filter(Objects::nonNull).map(igtTool -> { - Set set = new ObjectOpenHashSet<>(igtTool.getSecondaryOreDicts()); - set.add(igtTool.getOreDictName()); - return set; - }).forEach(this.oreDicts::addAll); - this.oreDicts.retainAll(VALID_OREDICTS); - this.toolClasses.clear(); for (int i = 0; i < this.getSlots(); i++) { if (tools[i] != null) this.toolClasses.addAll(tools[i].getToolClasses(stacks.get(i))); diff --git a/src/main/java/gregtech/client/ClientProxy.java b/src/main/java/gregtech/client/ClientProxy.java index a0fec925635..03783021f60 100644 --- a/src/main/java/gregtech/client/ClientProxy.java +++ b/src/main/java/gregtech/client/ClientProxy.java @@ -354,6 +354,8 @@ public static void onMouseEvent(@NotNull MouseEvent event) { if (event.getDwheel() != 0 && player.isSneaking()) { ItemStack stack = player.getHeldItemMainhand(); if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + // vanilla code in GuiIngame line 1235 does not copy the stack before storing it in the highlighting + // item stack, so unless we copy the stack the tool highlight will not refresh. stack = stack.copy(); toolbelt.changeSelectedToolMousewheel(event.getDwheel(), stack); InventoryPlayer inv = Minecraft.getMinecraft().player.inventory; diff --git a/src/main/java/gregtech/common/crafting/DyeableRecipes.java b/src/main/java/gregtech/common/crafting/DyeableRecipes.java index bcc9eabb183..fa975fd4197 100644 --- a/src/main/java/gregtech/common/crafting/DyeableRecipes.java +++ b/src/main/java/gregtech/common/crafting/DyeableRecipes.java @@ -120,6 +120,8 @@ public boolean matches(InventoryCrafting inv, @NotNull World worldIn) { k1 = (int) ((float) k1 * f3 / f4); int k2 = (i1 << 8) + j1; k2 = (k2 << 8) + k1; + // prevent consuming dye when the color would not change + if (dyeable.hasColor(itemstack) && dyeable.getColor(itemstack) == k2) return ItemStack.EMPTY; dyeable.setColor(itemstack, k2); return itemstack; } diff --git a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java index 24940f8dae0..fce807d0f04 100644 --- a/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapedOreRecipe.java @@ -166,7 +166,7 @@ else if (obj instanceof String str) { if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return net.minecraftforge.common.ForgeHooks.defaultRecipeGetRemainingItems(inv); + return super.getRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java index bc062c7c15b..c2f92e47c41 100644 --- a/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java +++ b/src/main/java/gregtech/common/crafting/GTShapelessOreRecipe.java @@ -5,7 +5,6 @@ import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.oredict.ShapelessOreRecipe; import org.jetbrains.annotations.NotNull; @@ -39,7 +38,7 @@ public GTShapelessOreRecipe(boolean isClearing, ResourceLocation group, @NotNull if (isClearing) { return NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); } else { - return ForgeHooks.defaultRecipeGetRemainingItems(inv); + return super.getRemainingItems(inv); } } } diff --git a/src/main/java/gregtech/common/items/ToolItems.java b/src/main/java/gregtech/common/items/ToolItems.java index 561cd094a74..a7003d8f4c3 100644 --- a/src/main/java/gregtech/common/items/ToolItems.java +++ b/src/main/java/gregtech/common/items/ToolItems.java @@ -393,11 +393,9 @@ public static void registerOreDict() { final ItemStack stack = new ItemStack(tool.get(), 1, GTValues.W); if (tool.getOreDictName() != null) { OreDictUnifier.registerOre(stack, tool.getOreDictName()); - TOOLBELT.registerValidOredict(tool.getOreDictName()); } tool.getSecondaryOreDicts().forEach(oreDict -> { OreDictUnifier.registerOre(stack, oreDict); - TOOLBELT.registerValidOredict(oreDict); }); }); } From 6e4f40a4e86695235a569789fb93953d089cebc0 Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Fri, 29 Nov 2024 18:55:30 -0700 Subject: [PATCH 78/82] i hate this, but it works --- .../api/items/toolitem/ItemGTToolbelt.java | 20 +++-- src/main/java/gregtech/core/CoreModule.java | 3 +- .../PacketToolbeltSelectionChange.java | 79 ++++++++++++++++--- .../mixins/minecraft/NetworkHandlerMixin.java | 41 ++++++++++ .../resources/mixins.gregtech.minecraft.json | 1 + 5 files changed, 125 insertions(+), 19 deletions(-) create mode 100644 src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index f44065b5a61..a01c2cc775b 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -24,6 +24,7 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -37,6 +38,7 @@ import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; @@ -75,6 +77,8 @@ public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { + private static final ThreadLocal slotThread = new ThreadLocal<>(); + public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { super(domain, id, -1, new ToolDefinitionBuilder().behaviors(behaviors).cannotAttack().attackSpeed(-2.4F).build(), @@ -388,6 +392,8 @@ public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { int match = getHandler(stack).checkIngredientAgainstTools(ingredient); if (match != -1) { setSelectedTool(match, stack); + PacketToolbeltSelectionChange.toClient(match, slotThread.get(), + (EntityPlayerMP) ForgeHooks.getCraftingPlayer()); } } @@ -418,8 +424,7 @@ public void changeSelectedToolMousewheel(int direction, ItemStack stack) { ToolStackHandler handler = getHandler(stack); if (direction < 0) handler.incrementSelectedSlot(); else handler.decrementSelectedSlot(); - GregTechAPI.networkHandler.sendToServer( - new PacketToolbeltSelectionChange(handler.selectedSlot)); + PacketToolbeltSelectionChange.toServer(handler.selectedSlot); } @SideOnly(Side.CLIENT) @@ -427,8 +432,7 @@ public void changeSelectedToolHotkey(int slot, ItemStack stack) { ToolStackHandler handler = getHandler(stack); if (slot < 0 || slot >= handler.getSlots()) handler.selectedSlot = -1; else handler.selectedSlot = slot; - GregTechAPI.networkHandler.sendToServer( - new PacketToolbeltSelectionChange(handler.selectedSlot)); + PacketToolbeltSelectionChange.toServer(handler.selectedSlot); } /** @@ -522,6 +526,10 @@ public static boolean checkIngredientAgainstToolbelt(@NotNull ItemStack input, @ return false; } + public static void setCraftingSlot(int slot) { + slotThread.set(slot); + } + public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @NotNull ItemStack tool) { if (toolbelt.getItem() instanceof ItemGTToolbelt belt && ToolHelper.isUtilityItem(tool)) { return belt.supportsTool(toolbelt, tool); @@ -685,7 +693,7 @@ public void deserializeNBT(NBTTagCompound nbt) { @Override protected void onLoad() { super.onLoad(); - for (int i = 0; i < this.getSlots(); i++) { + for (int i = 0; i < Math.min(tools.length, gtTools.length); i++) { this.updateSlot(i); } this.update(); @@ -707,7 +715,7 @@ protected void updateSlot(int slot) { protected void update() { this.toolClasses.clear(); - for (int i = 0; i < this.getSlots(); i++) { + for (int i = 0; i < Math.min(tools.length, gtTools.length); i++) { if (tools[i] != null) this.toolClasses.addAll(tools[i].getToolClasses(stacks.get(i))); } } diff --git a/src/main/java/gregtech/core/CoreModule.java b/src/main/java/gregtech/core/CoreModule.java index 9eb95fc6e9d..c964db8563f 100644 --- a/src/main/java/gregtech/core/CoreModule.java +++ b/src/main/java/gregtech/core/CoreModule.java @@ -246,7 +246,8 @@ public void registerPackets() { GregTechAPI.networkHandler.registerPacket(PacketNotifyCapeChange.class); GregTechAPI.networkHandler.registerPacket(PacketReloadShaders.class); GregTechAPI.networkHandler.registerPacket(PacketClipboardNBTUpdate.class); - GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.class); + GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.Server.class); + GregTechAPI.networkHandler.registerPacket(PacketToolbeltSelectionChange.Client.class); } @Override diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java index 7d7853e9271..369efbf04f3 100644 --- a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -1,20 +1,26 @@ package gregtech.core.network.packets; +import gregtech.api.GregTechAPI; import gregtech.api.items.toolitem.ItemGTToolbelt; +import gregtech.api.network.IClientExecutor; import gregtech.api.network.IPacket; import gregtech.api.network.IServerExecutor; import gregtech.core.sound.GTSoundEvents; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.EntityPlayerSP; +import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.PacketBuffer; import net.minecraft.util.SoundCategory; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; -public class PacketToolbeltSelectionChange implements IPacket, IServerExecutor { +public abstract class PacketToolbeltSelectionChange implements IPacket { - private int slot; + protected int slot; public PacketToolbeltSelectionChange() {} @@ -32,15 +38,64 @@ public void decode(PacketBuffer buf) { this.slot = buf.readByte(); } - @Override - public void executeServer(NetHandlerPlayServer handler) { - EntityPlayerMP player = handler.player; - ItemStack stack = player.getHeldItemMainhand(); - Item item = stack.getItem(); - if (item instanceof ItemGTToolbelt toolbelt) { - player.getServerWorld().playSound(null, player.posX, player.posY, player.posZ, GTSoundEvents.CLICK, - SoundCategory.PLAYERS, 2F, 1F); - toolbelt.setSelectedTool(slot, stack); + public static void toClient(int slot, int matrixSlot, EntityPlayerMP player) { + GregTechAPI.networkHandler.sendTo(new Client(slot, matrixSlot), player); + } + + public static void toServer(int slot) { + GregTechAPI.networkHandler.sendToServer(new Server(slot)); + } + + public static class Server extends PacketToolbeltSelectionChange implements IServerExecutor { + + public Server() {} + + public Server(int slot) { + super(slot); + } + + @Override + public void executeServer(NetHandlerPlayServer handler) { + EntityPlayerMP player = handler.player; + ItemStack stack = player.getHeldItemMainhand(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + player.getServerWorld().playSound(null, player.posX, player.posY, player.posZ, GTSoundEvents.CLICK, + SoundCategory.PLAYERS, 2F, 1F); + toolbelt.setSelectedTool(slot, stack); + } + } + } + + public static class Client extends PacketToolbeltSelectionChange implements IClientExecutor { + + int index; + + public Client() {} + + public Client(int slot, int index) { + super(slot); + this.index = index; + } + + @Override + public void encode(PacketBuffer buf) { + super.encode(buf); + buf.writeVarInt(index); + } + + @Override + public void decode(PacketBuffer buf) { + super.decode(buf); + this.index = buf.readVarInt(); + } + + @Override + @SideOnly(Side.CLIENT) + public void executeClient(NetHandlerPlayClient handler) { + EntityPlayerSP player = Minecraft.getMinecraft().player; + ItemStack stack = player.openContainer.getSlot(index).getStack(); + if (stack.getItem() instanceof ItemGTToolbelt toolbelt) + toolbelt.setSelectedTool(slot, stack); } } } diff --git a/src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java b/src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java new file mode 100644 index 00000000000..df472911ec7 --- /dev/null +++ b/src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java @@ -0,0 +1,41 @@ +package gregtech.mixins.minecraft; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Slot; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.play.client.CPacketClickWindow; +import net.minecraftforge.common.ForgeHooks; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(NetHandlerPlayServer.class) +public abstract class NetworkHandlerMixin { + + @Shadow + public EntityPlayerMP player; + + @Inject(method = "processClickWindow", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/inventory/Container;slotClick(IILnet/minecraft/inventory/ClickType;Lnet/minecraft/entity/player/EntityPlayer;)Lnet/minecraft/item/ItemStack;")) + private void setPlayer(CPacketClickWindow packetIn, CallbackInfo ci) { + ForgeHooks.setCraftingPlayer(this.player); + for (Slot slot : this.player.openContainer.inventorySlots) { + if (slot.getStack().getItem() instanceof ItemGTToolbelt) + ItemGTToolbelt.setCraftingSlot(slot.slotNumber); + } + } + + @Inject(method = "processClickWindow", + at = @At(value = "INVOKE_ASSIGN", + target = "Lnet/minecraft/inventory/Container;slotClick(IILnet/minecraft/inventory/ClickType;Lnet/minecraft/entity/player/EntityPlayer;)Lnet/minecraft/item/ItemStack;")) + private void clearPlayer(CPacketClickWindow packetIn, CallbackInfo ci) { + ForgeHooks.setCraftingPlayer(null); + ItemGTToolbelt.setCraftingSlot(-999); + } +} diff --git a/src/main/resources/mixins.gregtech.minecraft.json b/src/main/resources/mixins.gregtech.minecraft.json index 3c9abf97778..66868fd806f 100644 --- a/src/main/resources/mixins.gregtech.minecraft.json +++ b/src/main/resources/mixins.gregtech.minecraft.json @@ -9,6 +9,7 @@ }, "mixins": [ "BlockConcretePowderMixin", + "NetworkHandlerMixin", "DamageSourceMixin", "EnchantmentCanApplyMixin", "MinecraftMixin" From ee3d959731d820d749512ce74c560e4ce63de0ce Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Fri, 29 Nov 2024 21:22:43 -0700 Subject: [PATCH 79/82] resize arrays on load --- .../gregtech/api/items/toolitem/ItemGTToolbelt.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index a01c2cc775b..bfdf6deaa9f 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -608,14 +608,16 @@ protected static class ToolStackHandler extends ItemStackHandler { private @Range(from = -1, to = 128) int selectedSlot = -1; - protected final ItemTool[] tools = new ItemTool[this.getSlots()]; - protected final IGTTool[] gtTools = new IGTTool[this.getSlots()]; + protected ItemTool[] tools; + protected IGTTool[] gtTools; protected final Set toolClasses = new ObjectOpenHashSet<>(); private boolean passthrough = true; public ToolStackHandler(int size) { super(size); + tools = new ItemTool[size]; + gtTools = new IGTTool[size]; } public void incrementSelectedSlot() { @@ -692,8 +694,9 @@ public void deserializeNBT(NBTTagCompound nbt) { @Override protected void onLoad() { - super.onLoad(); - for (int i = 0; i < Math.min(tools.length, gtTools.length); i++) { + this.tools = new ItemTool[getSlots()]; + this.gtTools = new IGTTool[getSlots()]; + for (int i = 0; i < getSlots(); i++) { this.updateSlot(i); } this.update(); @@ -715,7 +718,7 @@ protected void updateSlot(int slot) { protected void update() { this.toolClasses.clear(); - for (int i = 0; i < Math.min(tools.length, gtTools.length); i++) { + for (int i = 0; i < getSlots(); i++) { if (tools[i] != null) this.toolClasses.addAll(tools[i].getToolClasses(stacks.get(i))); } } From d190f05d1cb9ea1dd31f5676745707494deee64a Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Sat, 30 Nov 2024 13:07:38 -0700 Subject: [PATCH 80/82] better fix for resizing arrays improve slotSizeSupplier skip initializing if we can't determine the material --- .../api/items/toolitem/ItemGTToolbelt.java | 37 ++++++++++--------- .../api/items/toolitem/ToolHelper.java | 8 +++- 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index bfdf6deaa9f..41d44e20e3e 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -8,7 +8,6 @@ import gregtech.api.mui.GTGuiTextures; import gregtech.api.mui.GTGuis; import gregtech.api.unification.material.Material; -import gregtech.api.unification.material.Materials; import gregtech.api.unification.material.properties.PropertyKey; import gregtech.api.unification.material.properties.ToolProperty; import gregtech.api.util.LocalizationUtils; @@ -545,14 +544,12 @@ protected static class ToolbeltCapabilityProvider implements ICapabilityProvider public ToolbeltCapabilityProvider(ItemStack stack) { slotCountSupplier = () -> { + if (!ToolHelper.hasMaterial(stack)) return 4; NBTTagCompound toolTag = stack.getOrCreateSubCompound(ToolHelper.TOOL_TAG_KEY); - String string = toolTag.getString(MATERIAL_KEY); - Material material = GregTechAPI.materialManager.getMaterial(string); - if (material == null) { - toolTag.setString(MATERIAL_KEY, (material = Materials.Iron).getRegistryName()); - } + Material material = GregTechAPI.materialManager.getMaterial(toolTag.getString(MATERIAL_KEY)); + if (material == null) return 4; ToolProperty toolProperty = material.getProperty(PropertyKey.TOOL); - return Math.min(8, 2 + (toolProperty == null ? 0 : toolProperty.getToolHarvestLevel())); + return Math.min(8, 2 + toolProperty.getToolHarvestLevel()); }; } @@ -564,24 +561,25 @@ public boolean hasCapability(@NotNull Capability capability, EnumFacing facin @Override public T getCapability(@NotNull Capability capability, EnumFacing facing) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) - return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(this.getHandler(0)); + return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(this.getHandler()); else return null; } @Override public NBTTagCompound serializeNBT() { - return this.getHandler(0).serializeNBT(); + return this.getHandler().serializeNBT(); } @Override public void deserializeNBT(NBTTagCompound nbt) { // .copy() prevents double damage ticks in singleplayer - this.getHandler(slotCountSupplier.getAsInt()).deserializeNBT(nbt.copy()); + this.getHandler().deserializeNBT(nbt.copy()); } - protected ToolStackHandler getHandler(int minsize) { - int slots = Math.max(slotCountSupplier.getAsInt(), minsize); - if (handler == null || handler.getSlots() != slots) handler = new ToolStackHandler(slots); + protected @NotNull ToolStackHandler getHandler() { + int size = slotCountSupplier.getAsInt(); + if (handler == null) handler = new ToolStackHandler(size); + else if (handler.getSlots() != size) handler.setSize(size); return handler; } } @@ -615,9 +613,7 @@ protected static class ToolStackHandler extends ItemStackHandler { private boolean passthrough = true; public ToolStackHandler(int size) { - super(size); - tools = new ItemTool[size]; - gtTools = new IGTTool[size]; + setSize(size); } public void incrementSelectedSlot() { @@ -692,10 +688,15 @@ public void deserializeNBT(NBTTagCompound nbt) { if (nbt.hasKey("SelectedSlot")) this.selectedSlot = nbt.getByte("SelectedSlot"); } + @Override + public void setSize(int size) { + super.setSize(size); + this.gtTools = new IGTTool[size]; + this.tools = new ItemTool[size]; + } + @Override protected void onLoad() { - this.tools = new ItemTool[getSlots()]; - this.gtTools = new IGTTool[getSlots()]; for (int i = 0; i < getSlots(); i++) { this.updateSlot(i); } diff --git a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java index 03032e099b8..3dc2f38b11d 100644 --- a/src/main/java/gregtech/api/items/toolitem/ToolHelper.java +++ b/src/main/java/gregtech/api/items/toolitem/ToolHelper.java @@ -203,7 +203,7 @@ public static NBTTagCompound getToolTag(ItemStack stack) { } public static ItemStack toolbeltPassthrough(ItemStack stack) { - if (stack.getItem() instanceof ItemGTToolbelt toolbelt) { + if (stack.getItem() instanceof ItemGTToolbelt toolbelt && hasMaterial(stack)) { ItemStack selected = toolbelt.getSelectedTool(stack); if (!selected.isEmpty()) stack = selected; } @@ -846,4 +846,10 @@ public static void playToolSound(ItemStack stack, EntityPlayer player) { ((IGTTool) stack.getItem()).playSound(player); } } + + public static boolean hasMaterial(ItemStack stack) { + var tag = stack.getTagCompound(); + if (tag == null || !tag.hasKey(TOOL_TAG_KEY)) return false; + return tag.getCompoundTag(TOOL_TAG_KEY).hasKey(MATERIAL_KEY); + } } From 7c39e004230ca63ebf3c2ad1a2312b454ccb1043 Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Wed, 18 Dec 2024 14:37:45 -0700 Subject: [PATCH 81/82] initialize threadlocal --- src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 41d44e20e3e..9975b0b5332 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -76,7 +76,7 @@ public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { - private static final ThreadLocal slotThread = new ThreadLocal<>(); + private static final ThreadLocal slotThread = ThreadLocal.withInitial(() -> -999); public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { super(domain, id, -1, From 8561291a77d12b003a00001b1b8362d4b9f27d19 Mon Sep 17 00:00:00 2001 From: Ghzdude <44148655+ghzdude@users.noreply.github.com> Date: Wed, 18 Dec 2024 16:19:21 -0700 Subject: [PATCH 82/82] actually fix syncing to client (please) --- .../api/items/toolitem/ItemGTToolbelt.java | 13 +++--- .../PacketToolbeltSelectionChange.java | 1 + .../mixins/minecraft/ContainerMixin.java | 29 +++++++++++++ .../mixins/minecraft/NetworkHandlerMixin.java | 41 ------------------- .../resources/mixins.gregtech.minecraft.json | 2 +- 5 files changed, 38 insertions(+), 48 deletions(-) create mode 100644 src/main/java/gregtech/mixins/minecraft/ContainerMixin.java delete mode 100644 src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java diff --git a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java index 9975b0b5332..01acd7b993c 100644 --- a/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java +++ b/src/main/java/gregtech/api/items/toolitem/ItemGTToolbelt.java @@ -37,7 +37,6 @@ import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; @@ -76,7 +75,8 @@ public class ItemGTToolbelt extends ItemGTTool implements IDyeableItem { - private static final ThreadLocal slotThread = ThreadLocal.withInitial(() -> -999); + private static final ThreadLocal lastSlot = ThreadLocal.withInitial(() -> -999); + private static final ThreadLocal lastPlayer = ThreadLocal.withInitial(() -> null); public ItemGTToolbelt(String domain, String id, Supplier markerItem, IToolBehavior... behaviors) { super(domain, id, -1, @@ -391,8 +391,8 @@ public void setOnCraftIngredient(ItemStack stack, Ingredient ingredient) { int match = getHandler(stack).checkIngredientAgainstTools(ingredient); if (match != -1) { setSelectedTool(match, stack); - PacketToolbeltSelectionChange.toClient(match, slotThread.get(), - (EntityPlayerMP) ForgeHooks.getCraftingPlayer()); + PacketToolbeltSelectionChange.toClient(match, + lastSlot.get(), (EntityPlayerMP) lastPlayer.get()); } } @@ -525,8 +525,9 @@ public static boolean checkIngredientAgainstToolbelt(@NotNull ItemStack input, @ return false; } - public static void setCraftingSlot(int slot) { - slotThread.set(slot); + public static void setCraftingSlot(int slot, EntityPlayer player) { + lastSlot.set(slot); + lastPlayer.set(player); } public static boolean checkToolAgainstToolbelt(@NotNull ItemStack toolbelt, @NotNull ItemStack tool) { diff --git a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java index 369efbf04f3..d9c41f61bc5 100644 --- a/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java +++ b/src/main/java/gregtech/core/network/packets/PacketToolbeltSelectionChange.java @@ -39,6 +39,7 @@ public void decode(PacketBuffer buf) { } public static void toClient(int slot, int matrixSlot, EntityPlayerMP player) { + if (player == null) return; GregTechAPI.networkHandler.sendTo(new Client(slot, matrixSlot), player); } diff --git a/src/main/java/gregtech/mixins/minecraft/ContainerMixin.java b/src/main/java/gregtech/mixins/minecraft/ContainerMixin.java new file mode 100644 index 00000000000..68261223856 --- /dev/null +++ b/src/main/java/gregtech/mixins/minecraft/ContainerMixin.java @@ -0,0 +1,29 @@ +package gregtech.mixins.minecraft; + +import gregtech.api.items.toolitem.ItemGTToolbelt; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ClickType; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(Container.class) +public abstract class ContainerMixin { + + @Inject(method = "slotClick", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/item/ItemStack;splitStack(I)Lnet/minecraft/item/ItemStack;", + ordinal = 1)) + private void setPlayer(int slotId, int dragType, ClickType clickTypeIn, EntityPlayer player, + CallbackInfoReturnable cir) { + var playerStack = player.inventory.getItemStack(); + if (playerStack.getItem() instanceof ItemGTToolbelt) { + ItemGTToolbelt.setCraftingSlot(slotId, player); + } + } +} diff --git a/src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java b/src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java deleted file mode 100644 index df472911ec7..00000000000 --- a/src/main/java/gregtech/mixins/minecraft/NetworkHandlerMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -package gregtech.mixins.minecraft; - -import gregtech.api.items.toolitem.ItemGTToolbelt; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Slot; -import net.minecraft.network.NetHandlerPlayServer; -import net.minecraft.network.play.client.CPacketClickWindow; -import net.minecraftforge.common.ForgeHooks; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(NetHandlerPlayServer.class) -public abstract class NetworkHandlerMixin { - - @Shadow - public EntityPlayerMP player; - - @Inject(method = "processClickWindow", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/inventory/Container;slotClick(IILnet/minecraft/inventory/ClickType;Lnet/minecraft/entity/player/EntityPlayer;)Lnet/minecraft/item/ItemStack;")) - private void setPlayer(CPacketClickWindow packetIn, CallbackInfo ci) { - ForgeHooks.setCraftingPlayer(this.player); - for (Slot slot : this.player.openContainer.inventorySlots) { - if (slot.getStack().getItem() instanceof ItemGTToolbelt) - ItemGTToolbelt.setCraftingSlot(slot.slotNumber); - } - } - - @Inject(method = "processClickWindow", - at = @At(value = "INVOKE_ASSIGN", - target = "Lnet/minecraft/inventory/Container;slotClick(IILnet/minecraft/inventory/ClickType;Lnet/minecraft/entity/player/EntityPlayer;)Lnet/minecraft/item/ItemStack;")) - private void clearPlayer(CPacketClickWindow packetIn, CallbackInfo ci) { - ForgeHooks.setCraftingPlayer(null); - ItemGTToolbelt.setCraftingSlot(-999); - } -} diff --git a/src/main/resources/mixins.gregtech.minecraft.json b/src/main/resources/mixins.gregtech.minecraft.json index 3d836d3a8cb..85676f99055 100644 --- a/src/main/resources/mixins.gregtech.minecraft.json +++ b/src/main/resources/mixins.gregtech.minecraft.json @@ -9,7 +9,7 @@ }, "mixins": [ "BlockConcretePowderMixin", - "NetworkHandlerMixin", + "ContainerMixin", "BlockRenderLayerMixin", "DamageSourceMixin", "EnchantmentCanApplyMixin",