Compare commits

...
Author SHA1 Message Date
slprime 7d4c8b82ba Add custom render for PositionedStack (#1002) 2026-08-13 21:49:05 +03:00
slprime c6170f9795 Bookmarks: Fix Permutations with different amount (#1000) 2026-08-12 22:45:39 +03:00
Dream Master 5a533c8994 update+gradle+bs+deps 2026-08-11 00:26:14 +07:00
Nikolay S.andslprime d70a47a3a4 Modernize Java code (#997)
Co-authored-by: slprime <[email protected]>
2026-08-10 14:55:40 +03:00
boubou19andgithub-actions[bot] 6c3db443d7 Cache enum .values() (#998)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-08-10 07:40:36 +02:00
boubou19 a51836fe9b Optimize updateUnlimitedItems (#995) 2026-08-07 19:05:01 +03:00
slprime 139ca22e51 Fix Untranslator With Broken Item (#993) 2026-08-04 19:43:34 +03:00
slprime 10fc78bdcf Add Recipe Filter syntax tooltip (#992) 2026-08-04 19:18:27 +03:00
slprime 5fb5ab6698 Added Bookmark Chain Visitor (#991) 2026-08-01 20:35:19 +03:00
slprime f47a8766a9 Create EmptyContainer (#990) 2026-08-01 20:19:54 +03:00
slprime 4cc72444d9 Fix Tooltip with Component in first line (#989) 2026-08-01 20:00:17 +03:00
slprime b48956ef94 Bookmarks Chain: fix container item multiplier limit (#988) 2026-07-29 00:57:12 +03:00
Algentandslprime 583d28ed12 Fix GL reset (#984)
Co-authored-by: slprime <[email protected]>
2026-07-26 23:36:37 +03:00
koolkrafter5 384813347c Overlay Button moves one item if the recipe stack is size zero (#985) 2026-07-26 23:28:39 +03:00
slprime 2b28068382 Simplify the keybinding (#982) 2026-07-25 02:14:12 +03:00
slprime 2c204c25aa Rework chat item link to support bookmarking recipes and groups (#971) 2026-07-11 20:38:01 +03:00
Jordan Rey 5e6ff1d63b fix: spawner placement logic (#973) 2026-07-11 20:33:51 +03:00
Algent 53ce50b35a oregenPattern this time for sure (#974) 2026-07-11 19:53:43 +03:00
69 changed files with 1119 additions and 424 deletions

No files matched your search

+5 -4
View File
@@ -5,12 +5,13 @@ configurations.create('gtnhlibEmbed') {
}
dependencies {
api('com.github.GTNewHorizons:CodeChickenCore:1.4.16:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.11.23:dev')
api('com.github.GTNewHorizons:CodeChickenCore:1.4.17:dev')
devOnlyNonPublishable('com.github.GTNewHorizons:GTNHLib:0.11.37:dev')
shadowImplementation('org.apache.commons:commons-csv:1.10.0')
compileOnly('maven.modrinth:forge-essentials:7.5.1')
compileOnly('com.cardinalstar.cubicchunks:CubicChunks1710:v0.1.14-alpha:dev')
antlr('org.antlr:antlr4:4.13.2')
shadowImplementation('org.antlr:antlr4-runtime:4.13.2')
@@ -22,8 +23,8 @@ dependencies {
testRuntimeOnly('org.junit.platform:junit-platform-launcher')
testRuntimeOnly("org.lwjgl.lwjgl:lwjgl:2.9.3");
compileOnly("com.github.GTNewHorizons:GTNHLib:0.11.23") { transitive = false }
gtnhlibEmbed("com.github.GTNewHorizons:GTNHLib:0.11.23") { transitive = false }
compileOnly("com.github.GTNewHorizons:GTNHLib:0.11.37") { transitive = false }
gtnhlibEmbed("com.github.GTNewHorizons:GTNHLib:0.11.37") { transitive = false }
}
[tasks.jar, tasks.shadowJar].each {
+10 -10
View File
@@ -1,12 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/c2dd35c9d0aaf0ba6ad0791320f99dfc/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/e5810bd7fd1f8a586644409d395a7e55/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/cf726b4a1c84b50457225f9bba6d7650/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/fa1e318c287360478e3c83a9a3ef1007/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/7b3c4877c0749019e6805bb61e421497/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/d76df094a9cbbabd3b08251f9e61444a/redirect
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/97d46b5ff4df0bf61e95652a190a5567/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/9ef54a08e06b0754cee9fc95ed3a3134/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/97d46b5ff4df0bf61e95652a190a5567/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/9ef54a08e06b0754cee9fc95ed3a3134/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/1df82b76031285ef2e6a4f59ffe9299d/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/c7d5be6a02945ac2e045048ee54a7d32/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/97d46b5ff4df0bf61e95652a190a5567/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/9ef54a08e06b0754cee9fc95ed3a3134/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/643f404f769811f5f265fd66f7af5d89/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/38256085a73e137cb4937ea9c4807fec/redirect
toolchainVersion=25
+1 -1
View File
@@ -17,7 +17,7 @@ pluginManagement {
}
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.26'
id 'com.gtnewhorizons.gtnhsettingsconvention' version '2.0.29'
}
@@ -913,9 +913,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
this.grid.createRecipeChainMath(groupId));
}
if (this.recipeChainTooltipLineHandler != null) {
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeChainTooltipLineHandler));
}
currenttip.add(GuiDraw.TOOLTIP_HANDLER + GuiDraw.getTipLineId(this.recipeChainTooltipLineHandler));
return currenttip;
}
@@ -1096,10 +1094,13 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
}
activeStack = items.get((items.size() - shift + stackIndex) % items.size());
this.acceptsFollowingTooltipLineHandler.setActiveStack(activeStack);
this.grid.getBookmarkItem(Math.abs(itemIndex)).itemStack = activeStack;
this.grid.onItemsChanged();
final int targetItemIndex = Math.abs(itemIndex);
final BookmarkItem oldItem = this.grid.getBookmarkItem(targetItemIndex);
final BookmarkItem newItem = oldItem.copyWithPerm(activeStack);
this.grid.replaceBookmarkItem(targetItemIndex, newItem);
}
return true;
@@ -1294,7 +1295,7 @@ public class BookmarkPanel extends PanelWidget<BookmarkGrid> {
public BookmarkRecipeId getBookmarkRecipeId(int itemIndex) {
BookmarkItem item = this.grid.getCalculatedItem(itemIndex);
return item == null || item.type == BookmarkItemType.INGREDIENT || item.recipeId == null ? null
: new BookmarkRecipeId(item.recipeId.getHandleName(), item.recipeId.getIngredients());
: new BookmarkRecipeId(item.recipeId.getHandlerName(), item.recipeId.getIngredients());
}
@Deprecated
@@ -112,7 +112,7 @@ public class CollapsibleItems {
group.setFilter(itemStr);
}
if (group != null && group.filter != null) {
if (group.filter != null) {
addGroup(group);
group = new GroupItem();
}
@@ -79,14 +79,13 @@ public class ContainerCreativeInv extends Container {
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int slotIndex) {
ItemStack transferredStack = null;
Slot slot = (Slot) inventorySlots.get(slotIndex);
Slot slot = inventorySlots.get(slotIndex);
if (slot != null && slot.getHasStack()) {
ItemStack stack = slot.getStack();
transferredStack = stack.copy();
if (stack.getItem() instanceof ItemArmor) {
ItemArmor armor = (ItemArmor) stack.getItem();
if (stack.getItem() instanceof ItemArmor armor) {
if (!getSlot(90 + armor.armorType).getHasStack()) {
getSlot(90 + armor.armorType).putStack(transferredStack);
slot.putStack(null);
@@ -8,7 +8,6 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ContainerEnchantment;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
@@ -164,14 +163,14 @@ public class ContainerEnchantmentModifier extends ContainerEnchantment {
public boolean addEnchantment(int e, int level) {
if (e < Enchantment.enchantmentsList.length && Enchantment.enchantmentsList[e] != null) {
((Slot) inventorySlots.get(0)).getStack().addEnchantment(Enchantment.enchantmentsList[e], level);
inventorySlots.get(0).getStack().addEnchantment(Enchantment.enchantmentsList[e], level);
return true;
}
return false;
}
public void removeEnchantment(int e) {
ItemStack stack = ((Slot) inventorySlots.get(0)).getStack();
ItemStack stack = inventorySlots.get(0).getStack();
NBTTagList nbttaglist = stack.getEnchantmentTagList();
if (nbttaglist != null) {
for (int i = 0; i < nbttaglist.tagCount(); i++) {
@@ -20,7 +20,7 @@ public class DefaultHighlightHandler implements IHighlightHandler {
String name = null;
try {
String s = GuiContainerManager.itemDisplayNameShort(stack);
if (s != null && !s.endsWith("Unnamed")) name = s;
if (!s.endsWith("Unnamed")) name = s;
if (name != null) currenttip.add(name);
} catch (Exception ignored) {}
@@ -91,7 +91,7 @@ public class FastTransferManager {
public static void clearSlots(Container container) {
for (int slotNo = 0; slotNo < container.inventorySlots.size(); slotNo++)
((Slot) container.inventorySlots.get(slotNo)).putStack(null);
container.inventorySlots.get(slotNo).putStack(null);
}
public void performMassTransfer(GuiContainer window, int fromSlot, int toSlot, ItemStack heldStack) {
@@ -289,7 +289,7 @@ public class FastTransferManager {
if (held == null) return -1;
for (int i = 0; held != null && i < window.inventorySlots.inventorySlots.size(); i++) {
for (int i = 0; i < window.inventorySlots.inventorySlots.size(); i++) {
final Slot slot = window.inventorySlots.inventorySlots.get(i);
if (slot.inventory instanceof InventoryPlayer && !slot.getHasStack() && slot.isItemValid(held)) {
@@ -225,7 +225,7 @@ public class FavoriteRecipes {
continue;
}
if (FAVORITE_ITEM.equals(recipeId.getHandleName()) || RecipeHandlerRef.of(recipeId) != null) {
if (FAVORITE_ITEM.equals(recipeId.getHandlerName()) || RecipeHandlerRef.of(recipeId) != null) {
manualFavorites.add(stack, recipeId);
} else {
hasErrors = true;
@@ -82,8 +82,8 @@ public class GuiEnchantmentModifier extends GuiContainer {
private void changeLevel(int i) {
container.level += i;
((GuiButton) buttonList.get(0)).enabled = container.level != 1;
((GuiButton) buttonList.get(1)).enabled = container.level != 10;
buttonList.get(0).enabled = container.level != 1;
buttonList.get(1).enabled = container.level != 10;
}
protected void mouseClicked(int i, int j, int k) {
@@ -30,14 +30,7 @@ public class InfiniteStackSizeHandler implements IInfiniteItemHandler {
@Override
public void replenishInfiniteStack(InventoryPlayer inv, int slotNo) {
ItemStack stack = inv.getStackInSlot(slotNo);
stack.stackSize = 111;
for (int i = 0; i < inv.getSizeInventory(); i++) {
if (i == slotNo) continue;
if (NEIServerUtils.areStacksSameType(stack, inv.getStackInSlot(i))) inv.setInventorySlotContents(i, null);
}
inv.getStackInSlot(slotNo).stackSize = 111;
}
@Override
@@ -241,7 +241,7 @@ public class ItemCraftablesPanel
private GuiContainer getGuiContainer() {
final GuiContainer firstGui = NEIClientUtils.getGuiContainer();
return (firstGui instanceof GuiRecipe gui) ? gui.firstGui : firstGui;
return (firstGui instanceof GuiRecipe<?>gui) ? gui.firstGui : firstGui;
}
private Map<ItemStack, RecipeId> generateCraftables(GuiContainer firstGui) {
@@ -150,8 +150,7 @@ public class ItemListLoader {
if (item == null) {
return;
}
if (item instanceof IFluidContainerItem) {
IFluidContainerItem fluidItem = (IFluidContainerItem) item;
if (item instanceof IFluidContainerItem fluidItem) {
runChecked(stack, () -> fluidItem.getFluid(stack), "getFluid");
}
runChecked(stack, () -> item.isDamaged(stack), "isDamaged");
@@ -23,6 +23,7 @@ import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@@ -65,27 +66,41 @@ public class ItemMobSpawner extends ItemBlock {
@Override
public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int x, int y, int z, int side,
float hitX, float hitY, float hitZ) {
int targetX = x;
int targetY = y;
int targetZ = z;
placedX = x;
placedY = y;
placedZ = z;
if (!world.getBlock(x, y, z).isReplaceable(world, x, y, z)) {
ForgeDirection direction = ForgeDirection.getOrientation(side);
targetX += direction.offsetX;
targetY += direction.offsetY;
targetZ += direction.offsetZ;
}
placedX = targetX;
placedY = targetY;
placedZ = targetZ;
String mobType = getMobTypeFromItemStack(itemstack);
boolean placed = super.onItemUse(itemstack, entityplayer, world, x, y, z, side, hitX, hitY, hitZ);
if (placed && !world.isRemote) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity instanceof TileEntityMobSpawner) {
TileEntityMobSpawner spawner = (TileEntityMobSpawner) tileEntity;
String mobType = getMobTypeFromItemStack(itemstack);
if (mobType != null) {
spawner.func_145881_a().setEntityName(mobType);
world.markBlockForUpdate(x, y, z);
NEICPH.sendMobSpawnerID(x, y, z, mobType);
if (placed) {
TileEntity tileEntity = world.getTileEntity(targetX, targetY, targetZ);
if (tileEntity instanceof TileEntityMobSpawner spawner && mobType != null) {
spawner.func_145881_a().setEntityName(mobType);
if (!world.isRemote) {
world.markBlockForUpdate(targetX, targetY, targetZ);
NEICPH.sendMobSpawnerID(targetX, targetY, targetZ, mobType);
}
}
return true;
}
return placed;
return false;
}
private String getMobTypeFromItemStack(ItemStack stack) {
@@ -223,7 +238,6 @@ public class ItemMobSpawner extends ItemBlock {
NEIClientConfig.logger.debug("Cleared all entity references from cache");
}
@SuppressWarnings("unchecked")
public static void loadSpawners() {
if (loaded) {
return;
@@ -231,8 +245,7 @@ public class ItemMobSpawner extends ItemBlock {
synchronized (ItemMobSpawner.class) {
try {
for (Map.Entry<Class<? extends Entity>, String> entry : ((Map<Class<? extends Entity>, String>) EntityList.classToStringMapping)
.entrySet()) {
for (Map.Entry<Class<? extends Entity>, String> entry : EntityList.classToStringMapping.entrySet()) {
Class<? extends Entity> clazz = entry.getKey();
String name = entry.getValue();
@@ -308,7 +321,7 @@ public class ItemMobSpawner extends ItemBlock {
String name = ENTITY_CLASS_TO_NAME_CACHE.get(entityClass);
if (name == null) {
name = (String) EntityList.classToStringMapping.get(entityClass);
name = EntityList.classToStringMapping.get(entityClass);
}
return name != null && shouldRegisterEntity(entityClass, name);
@@ -46,8 +46,7 @@ public class ItemStackMap<T> {
}
public boolean equals(Object o) {
if (!(o instanceof StackMetaKey)) return false;
StackMetaKey t = (StackMetaKey) o;
if (!(o instanceof StackMetaKey t)) return false;
return damage == t.damage && Objects.equal(tag, t.tag);
}
}
@@ -218,8 +217,7 @@ public class ItemStackMap<T> {
public void put(ItemStack key, T value) {
if (key == null || key.getItem() == null) return;
DetailMap map = itemMap.get(key.getItem());
if (map == null) itemMap.put(key.getItem(), map = new DetailMap());
DetailMap map = itemMap.computeIfAbsent(key.getItem(), k -> new DetailMap());
map.put(key, value);
}
+4 -4
View File
@@ -42,7 +42,7 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
if (this.stack != null && this.availableAreaWidth >= SLOT_SIZE * 2
&& (NEIClientConfig.getBooleanSetting("inventory.itemzoom.enabled")
|| KeyManager.isHashDown("itemzoom.hold"))
|| KeyManager.isKeyDown("itemzoom.hold"))
&& GuiContainerManager.shouldShowTooltip(NEIClientUtils.getGuiContainer())) {
final float inverseScaleFactor = 1.0f / this.scale;
final float screenScale = getScreenScale();
@@ -204,18 +204,18 @@ public class ItemZoom extends Widget implements IContainerInputHandler {
return true;
}
if (this.stack != null && KeyManager.isHashDown("itemzoom.hold")) {
if (this.stack != null && KeyManager.isKeyDown("itemzoom.hold")) {
return true;
}
if (this.stack != null && KeyManager.isHashDown("itemzoom.zoom_in")) {
if (this.stack != null && KeyManager.isKeyDown("itemzoom.zoom_in")) {
increaseZoom(gui);
previousKeyboardRepeatEnabled = Keyboard.areRepeatEventsEnabled();
Keyboard.enableRepeatEvents(true);
return true;
}
if (this.stack != null && KeyManager.isHashDown("itemzoom.zoom_out")) {
if (this.stack != null && KeyManager.isKeyDown("itemzoom.zoom_out")) {
decreaseZoom(gui);
previousKeyboardRepeatEnabled = Keyboard.areRepeatEventsEnabled();
Keyboard.enableRepeatEvents(true);
+10 -8
View File
@@ -67,17 +67,19 @@ public class KeyManager {
}
public static boolean isKeyDown(String ident) {
final int keyCode = getKeyCode(ident);
final KeyBinding binding = getKeyBinding(ident);
if (keyCode == Keyboard.KEY_NONE) {
return false;
if (binding != null) {
final int keyCode = binding.getKeyCode();
if (keyCode < 0) {
return Mouse.isButtonDown(keyCode + 100);
} else if (keyCode > Keyboard.KEY_NONE && keyCode < Keyboard.KEYBOARD_SIZE) {
return Keyboard.isKeyDown(keyCode);
}
}
if (keyCode < 0) {
return Mouse.isButtonDown(keyCode + 100);
}
return keyCode < Keyboard.KEYBOARD_SIZE && Keyboard.isKeyDown(keyCode);
return false;
}
public static boolean isHashDown(String ident) {
@@ -224,12 +224,12 @@ public class LayoutManager implements IContainerInputHandler, IContainerTooltipH
@Override
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyID) {
if (KeyManager.isHashDown("gui.hide")) {
if (KeyManager.isKeyDown("gui.hide")) {
toggleBooleanSetting("inventory.hidden");
return true;
}
if (KeyManager.isHashDown("bookmark.hide")) {
if (KeyManager.isKeyDown("bookmark.hide")) {
toggleBooleanSetting("inventory.bookmarks.enabled");
return true;
}
+16 -2
View File
@@ -6,6 +6,7 @@ import static codechicken.nei.PacketIDs.S2C;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.world.World;
@@ -14,6 +15,7 @@ import codechicken.core.ClientUtils;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.packet.PacketCustom.IClientPacketHandler;
import codechicken.nei.commands.CommandBookmarkAdd;
import cpw.mods.fml.relauncher.Side;
public class NEICPH implements IClientPacketHandler {
@@ -56,6 +58,18 @@ public class NEICPH implements IClientPacketHandler {
case S2C.OPEN_POTION_GUI:
ClientUtils.openSMPGui(packet.readUByte(), new GuiPotionCreator(mc.thePlayer.inventory));
break;
case S2C.CACHE_BOOKMARK_DATA:
handleCacheBookmarkData(packet);
break;
}
}
private void handleCacheBookmarkData(PacketCustom packet) {
final String payloadId = packet.readString();
final NBTTagCompound payloadTag = packet.readNBTTagCompound();
if (payloadTag != null) {
CommandBookmarkAdd.cachePayload(payloadId, payloadTag);
}
}
@@ -186,9 +200,9 @@ public class NEICPH implements IClientPacketHandler {
packet.sendToServer();
}
public static void sendChatLink(ItemStack stackover) {
public static void sendChatLink(NBTTagCompound payloadTag) {
PacketCustom packet = new PacketCustom(channel, C2S.SEND_CHAT_ITEM_LINK);
packet.writeItemStack(stackover);
packet.writeNBTTagCompound(payloadTag);
packet.sendToServer();
}
@@ -839,6 +839,7 @@ public class NEIClientConfig {
API.addKeyBind("bookmark.favorite_item", Keyboard.KEY_F);
API.addKeyBind("bookmark.remove_recipe", Keyboard.KEY_A);
API.addKeyBind("bookmark.pull_items", Keyboard.KEY_V);
API.addKeyBind("bookmark.chat_link", Keyboard.KEY_L);
API.addKeyBind("bookmark.hide", Keyboard.KEY_B);
API.addKeyBind("itemzoom.toggle", Keyboard.KEY_Z);
@@ -860,7 +861,6 @@ public class NEIClientConfig {
API.addKeyBind("copy.name", Keyboard.KEY_C);
API.addKeyBind("copy.oredict", Keyboard.KEY_D);
API.addKeyBind("copy.identifier", Keyboard.KEY_X);
API.addKeyBind("copy.chat_link_item", Keyboard.KEY_L);
}
public static OptionList getOptionList() {
@@ -921,9 +921,7 @@ public class NEIClientConfig {
return;
}
if (ItemPanels.bookmarkPanel != null) {
ItemPanels.bookmarkPanel.save();
}
ItemPanels.bookmarkPanel.save();
SubsetWidget.saveHidden();
FavoriteRecipes.save();
@@ -38,6 +38,7 @@ import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IChatComponent;
import net.minecraft.util.ResourceLocation;
@@ -379,8 +380,8 @@ public class NEIClientUtils extends NEIServerUtils {
else sendCommand(getStringSetting("command.heal"), mc().thePlayer.getCommandSenderName());
}
public static void sendChatItemLink(ItemStack stackover) {
if (hasSMPCounterPart()) NEICPH.sendChatLink(stackover);
public static void sendChatItemLink(NBTTagCompound payload) {
if (hasSMPCounterPart()) NEICPH.sendChatLink(payload);
}
public static void toggleMagnetMode() {
@@ -4,13 +4,13 @@ import static codechicken.lib.gui.GuiDraw.getMousePosition;
import static codechicken.nei.NEIClientConfig.canCheatItem;
import java.awt.Point;
import java.util.LinkedList;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.ClientCommandHandler;
@@ -27,7 +27,7 @@ import codechicken.nei.commands.CommandUntranslator;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.guihook.IContainerInputHandler;
import codechicken.nei.guihook.IContainerSlotClickHandler;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.util.EmptyContainer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@@ -77,29 +77,38 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
public static void updateUnlimitedItems(InventoryPlayer inventory) {
if (!NEIClientConfig.canPerformAction("item") || !NEIClientConfig.hasSMPCounterPart()) return;
LinkedList<ItemStack> beforeStacks = new LinkedList<>();
for (int i = 0; i < inventory.getSizeInventory(); i++)
beforeStacks.add(NEIServerUtils.copyStack(inventory.getStackInSlot(i)));
for (int i = 0; i < inventory.getSizeInventory(); i++) {
int size = inventory.getSizeInventory();
for (int i = 0; i < size; i++) {
ItemStack stack = inventory.getStackInSlot(i);
if (stack == null) continue;
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers)
if (handler.canHandleItem(stack) && handler.isItemInfinite(stack))
handler.replenishInfiniteStack(inventory, i);
}
for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers) {
if (!handler.canHandleItem(stack) || !handler.isItemInfinite(stack)) continue;
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack newstack = inventory.getStackInSlot(i);
long beforeSize = packStackSize(stack.stackSize, stack.getItemDamage());
handler.replenishInfiniteStack(inventory, i);
if (!NEIServerUtils.areStacksIdentical(beforeStacks.get(i), newstack)) {
inventory.setInventorySlotContents(i, beforeStacks.get(i)); // restore in case of SMP fail
NEIClientUtils.setSlotContents(i, newstack, false); // sends via SMP handler ;)
ItemStack newstack = inventory.getStackInSlot(i);
if (!sameStack(stack, beforeSize, newstack)) {
NEIClientUtils.setSlotContents(i, newstack, false); // sends via SMP handler ;)
stack.stackSize = (int) (beforeSize >> 32);
stack.setItemDamage((int) beforeSize);
inventory.setInventorySlotContents(i, stack); // restore in case of SMP fail
}
}
}
}
private static long packStackSize(int stackSize, int itemDamage) {
return ((long) stackSize << 32) | (itemDamage & 0xFFFFFFFFL);
}
private static boolean sameStack(ItemStack before, long beforeSize, ItemStack stack) {
if (stack == null) return before == null;
return before != null && Item.getIdFromItem(before.getItem()) == Item.getIdFromItem(stack.getItem())
&& beforeSize == packStackSize(stack.stackSize, stack.getItemDamage());
}
public static void processCreativeCycling(InventoryPlayer inventory) {
if (NEIClientConfig.invCreativeMode() && NEIClientUtils.controlKey()) {
if (selectedItem != inventory.currentItem) {
@@ -252,7 +261,7 @@ public class NEIController implements IContainerSlotClickHandler, IContainerInpu
// slot in GuiRecipe does not contain actual stack
// and scroll should be handled by GuiRecipe, not here
if (gui instanceof GuiRecipe) return false;
if (gui.inventorySlots instanceof EmptyContainer) return false;
Point mousePos = getMousePosition();
Slot mouseover = manager.window.getSlotAtPosition(mousePos.x, mousePos.y);
+3 -1
View File
@@ -11,6 +11,7 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.INetHandlerPlayServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityMobSpawner;
@@ -95,7 +96,8 @@ public class NEISPH implements IServerPacketHandler {
}
private void handleSendChatItemLink(EntityPlayerMP sender, PacketCustom packet) {
NEIServerUtils.sendChatItemLink(sender, packet.readItemStack());
final NBTTagCompound payloadTag = packet.readNBTTagCompound();
NEIServerUtils.sendChatItemLink(sender, payloadTag);
}
private void handleDummySlotSet(EntityPlayerMP sender, PacketCustom packet) {
@@ -10,6 +10,7 @@ import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipException;
import net.minecraft.command.ICommandSender;
@@ -28,11 +29,11 @@ import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings.GameType;
import net.minecraftforge.oredict.OreDictionary;
@@ -44,6 +45,7 @@ import codechicken.lib.inventory.InventoryRange;
import codechicken.lib.inventory.InventoryUtils;
import codechicken.lib.packet.PacketCustom;
import codechicken.nei.PacketIDs.S2C;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTHelper;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.registry.GameRegistry;
@@ -73,7 +75,7 @@ public class NEIServerUtils {
public static void toggleRaining(World world, boolean notify) {
boolean raining = !world.isRaining();
if (!raining) // turn off
((WorldServer) world).provider.resetRainAndThunder();
world.provider.resetRainAndThunder();
else world.getWorldInfo().setRaining(!isRaining(world));
if (notify)
@@ -86,16 +88,46 @@ public class NEIServerUtils {
player.extinguish();
}
public static void sendChatItemLink(EntityPlayerMP sender, ItemStack stackover) {
ServerUtils.sendChatToAll(
new ChatComponentTranslation(
"nei.chat.item_link.text",
sender.getDisplayName(),
stackover.func_151000_E().setChatStyle(
stackover.func_151000_E().getChatStyle().setChatClickEvent(
new ClickEvent(
ClickEvent.Action.RUN_COMMAND,
"/nei_bookmark " + stackover.writeToNBT(new NBTTagCompound()))))));
public static void sendChatItemLink(EntityPlayerMP sender, NBTTagCompound payload) {
if (payload == null) {
sender.addChatMessage(new ChatComponentText("Invalid bookmark payload"));
return;
}
final String linkType = payload.getString("linkType");
final String payloadId = UUID.randomUUID().toString().substring(0, 8);
final PacketCustom packet = new PacketCustom(NEISPH.channel, S2C.CACHE_BOOKMARK_DATA).writeString(payloadId)
.writeNBTTagCompound((NBTTagCompound) payload.copy());
for (EntityPlayer player : ServerUtils.getPlayers()) {
if (player instanceof EntityPlayerMP playerMP) {
packet.sendToPlayer(playerMP);
}
}
try {
final IChatComponent clickable;
if (payload.hasKey("item")) {
clickable = StackInfo.loadFromNBT(payload.getCompoundTag("item")).func_151000_E();
} else {
clickable = new ChatComponentText("[")
.appendSibling(new ChatComponentTranslation("nei.chat.item_link." + linkType + ".text"))
.appendText("]");
}
if (clickable == null) {
throw new Exception("Invalid ItemStack NBT");
}
clickable.getChatStyle()
.setChatClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/nei_bookmark " + payloadId));
ServerUtils.sendChatToAll(
new ChatComponentTranslation("nei.chat.item_link.text", sender.getDisplayName(), clickable));
} catch (Exception e) {
sender.addChatMessage(new ChatComponentText(e.toString()));
}
}
public static long getTime(World world) {
@@ -229,9 +261,6 @@ public class NEIServerUtils {
/**
* GT Items don't have any NBT set for the recipe, so if either of the stacks has a NULL nbt, and the other doesn't,
* pretend they stack
*
* @param ItemStack stack
* @return
*/
public static boolean isItemTool(ItemStack stack) {
return GTMetaBaseItemHolder.gtMetaBaseItem != null
@@ -423,7 +452,7 @@ public class NEIServerUtils {
}
public static List<Integer> getRange(final int start, final int end) {
return new AbstractList<Integer>() {
return new AbstractList<>() {
@Override
public Integer get(int index) {
@@ -37,5 +37,6 @@ public final class PacketIDs {
public static final int OPEN_ENCHANTMENT_GUI = 21;
public static final int SET_CREATIVE_PLUS_MODE = 23;
public static final int OPEN_POTION_GUI = 24;
public static final int CACHE_BOOKMARK_DATA = 25;
}
}
@@ -13,6 +13,7 @@ import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.ItemFilter;
import codechicken.nei.api.ItemInfo;
import codechicken.nei.guihook.GuiContainerManager;
import codechicken.nei.recipe.Badge;
import codechicken.nei.recipe.GuiRecipe;
import codechicken.nei.recipe.StackInfo;
@@ -20,19 +21,21 @@ import codechicken.nei.recipe.StackInfo;
/**
* Simply an {@link ItemStack} with position. Mainly used in the recipe handlers.
*/
public class PositionedStack {
public class PositionedStack implements Cloneable {
/** Maximum chance value representing 100% probability (1 unit = 0.01%). */
public static final int CHANCE_FULL = 10_000;
public int relx;
public int rely;
public int width = 16;
public int height = 16;
public ItemStack[] items;
// compatibility dummy
public ItemStack item;
protected int chance = CHANCE_FULL;
private boolean permutated = false;
protected boolean permutated = false;
public PositionedStack(Object object, int x, int y, boolean genPerms) {
items = NEIServerUtils.extractRecipeItems(object);
@@ -91,6 +94,10 @@ public class PositionedStack {
return null;
}
public List<String> getTooltip() {
return null;
}
public int getChance() {
return this.chance;
}
@@ -100,14 +107,20 @@ public class PositionedStack {
}
public PositionedStack copy() {
PositionedStack pStack = new PositionedStack(
Arrays.stream(this.items).map(ItemStack::copy).toArray(ItemStack[]::new),
relx,
rely,
false);
pStack.permutated = this.permutated;
pStack.chance = this.chance;
return pStack;
try {
PositionedStack pStack = (PositionedStack) super.clone();
pStack.items = Arrays.stream(this.items).map(ItemStack::copy).toArray(ItemStack[]::new);
pStack.item = this.item == null ? null : this.item.copy();
return pStack;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public void draw(int mousex, int mousey) {
final int x = this.relx + (this.width - 16) / 2;
final int y = this.rely + (this.height - 16) / 2;
GuiContainerManager.drawItem(x, y, this.item);
}
public List<ItemStack> getFilteredPermutations() {
@@ -164,7 +177,9 @@ public class PositionedStack {
}
public boolean contains(int mx, int my) {
return mx >= this.relx - 1 && mx < this.relx + 17 && my >= this.rely - 1 && my < this.rely + 17;
return mx >= this.relx - 1 && mx < this.relx + this.width + 1
&& my >= this.rely - 1
&& my < this.rely + this.height + 1;
}
public boolean contains(ItemStack ingredient) {
@@ -192,4 +207,21 @@ public class PositionedStack {
public String toString() {
return "PositionedStack(output='" + item.toString() + "')";
}
/**
* A {@link PositionedStack} that keeps its items but never draws them.
*/
public static class Placeholder extends PositionedStack {
public Placeholder(Object object, int x, int y, boolean genPerms) {
super(object, x, y, genPerms);
}
public Placeholder(Object object, int x, int y) {
this(object, x, y, true);
}
@Override
public void draw(int mousex, int mousey) {}
}
}
@@ -163,9 +163,7 @@ public class PresetsList {
public static void load() {
final File presetsFile = new File(CommonUtils.getMinecraftDir(), "saves/NEI/global/presets.ini");
if (presetsFile == null || !presetsFile.exists()) {
return;
}
if (!presetsFile.exists()) return;
List<String> itemStrings;
try (FileInputStream reader = new FileInputStream(presetsFile)) {
@@ -15,7 +15,6 @@ import net.minecraftforge.fluids.FluidStack;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.ItemList.NothingItemFilter;
import codechicken.nei.SearchTokenParser.ISearchParserProvider;
import codechicken.nei.SearchTokenParser.SearchMode;
import codechicken.nei.api.IRecipeFilter;
import codechicken.nei.api.IRecipeFilter.IRecipeFilterProvider;
import codechicken.nei.api.ItemFilter;
@@ -85,8 +84,8 @@ public class SearchField extends TextField implements ItemFilterProvider {
}
@Override
public SearchMode getSearchMode() {
return SearchMode.fromInt(NEIClientConfig.getIntSetting("inventory.search." + this.name + "SearchMode"));
public String getName() {
return this.name;
}
}
@@ -59,7 +59,13 @@ public class SearchTokenParser {
public EnumChatFormatting getHighlightedColor();
public SearchMode getSearchMode();
default SearchMode getSearchMode() {
return SearchMode.fromInt(NEIClientConfig.getIntSetting("inventory.search." + getName() + "SearchMode"));
}
default String getName() {
return String.valueOf(getPrefix());
}
}
private static class ProvidersCache {
@@ -179,7 +185,7 @@ public class SearchTokenParser {
public synchronized ItemFilter getFilter(String rawText, boolean skipRecipeTokens) {
final String filterText = EnumChatFormatting.getTextWithoutFormattingCodes(rawText).toLowerCase();
if (filterText == null || filterText.isEmpty()) {
if (filterText.isEmpty()) {
return new EverythingItemFilter();
}
@@ -253,7 +259,7 @@ public class SearchTokenParser {
public synchronized IRecipeFilter getRecipeFilter(String filterText) {
filterText = EnumChatFormatting.getTextWithoutFormattingCodes(filterText).toLowerCase();
if (filterText == null || filterText.isEmpty()) {
if (filterText.isEmpty()) {
return new RecipeFilter(FilterContext.ANY, true, new EverythingItemFilter());
}
@@ -46,8 +46,7 @@ public class ServerHandler {
@SubscribeEvent
public void tickEvent(TickEvent.PlayerTickEvent event) {
if (event.phase == Phase.START && event.player instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) event.player;
if (event.phase == Phase.START && event.player instanceof EntityPlayerMP player) {
PlayerSave save = NEIServerConfig.forPlayer(player.getCommandSenderName());
if (save == null) return;
updateMagneticPlayer(player, save);
@@ -399,8 +399,8 @@ public class SubsetWidget extends Button implements ItemFilterProvider {
}
@Override
public SearchMode getSearchMode() {
return SearchMode.fromInt(NEIClientConfig.getIntSetting("inventory.search.subsetsSearchMode"));
public String getName() {
return "subsets";
}
private boolean matches(String name, String searchText, Pattern pattern) {
@@ -1,7 +1,5 @@
package codechicken.nei;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
@@ -23,6 +21,8 @@ import net.minecraft.world.chunk.Chunk;
import org.lwjgl.opengl.GL11;
import com.cardinalstar.cubicchunks.world.api.IMinMaxHeight;
import codechicken.lib.math.MathHelper;
import codechicken.nei.KeyManager.IKeyStateTracker;
import cpw.mods.fml.relauncher.ReflectionHelper;
@@ -60,6 +60,7 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
}
public static void render(float frame) {
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LINE_BIT);
GL11.glPushMatrix();
Entity entity = Minecraft.getMinecraft().renderViewEntity;
@@ -73,9 +74,12 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glTranslated(-interpPosX + intOffsetX, -interpPosY + intOffsetY, -interpPosZ + intOffsetZ);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
renderChunkBounds(entity, intOffsetX, intOffsetY, intOffsetZ);
renderMobSpawnOverlay(entity, intOffsetX, intOffsetY, intOffsetZ);
GL11.glPopMatrix();
GL11.glPopAttrib();
}
private static void buildMobSpawnOverlay(Entity entity) {
@@ -412,38 +416,18 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
GL11.glDisable(GL11.GL_BLEND);
}
/** Holder defers class loading until Cubic Chunks is confirmed present. */
private static final class CCWorldBounds {
static final MethodHandle GET_MIN_HEIGHT;
static final MethodHandle GET_MAX_HEIGHT;
static {
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
// Mixined into World by CC, use reflection + MethodHandles to call these
GET_MIN_HEIGHT = lookup.unreflect(World.class.getMethod("getMinHeight"));
GET_MAX_HEIGHT = lookup.unreflect(World.class.getMethod("getMaxHeight"));
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
}
private static int worldMinHeight(World world) {
if (!NEIModContainer.isCCLoaded()) return 0;
try {
return (int) CCWorldBounds.GET_MIN_HEIGHT.invoke(world);
} catch (Throwable ignored) {
if (NEIModContainer.isCCLoaded() && world instanceof IMinMaxHeight worldHeights) {
return worldHeights.getMinHeight();
} else {
return 0;
}
}
private static int worldMaxHeight(World world) {
if (!NEIModContainer.isCCLoaded()) return world.getHeight();
try {
return (int) CCWorldBounds.GET_MAX_HEIGHT.invoke(world);
} catch (Throwable ignored) {
if (NEIModContainer.isCCLoaded() && world instanceof IMinMaxHeight worldHeights) {
return worldHeights.getMaxHeight();
} else {
return world.getHeight();
}
}
@@ -469,13 +453,9 @@ public class WorldOverlayRenderer implements IKeyStateTracker {
"gregtech.common.GT_Worldgenerator");
try {
// GT5-Unofficial >= 5.09.54.02 support
final Method server = gtWorldGenerator.getMethod("getServerOregenPattern");
final Method client = gtWorldGenerator.getMethod("getClientOregenPattern");
return () -> {
final Method accessor = Minecraft.getMinecraft().isSingleplayer() ? server : client;
return ((Enum<?>) accessor.invoke(null)).name();
};
// GT5-Unofficial >= 5.09.54.29 support
final Method accessor = gtWorldGenerator.getMethod("getOregenPattern");
return () -> ((Enum<?>) accessor.invoke(null)).name();
} catch (NoSuchMethodException legacy) {
// Older GT
final Field oregenPattern = gtWorldGenerator.getDeclaredField("oregenPattern");
@@ -77,10 +77,13 @@ import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
*/
public class ItemInfo {
public static enum Layout {
public enum Layout {
HEADER,
BODY,
FOOTER
FOOTER;
public static final Layout[] VALUES = values();
}
public static final ArrayListMultimap<Layout, IHighlightHandler> highlightHandlers = ArrayListMultimap.create();
@@ -472,7 +475,7 @@ public class ItemInfo {
MovingObjectPosition mop) {
List<String> retString = new ArrayList<>();
for (ItemInfo.Layout layout : ItemInfo.Layout.values())
for (ItemInfo.Layout layout : Layout.VALUES)
for (IHighlightHandler handler : ItemInfo.highlightHandlers.get(layout))
retString = handler.handleTextData(itemStack, world, player, mop, retString, layout);
@@ -30,6 +30,7 @@ import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkItem;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.bookmark.BookmarkPayload;
import codechicken.nei.bookmark.BookmarksGridSlot;
import codechicken.nei.recipe.AutoCraftingManager;
import codechicken.nei.recipe.GuiCraftingRecipe;
@@ -95,6 +96,11 @@ public abstract class ShortcutInputHandler {
return ItemPanels.bookmarkPanel.pullBookmarkItems(groupId, NEIClientUtils.shiftKey());
}
if (KeyManager.isKeyDown("bookmark.chat_link") && NEIClientUtils.controlKey()) {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(groupId).toNBT());
return true;
}
if (NEIClientConfig.autocraftingEnabled() && KeyManager.isKeyDown("gui.craft_items")
&& NEIClientUtils.shiftKey()
&& ItemPanels.bookmarkPanel.getGrid().isCraftingMode(groupId)) {
@@ -134,15 +140,15 @@ public abstract class ShortcutInputHandler {
return copyItemStackOreDictionary(stackover);
}
if (KeyManager.isHashDown("copy.chat_link_item", NEIClientUtils.CTRL_HASH)) {
return sendItemStackChatLink(stackover);
if (KeyManager.isKeyDown("bookmark.chat_link") && NEIClientUtils.controlKey()) {
return sendRecipeInChatLink(stackover, NEIClientUtils.shiftKey());
}
if (KeyManager.isHashDown("recipe.recipe")) {
if (KeyManager.isKeyDown("recipe.recipe")) {
return GuiCraftingRecipe.openRecipeGui("item", stackover);
}
if (KeyManager.isHashDown("recipe.usage")) {
if (KeyManager.isKeyDown("recipe.usage")) {
return GuiUsageRecipe.openRecipeGui("item", stackover);
}
@@ -198,10 +204,37 @@ public abstract class ShortcutInputHandler {
return true;
}
private static boolean sendItemStackChatLink(ItemStack stackover) {
if (stackover == null) return false;
private static boolean sendRecipeInChatLink(ItemStack stackover, boolean saveIngredients) {
final Point mousePos = GuiDraw.getMousePosition();
final BookmarksGridSlot slot = ItemPanels.bookmarkPanel.getSlotMouseOver(mousePos.x, mousePos.y);
NEIClientUtils.sendChatItemLink(stackover); // I wish clients could just send formatted messages
if (slot != null && saveIngredients && slot.getType() == BookmarkItemType.RESULT) {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(slot.getBookmarkItem()).toNBT());
return true;
}
final Recipe recipe = getFocusedRecipe(stackover, mousePos.x, mousePos.y, saveIngredients);
if (recipe != null && saveIngredients) {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(recipe).toNBT());
return true;
}
final RecipeId recipeId;
if (slot != null) {
recipeId = slot.getType() == BookmarkItemType.INGREDIENT ? null : slot.getRecipeId();
} else {
recipeId = recipe != null ? recipe.getRecipeId() : null;
}
final boolean existsRecipe = NEIClientConfig.getBooleanSetting("inventory.bookmarks.bookmarkItemsWithRecipe");
if (ItemPanels.itemPanel.containsWithSubpanels(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(stackover, existsRecipe ? recipeId : null).toNBT());
return true;
}
@@ -241,7 +274,7 @@ public abstract class ShortcutInputHandler {
if (slot.getGroup().crafting == null) {
final Recipe recipe = Recipe.of(slot.getRecipeId());
if (recipe != null) {
math = RecipeChainMath.of(recipe, Math.max(1, slot != null ? slot.getMultiplier() : 1));
math = RecipeChainMath.of(recipe, Math.max(1, slot.getMultiplier()));
}
} else {
math = ItemPanels.bookmarkPanel.getGrid()
@@ -408,7 +441,7 @@ public abstract class ShortcutInputHandler {
}
}
if (gui instanceof GuiRecipe guiRecipe) {
if (gui instanceof GuiRecipe<?>guiRecipe) {
recipe = guiRecipe.getFocusedRecipe();
}
@@ -449,6 +482,10 @@ public abstract class ShortcutInputHandler {
KeyManager.getKeyName("bookmark.remove_recipe", NEIClientUtils.SHIFT_HASH),
NEIClientUtils.translate("bookmark.group.remove_recipe"));
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.group.chat_link"));
if (BookmarkContainerInfo.getBookmarkContainerHandler(gui) != null) {
hotkeys.put(
KeyManager.getKeyName("bookmark.pull_items"),
@@ -579,9 +616,10 @@ public abstract class ShortcutInputHandler {
hotkeys.put(
KeyManager.getKeyName("copy.identifier", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.copy_id"));
hotkeys.put(
KeyManager.getKeyName("copy.chat_link_item", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("itempanel.chat_link_item"));
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.item.chat_link"));
if (!(gui instanceof GuiRecipe) && NEIClientConfig.canCheatItem(stack)) {
hotkeys.put(
@@ -639,6 +677,9 @@ public abstract class ShortcutInputHandler {
}
}
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("bookmark.recipe.chat_link"));
}
hotkeysCache.update(mousex, mousey, stack, groupId, hotkeys);
@@ -695,7 +736,7 @@ public abstract class ShortcutInputHandler {
return itemSlot.getRecipeId();
}
if (gui instanceof GuiRecipe guiRecipe) {
if (gui instanceof GuiRecipe<?>guiRecipe) {
final Recipe focusedRecipe = guiRecipe.getFocusedRecipe();
if (focusedRecipe != null) {
@@ -879,6 +879,16 @@ public class BookmarkGrid extends ItemsGrid<BookmarksGridSlot, BookmarkGrid.Book
return this.bookmarkItems.get(itemIndex);
}
public void replaceBookmarkItem(int itemIndex, BookmarkItem newItem) {
if (itemIndex < 0 || itemIndex >= this.bookmarkItems.size()) {
return;
}
this.bookmarkItems.set(itemIndex, newItem);
onItemsChanged();
}
public int getAbsoluteSlotIndex(int itemIndex) {
return this.gridGenerator.itemToSlot.getOrDefault(itemIndex, -1);
}
@@ -10,12 +10,16 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
public class BookmarkItem {
@@ -224,11 +228,15 @@ public class BookmarkItem {
final List<RecipeIngredient> items = type == BookmarkItemType.RESULT ? recipe.getResults()
: recipe.getIngredients();
final Builder builder = builder(groupId, stack).type(type).recipe(recipe);
final ItemStack emptyStack = StackInfo.withAmount(stack, 0);
long amount = 0;
for (RecipeIngredient res : items) {
if (res.contains(stack)) {
amount += 1L * res.getAmount() * res.getChance();
for (ItemStack perm : res.getPermutations()) {
if (NEIClientUtils.areStacksSameTypeWithNBT(emptyStack, StackInfo.withAmount(perm, 0))) {
amount += 1L * StackInfo.getAmount(perm) * res.getChance();
break;
}
}
}
@@ -245,6 +253,45 @@ public class BookmarkItem {
return builder(groupId, stack).build();
}
public static BookmarkItem of(JsonObject jsonObject) {
final NBTTagCompound itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject.get("item"));
final ItemStack itemStack = StackInfo.loadFromNBT(itemStackNBT);
if (itemStack != null) {
final int groupId = jsonObject.has("groupId") ? jsonObject.get("groupId").getAsInt()
: BookmarkGrid.DEFAULT_GROUP_ID;
final BookmarkItem.Builder builder = BookmarkItem.builder(groupId, itemStack);
if (jsonObject.has("type")) {
builder.type(BookmarkItemType.fromInt(jsonObject.get("type").getAsInt()));
} else if (jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean()) {
builder.type(BookmarkItemType.INGREDIENT);
} else {
builder.type(BookmarkItemType.RESULT);
}
if (jsonObject.has("multiplier")) {
builder.multiplier(jsonObject.get("multiplier").getAsInt());
}
if (jsonObject.has("factor")) {
builder.factor(jsonObject.get("factor").getAsInt());
}
if (jsonObject.has("chance")) {
builder.chance(jsonObject.get("chance").getAsInt());
}
if (jsonObject.get("recipeId") instanceof JsonObject recipeJson) {
builder.recipeId(RecipeId.of(recipeJson));
}
return builder.build();
}
return null;
}
public BookmarkItem copyWithMultiplier(long multiplier) {
return new BookmarkItem(
this.groupId,
@@ -265,6 +312,47 @@ public class BookmarkItem {
return copyWithMultiplier(this.multiplier);
}
public BookmarkItem copyWithPerm(ItemStack stack) {
if (this.recipeId != null
&& !NEIClientUtils.areStacksSameTypeWithNBT(StackInfo.withAmount(stack, 0), this.getItemStack(0))) {
final ItemStack oldPerm = findPermutation(this.itemStack);
final ItemStack newPerm = findPermutation(stack);
if (oldPerm != null && newPerm != null) {
final long oldAmount = StackInfo.getAmount(oldPerm);
final long amount = oldAmount > 0 ? this.factor * this.chance * StackInfo.getAmount(newPerm) / oldAmount
: 0;
final long factor = (amount % PositionedStack.CHANCE_FULL) == 0 ? amount / PositionedStack.CHANCE_FULL
: 1;
final long chance = factor == 1 ? amount : PositionedStack.CHANCE_FULL;
return new BookmarkItem(
this.groupId,
this.multiplier,
factor,
chance,
newPerm,
this.permutations,
this.recipeId,
this.type);
}
}
return copy();
}
private ItemStack findPermutation(ItemStack stack) {
for (ItemStack itemStack : this.permutations.values()) {
if (StackInfo.equalItemAndNBT(stack, itemStack, true)) {
return itemStack;
}
}
return null;
}
public boolean containsItems(BookmarkItem item) {
return this.permutations.keySet().stream().anyMatch(item.permutations::containsKey);
}
@@ -273,21 +361,47 @@ public class BookmarkItem {
return getAmount(this.multiplier);
}
public long getAmount(long multiplier, ItemStack perm) {
if (this.recipeId != null && perm != null
&& !NEIClientUtils.areStacksSameTypeWithNBT(StackInfo.withAmount(perm, 0), this.getItemStack(0))) {
final ItemStack oldPerm = findPermutation(this.itemStack);
final ItemStack newPerm = findPermutation(perm);
if (oldPerm != null && newPerm != null) {
final long oldAmount = StackInfo.getAmount(oldPerm);
final long amount = oldAmount > 0 ? this.factor * this.chance * StackInfo.getAmount(newPerm) / oldAmount
: 0;
final long factor = (amount % PositionedStack.CHANCE_FULL) == 0 ? amount / PositionedStack.CHANCE_FULL
: 1;
final long chance = factor == 1 ? amount : PositionedStack.CHANCE_FULL;
return getAmount(multiplier, factor, chance);
}
}
return getAmount(multiplier);
}
public long getAmount(long multiplier) {
long amount = this.factor * multiplier;
return getAmount(multiplier, this.factor, this.chance);
}
protected long getAmount(long multiplier, long factor, long chance) {
long amount = factor * multiplier;
if (this.fluidCellAmount > 1) {
amount = amount * this.fluidCellAmount;
}
if (this.chance != PositionedStack.CHANCE_FULL) {
if (chance != PositionedStack.CHANCE_FULL) {
if (this.type == BookmarkItemType.INGREDIENT) {
// For ingredients, round up the expected amount to be conservative.
amount = (amount * this.chance + PositionedStack.CHANCE_FULL - 1) / PositionedStack.CHANCE_FULL;
return (amount * chance + PositionedStack.CHANCE_FULL - 1) / PositionedStack.CHANCE_FULL;
} else {
// For results, round down the expected amount to be conservative.
amount = (amount * this.chance) / PositionedStack.CHANCE_FULL;
return (amount * chance) / PositionedStack.CHANCE_FULL;
}
}
@@ -364,4 +478,27 @@ public class BookmarkItem {
return false;
}
public JsonObject toJsonObject() {
final JsonObject jsonObject = new JsonObject();
jsonObject.add("item", NBTJson.toJsonObject(StackInfo.itemStackToNBT(getItemStack())));
jsonObject.add("multiplier", new JsonPrimitive(this.multiplier));
jsonObject.add("factor", new JsonPrimitive(this.factor));
jsonObject.add("type", new JsonPrimitive(this.type.toInt()));
if (this.groupId != BookmarkGrid.DEFAULT_GROUP_ID) {
jsonObject.add("groupId", new JsonPrimitive(this.groupId));
}
if (this.recipeId != null) {
jsonObject.add("recipeId", this.recipeId.toJsonObject());
}
if (this.chance != PositionedStack.CHANCE_FULL) {
jsonObject.add("chance", new JsonPrimitive(this.chance));
}
return jsonObject;
}
}
@@ -0,0 +1,283 @@
package codechicken.nei.bookmark;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import com.google.gson.JsonObject;
import codechicken.lib.gui.GuiDraw;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.ItemPanels;
import codechicken.nei.ItemQuantityField;
import codechicken.nei.ItemStackSet;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.Recipe.RecipeIngredient;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
public class BookmarkPayload {
private String linkType;
private NBTTagCompound target;
private NBTTagCompound group;
private NBTTagList items = new NBTTagList();
private NBTTagList recipes = new NBTTagList();
private BookmarkPayload(String linkType, ItemStack stack) {
this.linkType = linkType;
this.target = stack != null ? StackInfo.itemStackToNBT(stack) : null;
}
public static BookmarkPayload of(NBTTagCompound nbt) {
final BookmarkPayload payload = new BookmarkPayload(nbt.getString("linkType"), null);
if (nbt.hasKey("item")) {
payload.target = nbt.getCompoundTag("item");
}
if (nbt.hasKey("group")) {
payload.group = nbt.getCompoundTag("group");
}
payload.items = nbt.getTagList("items", 10);
payload.recipes = nbt.getTagList("recipes", 10);
return payload;
}
public static BookmarkPayload of(BookmarkItem item) {
final BookmarkPayload payload = new BookmarkPayload("recipe", item.getItemStack());
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final RecipeId recipeId = item.recipeId;
final int groupId = item.groupId;
payload.items = new NBTTagList();
payload.recipes = new NBTTagList();
if (recipeId != null) {
for (int itemIndex = 0; itemIndex < grid.size(); itemIndex++) {
final BookmarkItem currentItem = grid.getBookmarkItem(itemIndex);
if (currentItem != null && currentItem.groupId == groupId && recipeId.equals(currentItem.recipeId)) {
addBookmarkItemToPayload(payload, currentItem, recipesIndexes);
}
}
} else {
addBookmarkItemToPayload(payload, item, recipesIndexes);
}
return payload;
}
public static BookmarkPayload of(Recipe recipe) {
final BookmarkPayload payload = new BookmarkPayload("recipe", recipe.getResult());
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final ItemStackSet seenIngredients = new ItemStackSet();
final ItemStackSet seenResults = new ItemStackSet();
for (RecipeIngredient result : recipe.getResults()) {
ItemStack stack = result.getItemStack();
if (!seenResults.contains(stack)) {
final BookmarkItem item = BookmarkItem.builder(-1, stack, recipe, BookmarkItemType.RESULT).build();
addBookmarkItemToPayload(payload, item, recipesIndexes);
seenResults.add(stack);
}
}
for (RecipeIngredient ingr : recipe.getIngredients()) {
ItemStack stack = ingr.getItemStack();
if (!seenIngredients.contains(stack)) {
final BookmarkItem item = BookmarkItem.builder(-1, stack, recipe, BookmarkItemType.INGREDIENT).build();
addBookmarkItemToPayload(payload, item, recipesIndexes);
seenIngredients.add(stack);
}
}
return payload;
}
public static BookmarkPayload of(int groupId) {
final BookmarkPayload payload = new BookmarkPayload("group", null);
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
for (int itemIndex = 0; itemIndex < grid.size(); itemIndex++) {
final BookmarkItem item = grid.getBookmarkItem(itemIndex);
if (item != null && item.groupId == groupId) {
addBookmarkItemToPayload(payload, item, recipesIndexes);
}
}
payload.group = generateGroup(grid.getGroup(groupId));
return payload;
}
public static BookmarkPayload of(ItemStack stackover, RecipeId recipeId) {
final BookmarkPayload payload = new BookmarkPayload("item", stackover);
final Map<RecipeId, Integer> recipesIndexes = new HashMap<>();
final Point mousePos = GuiDraw.getMousePosition();
if (ItemPanels.itemPanel.containsWithSubpanels(mousePos.x, mousePos.y)) {
stackover = ItemQuantityField.prepareStackWithQuantity(stackover, 0);
}
final BookmarkItem item = BookmarkItem.builder(-1, stackover).recipeId(recipeId).type(BookmarkItemType.ITEM)
.build();
addBookmarkItemToPayload(payload, item, recipesIndexes);
return payload;
}
private static NBTTagCompound generateGroup(BookmarkGroup group) {
final NBTTagCompound groupTag = new NBTTagCompound();
final NBTTagList collapsedRecipes = new NBTTagList();
groupTag.setString("viewmode", group.viewMode.toString());
groupTag.setBoolean("crafting", group.crafting != null);
groupTag.setBoolean("collapsed", group.collapsed);
for (RecipeId recipeId : group.collapsedRecipes) {
collapsedRecipes.appendTag(NBTJson.toNbt(recipeId.toJsonObject()));
}
groupTag.setTag("collapsedRecipes", collapsedRecipes);
return groupTag;
}
private static void addBookmarkItemToPayload(BookmarkPayload payload, BookmarkItem item,
Map<RecipeId, Integer> recipesIndexes) {
final JsonObject itemTag = item.toJsonObject();
itemTag.remove("groupId");
if (item.recipeId != null) {
final int recipeIndex = recipesIndexes
.computeIfAbsent(item.recipeId, recipeId -> addRecipeToPayload(payload, recipeId, recipesIndexes));
itemTag.addProperty("recipeId", recipeIndex);
}
payload.items.appendTag(NBTJson.toNbt(itemTag));
}
private static int addRecipeToPayload(BookmarkPayload payload, RecipeId recipeId,
Map<RecipeId, Integer> recipesIndexes) {
final NBTTagCompound recipeTag = new NBTTagCompound();
final int recipeIndex = payload.recipes.tagCount();
recipeTag.setTag("recipeId", NBTJson.toNbt(recipeId.toJsonObject()));
recipeTag.setInteger("recipeIndex", recipeIndex);
payload.recipes.appendTag(recipeTag);
return recipeIndex;
}
public NBTTagCompound toNBT() {
final NBTTagCompound payloadTag = new NBTTagCompound();
payloadTag.setString("linkType", linkType);
if (target != null) {
payloadTag.setTag("item", target);
}
if (group != null) {
payloadTag.setTag("group", group);
}
payloadTag.setTag("items", items);
payloadTag.setTag("recipes", recipes);
return payloadTag;
}
public String getLinkType() {
return this.linkType;
}
public ItemStack getTargetStack() {
return this.target != null ? StackInfo.loadFromNBT(this.target) : null;
}
public BookmarkGroup getGroup() {
if (this.group == null) {
return null;
}
final boolean crafting = this.group.hasKey("crafting") && this.group.getBoolean("crafting");
final BookmarkViewMode viewMode;
if (this.group.hasKey("viewmode")) {
viewMode = BookmarkViewMode.valueOf(this.group.getString("viewmode"));
} else {
viewMode = BookmarkViewMode.TODO_LIST;
}
final BookmarkGroup group = new BookmarkGroup(viewMode, crafting);
if (this.group.hasKey("collapsed")) {
group.collapsed = this.group.getBoolean("collapsed");
}
if (this.group.hasKey("collapsedRecipes")) {
final NBTTagList collapsedRecipes = this.group.getTagList("collapsedRecipes", 10);
for (int i = 0; i < collapsedRecipes.tagCount(); i++) {
final NBTTagCompound recipeTag = collapsedRecipes.getCompoundTagAt(i);
final RecipeId recipeId = RecipeId.of((JsonObject) NBTJson.toJsonObject(recipeTag));
group.collapsedRecipes.add(recipeId);
}
}
return group;
}
public List<BookmarkItem> getBookmarkItems(int groupId) {
final List<BookmarkItem> bookmarkItems = new ArrayList<>();
final Map<Integer, RecipeId> recipesMap = new HashMap<>();
for (int i = 0; i < recipes.tagCount(); i++) {
final NBTTagCompound recipeTag = recipes.getCompoundTagAt(i);
final RecipeId recipeId = RecipeId
.of((JsonObject) NBTJson.toJsonObject(recipeTag.getCompoundTag("recipeId")));
recipesMap.put(recipeTag.getInteger("recipeIndex"), recipeId);
}
for (int i = 0; i < items.tagCount(); i++) {
final NBTTagCompound itemTag = items.getCompoundTagAt(i);
RecipeId recipeId = null;
if (itemTag.hasKey("recipeId")) {
recipeId = recipesMap.get(itemTag.getInteger("recipeId"));
itemTag.removeTag("recipeId");
}
final BookmarkItem item = BookmarkItem.of((JsonObject) NBTJson.toJsonObject(itemTag));
if (item != null) {
item.groupId = groupId;
item.recipeId = recipeId;
bookmarkItems.add(item);
}
}
return bookmarkItems;
}
}
@@ -10,7 +10,6 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.io.IOUtils;
@@ -25,10 +24,7 @@ import com.google.gson.JsonSyntaxException;
import codechicken.nei.BookmarkPanel.BookmarkViewMode;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.PositionedStack;
import codechicken.nei.bookmark.BookmarkItem.BookmarkItemType;
import codechicken.nei.recipe.Recipe.RecipeId;
import codechicken.nei.recipe.StackInfo;
import codechicken.nei.util.NBTJson;
public class BookmarkStorage {
@@ -199,7 +195,11 @@ public class BookmarkStorage {
continue;
}
if (!addItemToGrid(grid, parser.parse(itemStr).getAsJsonObject())) {
final BookmarkItem item = BookmarkItem.of(parser.parse(itemStr).getAsJsonObject());
if (item != null) {
grid.addItem(item, false);
} else {
wasError = true;
NEIClientConfig.logger.warn(
"Failed to load bookmarked ItemStack from json string, the item no longer exists:\n{}",
@@ -238,53 +238,6 @@ public class BookmarkStorage {
this.bookmarkFile = bookmarkFile;
}
private boolean addItemToGrid(BookmarkGrid grid, JsonObject jsonObject) {
NBTTagCompound itemStackNBT;
if (jsonObject.get("item") != null) {
itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject.get("item"));
} else { // old format
itemStackNBT = (NBTTagCompound) NBTJson.toNbt(jsonObject);
}
ItemStack itemStack = StackInfo.loadFromNBT(itemStackNBT);
if (itemStack != null) {
int groupId = jsonObject.has("groupId") && grid.groups.containsKey(jsonObject.get("groupId").getAsInt())
? jsonObject.get("groupId").getAsInt()
: BookmarkGrid.DEFAULT_GROUP_ID;
final BookmarkItem.Builder builder = BookmarkItem.builder(groupId, itemStack);
if (jsonObject.has("type")) {
builder.type(BookmarkItemType.fromInt(jsonObject.get("type").getAsInt()));
} else if (jsonObject.has("ingredient") && jsonObject.get("ingredient").getAsBoolean()) {
builder.type(BookmarkItemType.INGREDIENT);
} else {
builder.type(BookmarkItemType.RESULT);
}
if (jsonObject.has("multiplier")) {
builder.multiplier(jsonObject.get("multiplier").getAsInt());
}
if (jsonObject.has("factor")) {
builder.factor(jsonObject.get("factor").getAsInt());
}
if (jsonObject.has("chance")) {
builder.chance(jsonObject.get("chance").getAsInt());
}
if (jsonObject.get("recipeId") instanceof JsonObject recipeJson) {
builder.recipeId(RecipeId.of(recipeJson));
}
grid.addItem(builder.build(), false);
}
return itemStack != null;
}
public void save() {
if (this.bookmarkFile == null) {
@@ -325,26 +278,7 @@ public class BookmarkStorage {
for (BookmarkItem item : grid.bookmarkItems) {
try {
JsonObject row = new JsonObject();
row.add("item", NBTJson.toJsonObject(StackInfo.itemStackToNBT(item.getItemStack())));
row.add("multiplier", new JsonPrimitive(item.multiplier));
row.add("factor", new JsonPrimitive(item.factor));
row.add("type", new JsonPrimitive(item.type.toInt()));
if (item.groupId != BookmarkGrid.DEFAULT_GROUP_ID) {
row.add("groupId", new JsonPrimitive(item.groupId));
}
if (item.recipeId != null) {
row.add("recipeId", item.recipeId.toJsonObject());
}
if (item.chance != PositionedStack.CHANCE_FULL) {
row.add("chance", new JsonPrimitive(item.chance));
}
strings.add(NBTJson.toJson(row));
strings.add(NBTJson.toJson(item.toJsonObject()));
} catch (JsonSyntaxException e) {
NEIClientConfig.logger.error("Failed to stringify bookmarked ItemStack to json string");
}
@@ -193,7 +193,7 @@ public class BookmarksGridSlot extends ItemsGridSlot {
protected HandlerInfo getHandlerInfo() {
if (this.bookmarkItem.recipeId != null && this.handlerInfo == null) {
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.bookmarkItem.recipeId.getHandleName(), null);
this.handlerInfo = GuiRecipeTab.getHandlerInfo(this.bookmarkItem.recipeId.getHandlerName(), null);
}
return this.handlerInfo;
}
@@ -1,5 +1,7 @@
package codechicken.nei.bookmark;
import static codechicken.nei.bookmark.BookmarkGrid.DEFAULT_GROUP_ID;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
@@ -139,13 +141,11 @@ public class SortableItem {
return;
}
if (overGroupId != BookmarkGrid.DEFAULT_GROUP_ID
&& beforeGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
beforeGroupId = BookmarkGrid.DEFAULT_GROUP_ID;
if (overGroupId != DEFAULT_GROUP_ID && beforeGroupId != DEFAULT_GROUP_ID) {
beforeGroupId = DEFAULT_GROUP_ID;
}
if (overGroupId == BookmarkGrid.DEFAULT_GROUP_ID && beforeGroupId != BookmarkGrid.DEFAULT_GROUP_ID
&& afterGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
if (overGroupId == DEFAULT_GROUP_ID && afterGroupId != DEFAULT_GROUP_ID) {
return;
}
@@ -160,12 +160,11 @@ public class SortableItem {
return;
}
if (overGroupId != BookmarkGrid.DEFAULT_GROUP_ID && afterGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
afterGroupId = BookmarkGrid.DEFAULT_GROUP_ID;
if (overGroupId != DEFAULT_GROUP_ID && afterGroupId != DEFAULT_GROUP_ID) {
afterGroupId = DEFAULT_GROUP_ID;
}
if (overGroupId == BookmarkGrid.DEFAULT_GROUP_ID && beforeGroupId != BookmarkGrid.DEFAULT_GROUP_ID
&& afterGroupId != BookmarkGrid.DEFAULT_GROUP_ID) {
if (overGroupId == DEFAULT_GROUP_ID && beforeGroupId != DEFAULT_GROUP_ID) {
return;
}
@@ -1,18 +1,39 @@
package codechicken.nei.commands;
import java.util.Arrays;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import codechicken.nei.ItemPanels;
import codechicken.nei.LRUCache;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkGroup;
import codechicken.nei.bookmark.BookmarkPayload;
public class CommandBookmarkAdd extends CommandBase {
private static final LRUCache<String, NBTTagCompound> PAYLOAD_CACHE = new LRUCache<>(64);
public static void cachePayload(String payloadId, NBTTagCompound payload) {
if (payloadId == null || payloadId.isEmpty() || payload == null) {
return;
}
synchronized (PAYLOAD_CACHE) {
PAYLOAD_CACHE.put(payloadId, (NBTTagCompound) payload.copy());
}
}
private static NBTTagCompound getCachedPayload(String payloadId) {
synchronized (PAYLOAD_CACHE) {
return PAYLOAD_CACHE.get(payloadId);
}
}
@Override
public String getCommandName() {
return "nei_bookmark";
@@ -20,7 +41,7 @@ public class CommandBookmarkAdd extends CommandBase {
@Override
public String getCommandUsage(ICommandSender sender) {
return "/nei_bookmark <nbt>";
return "/nei_bookmark <payloadId>";
}
@Override
@@ -30,19 +51,37 @@ public class CommandBookmarkAdd extends CommandBase {
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length < 1 || args[0].length() < 3) {
sender.addChatMessage(new ChatComponentText("§c/nei_bookmark <nbt>"));
if (args.length < 1) {
sender.addChatMessage(new ChatComponentText("§c/nei_bookmark <payloadId>"));
return;
}
try {
ItemPanels.bookmarkPanel.addItem(
ItemStack.loadItemStackFromNBT((NBTTagCompound) JsonToNBT.func_150315_a(String.join(" ", args))));
final String payloadId = String.join(" ", Arrays.copyOfRange(args, 0, args.length));
final NBTTagCompound payload = getCachedPayload(payloadId);
if (payload == null) {
throw new IllegalArgumentException("Missing cached payload");
}
addBookmarkFromPayload((NBTTagCompound) payload.copy());
sender.addChatMessage(new ChatComponentTranslation("nei.chat.bookmark_added.text"));
} catch (NBTException e) {
} catch (Exception e) {
sender.addChatMessage(new ChatComponentText(e.toString()));
}
}
private static void addBookmarkFromPayload(NBTTagCompound nbt) {
final BookmarkPayload payload = BookmarkPayload.of(nbt);
final BookmarkGrid grid = ItemPanels.bookmarkPanel.getGrid();
final BookmarkGroup group = payload.getGroup();
int groupId = BookmarkGrid.DEFAULT_GROUP_ID;
if (group != null) {
groupId = grid.addGroup(group);
}
payload.getBookmarkItems(groupId).forEach(item -> grid.addItem(item, true));
}
}
@@ -17,7 +17,6 @@ import codechicken.nei.recipe.GuiRecipeTab;
import codechicken.nei.recipe.GuiUsageRecipe;
import codechicken.nei.recipe.HandlerInfo;
import codechicken.nei.recipe.IRecipeHandler;
import codechicken.nei.recipe.TemplateRecipeHandler;
import codechicken.nei.util.NBTJson;
public class HandlerDumper extends DataDumper {
@@ -37,10 +36,7 @@ public class HandlerDumper extends DataDumper {
LinkedList<String[]> list = new LinkedList<>();
for (IRecipeHandler handler : GuiUsageRecipe.usagehandlers) {
final String handlerName = handler.getHandlerId();
final String handlerId = Objects.firstNonNull(
handler instanceof TemplateRecipeHandler ? ((TemplateRecipeHandler) handler).getOverlayIdentifier()
: null,
"null");
final String handlerId = Objects.firstNonNull(handler.getOverlayIdentifier(), "null");
HandlerInfo info = GuiRecipeTab.getHandlerInfo(handlerName, handlerId);
list.add(
@@ -85,11 +85,11 @@ public class RightPanel extends GuiWidget {
setFocus(true);
}
if (focused() && KeyManager.isHashDown("gui.getprevioussearch")) {
if (focused() && KeyManager.isKeyDown("gui.getprevioussearch")) {
handleNavigateHistory(TextHistory.Direction.PREVIOUS);
}
if (focused() && KeyManager.isHashDown("gui.getnextsearch")) {
if (focused() && KeyManager.isKeyDown("gui.getnextsearch")) {
handleNavigateHistory(TextHistory.Direction.NEXT);
}
}
@@ -625,7 +625,7 @@ public class GuiContainerManager {
tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE);
}
} else if (!tooltip.isEmpty()) {
} else if (!tooltip.isEmpty() && !tooltip.get(0).startsWith(GuiDraw.TOOLTIP_HANDLER)) {
tooltip.set(0, tooltip.get(0) + GuiDraw.TOOLTIP_LINESPACE);
}
@@ -64,7 +64,7 @@ public class BookmarkRecipeId {
return false;
}
Short idx = 0;
short idx = 0;
for (PositionedStack pStack : stacks) {
final NBTTagCompound tagCompoundA = StackInfo
@@ -123,8 +123,7 @@ public class BookmarkRecipeId {
return true;
}
if (anObject instanceof BookmarkRecipeId) {
final BookmarkRecipeId anRecipeId = (BookmarkRecipeId) anObject;
if (anObject instanceof BookmarkRecipeId anRecipeId) {
if (!handlerName.equals(anRecipeId.handlerName)) {
return false;
@@ -13,7 +13,7 @@ public class BrewingOverlayHandler extends DefaultOverlayHandler {
public Slot[][] mapIngredSlots(GuiContainer gui, List<PositionedStack> ingredients) {
Slot[][] map = super.mapIngredSlots(gui, ingredients);
Slot[] potSlots = new Slot[3];
for (int i = 0; i < 3; i++) potSlots[i] = (Slot) gui.inventorySlots.inventorySlots.get(i);
for (int i = 0; i < 3; i++) potSlots[i] = gui.inventorySlots.inventorySlots.get(i);
map[1] = potSlots;
return map;
}
@@ -210,7 +210,7 @@ public class DefaultOverlayHandler implements IOverlayHandler {
for (IngredientDistribution distrib : assignedIngredients) {
if (distrib.slots.length == 0 || !slot.getHasStack() || !canStack(distrib.permutation, stack)) continue;
int transferCap = Math.min(slotTransferCap, multiplier * distrib.permutation.stackSize);
int transferCap = Math.min(slotTransferCap, Math.max(multiplier * distrib.permutation.stackSize, 1));
int stackSize = slot.getStack().stackSize;
boolean pickup = false;
@@ -53,8 +53,7 @@ public class FuelRecipeHandler extends FurnaceRecipeHandler {
private void loadAllSmelting() {
// Note: Not safe as written for parallelStream
final Map<ItemStack, ItemStack> smeltingRecipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting()
.getSmeltingList();
final Map<ItemStack, ItemStack> smeltingRecipes = FurnaceRecipes.smelting().getSmeltingList();
smeltingRecipes.entrySet().stream().map(recipe -> new SmeltingPair(recipe.getKey(), recipe.getValue()))
.collect(Collectors.toCollection(() -> mfurnace));
}
@@ -84,7 +84,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
public void loadCraftingRecipes(String outputId, Object... results) {
if (outputId.equals("smelting") && getClass() == FurnaceRecipeHandler.class) { // don't want subclasses getting
// a hold of this
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
arecipes.add(new SmeltingPair(recipe.getKey(), recipe.getValue()));
} else super.loadCraftingRecipes(outputId, results);
@@ -92,7 +92,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadCraftingRecipes(ItemStack result) {
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
if (NEIServerUtils.areStacksSameType(recipe.getValue(), result))
arecipes.add(new SmeltingPair(recipe.getKey(), recipe.getValue()));
@@ -108,7 +108,7 @@ public class FurnaceRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadUsageRecipes(ItemStack ingredient) {
Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList();
Map<ItemStack, ItemStack> recipes = FurnaceRecipes.smelting().getSmeltingList();
for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet())
if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getKey(), ingredient)) {
SmeltingPair arecipe = new SmeltingPair(recipe.getKey(), recipe.getValue());
@@ -82,8 +82,8 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
} else if ("recipeId".equals(outputId)) {
ItemStack stack = (ItemStack) results[0];
RecipeId recipeId = (RecipeId) results[1];
craftinghandlers = filterByHandlerName(craftinghandlers, recipeId.getHandleName());
serialCraftingHandlers = filterByHandlerName(serialCraftingHandlers, recipeId.getHandleName());
craftinghandlers = filterByHandlerName(craftinghandlers, recipeId.getHandlerName());
serialCraftingHandlers = filterByHandlerName(serialCraftingHandlers, recipeId.getHandlerName());
recipeHandlerFunction = h -> h.getRecipeHandler("item", stack);
} else {
recipeHandlerFunction = h -> h.getRecipeHandler(outputId, results);
@@ -119,7 +119,7 @@ public class GuiCraftingRecipe extends GuiRecipe<ICraftingHandler> {
public static RecipeId getRecipeId(GuiScreen gui, ItemStack stackover) {
if (gui instanceof GuiRecipe guiRecipe) {
if (gui instanceof GuiRecipe<?>guiRecipe) {
final Recipe focusedRecipe = guiRecipe.getFocusedRecipe();
if (focusedRecipe != null) {
@@ -155,11 +155,16 @@ public class GuiFavoriteButton extends GuiRecipeButton {
if (this.selectedResult == null) return;
NEIClientUtils.gl2DRenderContext(
() -> GuiDraw.drawRect(this.selectedResult.relx, this.selectedResult.rely, 16, 16, 0x66333333));
() -> GuiDraw.drawRect(
this.selectedResult.relx,
this.selectedResult.rely,
this.selectedResult.width,
this.selectedResult.height,
0x66333333));
final Image icon = isFavorite() ? ICON_STATE_ON : ICON_STATE_OFF;
final int iconX = this.selectedResult.relx + (16 - icon.width) / 2;
final int iconY = this.selectedResult.rely + (18 - icon.height) / 2;
final int iconX = this.selectedResult.relx + (this.selectedResult.width - icon.width) / 2;
final int iconY = this.selectedResult.rely + (this.selectedResult.height + 2 - icon.height) / 2;
LayoutManager.drawIcon(iconX, iconY, icon);
}
@@ -230,7 +235,7 @@ public class GuiFavoriteButton extends GuiRecipeButton {
}
}
if (recipeId != null && FavoriteRecipes.FAVORITE_ITEM.contains(recipeId.getHandleName())) {
if (recipeId != null && FavoriteRecipes.FAVORITE_ITEM.contains(recipeId.getHandlerName())) {
items.add(stack);
} else {
Recipe recipe = Recipe.of(recipeId);
@@ -22,6 +22,7 @@ import codechicken.nei.NEIClientUtils;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.IOverlayHandler;
import codechicken.nei.bookmark.BookmarkGrid;
import codechicken.nei.bookmark.BookmarkPayload;
import codechicken.nei.drawable.DrawableBuilder;
import codechicken.nei.drawable.DrawableResource;
import codechicken.nei.util.NEIMouseUtils;
@@ -171,6 +172,10 @@ public class GuiOverlayButton extends GuiRecipeButton {
KeyManager.getKeyName("bookmark.add", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("recipe.overlay.bookmarkRecipeAndCount"));
hotkeys.put(
KeyManager.getKeyName("bookmark.chat_link", NEIClientUtils.SHIFT_HASH + NEIClientUtils.CTRL_HASH),
NEIClientUtils.translate("recipe.overlay.sendRecipeToChat"));
return hotkeys;
}
@@ -329,6 +334,10 @@ public class GuiOverlayButton extends GuiRecipeButton {
if (KeyManager.isKeyDown("bookmark.add") && NEIClientUtils.shiftKey()) {
saveRecipeInBookmark();
}
if (KeyManager.isKeyDown("bookmark.chat_link") && NEIClientUtils.controlKey() && NEIClientUtils.shiftKey()) {
sendRecipeChatLink();
}
}
public void saveRecipeInBookmark() {
@@ -343,4 +352,7 @@ public class GuiOverlayButton extends GuiRecipeButton {
}
}
private void sendRecipeChatLink() {
NEIClientUtils.sendChatItemLink(BookmarkPayload.of(getRecipe()).toNBT());
}
}
@@ -34,6 +34,8 @@ import codechicken.nei.PositionedStack;
import codechicken.nei.RecipeSearchField;
import codechicken.nei.RestartableTask;
import codechicken.nei.SearchField;
import codechicken.nei.SearchTokenParser.ISearchParserProvider;
import codechicken.nei.SearchTokenParser.SearchMode;
import codechicken.nei.VisiblityData;
import codechicken.nei.Widget;
import codechicken.nei.api.IGuiContainerOverlay;
@@ -54,6 +56,8 @@ import codechicken.nei.scroll.ScrollBar;
import codechicken.nei.scroll.ScrollBar.OverflowType;
import codechicken.nei.scroll.ScrollBar.ScrollPlace;
import codechicken.nei.scroll.ScrollContainer;
import codechicken.nei.search.SearchExpressionUtils;
import codechicken.nei.util.EmptyContainer;
import codechicken.nei.util.SlotInaccessible;
public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer implements IGuiContainerOverlay,
@@ -172,6 +176,59 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
return true;
}
@Override
public void addTooltips(List<String> tooltip) {
tooltip.add(NEIClientUtils.translate("recipe.search.tooltip.name") + GuiDraw.TOOLTIP_LINESPACE);
if (NEIClientUtils.shiftKey()) {
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.input",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + "<"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.output",
SearchExpressionUtils.HIGHLIGHTS.RECIPE + ">"));
for (ISearchParserProvider provider : SearchField.searchParser.getProviders()) {
if (provider.getSearchMode() == SearchMode.PREFIX) {
addPrefixTooltip(tooltip, provider);
}
}
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exclude",
SearchExpressionUtils.HIGHLIGHTS.NEGATE + "-"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exclude_recipe",
SearchExpressionUtils.HIGHLIGHTS.NEGATE + "!"));
tooltip.add(
NEIClientUtils
.translate("recipe.search.tooltip.or", SearchExpressionUtils.HIGHLIGHTS.OR.f + "|"));
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.exact",
SearchExpressionUtils.HIGHLIGHTS.QUOTED + "\"",
SearchExpressionUtils.HIGHLIGHTS.QUOTED + "\""));
} else {
tooltip.add(NEIClientUtils.translate("recipe.search.tooltip.shift"));
}
}
private void addPrefixTooltip(List<String> tooltip, ISearchParserProvider provider) {
final char prefix = SearchField.searchParser.getRedefinedPrefix(provider.getPrefix());
final String modeName = NEIClientUtils.translate("recipe.search.tooltip.prefix." + provider.getName());
tooltip.add(
NEIClientUtils.translate(
"recipe.search.tooltip.prefix",
provider.getHighlightedColor() + String.valueOf(prefix),
modeName));
}
};
/**
@@ -181,7 +238,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
private boolean isHeightHackApplied = false;
protected GuiRecipe(GuiScreen prevgui) {
super(new ContainerRecipe());
super(new EmptyContainer());
this.recipeTabs = new GuiRecipeTabs() {
@Override
@@ -191,7 +248,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
};
this.recipeCatalyst = new GuiRecipeCatalyst();
this.slotcontainer = (ContainerRecipe) this.inventorySlots;
this.slotcontainer = (EmptyContainer) this.inventorySlots;
this.prevGui = prevgui;
this.firstGuiGeneral = prevgui;
@@ -476,7 +533,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
final H localHandler = this.currenthandlers.get(j);
final HandlerInfo localHandlerInfo = GuiRecipeTab.getHandlerInfo(localHandler);
if (localHandlerInfo.getHandlerName().equals(this.recipeId.getHandleName())) {
if (localHandlerInfo.getHandlerName().equals(this.recipeId.getHandlerName())) {
recipetype = j;
if (!this.recipeId.getIngredients().isEmpty()) {
@@ -526,7 +583,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
@Override
public Slot getSlotAtPosition(int mousex, int mousey) {
final Widget activeWidget = this.container.getWidgetUnderMouse(mousex, mousey);
final ContainerRecipe slotcontainer = (ContainerRecipe) inventorySlots;
final EmptyContainer slotcontainer = (EmptyContainer) inventorySlots;
slotcontainer.setActiveStack(null);
if (activeWidget instanceof NEIRecipeWidget recipeWidget) {
@@ -759,6 +816,10 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
this.recipeTabs.handleTooltip(mousex, mousey, currenttip);
if (this.handler != null && this.handler.searchingAvailable()) {
currenttip = GuiRecipe.toggleSearch.handleTooltip(mousex, mousey, currenttip);
}
if (currenttip.isEmpty() && isHandlerTitleHovered(mousex, mousey)) {
currenttip.add(NEIClientUtils.translate("recipe.tab.view_all.tooltip"));
}
@@ -1022,7 +1083,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
final int curRecipe = indices.isEmpty() ? 0 : indices.get(0);
final Recipe recipe = Recipe.of(gRecipe.handler.original, curRecipe);
return recipe != null ? recipe.getRecipeId() : null;
return recipe.getRecipeId();
}
return null;
@@ -1033,7 +1094,7 @@ public abstract class GuiRecipe<H extends IRecipeHandler> extends GuiContainer i
private GuiOverlayButton[] overlayButtons = new GuiOverlayButton[0];
@Deprecated
public ContainerRecipe slotcontainer;
public EmptyContainer slotcontainer;
@Deprecated
public List<GuiButton> getOverlayButtons() {
@@ -223,7 +223,7 @@ public class NEIRecipeWidget extends Widget {
button -> (this.showAsWidget ? button instanceof GuiOverlayButton : button.contains(mouseX, mouseY))
? button
: null,
(GuiRecipeButton) null);
null);
if (overlayButton != null) {
NEIClientUtils.gl2DRenderContext(() -> overlayButton.drawItemOverlay());
@@ -247,14 +247,15 @@ public class NEIRecipeWidget extends Widget {
}
protected void drawItem(PositionedStack pStack, int mouseX, int mouseY, int yShift, boolean input) {
GuiContainerManager.drawItem(pStack.relx, pStack.rely, pStack.item);
pStack.draw(mouseX - this.x, mouseY - this.y - yShift);
if (this.handlerInfo.getShowBadge()) {
drawBadge(pStack, input);
}
if (pStack.contains(mouseX - this.x, mouseY - this.y - yShift)) {
NEIClientUtils.gl2DRenderContext(() -> GuiDraw.drawRect(pStack.relx, pStack.rely, 16, 16, 0x80FFFFFF));
NEIClientUtils.gl2DRenderContext(
() -> GuiDraw.drawRect(pStack.relx, pStack.rely, pStack.width, pStack.height, 0x80FFFFFF));
}
}
@@ -291,7 +292,7 @@ public class NEIRecipeWidget extends Widget {
final List<Badge> badges = getBadges(pStack, input);
for (Badge badge : badges) {
badge.draw(new Rectangle4i(pStack.relx, pStack.rely, 16, 16));
badge.draw(new Rectangle4i(pStack.relx, pStack.rely, pStack.width, pStack.height));
}
}
@@ -409,14 +410,22 @@ public class NEIRecipeWidget extends Widget {
if (itemstack != null) {
final PositionedStack hovered = getPositionedStackMouseOver(mousex, mousey);
if (hovered != null && this.handlerInfo.getShowBadge()) {
final List<Badge> badges = getBadges(hovered, getOutputs().indexOf(hovered) == -1);
if (hovered != null) {
if (this.handlerInfo.getShowBadge()) {
final List<Badge> badges = getBadges(hovered, getOutputs().indexOf(hovered) == -1);
for (Badge badge : badges) {
if (badge.getTooltip() != null && !badge.getTooltip().isEmpty()) {
tooltip.addAll(badge.getTooltip());
for (Badge badge : badges) {
if (badge.getTooltip() != null && !badge.getTooltip().isEmpty()) {
tooltip.addAll(badge.getTooltip());
}
}
}
final List<String> customTooltip = hovered.getTooltip();
if (customTooltip != null && !customTooltip.isEmpty()) {
tooltip.addAll(customTooltip);
}
}
if (hovered == null || !NEIClientConfig.showCycledIngredientsTooltip()
@@ -168,7 +168,7 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
private boolean isHandlerTitleHovered(int recipe, Point mouse) {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe guiRecipe) {
if (guiContainer instanceof GuiRecipe<?>guiRecipe) {
final Point recipePosition = guiRecipe.getRecipePosition(recipe);
return new Rectangle(recipePosition.x, recipePosition.y, WIDTH, 16)
.contains(mouse.x - guiContainer.guiLeft, mouse.y - guiContainer.guiTop);
@@ -250,7 +250,7 @@ public class ProfilerRecipeHandler implements ICraftingHandler, IUsageHandler {
if (r.handler != null) {
final GuiContainer guiContainer = NEIClientUtils.getGuiContainer();
if (guiContainer instanceof GuiRecipe guiRecipe) {
if (guiContainer instanceof GuiRecipe<?>guiRecipe) {
int index = guiRecipe.currenthandlers.indexOf(r.handler);
if (index != -1) {
@@ -89,7 +89,7 @@ public class Recipe {
return new RecipeId(result, handlerName, ingredients);
}
public String getHandleName() {
public String getHandlerName() {
return this.handlerName;
}
@@ -288,13 +288,18 @@ public class Recipe {
protected int relx;
protected int rely;
protected int width;
protected int height;
public RecipeIngredient(int relx, int rely, List<ItemStack> items, int chance, int activeIndex) {
public RecipeIngredient(int relx, int rely, int width, int height, List<ItemStack> items, int chance,
int activeIndex) {
this.items = items.stream().map(ItemStack::copy).toArray(size -> new ItemStack[size]);
this.amount = StackInfo.getAmount(this.items[activeIndex]);
this.activeIndex = activeIndex;
this.relx = relx;
this.rely = rely;
this.width = width;
this.height = height;
this.chance = chance;
}
@@ -314,11 +319,19 @@ public class Recipe {
}
}
return of(positionedStack.relx, positionedStack.rely, stacks, positionedStack.getChance(), activeIndex);
return of(
positionedStack.relx,
positionedStack.rely,
positionedStack.width,
positionedStack.height,
stacks,
positionedStack.getChance(),
activeIndex);
}
public static RecipeIngredient of(int relx, int rely, List<ItemStack> stacks, int chance, int activeIndex) {
return new RecipeIngredient(relx, rely, stacks, chance, activeIndex);
public static RecipeIngredient of(int relx, int rely, int width, int height, List<ItemStack> stacks, int chance,
int activeIndex) {
return new RecipeIngredient(relx, rely, width, height, stacks, chance, activeIndex);
}
public int getAmount() {
@@ -335,34 +348,25 @@ public class Recipe {
public void setActiveIndex(int activeIndex) {
this.activeIndex = Math.max(0, Math.min(activeIndex, this.items.length - 1));
this.amount = StackInfo.getAmount(this.items[this.activeIndex]);
}
public boolean contains(ItemStack stackA) {
return getPermutations().stream()
.anyMatch(stackB -> NEIClientUtils.areStacksSameTypeWithNBT(stackB, stackA));
final ItemStack stack = StackInfo.withAmount(stackA, 0);
return getPermutations().stream().anyMatch(
stackB -> NEIClientUtils.areStacksSameTypeWithNBT(StackInfo.withAmount(stackB, 0), stack));
}
public List<ItemStack> getPermutations() {
return Arrays.asList(this.items);
}
public RecipeIngredient setAmount(int amount) {
for (int index = 0; index < this.items.length; index++) {
this.items[index] = StackInfo.withAmount(this.items[index], amount);
}
return this;
}
public void setChance(int chance) {
this.chance = chance;
}
public RecipeIngredient copy() {
return new RecipeIngredient(
this.relx,
this.rely,
this.width,
this.height,
getPermutations().stream().map(ItemStack::copy).collect(Collectors.toList()),
this.chance,
this.activeIndex);
@@ -447,7 +451,7 @@ public class Recipe {
}
if (item instanceof ItemStack stack) {
return RecipeIngredient.of(0, 0, Arrays.asList(stack), PositionedStack.CHANCE_FULL, 0);
return RecipeIngredient.of(0, 0, 16, 16, Arrays.asList(stack), PositionedStack.CHANCE_FULL, 0);
}
if (item instanceof RecipeIngredient ingr) {
@@ -59,7 +59,7 @@ public class RecipeHandlerRef {
private GuiContainer prepareGui(GuiContainer firstGui) {
if (firstGui instanceof GuiRecipe gui) {
if (firstGui instanceof GuiRecipe<?>gui) {
firstGui = gui.firstGui;
}
@@ -50,8 +50,7 @@ public class RecipeInfo {
public static void registerGuiOverlay(Class<? extends GuiContainer> classz, String ident,
IStackPositioner positioner) {
positionerMap.put(new OverlayKey(classz, ident), positioner);
if (positioner instanceof OffsetPositioner && !offsets.containsKey(classz)) {
OffsetPositioner p = (OffsetPositioner) positioner;
if (positioner instanceof OffsetPositioner p && !offsets.containsKey(classz)) {
setGuiOffset(classz, p.offsetx, p.offsety);
}
}
@@ -1,6 +1,8 @@
package codechicken.nei.recipe;
import java.awt.Rectangle;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
@@ -13,8 +15,6 @@ import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraftforge.oredict.ShapedOreRecipe;
import codechicken.core.ReflectionManager;
import codechicken.nei.NEIClientConfig;
import codechicken.nei.NEIClientUtils;
import codechicken.nei.NEIServerUtils;
import codechicken.nei.PositionedStack;
@@ -25,6 +25,24 @@ import codechicken.nei.api.IStackPositioner;
public class ShapedRecipeHandler extends TemplateRecipeHandler {
private static final MethodHandle SHAPED_ORE_RECIPE_WIDTH, SHAPED_ORE_RECIPE_HEIGHT;
static {
try {
final var lookup = MethodHandles.lookup();
final var widthField = ShapedOreRecipe.class.getDeclaredField("width");
final var heightField = ShapedOreRecipe.class.getDeclaredField("height");
widthField.setAccessible(true);
heightField.setAccessible(true);
SHAPED_ORE_RECIPE_WIDTH = lookup.unreflectGetter(widthField);
SHAPED_ORE_RECIPE_HEIGHT = lookup.unreflectGetter(heightField);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public class CachedShapedRecipe extends CachedRecipe {
public ArrayList<PositionedStack> ingredients;
@@ -84,7 +102,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadCraftingRecipes(String outputId, Object... results) {
if (outputId.equals("crafting") && getClass() == ShapedRecipeHandler.class) {
for (IRecipe irecipe : (List<IRecipe>) CraftingManager.getInstance().getRecipeList()) {
for (IRecipe irecipe : CraftingManager.getInstance().getRecipeList()) {
CachedShapedRecipe recipe = null;
if (irecipe instanceof ShapedRecipes shaped) {
@@ -99,7 +117,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
}
}
} else if (outputId.equals("crafting2x2") && getClass() == ShapedRecipeHandler.class) {
for (IRecipe irecipe : (List<IRecipe>) CraftingManager.getInstance().getRecipeList()) {
for (IRecipe irecipe : CraftingManager.getInstance().getRecipeList()) {
if (irecipe instanceof ShapedRecipes shaped && shaped.recipeWidth <= 2 && shaped.recipeHeight <= 2) {
CachedShapedRecipe recipe = new CachedShapedRecipe(shaped);
@@ -115,7 +133,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadCraftingRecipes(ItemStack result) {
for (IRecipe irecipe : (List<IRecipe>) CraftingManager.getInstance().getRecipeList()) {
for (IRecipe irecipe : CraftingManager.getInstance().getRecipeList()) {
if (NEIServerUtils.areStacksSameTypeCrafting(irecipe.getRecipeOutput(), result)) {
CachedShapedRecipe recipe = null;
if (irecipe instanceof ShapedRecipes) recipe = new CachedShapedRecipe((ShapedRecipes) irecipe);
@@ -131,7 +149,7 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
@Override
public void loadUsageRecipes(ItemStack ingredient) {
for (IRecipe irecipe : (List<IRecipe>) CraftingManager.getInstance().getRecipeList()) {
for (IRecipe irecipe : CraftingManager.getInstance().getRecipeList()) {
CachedShapedRecipe recipe = null;
if (irecipe instanceof ShapedRecipes) recipe = new CachedShapedRecipe((ShapedRecipes) irecipe);
else if (irecipe instanceof ShapedOreRecipe) recipe = forgeShapedRecipe((ShapedOreRecipe) irecipe);
@@ -147,19 +165,21 @@ public class ShapedRecipeHandler extends TemplateRecipeHandler {
}
public CachedShapedRecipe forgeShapedRecipe(ShapedOreRecipe recipe) {
int width, height;
try {
int width = ReflectionManager.getField(ShapedOreRecipe.class, Integer.class, recipe, 4);
int height = ReflectionManager.getField(ShapedOreRecipe.class, Integer.class, recipe, 5);
Object[] items = recipe.getInput();
for (Object item : items) if (item instanceof List && ((List<?>) item).isEmpty()) // ore handler, no ores
return null;
return new CachedShapedRecipe(width, height, items, recipe.getRecipeOutput());
} catch (Exception e) {
NEIClientConfig.logger.error("Error loading recipe: ", e);
return null;
width = (int) SHAPED_ORE_RECIPE_WIDTH.invokeExact(recipe);
height = (int) SHAPED_ORE_RECIPE_HEIGHT.invokeExact(recipe);
} catch (Throwable e) {
throw new IllegalStateException("Unreachable");
}
Object[] items = recipe.getInput();
for (Object item : items) {
if (item instanceof List<?>ores && ores.isEmpty()) // ore handler, no ores
return null;
}
return new CachedShapedRecipe(width, height, items, recipe.getRecipeOutput());
}
@Override
@@ -289,9 +289,9 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
public boolean lastKeyTyped(GuiContainer gui, char keyChar, int keyCode) {
if (!canHandle(gui)) return false;
if (KeyManager.isHashDown("recipe.recipe")) {
if (KeyManager.isKeyDown("recipe.recipe")) {
return transferRect(gui, false);
} else if (KeyManager.isHashDown("recipe.usage")) {
} else if (KeyManager.isKeyDown("recipe.usage")) {
return transferRect(gui, true);
}
@@ -673,9 +673,9 @@ public abstract class TemplateRecipeHandler implements ICraftingHandler, IUsageH
@Override
public boolean keyTyped(GuiRecipe<?> gui, char keyChar, int keyCode, int recipe) {
if (KeyManager.isHashDown("recipe.recipe")) {
if (KeyManager.isKeyDown("recipe.recipe")) {
return transferRect(gui, recipe, false);
} else if (KeyManager.isHashDown("recipe.usage")) {
} else if (KeyManager.isKeyDown("recipe.usage")) {
return transferRect(gui, recipe, true);
}
@@ -25,6 +25,34 @@ import codechicken.nei.recipe.StackInfo;
public class RecipeChainMath {
public interface ChainVisitor {
void enterRecipe(RecipeId recipeId, long multiplier);
void addIngredient(BookmarkItem ingrItem, long requestedAmount);
void addIngredientFresh(BookmarkItem ingrItem, long freshAmount);
void leaveRecipe();
}
private static class EmptyChainVisitor implements ChainVisitor {
@Override
public void enterRecipe(RecipeId recipeId, long multiplier) {}
@Override
public void addIngredient(BookmarkItem ingrItem, long requestedAmount) {}
@Override
public void addIngredientFresh(BookmarkItem ingrItem, long freshAmount) {}
@Override
public void leaveRecipe() {}
}
private static class ContainerItemResult {
public ItemStack stack;
@@ -38,6 +66,8 @@ public class RecipeChainMath {
}
}
private static final ChainVisitor EMPTY_CHAIN_VISITOR = new EmptyChainVisitor();
private static final ItemStack ROOT_ITEM = new ItemStack(Blocks.fire);
private static final RecipeId ROOT_RECIPE_ID = RecipeId
.of(ROOT_ITEM, "recipe-autocrafting", Collections.emptyList());
@@ -203,7 +233,7 @@ public class RecipeChainMath {
final long amount = item.getAmount(multiplier);
rootIngredients.add(
BookmarkItem.builder(-1, item.getItemStack(amount)).factor(item.getStackSize(amount))
.permutations(BookmarkItem.Builder.generatePermutations(item.itemStack))
.permutations(BookmarkItem.Builder.generatePermutations(item.getItemStack(amount)))
.recipeId(ROOT_RECIPE_ID).type(BookmarkItemType.INGREDIENT).build());
}
@@ -298,6 +328,10 @@ public class RecipeChainMath {
}
public RecipeChainMath refresh() {
return refresh(EMPTY_CHAIN_VISITOR);
}
public RecipeChainMath refresh(ChainVisitor visitor) {
final boolean isPausedItemDamageSound = StackInfo.isPausedItemDamageSound();
StackInfo.pauseItemDamageSound(true);
@@ -314,14 +348,14 @@ public class RecipeChainMath {
for (BookmarkItem prefItem : this.recipeResults) {
if (!prefItem.emptyFactor() && this.outputRecipes.containsKey(prefItem.recipeId)) {
final long prefAmount = prefItem.getAmount(this.outputRecipes.get(prefItem.recipeId));
final long prefMultiplier = this.outputRecipes.get(prefItem.recipeId);
if (prefItem.itemStack.getItem().hasContainerItem(prefItem.itemStack)) {
this.containerItemsBlacklist.add(prefItem.itemStack);
}
this.preferredItems.put(prefItem, prefItem);
calculateSuitableRecipe(prefItem, prefAmount, new ArrayList<>());
calculateSuitableRecipe(prefItem, prefMultiplier, new ArrayList<>(), visitor);
this.preferredItems.remove(prefItem);
}
}
@@ -338,8 +372,13 @@ public class RecipeChainMath {
return this;
}
private void calculateSuitableRecipe(BookmarkItem ingrItem, long ingrAmount, List<RecipeId> visited) {
private void calculateSuitableRecipe(BookmarkItem ingrItem, long ingrMultiplier, List<RecipeId> visited,
ChainVisitor visitor) {
final BookmarkItem prefItem = this.preferredItems.get(ingrItem);
long ingrAmount = ingrItem
.getAmount(ingrMultiplier, prefItem != null ? prefItem.itemStack : ingrItem.itemStack);
visitor.addIngredient(prefItem != null ? prefItem : ingrItem, ingrAmount);
// calculate existing containers
if (ingrAmount > 0) {
@@ -358,7 +397,7 @@ public class RecipeChainMath {
if (ingrAmount > 0) {
for (BookmarkItem item : this.initialItems) {
if (item.containsItems(ingrItem)
&& (ingrAmount = addRequiredAmount(item, ingrAmount, item.getAmount())) == 0) {
&& (ingrAmount = addRequiredAmount(item, ingrAmount, item.getAmount(), visitor)) == 0) {
break;
}
}
@@ -366,33 +405,37 @@ public class RecipeChainMath {
// shift amount
if (prefItem == null) {
addRequiredAmount(ingrItem, ingrAmount, Long.MAX_VALUE);
addRequiredAmount(ingrItem, ingrAmount, Long.MAX_VALUE, visitor);
} else if (visited.contains(prefItem.recipeId)) {
addRequiredAmount(prefItem, ingrAmount, Long.MAX_VALUE);
addRequiredAmount(prefItem, ingrAmount, Long.MAX_VALUE, visitor);
} else {
addRequiredAmount(prefItem, ingrAmount, Long.MAX_VALUE);
addRequiredAmount(prefItem, ingrAmount, Long.MAX_VALUE, visitor);
final long multiplier = Math
.max(0, prefItem.getMultiplierFromAmount(this.requiredAmount.get(prefItem)) - prefItem.multiplier);
if (multiplier > 0) {
addShift(prefItem.recipeId, multiplier);
visited.add(prefItem.recipeId);
prepareIngredients(prefItem.recipeId, multiplier, visited);
prepareIngredients(prefItem.recipeId, multiplier, visited, visitor);
visited.remove(prefItem.recipeId);
}
}
}
private void prepareIngredients(RecipeId recipeId, long multiplier, List<RecipeId> visited) {
private void prepareIngredients(RecipeId recipeId, long multiplier, List<RecipeId> visited, ChainVisitor visitor) {
visitor.enterRecipe(recipeId, multiplier);
for (BookmarkItem item : this.recipeIngredients) {
if (!item.emptyFactor() && recipeId.equals(item.recipeId)) {
calculateSuitableRecipe(item, item.getAmount(multiplier), visited);
calculateSuitableRecipe(item, multiplier, visited, visitor);
}
}
visitor.leaveRecipe();
}
private long addRequiredAmount(BookmarkItem prefItem, long ingrAmount, long maxAmount) {
private long addRequiredAmount(BookmarkItem prefItem, long ingrAmount, long maxAmount, ChainVisitor visitor) {
long shiftAmount = this.requiredAmount.getOrDefault(prefItem, 0L);
if (hasContainerItem(prefItem.itemStack)) {
@@ -411,8 +454,9 @@ public class RecipeChainMath {
final ContainerItemResult result = getToolsContainerItems(itemStack, steps);
if (result.stack == null) {
multiplier = steps / (steps - result.leftSteps);
steps = steps % (steps - result.leftSteps);
final long stepsPerReplacement = steps - result.leftSteps;
multiplier = Math.min(steps / stepsPerReplacement, maxAmount - shiftAmount);
steps -= multiplier * stepsPerReplacement;
} else {
steps = result.leftSteps;
}
@@ -448,6 +492,7 @@ public class RecipeChainMath {
ingrAmount -= initAmount;
}
visitor.addIngredientFresh(prefItem, shiftAmount - this.requiredAmount.getOrDefault(prefItem, 0L));
this.requiredAmount.put(prefItem, shiftAmount);
return ingrAmount;
@@ -382,7 +382,7 @@ public class DebugHandlerWidget extends Widget {
public void update() {
final GuiContainer gui = NEIClientUtils.getGuiContainer();
if (this.showWidget && gui instanceof GuiRecipe recipe) {
if (this.showWidget && gui instanceof GuiRecipe<?>recipe) {
if (this.record == null || !this.record.handlerKey.equals(getHandlerID(recipe.getHandler()))) {
final IRecipeHandler handler = recipe.getHandler();
@@ -85,8 +85,7 @@ public class SearchExpressionFormatVisitor extends AbstractSearchExpressionVisit
}
private String formatChild(ParseTree child, Character prefix) {
if (child instanceof TerminalNode) {
final TerminalNode node = (TerminalNode) child;
if (child instanceof TerminalNode node) {
final int type = node.getSymbol().getType();
final String format = Optional.ofNullable(
// check if highlight is defined for the token
@@ -1,4 +1,4 @@
package codechicken.nei.recipe;
package codechicken.nei.util;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
@@ -8,7 +8,7 @@ import net.minecraft.item.ItemStack;
import codechicken.nei.PositionedStack;
import codechicken.nei.api.ShortcutInputHandler;
public class ContainerRecipe extends Container {
public class EmptyContainer extends Container {
private ItemStack activeStack = null;
@@ -36,7 +36,7 @@ import cpw.mods.fml.relauncher.ReflectionHelper;
public class ItemUntranslator {
private class LanguageRegistryPatch implements AutoCloseable {
private static class LanguageRegistryPatch implements AutoCloseable {
// RAII-style helper that temporarily swaps language data in
// LanguageRegistry / StringTranslate using reflection. This allows
// reading translation entries for a different language (eg. en_US)
@@ -252,13 +252,20 @@ public class ItemUntranslator {
return this.processedNames.computeIfAbsent(guidKey, stackKey -> {
String displayName = this.secondNames.get(stackKey);
if (displayName == null) {
final String guid = findBestGUIDForLookup(stack);
displayName = this.secondNames
.computeIfAbsent(guid == null ? stackKey : guid, g -> getFallbackDisplayName(stack));
try {
if (displayName == null) {
final String guid = findBestGUIDForLookup(stack);
displayName = this.secondNames
.computeIfAbsent(guid == null ? stackKey : guid, g -> getFallbackDisplayName(stack));
}
return displayName.equals(stripFormatting(stack.getDisplayName())) ? "" : displayName;
} catch (Throwable e) {
NEIClientConfig.logger.warn("Failed to get display name for itemstack {}", stack, e);
}
return displayName.equals(stripFormatting(stack.getDisplayName())) ? "" : displayName;
return displayName != null ? displayName : "";
});
}
@@ -39,13 +39,12 @@ public class NBTJson {
@SuppressWarnings("unchecked")
public static JsonElement toJsonObject(NBTBase nbt) {
if (nbt instanceof NBTTagCompound) {
if (nbt instanceof NBTTagCompound nbtTagCompound) {
// NBTTagCompound
final NBTTagCompound nbtTagCompound = (NBTTagCompound) nbt;
final Map<String, NBTBase> tagMap = (Map<String, NBTBase>) nbtTagCompound.tagMap;
final JsonObject root = new JsonObject();
tagMap.entrySet().stream().sorted(Map.Entry.<String, NBTBase>comparingByKey())
tagMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEach(nbtEntry -> { root.add(nbtEntry.getKey(), toJsonObject(nbtEntry.getValue())); });
return root;
@@ -73,9 +72,8 @@ public class NBTJson {
} else if (nbt instanceof NBTTagString) {
// String
return new JsonPrimitive(((NBTTagString) nbt).func_150285_a_());
} else if (nbt instanceof NBTTagList) {
} else if (nbt instanceof NBTTagList list) {
// Tag List
final NBTTagList list = (NBTTagList) nbt;
if (list.tagList.isEmpty()) {
return createEmptyList(list);
@@ -85,9 +83,8 @@ public class NBTJson {
return arr;
}
} else if (nbt instanceof NBTTagIntArray) {
} else if (nbt instanceof NBTTagIntArray list) {
// Int Array
final NBTTagIntArray list = (NBTTagIntArray) nbt;
if (list.func_150302_c().length == 0) {
return createEmptyList(list);
@@ -101,9 +98,8 @@ public class NBTJson {
return arr;
}
} else if (nbt instanceof NBTTagByteArray) {
} else if (nbt instanceof NBTTagByteArray list) {
// Byte Array
final NBTTagByteArray list = (NBTTagByteArray) nbt;
if (list.func_150292_c().length == 0) {
return createEmptyList(list);
@@ -123,9 +119,8 @@ public class NBTJson {
}
public static NBTBase toNbt(JsonElement jsonElement) {
if (jsonElement instanceof JsonPrimitive) {
if (jsonElement instanceof JsonPrimitive jsonPrimitive) {
// Number or String
final JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonElement;
final String jsonString = jsonPrimitive.getAsString();
final Matcher m = numberPattern.matcher(jsonString);
if (m.find()) {
@@ -158,9 +153,8 @@ public class NBTJson {
// String
return new NBTTagString(jsonString);
}
} else if (jsonElement instanceof JsonArray) {
} else if (jsonElement instanceof JsonArray jsonArray) {
// NBTTagIntArray or NBTTagList
final JsonArray jsonArray = (JsonArray) jsonElement;
final List<NBTBase> nbtList = new ArrayList<>();
for (JsonElement element : jsonArray) {
@@ -183,9 +177,8 @@ public class NBTJson {
return nbtTagList;
}
} else if (jsonElement instanceof JsonObject) {
} else if (jsonElement instanceof JsonObject jsonObject) {
// NBTTagCompound
final JsonObject jsonObject = (JsonObject) jsonElement;
final NBTBase custom = restoreEmptyList(jsonObject);
if (custom == null) {
+27 -1
View File
@@ -32,7 +32,9 @@ nei.bookmark.group.pull_items=Pull all Items
nei.bookmark.group.pull_items_shift=Pull missing Items
nei.bookmark.group.craft_missing=Craft Missing Items
nei.bookmark.group.craft_all=Craft Items
nei.bookmark.group.chat_link=Send Bookmark Group to Chat
nei.bookmark.item.sorting=Move Position
nei.bookmark.item.chat_link=Send Item to Chat
nei.bookmark.remove_recipe=Remove Recipe
nei.bookmark.remove_item=Remove Item
nei.bookmark.add_item=Add Bookmark
@@ -42,6 +44,7 @@ nei.bookmark.add_item_with_count=Add Bookmark with Count
nei.bookmark.change_quantity=Change Quantity
nei.bookmark.change_quantity_step=Change Quantity with Multiplier
nei.bookmark.recipe.toggle_collapse=Toggle Collapse/Expand
nei.bookmark.recipe.chat_link=Send Recipe to Chat
nei.bookmark.crafting_chain=Crafting Chain
nei.bookmark.crafting_chain.input=Ingredients
nei.bookmark.crafting_chain.missing=Missing Items
@@ -68,6 +71,7 @@ nei.itempanel.infinite_item=Give Infinite Item
nei.itempanel.copy_name=Copy Item Name
nei.itempanel.copy_oredict=Copy Item OreDictionary
nei.itempanel.copy_id=Copy Item ID
nei.itempanel.chat_link_item=Send item link to chat
nei.enchant=Enchant
@@ -143,6 +147,9 @@ nei.chat.chunkoverlay.3=Chunk Overlay: GT Ore Veins
nei.chat.moboverlay.0=Mob Spawning Overlay: §cOff
nei.chat.moboverlay.1=Mob Spawning Overlay: §2On
nei.chat.item_link.text=<%s> §6Click to add bookmark: %s
nei.chat.item_link.item.text=Bookmark Item
nei.chat.item_link.recipe.text=Bookmark Recipe
nei.chat.item_link.group.text=Bookmark Group
nei.chat.bookmark_added.text=Bookmark added!
nei.chat.recipeid.many_params=Too many parameters! Usage: %s
@@ -194,6 +201,7 @@ nei.options.keys.bookmark.add=Add Bookmark
nei.options.keys.bookmark.remove_recipe=Remove Group from Bookmarks (Shift +)
nei.options.keys.bookmark.pull_items=Pull all Bookmarked Items
nei.options.keys.bookmark.hide=Toggle Bookmark Panel Visibility
nei.options.keys.bookmark.chat_link=Send link to chat (Ctrl +)
nei.options.keys.gui.overlay=Fill/Overlay Crafting Grid
nei.options.keys.gui.getprevioussearch=Previous Search
nei.options.keys.gui.getnextsearch=Next Search
@@ -202,7 +210,6 @@ nei.options.keys.copy.name=Copy Item Name (Ctrl +)
nei.options.keys.gui.craft_items=Craft Items (Shift +)
nei.options.keys.copy.oredict=Copy Item OreDictionary (Ctrl +)
nei.options.keys.copy.identifier=Copy Item ID (Ctrl +)
nei.options.keys.copy.chat_link_item=Send item link to chat (Ctrl +)
nei.options.keys.itemzoom.toggle=Toggle Item Zoom (Shift +)
nei.options.keys.itemzoom.hold=Hold to Display Item Zoom
nei.options.keys.itemzoom.zoom_in=Item Zoom In
@@ -564,6 +571,24 @@ nei.debug.RecipeHandler.reset=Reset
nei.recipe.page=Page %s/%s
nei.recipe.tooltip=Recipes
nei.recipe.tab.view_all.tooltip=View all categories
nei.recipe.search.tooltip.name=Filter Syntax
nei.recipe.search.tooltip.shift=§7Hold §6Shift§7 for more info
nei.recipe.search.tooltip.input=%s§ftext§8 - §7search in inputs
nei.recipe.search.tooltip.output=%s§ftext§8 - §7search in outputs
nei.recipe.search.tooltip.prefix=%stext§8 - §7%s
nei.recipe.search.tooltip.prefix.modName=search by mod
nei.recipe.search.tooltip.prefix.tooltip=search by tooltip
nei.recipe.search.tooltip.prefix.oreDict=search by ore dict
nei.recipe.search.tooltip.prefix.identifier=search by resource ID
nei.recipe.search.tooltip.prefix.subsets=search by subsets
nei.recipe.search.tooltip.prefix.chemicalFormula=search by chemical formula
nei.recipe.search.tooltip.exclude=%s§ftext§8 - §7exclude items with text
nei.recipe.search.tooltip.exclude_recipe=%s§ftext§8 - §7exclude recipes with text
nei.recipe.search.tooltip.or=§fa%s§fb§8 - §7match a or b
nei.recipe.search.tooltip.exact=%s§ftext%s§8 - §7match exact phrase
nei.recipe.shaped=Shaped Crafting
nei.recipe.shapeless=Shapeless Crafting
nei.recipe.furnace=Smelting
@@ -605,6 +630,7 @@ nei.recipe.overlay.overlayRecipe=Overlay Recipe
nei.recipe.overlay.fillCraftingGrid=Fill Crafting Grid
nei.recipe.overlay.bookmarkRecipe=Save with Recipe
nei.recipe.overlay.bookmarkRecipeAndCount=Save with Recipe & Count
nei.recipe.overlay.sendRecipeToChat=Send Recipe to Chat
nei.recipe.favorite=Favorite
nei.recipe.favorite.bookmark_recipe=Save Recipe Tree
@@ -20,6 +20,7 @@ nei.bookmark.group.sorting=Сортировка
nei.bookmark.group.remove_recipe=Удалить группу
nei.bookmark.group.pull_items=Переместить все предметы
nei.bookmark.group.pull_items_shift=Переместить недостающие предметы
nei.bookmark.group.chat_link=Отправить группу в чат
nei.bookmark.crafting_chain=Цепочка крафта
nei.bookmark.crafting_chain.input=Ингредиенты
nei.bookmark.crafting_chain.output=Результаты
@@ -141,6 +142,7 @@ nei.options.keys.bookmark.add=Добавить закладку
nei.options.keys.bookmark.remove_recipe=Удалить группу из закладок (Shift +)
nei.options.keys.bookmark.pull_items=Переместить все отмеченные предметы
nei.options.keys.bookmark.hide=Переключить видимость панели закладок
nei.options.keys.bookmark.chat_link=Отправить ссылку в чат (Ctrl +)
nei.options.keys.gui.overlay=Заполнить сетку крафта
nei.options.keys.gui.getprevioussearch=Предыдущий поиск
nei.options.keys.gui.getnextsearch=Следующий поиск
@@ -149,7 +151,6 @@ nei.options.keys.copy.name=Скопировать название предме
nei.options.keys.gui.craft_items=Создать предметы (Shift +)
nei.options.keys.copy.oredict=Скопировать OreDictionary предмета (Ctrl +)
nei.options.keys.copy.identifier=Скопировать ID предмета (Ctrl +)
nei.options.keys.copy.chat_link_item=Отправить ссылку на предмет в чат (Ctrl +)
nei.options.keys.itemzoom.toggle=Переключить увеличение предмета (Shift +)
nei.options.keys.itemzoom.hold=Удерживать для отображения увеличения предмета
nei.options.keys.itemzoom.zoom_in=Увеличить предмет
@@ -422,6 +423,7 @@ nei.recipe.overlay.missing=Отсутствует следующее
nei.recipe.overlay.mismatch=Несоответствие сетки крафта
nei.recipe.overlay.fillCraftingGrid=Заполнить сетку крафта
nei.recipe.overlay.bookmarkRecipe=Сохранить с рецептом
nei.recipe.overlay.sendRecipeToChat=Отправить рецепт в чат
nei.itemsort.minecraft=Minecraft
nei.itemsort.minecraft.tip=Сортирует предметы из ванильного Minecraft первыми