diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index dc3e38d7a..d44455886 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -275,6 +275,8 @@ public enum Mixins implements IMixins { , "shaders.MixinRenderNameTag" , "shaders.MixinRenderPlayerArmor" , "shaders.MixinTileEntityBeaconRenderer" + , "shaders.MixinWorldNbtCache" + , "shaders.MixinNetHandlerPlayClient_NbtRemesh" , "shaders.MixinRenderEndPortal" , "shaders.MixinTileEntityRendererDispatcher" , "shaders.MixinGlProgram" diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java index 964087a93..f30ee3fe1 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java @@ -12,8 +12,10 @@ import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; import net.coderbot.iris.vertices.ExtendedDataHelper; import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -118,6 +120,10 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask blockTypeIds = provider != null ? provider.getBlockTypeIds() : null; final BlockRenderContext blockRenderContext = buildContext.getBlockRenderContext(); + final NbtConditionalIdMap teMap = BlockRenderingSettings.INSTANCE.getBlockNbtMap(); + final net.minecraft.world.World mcWorld = Minecraft.getMinecraft().theWorld; + final long currentTick = mcWorld != null ? mcWorld.getTotalWorldTime() : 0L; + final boolean threaded = isThreaded(); final List deferredBlocks = threaded ? new ArrayList<>() : null; @@ -192,7 +198,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask meshes = @@ -236,7 +242,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask teMap, long currentTick) { final var blockMaterial = block.getMaterial(); final boolean isFluid = blockMaterial == net.minecraft.block.material.Material.water || blockMaterial == net.minecraft.block.material.Material.lava; @@ -272,6 +278,27 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask deferredBlocks, AngelicaChunkBuildContext buildContext, ChunkBuildBuffers buffers, IBlockAccess region, int minX, int minY, int minZ) { + private void processDeferredBlocks(List deferredBlocks, AngelicaChunkBuildContext buildContext, ChunkBuildBuffers buffers, IBlockAccess region, int minX, int minY, int minZ, NbtConditionalIdMap teMap, long currentTick) { final BlockRenderContext blockRenderContext = buildContext.getBlockRenderContext(); @@ -308,7 +335,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask blockMetaMap, NbtConditionalIdMap tileEntityMap) {} + /** Meta-key bit OR'd in at runtime when a snowy-tagged block has snow above it. */ public static final int SNOWY_META_BIT = 0x10; /** - * Creates a two-level map structure for block material IDs. - * Based on Iris's BlockState mapping approach adapted for 1.7.10's metadata system. + * Creates the standard block meta ID map, the TileEntity NBT-conditional map, and registers + * snowy blocks on {@link BlockRenderingSettings}. */ - public static Reference2ObjectMap createBlockMetaIdMap(Int2ObjectMap> blockPropertiesMap, boolean skipFlattening) { + public static BlockIdMaps createBlockIdMaps(Int2ObjectMap> blockPropertiesMap, boolean skipFlattening) { final Reference2ObjectMap blockMatches = new Reference2ObjectOpenHashMap<>(); + final NbtConditionalIdMap tileEntityMap = new NbtConditionalIdMap<>(); final ReferenceSet snowyBlocks = new ReferenceOpenHashSet<>(); blockPropertiesMap.forEach((intId, entries) -> { for (BlockEntry entry : entries) { - addBlockMetas(entry, blockMatches, intId, skipFlattening, snowyBlocks); + if (entry.hasNbtProperties()) { + addTileEntityEntry(entry, tileEntityMap, intId); + } else { + addBlockMetas(entry, blockMatches, tileEntityMap, intId, skipFlattening, snowyBlocks); + } } }); BlockRenderingSettings.INSTANCE.setHasSnowyEntries(!snowyBlocks.isEmpty()); BlockRenderingSettings.INSTANCE.setSnowyBlocks(snowyBlocks); - return blockMatches; + return new BlockIdMaps(blockMatches, tileEntityMap); } public static Map createBlockTypeMap(Map blockPropertiesMap) { @@ -55,7 +62,8 @@ public class BlockMaterialMapping { if (block == null && "minecraft".equals(id.getNamespace())) { final List legacyEntries = FlatteningMap.toLegacy(id.getName(), Map.of()); if (legacyEntries != null) { - block = resolveBlockOrNull(legacyEntries.getFirst().getId()); + // Use the first entry for render type (render type applies per-block) + block = resolveBlockOrNull(legacyEntries.getFirst().id()); } } @@ -80,28 +88,64 @@ public class BlockMaterialMapping { }; } + /** + * Creates an NBT-conditional ID map keyed by NamespacedId, for items or entities. + */ + public static NbtConditionalIdMap createNamespacedNbtMap(Int2ObjectMap> nbtEntries) { + NbtConditionalIdMap map = new NbtConditionalIdMap<>(); + + nbtEntries.forEach((intId, entries) -> { + for (BlockEntry entry : entries) { + if (entry.hasNbtProperties()) { + map.addCondition(entry.id(), entry.nbtProperties(), intId); + } + } + }); + + return map; + } + + private static void addTileEntityEntry(BlockEntry entry, NbtConditionalIdMap teMap, int intId) { + final NamespacedId id = entry.id(); + final ResourceLocation resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); + + final Block block = (Block) Block.blockRegistry.getObject(resourceLocation.toString()); + + if (block == null || block == Blocks.air) { + return; + } + + teMap.addCondition(block, entry.nbtProperties(), intId); + } + /** * Adds block+metadata combinations to the material ID map. * Based on Iris's addBlockStates method, adapted for 1.7.10 metadata system. */ - private static void addBlockMetas(BlockEntry entry, Reference2ObjectMap idMap, int intId, boolean skipFlattening, ReferenceSet snowyBlocks) { - final NamespacedId id = entry.getId(); - final Map stateProps = entry.getStateProperties(); + private static void addBlockMetas(BlockEntry entry, Reference2ObjectMap idMap, + NbtConditionalIdMap tileEntityMap, int intId, + boolean skipFlattening, ReferenceSet snowyBlocks) { + final NamespacedId id = entry.id(); + final Map stateProps = entry.stateProperties(); final String snowy = stateProps.get("snowy"); final int snowyBit = "true".equals(snowy) ? SNOWY_META_BIT : 0; // Vanilla modern names go through FlatteningMap; legacy-section packs and modded blocks // resolve directly from the registry. List targets = null; - if (!skipFlattening && "minecraft".equals(id.getNamespace()) && (!stateProps.isEmpty() || entry.getMetas().isEmpty())) { + if (!skipFlattening && "minecraft".equals(id.getNamespace()) && (!stateProps.isEmpty() || entry.metas().isEmpty())) { targets = FlatteningMap.toLegacy(id.getName(), stateProps); } if (targets == null) targets = List.of(entry); for (BlockEntry target : targets) { - final Block block = resolveBlockOrNull(target.getId()); + if (target.hasNbtProperties()) { + addTileEntityEntry(target, tileEntityMap, intId); + continue; + } + final Block block = resolveBlockOrNull(target.id()); if (block == null) continue; - applyMetas(block, target.getMetas(), idMap, intId, snowyBit); + applyMetas(block, target.metas(), idMap, intId, snowyBit); if (snowy != null) snowyBlocks.add(block); } } diff --git a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java b/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java index 2ab786f53..75cc38b96 100644 --- a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java +++ b/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java @@ -2,6 +2,7 @@ package net.coderbot.iris.block_rendering; import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer; import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.longs.Long2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.ReferenceSet; @@ -18,16 +19,76 @@ import java.util.Map; public class BlockRenderingSettings { public static final BlockRenderingSettings INSTANCE = new BlockRenderingSettings(); + public static final int CACHE_MISS = Integer.MIN_VALUE; + + private static final int NBT_CACHE_INTERVAL_TICKS = 20; + private static final int TE_NBT_CACHE_MAX = 8192; + + private static final Long2LongLinkedOpenHashMap teNbtIdCache = new Long2LongLinkedOpenHashMap(256); + private static final Object teNbtIdCacheLock = new Object(); + + static { + teNbtIdCache.defaultReturnValue(-1L); + } + + public static long packBlockPos(int x, int y, int z) { + return ((long) x & 0x3FFFFFFL) << 38 | ((long) y & 0xFFFL) << 26 | ((long) z & 0x3FFFFFFL); + } + + public static void invalidateTeNbtCache(int x, int y, int z) { + final long key = packBlockPos(x, y, z); + synchronized (teNbtIdCacheLock) { + teNbtIdCache.remove(key); + } + } + + public static int getCachedTeNbtId(long packedPos, long currentTick) { + final long entry; + synchronized (teNbtIdCacheLock) { + entry = teNbtIdCache.get(packedPos); + } + if (entry == -1L) { + return CACHE_MISS; + } + final long entryTick = entry >>> 32; + if (currentTick - entryTick >= NBT_CACHE_INTERVAL_TICKS) { + return CACHE_MISS; + } + return (int) entry; + } + + public static void cacheTeNbtId(long packedPos, int shaderId, long currentTick) { + // Mask tick into low 31 bits so packed value never collides with the -1L sentinel. + final long packed = ((currentTick & 0x7FFFFFFFL) << 32) | (shaderId & 0xFFFFFFFFL); + synchronized (teNbtIdCacheLock) { + teNbtIdCache.put(packedPos, packed); + while (teNbtIdCache.size() > TE_NBT_CACHE_MAX) { + teNbtIdCache.removeFirstLong(); + } + } + } + + public static void clearTeNbtCache() { + synchronized (teNbtIdCacheLock) { + teNbtIdCache.clear(); + } + } + @Getter private boolean reloadRequired; private Reference2ObjectMap blockMetaMatches; + private NbtConditionalIdMap blockNbtMap; private Map blockTypeIds; // note: no reload needed, entities are rebuilt every frame. @Setter private Object2IntFunction entityIds; + @Setter + private NbtConditionalIdMap entityNbtMap; // note: no reload needed, items are rendered every frame. @Setter private Object2IntFunction itemIds; + @Setter + private NbtConditionalIdMap itemNbtMap; @Getter private float ambientOcclusionLevel; private boolean disableDirectionalShading; @@ -41,6 +102,7 @@ public class BlockRenderingSettings { public BlockRenderingSettings() { reloadRequired = false; blockMetaMatches = null; + blockNbtMap = null; blockTypeIds = null; ambientOcclusionLevel = 1.0F; disableDirectionalShading = false; @@ -82,11 +144,32 @@ public class BlockRenderingSettings { return itemIds; } + @Nullable + public NbtConditionalIdMap getBlockNbtMap() { + return blockNbtMap; + } + + @Nullable + public NbtConditionalIdMap getItemNbtMap() { + return itemNbtMap; + } + + @Nullable + public NbtConditionalIdMap getEntityNbtMap() { + return entityNbtMap; + } + public void setBlockMetaMatches(Reference2ObjectMap blockMetaIds) { this.reloadRequired = true; this.blockMetaMatches = blockMetaIds; } + public void setBlockNbtMap(NbtConditionalIdMap blockNbtMap) { + this.reloadRequired = true; + this.blockNbtMap = blockNbtMap; + clearTeNbtCache(); + } + public boolean hasSnowyEntries() { return hasSnowyEntries; } diff --git a/src/main/java/net/coderbot/iris/block_rendering/NbtConditionalIdMap.java b/src/main/java/net/coderbot/iris/block_rendering/NbtConditionalIdMap.java new file mode 100644 index 000000000..eab175b7f --- /dev/null +++ b/src/main/java/net/coderbot/iris/block_rendering/NbtConditionalIdMap.java @@ -0,0 +1,233 @@ +package net.coderbot.iris.block_rendering; + +import net.coderbot.iris.Iris; +import net.coderbot.iris.shaderpack.materialmap.PropertiesTokenizer; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ResourceLocation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Maps objects with specific NBT properties to shader IDs. Generic over the + * key type so it works for blocks, items, and entities. + * + * Example: + * block.37=flower_pot[Item=minecraft:red_flower,Data=0] + * item.10=diamond_sword[display.Name='Pointy Stick'] + */ +public class NbtConditionalIdMap { + + /** + * A single property matcher within a condition. + */ + record PropertyMatcher(String key, String[] path, String expectedValue, + long expectedLong, boolean isExpectedLong, + double expectedDouble, boolean isExpectedDouble) { + boolean isPathMatch() { return path != null; } + boolean isExistenceOnly() { return expectedValue == null; } + } + + record NbtCondition(PropertyMatcher[] matchers, int shaderId) {} + + private final Map> conditionsByKey; + + public NbtConditionalIdMap() { + this.conditionsByKey = new HashMap<>(); + } + + /** + * Registers an NBT condition. Unquoted values are resolved via item/block + * registries at registration time. Single-quoted values are kept as literals. + * Dot notation paths are pre-split here so we prevent allocations. + */ + public void addCondition(K key, Map nbtProperties, int shaderId) { + final PropertyMatcher[] matchers = new PropertyMatcher[nbtProperties.size()]; + int i = 0; + + for (Map.Entry entry : nbtProperties.entrySet()) { + final String nbtKey = entry.getKey(); + final PropertiesTokenizer.NbtValue nbtValue = entry.getValue(); + + final String resolvedValue; + if (nbtValue == null) { + resolvedValue = null; + + } else if (nbtValue.literal()) { + resolvedValue = nbtValue.value(); + + } else { + resolvedValue = resolveValue(nbtValue.value()); + } + + final String[] path = nbtKey.contains(".") ? nbtKey.split("\\.") : null; + + long expectedLong = 0; + boolean isExpectedLong = false; + double expectedDouble = 0; + boolean isExpectedDouble = false; + if (resolvedValue != null) { + try { + expectedLong = Long.parseLong(resolvedValue); + isExpectedLong = true; + } catch (NumberFormatException ignored) {} + try { + expectedDouble = Double.parseDouble(resolvedValue); + isExpectedDouble = true; + } catch (NumberFormatException ignored) {} + } + + matchers[i++] = new PropertyMatcher(nbtKey, path, resolvedValue, + expectedLong, isExpectedLong, expectedDouble, isExpectedDouble); + } + + conditionsByKey.computeIfAbsent(key, k -> new ArrayList<>()) + .add(new NbtCondition(matchers, shaderId)); + } + + public boolean hasConditions(K key) { + return conditionsByKey.containsKey(key); + } + + public boolean isEmpty() { + return conditionsByKey.isEmpty(); + } + + /** + * Resolves the shader ID by matching the provided NBT data. + */ + public int resolve(K key, NBTTagCompound nbt) { + final List conditions = conditionsByKey.get(key); + if (conditions == null) { + return -1; + } + + for (NbtCondition condition : conditions) { + if (matchesNbt(nbt, condition.matchers())) { + return condition.shaderId; + } + } + + return -1; + } + + private static boolean matchesNbt(NBTTagCompound nbt, PropertyMatcher[] matchers) { + for (PropertyMatcher matcher : matchers) { + if (matcher.isPathMatch()) { + if (!matchesPath(nbt, matcher.path(), 0, matcher)) { + return false; + } + + } else { + if (!nbt.hasKey(matcher.key())) { + return false; + } + + if (!matcher.isExistenceOnly()) { + if (!matchesNbtValue(nbt.getTag(matcher.key()), matcher)) { + return false; + } + } + } + } + return true; + } + + /** + * Search through dot-separated path in NBT data. + */ + private static boolean matchesPath(NBTBase tag, String[] path, int depth, PropertyMatcher matcher) { + if (depth == path.length) { + if (matcher.isExistenceOnly()) { + return true; + } + + return matchesNbtValue(tag, matcher); + } + + final String segment = path[depth]; + + if (tag instanceof NBTTagCompound compound) { + if (!compound.hasKey(segment)) { + return false; + } + + return matchesPath(compound.getTag(segment), path, depth + 1, matcher); + } + + if (tag instanceof NBTTagList list) { + for (int i = 0; i < list.tagCount(); i++) { + if (matchesPath(list.getCompoundTagAt(i), path, depth, matcher)) { + return true; + } + } + + return false; + } + + return false; + } + + /** + * Compares an NBT tag's value against an expected string using type-specific + * accessors to avoid toString() allocations where possible. + * Makes it so you don't need to specify the type either in the .properties files. + */ + private static boolean matchesNbtValue(NBTBase tag, PropertyMatcher matcher) { + return switch (tag.getId()) { + case 1 -> // TAG_Byte + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagByte) tag).func_150290_f() == matcher.expectedLong(); + case 2 -> // TAG_Short + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagShort) tag).func_150289_e() == matcher.expectedLong(); + case 3 -> // TAG_Int + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagInt) tag).func_150287_d() == matcher.expectedLong(); + case 4 -> // TAG_Long + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagLong) tag).func_150291_c() == matcher.expectedLong(); + case 5 -> // TAG_Float + matcher.isExpectedDouble() && ((net.minecraft.nbt.NBTTagFloat) tag).func_150288_h() == (float) matcher.expectedDouble(); + case 6 -> // TAG_Double + matcher.isExpectedDouble() && ((net.minecraft.nbt.NBTTagDouble) tag).func_150286_g() == matcher.expectedDouble(); + case 8 -> // TAG_String + matcher.expectedValue().equals(((net.minecraft.nbt.NBTTagString) tag).func_150285_a_()); + default -> // Compounds, lists, arrays — fall back to toString + matcher.expectedValue().equals(PropertiesTokenizer.stripQuotes(tag.toString())); + }; + } + + /** + * Tries to resolve a value as a registry name (item or block) to its numeric ID. + * If the value is already numeric or can't be resolved, return it unchanged. + */ + private static String resolveValue(String value) { + try { + Integer.parseInt(value); + return value; + } catch (NumberFormatException ignored) {} + + if (!value.contains(":")) { + Iris.logger.warn("NBT value '{}' is missing a namespace, please use the full form e.g. 'minecraft:{}'", value, value); + return value; + } + + final ResourceLocation loc = new ResourceLocation(value); + + final Item item = (Item) Item.itemRegistry.getObject(loc.toString()); + if (item != null) { + return String.valueOf(Item.getIdFromItem(item)); + } + + final Block block = (Block) Block.blockRegistry.getObject(loc.toString()); + if (block != null) { + return String.valueOf(Block.getIdFromBlock(block)); + } + + Iris.logger.warn("Could not resolve '{}' to an item or block ID", value); + return value; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 989dfe262..56734967e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -277,15 +277,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R holder -> CommonUniforms.addNonDynamicUniforms(holder, programs.getPack().getIdMap(), programs.getPackDirectives(), this.updateNotifier) ); - BlockRenderingSettings.INSTANCE.setBlockMetaMatches(BlockMaterialMapping.createBlockMetaIdMap( + final var blockIdMaps = BlockMaterialMapping.createBlockIdMaps( programs.getPack().getIdMap().getBlockProperties(), - programs.getPack().getIdMap().hasLegacySection())); + programs.getPack().getIdMap().hasLegacySection()); + BlockRenderingSettings.INSTANCE.setBlockMetaMatches(blockIdMaps.blockMetaMap()); + BlockRenderingSettings.INSTANCE.setBlockNbtMap(blockIdMaps.tileEntityMap()); BlockRenderingSettings.INSTANCE.setBlockTypeIds(BlockMaterialMapping.createBlockTypeMap(programs.getPack().getIdMap().getBlockRenderTypeMap())); BlockRenderingSettings.INSTANCE.setEntityIds(programs.getPack().getIdMap().getEntityIdMap()); + BlockRenderingSettings.INSTANCE.setEntityNbtMap(BlockMaterialMapping.createNamespacedNbtMap(programs.getPack().getIdMap().getEntityNbtEntries())); ItemMaterialHelper.clearCache(); BlockRenderingSettings.INSTANCE.setItemIds(programs.getPack().getIdMap().getItemIdMap()); + BlockRenderingSettings.INSTANCE.setItemNbtMap(BlockMaterialMapping.createNamespacedNbtMap(programs.getPack().getIdMap().getItemNbtEntries())); BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programs.getPackDirectives().getAmbientOcclusionLevel()); BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); BlockRenderingSettings.INSTANCE.setUseSeparateAo(programs.getPackDirectives().shouldUseSeparateAo()); diff --git a/src/main/java/net/coderbot/iris/shaderpack/IdMap.java b/src/main/java/net/coderbot/iris/shaderpack/IdMap.java index edb2f12c1..7272d6039 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/IdMap.java +++ b/src/main/java/net/coderbot/iris/shaderpack/IdMap.java @@ -14,6 +14,7 @@ import net.coderbot.iris.shaderpack.materialmap.BlockEntry; import net.coderbot.iris.shaderpack.materialmap.EntityFlatteningMap; import net.coderbot.iris.shaderpack.materialmap.BlockRenderType; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; +import net.coderbot.iris.shaderpack.materialmap.PropertiesTokenizer; import net.coderbot.iris.shaderpack.option.ShaderPackOptions; import net.coderbot.iris.shaderpack.preprocessor.PropertiesPreprocessor; import net.minecraft.item.Item; @@ -45,11 +46,15 @@ public class IdMap { * Maps a given item ID to an integer ID */ private final Object2IntMap itemIdMap; + @Getter + private final Int2ObjectMap> itemNbtEntries; /** * Maps a given entity ID to an integer ID */ private final Object2IntMap entityIdMap; + @Getter + private final Int2ObjectMap> entityNbtEntries; /** * Maps block states to block ids defined in block.properties @@ -106,8 +111,17 @@ public class IdMap { }); } - itemIdMap = loadProperties(shaderPath, "item.properties", shaderPackOptions, resolvedDefines).map(IdMap::parseItemIdMap).orElse(Object2IntMaps.emptyMap()); - entityIdMap = loadProperties(shaderPath, "entity.properties", shaderPackOptions, resolvedDefines).map(IdMap::parseEntityIdMap).orElse(Object2IntMaps.emptyMap()); + final ParsedIdMap parsedItems = loadProperties(shaderPath, "item.properties", shaderPackOptions, resolvedDefines) + .map(p -> parseIdMap(p, "item.", "item.properties")) + .orElse(new ParsedIdMap(Object2IntMaps.emptyMap(), new Int2ObjectOpenHashMap<>())); + itemIdMap = parsedItems.simpleMap(); + itemNbtEntries = parsedItems.nbtEntries(); + + final ParsedIdMap parsedEntities = loadProperties(shaderPath, "entity.properties", shaderPackOptions, resolvedDefines) + .map(p -> parseIdMap(p, "entity.", "entity.properties")) + .orElse(new ParsedIdMap(Object2IntMaps.emptyMap(), new Int2ObjectOpenHashMap<>())); + entityIdMap = augmentEntityIdMap(parsedEntities.simpleMap(), parsedEntities.nbtEntries()); + entityNbtEntries = parsedEntities.nbtEntries(); // TODO: Properly override block render layers @@ -166,25 +180,37 @@ public class IdMap { } } - private static Object2IntMap parseItemIdMap(Properties properties) { - return parseIdMap(properties, "item.", "item.properties"); - } - - private static Object2IntMap parseEntityIdMap(Properties properties) { - Object2IntMap idMap = parseIdMap(properties, "entity.", "entity.properties"); - - // For modern shader packs: translate modern entity names to 1.7.10 names - // so runtime lookups match EntityList's registered names directly. + /** + * For modern shaderpacks: also expose entries under their 1.7.10 entity names + * so runtime lookups match EntityList's registered names directly. + * + * Modern names whose 1.7.10 counterpart is NBT-discriminated (e.g. wither_skeleton + * is just Skeleton with SkeletonType=1) are routed into the NBT-conditional map + * instead of being aliased into the simple map — otherwise the simple lookup for + * "Skeleton" would short-circuit and match every skeleton variant. + */ + private static Object2IntMap augmentEntityIdMap( + Object2IntMap idMap, + Int2ObjectMap> nbtEntries) { Object2IntMap augmented = new Object2IntOpenHashMap<>(idMap); augmented.defaultReturnValue(-1); for (Object2IntMap.Entry entry : idMap.object2IntEntrySet()) { NamespacedId id = entry.getKey(); - if ("minecraft".equals(id.getNamespace())) { - String legacyName = EntityFlatteningMap.toLegacy(id.getName()); - if (legacyName != null) { - augmented.putIfAbsent(new NamespacedId(legacyName), entry.getIntValue()); - } + if (!"minecraft".equals(id.getNamespace())) { + continue; + } + final int intId = entry.getIntValue(); + + BlockEntry nbtMapping = EntityFlatteningMap.toLegacyWithNbt(id.getName()); + if (nbtMapping != null) { + nbtEntries.computeIfAbsent(intId, k -> new ArrayList<>()).add(nbtMapping); + continue; + } + + String legacyName = EntityFlatteningMap.toLegacy(id.getName()); + if (legacyName != null) { + augmented.putIfAbsent(new NamespacedId(legacyName), intId); } } @@ -212,67 +238,18 @@ public class IdMap { * @return List of parsed identifiers */ static List parseIdentifierList(String value, String fileName, String key) { - if (value.indexOf('"') == -1) { - String[] parts = value.split("\\s+"); - List result = new ArrayList<>(parts.length); - for (String part : parts) { - if (!part.isEmpty()) { - result.add(part); - } - } - return result; - } - - // Found quote, start of a dumb block ID - List result = new ArrayList<>(); - StringBuilder current = new StringBuilder(); - boolean inQuotes = false; - boolean escaped = false; - - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - - if (escaped) { - current.append(c); - escaped = false; - } else if (c == '\\') { - escaped = true; - } else if (c == '"') { - inQuotes = !inQuotes; - } else if (Character.isWhitespace(c) && !inQuotes) { - if (!current.isEmpty()) { - result.add(current.toString()); - current.setLength(0); - } - } else { - current.append(c); - } - } - - // Didn't close a quote, warn - if (inQuotes) { - Iris.logger.warn(fileName + " [" + key + "]: Unclosed quote"); - } - - // Trailing backslash, warn - if (escaped) { - Iris.logger.warn(fileName + " [" + key + "]: Trailing backslash"); - } - - // Add final token - if (!current.isEmpty()) { - result.add(current.toString()); - } - - return result; + return PropertiesTokenizer.tokenizeValues(value, ' '); } + record ParsedIdMap(Object2IntMap simpleMap, Int2ObjectMap> nbtEntries) {} + /** * Parses a NamespacedId map in OptiFine format */ - private static Object2IntMap parseIdMap(Properties properties, String keyPrefix, String fileName) { + private static ParsedIdMap parseIdMap(Properties properties, String keyPrefix, String fileName) { Object2IntMap idMap = new Object2IntOpenHashMap<>(); idMap.defaultReturnValue(-1); + Int2ObjectMap> nbtEntries = new Int2ObjectOpenHashMap<>(); properties.forEach((keyObject, valueObject) -> { String key = (String) keyObject; @@ -295,6 +272,20 @@ public class IdMap { // Parse identifiers for (String part : parseIdentifierList(value, fileName, key)) { + if (part.contains("[")) { + // NBT-conditional entry + try { + BlockEntry entry = BlockEntry.parse(part); + if (entry.hasNbtProperties()) { + nbtEntries.computeIfAbsent(intId, k -> new ArrayList<>()).add(entry); + } else { + idMap.put(entry.id(), intId); + } + } catch (Exception e) { + Iris.logger.warn("Failed to parse NBT entry in " + fileName + " for key " + key + ": " + part, e); + } + continue; + } if (part.contains("=")) { // Avoid tons of logspam for now Iris.logger.warn("Failed to parse an ResourceLocation in " + fileName + " for the key " + key + ": state properties are currently not supported: " + part); @@ -307,7 +298,7 @@ public class IdMap { } }); - return Object2IntMaps.unmodifiable(idMap); + return new ParsedIdMap(Object2IntMaps.unmodifiable(idMap), nbtEntries); } private static Int2ObjectMap> parseBlockMap(Properties properties, String keyPrefix, String fileName) { @@ -408,7 +399,7 @@ public class IdMap { return itemIdMap; } - public Object2IntFunction getEntityIdMap() { + public Object2IntFunction getEntityIdMap() { return entityIdMap; } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java index 51582af76..1b8447ce7 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java @@ -1,124 +1,45 @@ package net.coderbot.iris.shaderpack.materialmap; -import lombok.Getter; -import net.coderbot.iris.Iris; -import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Objects; import java.util.Set; -@Getter -public class BlockEntry { - private final NamespacedId id; - private final Set metas; - private final Map stateProperties; +public record BlockEntry( + NamespacedId id, + Set metas, + Map stateProperties, + Map nbtProperties +) { + public BlockEntry(NamespacedId id, Set metas) { + this(id, metas, Collections.emptyMap(), Collections.emptyMap()); + } - public BlockEntry(NamespacedId id, Set metas) { - this(id, metas, Collections.emptyMap()); - } + public BlockEntry(NamespacedId id, Set metas, Map stateProperties) { + this(id, metas, stateProperties, Collections.emptyMap()); + } - public BlockEntry(NamespacedId id, Set metas, Map stateProperties) { - this.id = id; - this.metas = metas; - this.stateProperties = stateProperties; - } + public boolean hasNbtProperties() { + return !nbtProperties.isEmpty(); + } - /** - * Parses a block ID entry. - * - * @param entry The string representation of the entry. Must not be empty. - */ - @NotNull - public static BlockEntry parse(@NotNull String entry) { - if (entry.isEmpty()) { - throw new IllegalArgumentException("Called BlockEntry::parse with an empty string"); - } + public boolean hasStateProperties() { + return !stateProperties.isEmpty(); + } - // We can assume that this array is of at least array length because the input string is non-empty. - final String[] splitStates = entry.split(":"); - - // Trivial case: no states, no namespace - if (splitStates.length == 1) { - return new BlockEntry(new NamespacedId("minecraft", entry), Collections.emptySet()); - } - - // Examples of what we accept: - // stone - // stone:0 - // minecraft:stone:0 - // minecraft:stone:0,1,2 - // minecraft:furnace:lit=true (blockstate property) - // minecraft:oak_log:axis=y (blockstate property) - - // Less trivial case: no metas or state properties, just a namespace - if (splitStates.length == 2 && !StringUtils.isNumeric(splitStates[1].substring(0, 1)) - && !splitStates[1].contains("=")) { - return new BlockEntry(new NamespacedId(splitStates[0], splitStates[1]), Collections.emptySet()); - } - - // Complex case: metas and/or state properties - final int statesStart; - final NamespacedId id; - - if (splitStates.length == 2) { - // "stone:0" or "stone:lit=true" - statesStart = 1; - id = new NamespacedId("minecraft", splitStates[0]); - } else if (StringUtils.isNumeric(splitStates[1].substring(0, 1)) || splitStates[1].contains("=")) { - // "stone:0:something" or "stone:lit=true:something" — unlikely but handle it - statesStart = 1; - id = new NamespacedId("minecraft", splitStates[0]); - } else { - // "minecraft:stone:0" or "minecraft:furnace:lit=true" - statesStart = 2; - id = new NamespacedId(splitStates[0], splitStates[1]); - } - - final Set metas = new HashSet<>(); - final Map properties = new HashMap<>(); - - for (int index = statesStart; index < splitStates.length; index++) { - String segment = splitStates[index]; - - if (segment.contains("=")) { - // Blockstate property: key=value - for (String prop : segment.split(",")) { - int eq = prop.indexOf('='); - if (eq > 0 && eq < prop.length() - 1) { - properties.put(prop.substring(0, eq), prop.substring(eq + 1)); - } - } - } else { - // Metadata IDs: comma-separated integers - for (String metaPart : segment.split(",")) { - try { - metas.add(Integer.parseInt(metaPart)); - } catch (NumberFormatException e) { - Iris.logger.warn("Warning: the block ID map entry \"" + entry + "\" could not be fully parsed:"); - Iris.logger.warn("- Metadata ids must be a comma separated list of one or more integers, but " + segment + " is not of that form!"); - } - } - } + /** + * Parses a block ID entry. All tokenization is delegated to {@link PropertiesTokenizer}. + * + * @param entry The string representation of the entry. Must not be empty. + */ + @NotNull + public static BlockEntry parse(@NotNull String entry) { + if (entry.isEmpty()) { + throw new IllegalArgumentException("Called BlockEntry::parse with an empty string"); } - return new BlockEntry(id, metas, properties); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final BlockEntry that = (BlockEntry) o; - return Objects.equals(id, that.id) && Objects.equals(metas, that.metas) && Objects.equals(stateProperties, that.stateProperties); - } - - @Override - public int hashCode() { - return Objects.hash(id, metas, stateProperties); - } + final PropertiesTokenizer.ParsedBlockIdentifier parsed = PropertiesTokenizer.parseBlockIdentifier(entry); + return new BlockEntry(parsed.id(), parsed.metas(), parsed.stateProperties(), parsed.nbtProperties()); + } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java index ee32f528d..c69848428 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java @@ -1,5 +1,6 @@ package net.coderbot.iris.shaderpack.materialmap; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -10,14 +11,15 @@ import java.util.Map; * In 1.7.10, entities are registered with names like "CaveSpider". * Some entities were also renamed or split into multiple types. * - * This map is used at lookup time: when a modern shader pack references an entity by its - * modern name, we resolve it to the 1.7.10 name that EntityList uses. */ public class EntityFlatteningMap { /** Maps modern entity name -> 1.7.10 entity name. */ private static final Map MODERN_TO_LEGACY = new HashMap<>(); + /** Maps modern entity name -> legacy entity name + NBT. */ + private static final Map MODERN_TO_LEGACY_NBT = new HashMap<>(); + static { // Simple case changes simple("Arrow", "arrow"); @@ -35,7 +37,6 @@ public class EntityFlatteningMap { simple("Pig", "pig"); simple("Sheep", "sheep"); simple("Silverfish", "silverfish"); - simple("Skeleton", "skeleton"); simple("Slime", "slime"); simple("Snowball", "snowball"); simple("Spider", "spider"); @@ -49,7 +50,6 @@ public class EntityFlatteningMap { simple("CaveSpider", "cave_spider"); simple("EnderCrystal", "end_crystal"); simple("EnderDragon", "ender_dragon"); - simple("EntityHorse", "horse"); simple("EyeOfEnderSignal", "eye_of_ender"); simple("FallingSand", "falling_block"); simple("Fireball", "fireball"); @@ -79,6 +79,36 @@ public class EntityFlatteningMap { simple("MinecartHopper", "hopper_minecart"); simple("MinecartSpawner", "spawner_minecart"); simple("MinecartTNT", "tnt_minecart"); + + MODERN_TO_LEGACY_NBT.put("skeleton", new BlockEntry( + new NamespacedId("Skeleton"), Collections.emptySet(), Collections.emptyMap(), + Map.of("SkeletonType", new PropertiesTokenizer.NbtValue("0", false)))); + MODERN_TO_LEGACY_NBT.put("wither_skeleton", new BlockEntry( + new NamespacedId("Skeleton"), Collections.emptySet(), Collections.emptyMap(), + Map.of("SkeletonType", new PropertiesTokenizer.NbtValue("1", false)))); + + // 1.7.10 EntityHorse with Type byte: 0=horse, 1=donkey, 2=mule, 3=zombie_horse, + // 4=skeleton_horse. 1.11+ split each into its own entity type. + MODERN_TO_LEGACY_NBT.put("horse", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("0", false)))); + MODERN_TO_LEGACY_NBT.put("donkey", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("1", false)))); + MODERN_TO_LEGACY_NBT.put("mule", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("2", false)))); + MODERN_TO_LEGACY_NBT.put("zombie_horse", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("3", false)))); + MODERN_TO_LEGACY_NBT.put("skeleton_horse", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("4", false)))); + + // 1.7.10 Zombie with IsVillager. + MODERN_TO_LEGACY_NBT.put("zombie_villager", new BlockEntry( + new NamespacedId("Zombie"), Collections.emptySet(), Collections.emptyMap(), + Map.of("IsVillager", new PropertiesTokenizer.NbtValue("1", false)))); } /** @@ -89,6 +119,10 @@ public class EntityFlatteningMap { return MODERN_TO_LEGACY.get(modernName); } + public static BlockEntry toLegacyWithNbt(String modernName) { + return MODERN_TO_LEGACY_NBT.get(modernName); + } + private static void simple(String legacy, String modern) { MODERN_TO_LEGACY.put(modern, legacy); } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java index c2108dca3..324d5ab8e 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java @@ -158,18 +158,18 @@ public class FlatteningMap { rename("dark_oak_wall_sign", "wall_sign"); // === Skull / Head blocks (ID 144) === - // In 1.7.10, skull type is stored in tile entity, not metadata. - // All modern skull blocks map to the same 1.7.10 block. - rename("skeleton_skull", "skull"); - rename("skeleton_wall_skull", "skull"); - rename("wither_skeleton_skull", "skull"); - rename("wither_skeleton_wall_skull", "skull"); - rename("zombie_head", "skull"); - rename("zombie_wall_head", "skull"); - rename("player_head", "skull"); - rename("player_wall_head", "skull"); - rename("creeper_head", "skull"); - rename("creeper_wall_head", "skull"); + // 1.7.10 stores skull type in TileEntitySkull's SkullType byte (0=skeleton, + // 1=wither, 2=zombie, 3=player, 4=creeper). + MODERN_TO_LEGACY.put("skeleton_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("skeleton_wall_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("wither_skeleton_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("wither_skeleton_wall_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("zombie_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("zombie_wall_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("player_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("player_wall_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("creeper_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("4", false))))); + MODERN_TO_LEGACY.put("creeper_wall_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("4", false))))); // ========================================== // Metadata variants (block split by flattening) @@ -321,29 +321,29 @@ public class FlatteningMap { meta("mossy_cobblestone_wall", "cobblestone_wall", 1); // === Flower pot (ID 140) === - // In 1.7.10, flower pot contents are in the tile entity. - // In 1.13+, each potted plant is a separate block. - rename("potted_oak_sapling", "flower_pot"); - rename("potted_spruce_sapling", "flower_pot"); - rename("potted_birch_sapling", "flower_pot"); - rename("potted_jungle_sapling", "flower_pot"); - rename("potted_acacia_sapling", "flower_pot"); - rename("potted_dark_oak_sapling", "flower_pot"); - rename("potted_fern", "flower_pot"); - rename("potted_dandelion", "flower_pot"); - rename("potted_poppy", "flower_pot"); - rename("potted_blue_orchid", "flower_pot"); - rename("potted_allium", "flower_pot"); - rename("potted_azure_bluet", "flower_pot"); - rename("potted_red_tulip", "flower_pot"); - rename("potted_orange_tulip", "flower_pot"); - rename("potted_white_tulip", "flower_pot"); - rename("potted_pink_tulip", "flower_pot"); - rename("potted_oxeye_daisy", "flower_pot"); - rename("potted_red_mushroom", "flower_pot"); - rename("potted_brown_mushroom", "flower_pot"); - rename("potted_dead_bush", "flower_pot"); - rename("potted_cactus", "flower_pot"); + // 1.7.10 stores potted contents in TileEntityFlowerPot's NBT. 1.13+ has a separate block + // per potted plant. + MODERN_TO_LEGACY.put("potted_oak_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_spruce_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("potted_birch_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("potted_jungle_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("potted_acacia_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("4", false))))); + MODERN_TO_LEGACY.put("potted_dark_oak_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("5", false))))); + MODERN_TO_LEGACY.put("potted_fern", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:tallgrass", false), "Data", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("potted_dandelion", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:yellow_flower", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_poppy", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_blue_orchid", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("potted_allium", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("potted_azure_bluet", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("potted_red_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("4", false))))); + MODERN_TO_LEGACY.put("potted_orange_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("5", false))))); + MODERN_TO_LEGACY.put("potted_white_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("6", false))))); + MODERN_TO_LEGACY.put("potted_pink_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("7", false))))); + MODERN_TO_LEGACY.put("potted_oxeye_daisy", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("8", false))))); + MODERN_TO_LEGACY.put("potted_red_mushroom", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_mushroom", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_brown_mushroom", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:brown_mushroom", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_dead_bush", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:deadbush", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_cactus", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:cactus", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); // === Anvil (ID 145) === // Bits 0-1 = facing, bits 2-3 = damage level @@ -928,26 +928,26 @@ public class FlatteningMap { List result = new ArrayList<>(Math.min(a.size(), b.size())); for (BlockEntry entryA : a) { for (BlockEntry entryB : b) { - if (!entryA.getId().equals(entryB.getId())) continue; + if (!entryA.id().equals(entryB.id())) continue; - Set metasA = entryA.getMetas(); - Set metasB = entryB.getMetas(); + Set metasA = entryA.metas(); + Set metasB = entryB.metas(); if (metasA.isEmpty() && metasB.isEmpty()) { // Both wildcard -> wildcard - result.add(new BlockEntry(entryA.getId(), Collections.emptySet())); + result.add(new BlockEntry(entryA.id(), Collections.emptySet())); } else if (metasA.isEmpty()) { // A is wildcard -> use B's constraint - result.add(new BlockEntry(entryA.getId(), metasB)); + result.add(new BlockEntry(entryA.id(), metasB)); } else if (metasB.isEmpty()) { // B is wildcard -> use A's constraint - result.add(new BlockEntry(entryA.getId(), metasA)); + result.add(new BlockEntry(entryA.id(), metasA)); } else { // Both have specific metas -> intersect Set intersection = new IntOpenHashSet(metasA); intersection.retainAll(metasB); if (!intersection.isEmpty()) { - result.add(new BlockEntry(entryA.getId(), intersection)); + result.add(new BlockEntry(entryA.id(), intersection)); } } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/PropertiesTokenizer.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/PropertiesTokenizer.java new file mode 100644 index 000000000..5958e6b48 --- /dev/null +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/PropertiesTokenizer.java @@ -0,0 +1,388 @@ +package net.coderbot.iris.shaderpack.materialmap; + +import net.coderbot.iris.Iris; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +// This got complicated fast + +/** + * This class handles all processing of individual block entries per material ID line. + */ +public final class PropertiesTokenizer { + + private PropertiesTokenizer() { + } + + /** + * Splits a property value into individual block identifier tokens. + */ + public static List tokenizeValues(String input, char delimiter) { + if (input.indexOf('"') == -1 && input.indexOf('\\') == -1 && input.indexOf('[') == -1) { + return tokenizeSimple(input, delimiter); + } + return tokenizeFull(input, delimiter); + } + + // Most blocks should take this path + private static List tokenizeSimple(String input, char delimiter) { + final List result = new ArrayList<>(); + final boolean isWhitespaceDelim = Character.isWhitespace(delimiter); + + if (isWhitespaceDelim) { + for (String part : input.split("\\s+")) { + if (!part.isEmpty()) { + result.add(part); + } + } + } else { + for (String part : input.split(String.valueOf(delimiter))) { + final String trimmed = part.trim(); + if (!trimmed.isEmpty()) { + result.add(trimmed); + } + } + } + return result; + } + + // Found special characters + private static List tokenizeFull(String input, char delimiter) { + final boolean isWhitespaceDelim = Character.isWhitespace(delimiter); + final List result = new ArrayList<>(); + final StringBuilder current = new StringBuilder(); + boolean inQuotes = false; + boolean escaped = false; + int bracketDepth = 0; + + for (int i = 0; i < input.length(); i++) { + final char c = input.charAt(i); + + if (escaped) { + if (bracketDepth > 0) { + // Preserve escapes inside brackets for parseBlockIdentifier + current.append('\\'); + } + current.append(c); + escaped = false; + + } else if (c == '\\') { + escaped = true; + + } else if (bracketDepth > 0) { + current.append(c); + + if (c == '[') { + bracketDepth++; + } + + else if (c == ']') { + bracketDepth--; + } + + } else if (c == '[' && !inQuotes) { + current.append(c); + bracketDepth = 1; + + } else if (c == '"') { + inQuotes = !inQuotes; + + } else if (!inQuotes && (isWhitespaceDelim ? Character.isWhitespace(c) : c == delimiter)) { + if (!current.isEmpty()) { + result.add(current.toString()); + current.setLength(0); + } + + } else { + current.append(c); + } + } + + if (inQuotes) { + Iris.logger.warn("Unclosed quote in properties token: {}", input); + } + + if (!current.isEmpty()) { + result.add(current.toString()); + } + + return result; + } + + // Begin reading the special case block + public static ParsedBlockIdentifier parseBlockIdentifier(String entry) { + final StringBuilder blockIdBuilder = new StringBuilder(); + final Map nbt = new LinkedHashMap<>(); + + boolean escaped = false; + boolean inDoubleQuotes = false; + boolean inSingleQuotes = false; + boolean inBracket = false; + + // NBT pair + StringBuilder nbtKey = new StringBuilder(); + StringBuilder nbtValue = new StringBuilder(); + boolean readingValue = false; + boolean valueLiteral = false; + + for (int i = 0; i < entry.length(); i++) { + final char c = entry.charAt(i); + + // Ignore special characters + if (escaped) { + appendCurrent(inBracket, readingValue, blockIdBuilder, nbtKey, nbtValue, c); + escaped = false; + continue; + } + if (c == '\\') { + escaped = true; + continue; + } + + // Detect special characters + if (inSingleQuotes) { + if (c == '\'') { + inSingleQuotes = false; + + } else { + nbtValue.append(c); + } + continue; + } + + if (inDoubleQuotes) { + if (c == '"') { + inDoubleQuotes = false; + + } else { + appendCurrent(inBracket, readingValue, blockIdBuilder, nbtKey, nbtValue, c); + } + continue; + } + + + if (c == '"') { + inDoubleQuotes = true; + continue; + } + + if (!inBracket) { + if (c == '[') { + inBracket = true; + nbtKey.setLength(0); + nbtValue.setLength(0); + readingValue = false; + valueLiteral = false; + + } else { + blockIdBuilder.append(c); + } + + } else { + if (c == ']') { + flushNbtPair(nbtKey, nbtValue, readingValue, valueLiteral, nbt); + inBracket = false; + + } else if (c == '=' && !readingValue) { + readingValue = true; + valueLiteral = false; + + } else if (c == '\'' && readingValue && nbtValue.isEmpty()) { + inSingleQuotes = true; + valueLiteral = true; + + } else if (c == ',') { + flushNbtPair(nbtKey, nbtValue, readingValue, valueLiteral, nbt); + nbtKey.setLength(0); + nbtValue.setLength(0); + readingValue = false; + valueLiteral = false; + + } else { + if (readingValue) { + nbtValue.append(c); + + } else { + nbtKey.append(c); + } + } + } + } + + if (inDoubleQuotes) { + Iris.logger.warn("Unclosed double quote in block entry: {}", entry); + } + if (inSingleQuotes) { + Iris.logger.warn("Unclosed single quote in block entry: {}", entry); + } + if (escaped) { + Iris.logger.warn("Trailing backslash in block entry: {}", entry); + } + if (inBracket) { + Iris.logger.warn("Unclosed bracket in block entry: {}", entry); + flushNbtPair(nbtKey, nbtValue, readingValue, valueLiteral, nbt); + } + + final String baseEntry = blockIdBuilder.toString().trim(); + final Map nbtProperties = nbt.isEmpty() ? Collections.emptyMap() : nbt; + + return splitBaseEntry(entry, baseEntry, nbtProperties); + } + + /** + * Splits the bracket-stripped portion of a block identifier (e.g. {@code minecraft:furnace:lit=true}) + * into its components. + * + * Accepted forms: + * stone (vanilla block) + * stone:0 (vanilla block with meta) + * minecraft:stone (block with namespaced id specified) + * minecraft:stone:0 (single meta) + * minecraft:stone:0,1,2 (multiple metas) + * minecraft:furnace:lit=true (blockstate property) + * minecraft:oak_log:axis=y,x:variant=oak (multiple blockstate properties) + * flower_pot:1[Item=minecraft:red_flower,Data=0] (used together with NBT brackets) + */ + private static ParsedBlockIdentifier splitBaseEntry(String entry, String baseEntry, Map nbtProperties) { + final Set metas = new HashSet<>(); + final Map stateProperties = new LinkedHashMap<>(); + + if (baseEntry.isEmpty()) { + return new ParsedBlockIdentifier( + new NamespacedId("minecraft", baseEntry), + Collections.emptySet(), + Collections.emptyMap(), + nbtProperties + ); + } + + final String[] splitStates = baseEntry.split(":"); + + // Vanilla block (minecraft namespaced) + if (splitStates.length == 1) { + return new ParsedBlockIdentifier( + new NamespacedId("minecraft", baseEntry), + Collections.emptySet(), + Collections.emptyMap(), + nbtProperties + ); + } + + // Two-segment with no metas/state properties: "minecraft:stone" + if (splitStates.length == 2 + && !StringUtils.isNumeric(splitStates[1].substring(0, 1)) + && !splitStates[1].contains("=")) { + return new ParsedBlockIdentifier( + new NamespacedId(splitStates[0], splitStates[1]), + Collections.emptySet(), + Collections.emptyMap(), + nbtProperties + ); + } + + // Metas and/or state properties + final NamespacedId id; + final int statesStart; + + if (splitStates.length == 2) { + // "stone:0" or "stone:lit=true" + id = new NamespacedId("minecraft", splitStates[0]); + statesStart = 1; + + } else if (StringUtils.isNumeric(splitStates[1].substring(0, 1)) || splitStates[1].contains("=")) { + // "stone:0:something" or "stone:lit=true:something", likely will need this for snowy blocks in the future. + id = new NamespacedId("minecraft", splitStates[0]); + statesStart = 1; + + } else { + // "minecraft:stone:0" or "minecraft:furnace:lit=true" + id = new NamespacedId(splitStates[0], splitStates[1]); + statesStart = 2; + } + + for (int index = statesStart; index < splitStates.length; index++) { + final String segment = splitStates[index]; + + if (segment.contains("=")) { + // Blockstate property segment: key=value[,key=value...] + for (String prop : segment.split(",")) { + final int eq = prop.indexOf('='); + if (eq > 0 && eq < prop.length() - 1) { + stateProperties.put(prop.substring(0, eq), prop.substring(eq + 1)); + } + } + } else { + // Metadata segment (stone:[1,2,3,4,5]) + for (String metaPart : segment.split(",")) { + try { + metas.add(Integer.parseInt(metaPart)); + } catch (NumberFormatException e) { + Iris.logger.warn("Warning: the block ID map entry \"{}\" could not be fully parsed:", entry); + Iris.logger.warn("- Metadata ids must be a comma separated list of one or more integers, but {} is not of that form!", segment); + } + } + } + } + + return new ParsedBlockIdentifier( + id, + metas.isEmpty() ? Collections.emptySet() : metas, + stateProperties.isEmpty() ? Collections.emptyMap() : stateProperties, + nbtProperties + ); + } + + private static void appendCurrent(boolean inBracket, boolean readingValue, + StringBuilder blockIdBuilder, StringBuilder nbtKey, + StringBuilder nbtValue, char c) { + if (!inBracket) { + blockIdBuilder.append(c); + + } else if (readingValue) { + nbtValue.append(c); + + } else { + nbtKey.append(c); + } + } + + private static void flushNbtPair(StringBuilder key, StringBuilder value, + boolean readingValue, boolean valueLiteral, + Map nbt) { + final String k = key.toString().trim(); + if (k.isEmpty()) return; + + if (!readingValue) { + // No = was found, existence is good enough + nbt.put(k, null); + return; + } + + nbt.put(k, new NbtValue(value.toString().trim(), valueLiteral)); + } + + public static String stripQuotes(String value) { + if (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"') { + return value.substring(1, value.length() - 1); + } + return value; + } + + public record NbtValue(String value, boolean literal) { + } + + public record ParsedBlockIdentifier( + NamespacedId id, + Set metas, + Map stateProperties, + Map nbtProperties + ) { + } +} diff --git a/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java b/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java index d003e3cb2..87b9d9130 100644 --- a/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java +++ b/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java @@ -1,10 +1,16 @@ package net.coderbot.iris.uniforms; +import it.unimi.dsi.fastutil.ints.Int2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.IdentityHashMap; +import java.util.Map; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -21,10 +27,16 @@ public final class EntityIdHelper { private static final NamespacedId LIGHTNING_BOLT_ID = new NamespacedId("minecraft", "lightning_bolt"); private static final Object2IntMap> entityIdCache = new Object2IntOpenHashMap<>(); + private static final Map, NamespacedId> entityNameCache = new IdentityHashMap<>(); private static Object2IntFunction cachedEntityIdMap; + private static final Int2LongLinkedOpenHashMap entityNbtCache = new Int2LongLinkedOpenHashMap(); + private static final int NBT_CACHE_INTERVAL_TICKS = 20; + private static final int ENTITY_NBT_CACHE_MAX = 256; + static { entityIdCache.defaultReturnValue(Integer.MIN_VALUE); + entityNbtCache.defaultReturnValue(-1L); } private EntityIdHelper() { @@ -42,17 +54,48 @@ public final class EntityIdHelper { return -1; } - // Invalidate cache if the map changed (shader reload) + // Invalidate caches if the map changed (shader reload) if (entityIdMap != cachedEntityIdMap) { entityIdCache.clear(); + entityNameCache.clear(); + entityNbtCache.clear(); cachedEntityIdMap = entityIdMap; } + // Check NBT-conditional match first + final NbtConditionalIdMap entityNbtMap = BlockRenderingSettings.INSTANCE.getEntityNbtMap(); + if (entityNbtMap != null && !entityNbtMap.isEmpty() && entity.worldObj != null) { + final NamespacedId namespacedId = getCachedEntityName(entity); + if (namespacedId != null && entityNbtMap.hasConditions(namespacedId)) { + final int entityRuntimeId = entity.getEntityId(); + final long currentTick = entity.worldObj.getTotalWorldTime(); + final long cached = entityNbtCache.get(entityRuntimeId); + + final int nbtId; + if (cached != -1L && (currentTick - (cached >>> 32)) < NBT_CACHE_INTERVAL_TICKS) { + nbtId = (int) cached; + } else { + final NBTTagCompound nbt = new NBTTagCompound(); + entity.writeToNBT(nbt); + nbtId = entityNbtMap.resolve(namespacedId, nbt); + final long packed = ((currentTick & 0x7FFFFFFFL) << 32) | (nbtId & 0xFFFFFFFFL); + entityNbtCache.put(entityRuntimeId, packed); + while (entityNbtCache.size() > ENTITY_NBT_CACHE_MAX) { + entityNbtCache.removeFirstLong(); + } + } + + if (nbtId != -1) { + return nbtId; + } + } + } + // Normal entity type lookup - int normalId = getNormalEntityId(entity, entityIdMap); + final int normalId = getNormalEntityId(entity, entityIdMap); // Check for special entity type overrides - int specialId = getSpecialEntityId(entity, entityIdMap); + final int specialId = getSpecialEntityId(entity, entityIdMap); if (specialId != -1) { return specialId; } @@ -134,4 +177,24 @@ public final class EntityIdHelper { return id; } + + /** + * Returns a cached NamespacedId for the entity's registered type. + */ + private static NamespacedId getCachedEntityName(Entity entity) { + Class entityClass = entity.getClass(); + NamespacedId cached = entityNameCache.get(entityClass); + if (cached != null) { + return cached; + } + + String entityType = EntityList.getEntityString(entity); + if (entityType == null) { + return null; + } + + cached = new NamespacedId(entityType); + entityNameCache.put(entityClass, cached); + return cached; + } } diff --git a/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java b/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java index 74c064bb4..424f8faef 100644 --- a/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java +++ b/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java @@ -6,6 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.minecraft.block.Block; import net.minecraft.item.Item; @@ -20,6 +21,7 @@ import net.minecraft.util.ResourceLocation; public class ItemMaterialHelper { private static final Reference2ObjectMap MATERIAL_CACHE = new Reference2ObjectOpenHashMap<>(); private static final int CACHE_MISS_SENTINEL = Integer.MIN_VALUE; + private static final Reference2ObjectMap ITEM_NAME_CACHE = new Reference2ObjectOpenHashMap<>(); /** * Get the material ID for an ItemStack. * For ItemBlock: checks block.properties first, then item.properties. @@ -32,6 +34,19 @@ public class ItemMaterialHelper { if (itemStack == null || itemStack.getItem() == null) { return -1; } + + // Check item NBT conditions first + final NbtConditionalIdMap itemNbtMap = BlockRenderingSettings.INSTANCE.getItemNbtMap(); + if (itemNbtMap != null && !itemNbtMap.isEmpty() && itemStack.hasTagCompound()) { + NamespacedId namespacedId = getCachedItemName(itemStack.getItem()); + if (namespacedId != null && itemNbtMap.hasConditions(namespacedId)) { + int nbtId = itemNbtMap.resolve(namespacedId, itemStack.getTagCompound()); + if (nbtId != -1) { + return nbtId; + } + } + } + return getMaterialId(itemStack.getItem(), itemStack.getItemDamage()); } @@ -73,8 +88,7 @@ public class ItemMaterialHelper { */ private static int lookupMaterialId(Item item, int metadata) { // For ItemBlock: check block.properties first - if (item instanceof ItemBlock) { - final ItemBlock itemBlock = (ItemBlock) item; + if (item instanceof ItemBlock itemBlock) { final Block block = itemBlock.field_150939_a; // The block this item places if (block != null) { @@ -94,7 +108,7 @@ public class ItemMaterialHelper { // Fall back to item.properties Object2IntFunction itemIds = BlockRenderingSettings.INSTANCE.getItemIds(); if (itemIds != null) { - String itemIdString = (String) Item.itemRegistry.getNameForObject(item); + String itemIdString = Item.itemRegistry.getNameForObject(item); if (itemIdString != null) { ResourceLocation itemId = new ResourceLocation(itemIdString); return itemIds.applyAsInt(new NamespacedId(itemId.getResourceDomain(), itemId.getResourcePath())); @@ -110,5 +124,23 @@ public class ItemMaterialHelper { */ public static void clearCache() { MATERIAL_CACHE.clear(); + ITEM_NAME_CACHE.clear(); + } + + private static NamespacedId getCachedItemName(Item item) { + NamespacedId cached = ITEM_NAME_CACHE.get(item); + if (cached != null) { + return cached; + } + + String itemIdString = Item.itemRegistry.getNameForObject(item); + if (itemIdString == null) { + return null; + } + + ResourceLocation itemId = new ResourceLocation(itemIdString); + cached = new NamespacedId(itemId.getResourceDomain(), itemId.getResourcePath()); + ITEM_NAME_CACHE.put(item, cached); + return cached; } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinNetHandlerPlayClient_NbtRemesh.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinNetHandlerPlayClient_NbtRemesh.java new file mode 100644 index 000000000..438cb3e56 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinNetHandlerPlayClient_NbtRemesh.java @@ -0,0 +1,41 @@ +package com.gtnewhorizons.angelica.mixins.early.shaders; + +import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(NetHandlerPlayClient.class) +public class MixinNetHandlerPlayClient_NbtRemesh { + + // Needed or TEs will be missed when meshing + @Inject(method = "handleUpdateTileEntity", at = @At("RETURN")) + private void angelica$remeshOnTileEntityUpdate(S35PacketUpdateTileEntity packet, CallbackInfo ci) { + final NbtConditionalIdMap teMap = BlockRenderingSettings.INSTANCE.getBlockNbtMap(); + if (teMap == null || teMap.isEmpty()) { + return; + } + + final World world = Minecraft.getMinecraft().theWorld; + if (world == null) { + return; + } + + final int x = packet.func_148856_c/*getX*/() ; + final int y = packet.func_148855_d/*getY*/(); + final int z = packet.func_148854_e/*getZ*/(); + final Block block = world.getBlock(x, y, z); + if (block == null || !teMap.hasConditions(block)) { + return; + } + + world.markBlockForUpdate(x, y, z); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinWorldNbtCache.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinWorldNbtCache.java new file mode 100644 index 000000000..c42020415 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinWorldNbtCache.java @@ -0,0 +1,17 @@ +package com.gtnewhorizons.angelica.mixins.early.shaders; + +import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(World.class) +public class MixinWorldNbtCache { + + @Inject(method = "markBlockForUpdate", at = @At("HEAD")) + private void angelica$onMarkBlockForUpdate(int x, int y, int z, CallbackInfo ci) { + BlockRenderingSettings.invalidateTeNbtCache(x, y, z); + } +}