Merge upstream port lane c

This commit is contained in:
piexel committed 2026-11-10 01:31:37 +01:00
commit 55786d6297
50 files changed
+2014 -256

No files matched your search

@@ -179,8 +179,6 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
if (level.getChunkSource().getGenerator() != this) {
throw new IllegalArgumentException("ServerLevel does not use Iris generator '" + dimensionKey + "'");
}
requireGlobalStructureGeneration(
level.getServer().getWorldGenSettings().options().generateStructures(), dimensionKey);
Engine replacement = ModdedWorldEngines.prepareReplacement(level, pack, packDimensionKey, seed);
try {
ModdedWorldEngines.installReplacement(level, replacement);
@@ -447,13 +445,6 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
private Engine bindEngine(ServerLevel level) {
requireBindingAllowed();
try {
requireGlobalStructureGeneration(
level.getServer().getWorldGenSettings().options().generateStructures(), dimensionKey);
} catch (RuntimeException error) {
engineBinding.fail(error);
throw error;
}
// Cache the owning level so hot paths never scan the level map to find themselves.
boundLevel = level;
Engine cached = engine;
@@ -527,29 +518,6 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator {
}
}
static void requireGlobalStructureGeneration(boolean enabled, String dimensionKey) {
if (enabled) {
return;
}
String remedy = integratedEnvironment()
? "enable 'Generate Structures' for this world; Iris requires it, then deny families through "
+ "importedStructures.disabled or complete keys through importedStructures.disabledExact"
: "set generate-structures=true in server.properties, restart the server, "
+ "then deny families through importedStructures.disabled or complete keys through "
+ "importedStructures.disabledExact";
throw new IllegalStateException("Iris generator '" + dimensionKey
+ "' cannot bind while generate-structures=false; " + remedy);
}
private static boolean integratedEnvironment() {
try {
return ModdedEngineBootstrap.loader().clientEnvironment();
} catch (Throwable e) {
// No loader bound (unit tests, very early boot): assume dedicated wording.
return false;
}
}
Engine engineOrNull() {
requireBindingAllowed();
Engine cached = engine;
@@ -21,6 +21,7 @@ package art.arcane.iris.modded;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.core.modules.ModuleServices;
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords;
import art.arcane.iris.engine.framework.NativeStructureLayouts;
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
@@ -278,16 +279,6 @@ final class ModdedNativeStructureStage {
}
void placeVanillaStructures(WorldGenLevel world, ChunkAccess chunk, StructureManager structureManager) {
if (!structureManager.shouldGenerateStructures()) {
ChunkPos disabledChunk = chunk.getPos();
throw new IllegalStateException("Iris cannot generate native structures in chunk "
+ disabledChunk.x() + "," + disabledChunk.z()
+ " because generate-structures=false disables them outside the pack. That flag is fixed when "
+ "the world is created (server.properties generate-structures, or the Generate Structures "
+ "toggle in singleplayer), so it cannot be changed for this world: create a new world with "
+ "structures enabled, then deny families through importedStructures.disabled or complete keys "
+ "through importedStructures.disabledExact");
}
ChunkPos chunkPos = chunk.getPos();
SectionPos sectionPos = SectionPos.of(chunkPos, world.getMinSectionY());
BlockPos origin = sectionPos.origin();
@@ -411,7 +402,7 @@ final class ModdedNativeStructureStage {
String structureId, NativePlacement placement) {
Engine current = generator.engine();
int runtimeMinY = world.getMinY();
WorldGenLevel boundedWorld = ModdedNativeStructureWorldgenAccess.create(
ModdedNativeStructureWorldgenAccess boundedWorld = ModdedNativeStructureWorldgenAccess.create(
world, chunkPos,
worldgenSurfaceHeight(current, runtimeMinY),
worldgenFloorHeight(current, runtimeMinY));
@@ -423,6 +414,7 @@ final class ModdedNativeStructureStage {
generator.getSeaLevel(), area.minY(), area.maxY() + 1);
start.placeInChunk(boundedWorld, structureManager, generator, random, area, chunkPos);
} finally {
DeferredPlacementRecords.clearWritten(current, boundedWorld.writtenBlocks());
world.setCurrentlyGenerating(null);
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.modded;
import art.arcane.iris.engine.mantle.DeferredPlacementRecords.WrittenBlocks;
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
@@ -70,6 +71,7 @@ final class ModdedNativeStructureWorldgenAccess implements WorldGenLevel {
private final LevelTickAccess<Fluid> fluidTicks;
private final Long2LongOpenHashMap terrainHeights;
private final Long2ObjectOpenHashMap<ChunkAccess> outsideChunks;
private final WrittenBlocks writtenBlocks = new WrittenBlocks();
private ModdedNativeStructureWorldgenAccess(WorldGenLevel delegate, Boundary boundary) {
this.delegate = Objects.requireNonNull(delegate, "Native structure world access requires a delegate");
@@ -405,17 +407,28 @@ final class ModdedNativeStructureWorldgenAccess implements WorldGenLevel {
@Override
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
return isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit);
return recordWrite(position, isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit));
}
@Override
public boolean removeBlock(BlockPos position, boolean move) {
return isWritable(position) && delegate.removeBlock(position, move);
return recordWrite(position, isWritable(position) && delegate.removeBlock(position, move));
}
@Override
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
return isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit);
return recordWrite(position, isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit));
}
WrittenBlocks writtenBlocks() {
return writtenBlocks;
}
private boolean recordWrite(BlockPos position, boolean written) {
if (written) {
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
}
return written;
}
@Override
@@ -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<Matter> chunk) {
void runCustomPass(Engine engine, ServerLevel level, int chunkX, int chunkZ, MantleChunk<Matter> 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<Matter> 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<String, Optional<Block>> carriers = new HashMap<>();
private int skipped;
private boolean carrierReplaced(String key, BlockState live) {
Optional<Block> 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<Block> carrierBlock(String key) {
ModdedBlockData resolved = ModdedCustomContentRegistry.resolveBlock(key);
if (resolved == null || resolved.state().isAir()) {
return Optional.empty();
}
return Optional.of(resolved.state().getBlock());
}
}
}
@@ -12,7 +12,6 @@ import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class NativeStructureFailureContractTest {
@@ -42,18 +41,13 @@ public class NativeStructureFailureContractTest {
}
@Test
public void globalStructureDisableRefusesGeneratorBinding() {
IrisModdedChunkGenerator.requireGlobalStructureGeneration(true, "overworld:overworld");
public void disabledGlobalStructuresNeitherRefuseBindingNorFailPlacement() throws IOException {
String generator = moddedSource("IrisModdedChunkGenerator.java");
String stage = moddedSource("ModdedNativeStructureStage.java");
IllegalStateException error = assertThrows(
IllegalStateException.class,
() -> IrisModdedChunkGenerator.requireGlobalStructureGeneration(
false, "overworld:overworld"));
assertTrue(error.getMessage().contains("overworld:overworld"));
assertTrue(error.getMessage().contains("generate-structures=false"));
assertTrue(error.getMessage().contains("importedStructures.disabled"));
assertTrue(error.getMessage().contains("importedStructures.disabledExact"));
assertFalse(generator.contains("generateStructures()"));
assertFalse(generator.contains("requireGlobalStructureGeneration"));
assertFalse(stage.contains("shouldGenerateStructures()"));
}
@Test
@@ -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<BlockPos> 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<String> debug = new ArrayList<>();
try (MockedStatic<IrisLogging> 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<Integer, BlockState> 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<Matter> emptyAdapter() {
return (MantleDataAdapter<Matter>) 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<Matter> {
private final List<Placed> records;
private boolean customDeleted;
private RecordMantleChunk(List<Placed> records) {
super(1, 0, 0, emptyAdapter(), MantleHooks.NONE);
this.records = records;
}
@Override
public <T> void iterate(Class<T> type, Consumer4<Integer, Integer, Integer, T> 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<net.minecraft.resources.Identifier> 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<String, String> 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());
}
}
}