diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java index 74fcbbe65..0f8d31ecf 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java @@ -29,6 +29,7 @@ import art.arcane.iris.modded.ModdedBlockResolution; import art.arcane.iris.modded.ModdedLootApplier; import art.arcane.iris.modded.ModdedServerLevels; import art.arcane.iris.modded.ModdedTileData; +import art.arcane.iris.modded.api.ModdedBlockData; import art.arcane.iris.modded.api.ModdedCustomContentRegistry; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.project.matter.TileWrapper; @@ -50,6 +51,9 @@ import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; @@ -216,10 +220,11 @@ public final class ModdedChunkUpdateService implements ModdedTickableService { })); } - private void runCustomPass(Engine engine, ServerLevel level, int chunkX, int chunkZ, MantleChunk chunk) { + void runCustomPass(Engine engine, ServerLevel level, int chunkX, int chunkZ, MantleChunk chunk) { int baseX = chunkX << 4; int baseZ = chunkZ << 4; int minHeight = engine.getWorld().minHeight(); + StaleCarriers stale = new StaleCarriers(); materializeDeferredSlice(chunk, Identifier.class, () -> chunk.iterate(Identifier.class, (Integer x, Integer yf, Integer z, Identifier identifier) -> { int y = yf + minHeight; @@ -227,8 +232,13 @@ public final class ModdedChunkUpdateService implements ModdedTickableService { return; } BlockPos position = new BlockPos(baseX + (x & 15), y, baseZ + (z & 15)); - ModdedCustomContentRegistry.processBlockPlacement(engine, level, position, identifier.toString()); + String key = identifier.toString(); + if (stale.carrierReplaced(key, level.getBlockState(position))) { + return; + } + ModdedCustomContentRegistry.processBlockPlacement(engine, level, position, key); })); + stale.report(level.dimension().identifier().toString(), chunkX, chunkZ); } static void materializeDeferredSlice(MantleChunk chunk, Class sliceType, Runnable materializer) { @@ -374,4 +384,34 @@ public final class ModdedChunkUpdateService implements ModdedTickableService { level.setBlock(pos, state, Block.UPDATE_ALL); } } + + private static final class StaleCarriers { + private final Map> carriers = new HashMap<>(); + private int skipped; + + private boolean carrierReplaced(String key, BlockState live) { + Optional carrier = carriers.computeIfAbsent(key, StaleCarriers::carrierBlock); + if (carrier.isEmpty() || carrier.get() == live.getBlock()) { + return false; + } + skipped++; + return true; + } + + private void report(String levelName, int chunkX, int chunkZ) { + if (skipped == 0) { + return; + } + IrisLogging.debug("Skipped %d stale custom block records at chunk %d,%d in %s", + skipped, chunkX, chunkZ, levelName); + } + + private static Optional carrierBlock(String key) { + ModdedBlockData resolved = ModdedCustomContentRegistry.resolveBlock(key); + if (resolved == null || resolved.state().isAir()) { + return Optional.empty(); + } + return Optional.of(resolved.state().getBlock()); + } + } } diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceCarrierTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceCarrierTest.java new file mode 100644 index 000000000..5aeebbdf8 --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceCarrierTest.java @@ -0,0 +1,210 @@ +package art.arcane.iris.modded.service; + +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.engine.IrisEngine; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.modded.api.ModdedBlockData; +import art.arcane.iris.modded.api.ModdedBlockPlacementContext; +import art.arcane.iris.modded.api.ModdedCustomContentRegistry; +import art.arcane.iris.modded.api.ModdedDataProvider; +import art.arcane.iris.modded.api.ModdedDataType; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.function.Consumer4; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.mantle.runtime.MantleDataAdapter; +import art.arcane.volmlib.util.mantle.runtime.MantleHooks; +import art.arcane.volmlib.util.matter.Matter; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.NoteBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.invocation.InvocationOnMock; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +public class ModdedChunkUpdateServiceCarrierTest { + private static final String MOD_ID = "iris_carrier_guard_test"; + private static final net.minecraft.resources.Identifier LAMP = + net.minecraft.resources.Identifier.parse(MOD_ID + ":lamp"); + private static final net.minecraft.resources.Identifier CHAIR = + net.minecraft.resources.Identifier.parse(MOD_ID + ":chair"); + private static final int MIN_HEIGHT = -64; + private static final int RECORD_Y = 70; + private static final List PLACED = new CopyOnWriteArrayList<>(); + + @BeforeClass + public static void bootstrapMinecraftRegistries() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + ModdedCustomContentRegistry.register(new CarrierProvider()); + } + + @Before + public void clearPlacements() { + PLACED.clear(); + } + + @Test + public void staleRecordsAreSkippedWhileIntactAndAirCarrierRecordsArePlaced() throws Exception { + RecordMantleChunk chunk = new RecordMantleChunk(List.of( + new Placed(1, LAMP.toString()), + new Placed(2, LAMP.toString()), + new Placed(3, LAMP.toString()), + new Placed(4, CHAIR.toString()))); + ServerLevel level = level(Map.of( + 1, Blocks.NOTE_BLOCK.defaultBlockState().setValue(NoteBlock.NOTE, 7), + 2, Blocks.AIR.defaultBlockState(), + 3, Blocks.COBBLESTONE.defaultBlockState(), + 4, Blocks.COBBLESTONE.defaultBlockState())); + List debug = new ArrayList<>(); + + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + logging.when(() -> IrisLogging.debug(anyString(), any(Object[].class))).thenAnswer((InvocationOnMock invocation) -> { + Object[] arguments = invocation.getArguments(); + debug.add(String.format((String) arguments[0], Arrays.copyOfRange(arguments, 1, arguments.length))); + return null; + }); + + new ModdedChunkUpdateService().runCustomPass(engine(), level, 0, 0, chunk); + } + + assertEquals(List.of(new BlockPos(1, RECORD_Y, 1), new BlockPos(4, RECORD_Y, 4)), PLACED); + assertTrue(chunk.customDeleted()); + assertEquals(1, debug.size()); + assertTrue(debug.getFirst(), debug.getFirst().contains("2 stale")); + } + + private static ServerLevel level(Map live) { + ServerLevel level = mock(ServerLevel.class); + when(level.getMinY()).thenReturn(MIN_HEIGHT); + when(level.getMaxY()).thenReturn(320); + when(level.dimension()).thenReturn(Level.OVERWORLD); + when(level.getBlockState(any(BlockPos.class))).thenAnswer((InvocationOnMock invocation) -> { + BlockPos position = invocation.getArgument(0); + return live.getOrDefault(position.getX(), Blocks.STONE.defaultBlockState()); + }); + return level; + } + + private static Engine engine() throws Exception { + Field unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + Object unsafe = unsafeField.get(null); + Method allocateInstance = unsafe.getClass().getMethod("allocateInstance", Class.class); + WorldEngine engine = (WorldEngine) allocateInstance.invoke(unsafe, WorldEngine.class); + engine.world = IrisWorld.builder().minHeight(MIN_HEIGHT).build(); + return engine; + } + + private static final class WorldEngine extends IrisEngine { + private IrisWorld world; + + private WorldEngine() { + super(null, InitializationMode.RUNTIME); + } + + @Override + public IrisWorld getWorld() { + return world; + } + } + + @SuppressWarnings("unchecked") + private static MantleDataAdapter emptyAdapter() { + return (MantleDataAdapter) Proxy.newProxyInstance( + MantleDataAdapter.class.getClassLoader(), + new Class[]{MantleDataAdapter.class}, + (proxy, method, arguments) -> { + throw new UnsupportedOperationException(method.getName()); + } + ); + } + + private record Placed(int offset, String key) { + } + + private static final class RecordMantleChunk extends MantleChunk { + private final List records; + private boolean customDeleted; + + private RecordMantleChunk(List records) { + super(1, 0, 0, emptyAdapter(), MantleHooks.NONE); + this.records = records; + } + + @Override + public void iterate(Class type, Consumer4 iterator) { + if (type != Identifier.class) { + return; + } + for (Placed record : records) { + iterator.accept(record.offset(), RECORD_Y - MIN_HEIGHT, record.offset(), + type.cast(Identifier.fromString(record.key()))); + } + } + + @Override + public void deleteSlices(Class type) { + if (type == Identifier.class) { + customDeleted = true; + } + } + + private boolean customDeleted() { + return customDeleted; + } + } + + private static final class CarrierProvider implements ModdedDataProvider { + @Override + public String modId() { + return MOD_ID; + } + + @Override + public Collection getTypes(ModdedDataType type) { + return type == ModdedDataType.BLOCK ? List.of(LAMP, CHAIR) : List.of(); + } + + @Override + public boolean isValidProvider(net.minecraft.resources.Identifier id, ModdedDataType type) { + return type == ModdedDataType.BLOCK && (LAMP.equals(id) || CHAIR.equals(id)); + } + + @Override + public ModdedBlockData getBlockData(net.minecraft.resources.Identifier blockId, Map state) { + BlockState carrier = CHAIR.equals(blockId) ? Blocks.AIR.defaultBlockState() : Blocks.NOTE_BLOCK.defaultBlockState(); + return ModdedBlockData.deferred(carrier); + } + + @Override + public void processBlockPlacement(ModdedBlockPlacementContext context) { + PLACED.add(context.position()); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java index 5ace02c2d..9b021b395 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/EngineBukkitOps.java @@ -33,6 +33,7 @@ import art.arcane.iris.engine.framework.WrongEngineBroException; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.util.common.data.IrisCustomData; import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.platform.bukkit.BukkitBlockState; import art.arcane.iris.spi.IrisLogging; @@ -80,7 +81,9 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.loot.Lootable; import java.lang.reflect.Method; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CancellationException; @@ -194,12 +197,16 @@ public final class EngineBukkitOps { } static void materializeTiles(Engine engine, Chunk chunk, MantleChunk mantleChunk) { + StaleRecords stale = new StaleRecords(); mantleChunk.iterate(TileWrapper.class, (x, y, z, value) -> { int worldY = y + engine.getWorld().minHeight(); if (worldY < chunk.getWorld().getMinHeight() || worldY >= chunk.getWorld().getMaxHeight()) { return; } Block block = chunk.getBlock(x & 15, worldY, z & 15); + if (stale.tileReplaced(block, value.getData())) { + return; + } if (!TileData.setTileState(block, value.getData())) { NamespacedKey blockTypeKey = KeyedType.getKey(block.getType()); String blockType = blockTypeKey == null ? block.getType().name() : blockTypeKey.toString(); @@ -208,21 +215,25 @@ public final class EngineBukkitOps { } }); mantleChunk.deleteSlices(TileWrapper.class); + stale.report("tile", chunk); } static void materializeCustomBlocks(Engine engine, Chunk chunk, MantleChunk mantleChunk) { + StaleRecords stale = new StaleRecords(); mantleChunk.iterate(Identifier.class, (x, y, z, value) -> { int worldY = y + engine.getWorld().minHeight(); if (worldY < chunk.getWorld().getMinHeight() || worldY >= chunk.getWorld().getMaxHeight()) { return; } - IrisServices.get(ExternalDataSVC.class).processUpdate( - engine, - chunk.getBlock(x & 15, worldY, z & 15), - value - ); + ExternalDataSVC service = IrisServices.get(ExternalDataSVC.class); + Block block = chunk.getBlock(x & 15, worldY, z & 15); + if (stale.carrierReplaced(service, block, value)) { + return; + } + service.processUpdate(engine, block, value); }); mantleChunk.deleteSlices(Identifier.class); + stale.report("custom block", chunk); } static void runMaterializationPasses( @@ -693,4 +704,44 @@ public final class EngineBukkitOps { record LootMutationTask(World world, int chunkX, int chunkZ, Runnable mutation) { } + + private static final class StaleRecords { + private final Map carriers = new HashMap<>(); + private int skipped; + + private boolean carrierReplaced(ExternalDataSVC service, Block block, Identifier record) { + Material carrier = carriers.computeIfAbsent(record, key -> carrierType(service, key)); + if (carrier == Material.AIR || block.getType() == carrier) { + return false; + } + skipped++; + return true; + } + + private boolean tileReplaced(Block block, TileData tile) { + if (tile.resolveMaterial() == null || tile.isApplicable(block.getBlockData())) { + return false; + } + skipped++; + return true; + } + + private void report(String records, Chunk chunk) { + if (skipped == 0) { + return; + } + IrisLogging.debug("Skipped %d stale %s records at chunk %d,%d in %s", + skipped, records, chunk.getX(), chunk.getZ(), chunk.getWorld().getName()); + } + + private static Material carrierType(ExternalDataSVC service, Identifier record) { + Optional resolved = service.getBlockData(record); + if (resolved.isEmpty()) { + return Material.AIR; + } + BlockData data = resolved.get(); + Material type = (data instanceof IrisCustomData custom ? custom.getBase() : data).getMaterial(); + return type == Material.CAVE_AIR || type == Material.VOID_AIR ? Material.AIR : type; + } + } } diff --git a/core/src/test/java/art/arcane/iris/engine/platform/EngineBukkitOpsStaleRecordTest.java b/core/src/test/java/art/arcane/iris/engine/platform/EngineBukkitOpsStaleRecordTest.java new file mode 100644 index 000000000..0fcfca02c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/platform/EngineBukkitOpsStaleRecordTest.java @@ -0,0 +1,281 @@ +package art.arcane.iris.engine.platform; + +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.core.service.ExternalDataSVC; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.engine.object.world.IrisWorld; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.spi.PlatformRegistries; +import art.arcane.iris.util.common.data.IrisCustomData; +import art.arcane.iris.util.project.matter.TileWrapper; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.function.Consumer4; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.TileState; +import org.bukkit.block.data.BlockData; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.invocation.InvocationOnMock; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class EngineBukkitOpsStaleRecordTest { + private static final Identifier ORE = Identifier.fromString("itemsadder:forest/amber_ore"); + private static final Identifier CHAIR = Identifier.fromString("craftengine:test/chair[variant=alpha]"); + + @Before + public void bindPlatform() { + IrisPlatforms.unbind(); + PlatformRegistries registries = mock(PlatformRegistries.class); + IrisPlatform platform = mock(IrisPlatform.class); + when(registries.block(anyString())).thenReturn(mock(PlatformBlockState.class)); + when(platform.registries()).thenReturn(registries); + IrisPlatforms.bind(platform); + } + + @After + public void unbindPlatform() { + IrisPlatforms.unbind(); + } + + @Test + public void customRecordOverFlattenedAirIsNotPlaced() { + Fixture fixture = new Fixture(); + fixture.carrier(ORE, Material.NOTE_BLOCK); + Block flattened = fixture.block(1, 10, 1, Material.AIR); + MantleChunk records = customRecords(new Placed<>(1, 10, 1, ORE)); + + fixture.materializeCustomBlocks(records); + + verify(fixture.service, never()).processUpdate(any(), eq(flattened), any()); + verify(records).deleteSlices(Identifier.class); + } + + @Test + public void customRecordOverReplacedBlockIsNotPlaced() { + Fixture fixture = new Fixture(); + fixture.carrier(ORE, Material.NOTE_BLOCK); + Block wall = fixture.block(2, 10, 2, Material.COBBLESTONE); + MantleChunk records = customRecords(new Placed<>(2, 10, 2, ORE)); + + fixture.materializeCustomBlocks(records); + + verify(fixture.service, never()).processUpdate(any(), eq(wall), any()); + verify(records).deleteSlices(Identifier.class); + } + + @Test + public void customRecordOverIntactCarrierIsPlaced() { + Fixture fixture = new Fixture(); + fixture.carrier(ORE, Material.NOTE_BLOCK); + Block intact = fixture.block(3, 10, 3, Material.NOTE_BLOCK); + + fixture.materializeCustomBlocks(customRecords(new Placed<>(3, 10, 3, ORE))); + + verify(fixture.service).processUpdate(fixture.engine, intact, ORE); + } + + @Test + public void airCarrierFurnitureRecordIsPlacedWhateverTheLiveBlock() { + Fixture fixture = new Fixture(); + fixture.carrier(CHAIR, Material.AIR); + Block open = fixture.block(4, 10, 4, Material.AIR); + Block covered = fixture.block(5, 10, 5, Material.COBBLESTONE); + + fixture.materializeCustomBlocks(customRecords( + new Placed<>(4, 10, 4, CHAIR), + new Placed<>(5, 10, 5, CHAIR))); + + verify(fixture.service).processUpdate(fixture.engine, open, CHAIR); + verify(fixture.service).processUpdate(fixture.engine, covered, CHAIR); + } + + @Test + public void unresolvableCarrierLeavesPlacementToTheProvider() { + Fixture fixture = new Fixture(); + when(fixture.service.getBlockData(ORE)).thenReturn(Optional.empty()); + Block block = fixture.block(6, 10, 6, Material.STONE); + + fixture.materializeCustomBlocks(customRecords(new Placed<>(6, 10, 6, ORE))); + + verify(fixture.service).processUpdate(fixture.engine, block, ORE); + } + + @Test + public void carrierResolvesOncePerIdentifierAndStaleRecordsLogOncePerChunk() { + Fixture fixture = new Fixture(); + fixture.carrier(ORE, Material.NOTE_BLOCK); + fixture.block(1, 10, 1, Material.AIR); + fixture.block(2, 10, 2, Material.COBBLESTONE); + Block intact = fixture.block(3, 10, 3, Material.NOTE_BLOCK); + MantleChunk records = customRecords( + new Placed<>(1, 10, 1, ORE), + new Placed<>(2, 10, 2, ORE), + new Placed<>(3, 10, 3, ORE)); + + List debug = fixture.materializeCustomBlocksCapturingDebug(records); + + verify(fixture.service, times(1)).getBlockData(ORE); + verify(fixture.service, times(1)).processUpdate(any(), any(), any()); + verify(fixture.service).processUpdate(fixture.engine, intact, ORE); + assertEquals(1, debug.size()); + assertTrue(debug.getFirst(), debug.getFirst().contains("2 stale")); + } + + @Test + public void staleTileRecordIsSkippedWithoutWarning() { + Fixture fixture = new Fixture(); + TileData chest = chestTile(); + Block replaced = fixture.block(7, 10, 7, Material.STONE); + BlockData stone = blockData(Material.STONE); + when(replaced.getBlockData()).thenReturn(stone); + + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + EngineBukkitOps.materializeTiles(fixture.engine, fixture.chunk, tileRecords(new Placed<>(7, 10, 7, chest))); + + logging.verify(() -> IrisLogging.warn(anyString(), any(Object[].class)), never()); + logging.verify(() -> IrisLogging.debug(anyString(), any(Object[].class)), times(1)); + } + verify(chest, never()).toBukkitTry(any()); + } + + @Test + public void intactTileRecordIsApplied() { + Fixture fixture = new Fixture(); + TileData chest = chestTile(); + Block intact = fixture.block(8, 10, 8, Material.CHEST); + BlockData chestData = blockData(Material.CHEST); + when(intact.getBlockData()).thenReturn(chestData); + when(intact.getState()).thenReturn(mock(TileState.class)); + doReturn(true).when(chest).toBukkitTry(intact); + + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + EngineBukkitOps.materializeTiles(fixture.engine, fixture.chunk, tileRecords(new Placed<>(8, 10, 8, chest))); + + logging.verify(() -> IrisLogging.warn(anyString(), any(Object[].class)), never()); + } + verify(chest).toBukkitTry(intact); + } + + private static TileData chestTile() { + TileData tile = spy(new TileData("minecraft:chest", new KMap<>())); + doReturn(Material.CHEST).when(tile).resolveMaterial(); + return tile; + } + + private static BlockData blockData(Material material) { + BlockData data = mock(BlockData.class); + when(data.getMaterial()).thenReturn(material); + return data; + } + + @SafeVarargs + private static MantleChunk customRecords(Placed... records) { + return records(Identifier.class, records); + } + + @SafeVarargs + private static MantleChunk tileRecords(Placed... records) { + List> wrapped = new ArrayList<>(records.length); + for (Placed record : records) { + wrapped.add(new Placed<>(record.x(), record.y(), record.z(), new TileWrapper(record.value()))); + } + return records(TileWrapper.class, wrapped.toArray(Placed[]::new)); + } + + @SuppressWarnings("unchecked") + private static MantleChunk records(Class type, Placed[] records) { + MantleChunk chunk = mock(MantleChunk.class); + doAnswer((InvocationOnMock invocation) -> { + Consumer4 iterator = invocation.getArgument(1); + for (Placed record : records) { + iterator.accept(record.x(), record.y(), record.z(), record.value()); + } + return null; + }).when(chunk).iterate(eq(type), any()); + return chunk; + } + + private record Placed(int x, int y, int z, T value) { + } + + private static final class Fixture { + private final Engine engine = mock(Engine.class); + private final Chunk chunk = mock(Chunk.class); + private final ExternalDataSVC service = mock(ExternalDataSVC.class); + + private Fixture() { + IrisWorld irisWorld = mock(IrisWorld.class); + when(engine.getWorld()).thenReturn(irisWorld); + World world = mock(World.class); + when(world.getMinHeight()).thenReturn(0); + when(world.getMaxHeight()).thenReturn(256); + when(world.getName()).thenReturn("example"); + when(chunk.getWorld()).thenReturn(world); + } + + private void carrier(Identifier identifier, Material material) { + BlockData carrier = IrisCustomData.of(blockData(material), identifier); + when(service.getBlockData(identifier)).thenReturn(Optional.of(carrier)); + } + + private Block block(int x, int y, int z, Material type) { + Block block = mock(Block.class); + when(block.getType()).thenReturn(type); + when(chunk.getBlock(x, y, z)).thenReturn(block); + return block; + } + + private void materializeCustomBlocks(MantleChunk records) { + try (MockedStatic services = mockStatic(IrisServices.class)) { + services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(service); + EngineBukkitOps.materializeCustomBlocks(engine, chunk, records); + } + } + + private List materializeCustomBlocksCapturingDebug(MantleChunk records) { + List messages = new ArrayList<>(); + try (MockedStatic services = mockStatic(IrisServices.class); + MockedStatic logging = mockStatic(IrisLogging.class)) { + services.when(() -> IrisServices.get(ExternalDataSVC.class)).thenReturn(service); + logging.when(() -> IrisLogging.debug(anyString(), any(Object[].class))).thenAnswer((InvocationOnMock invocation) -> { + Object[] arguments = invocation.getArguments(); + messages.add(String.format((String) arguments[0], Arrays.copyOfRange(arguments, 1, arguments.length))); + return null; + }); + EngineBukkitOps.materializeCustomBlocks(engine, chunk, records); + } + return messages; + } + } +}