Replace fixed placement hooks with a module-owned stage graph

Modules now define every stage themselves through IrisModule.install(StageGraph):
typed stage constants, hard requires(...) on other modules' constants, soft
ordering by id, when(...) activation and typed outputs. Placement and chunk
generation resolve on the same machinery; adjacent per-block stages fuse into
one block pass.

The host-defined PlacementModifier hooks, string Dependencies, GenerationPlan,
PlacementPipeline, DependencyOrder and OccurrenceOrder are removed.
This commit is contained in:
piexel committed 2026-10-05 17:23:31 +02:00
1 parent 9043d93fbd
commit eeb5486098
76 files changed
+2717 -1567

No files matched your search

@@ -1,12 +1,8 @@
package com.volmit;
import com.volmit.config.*;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.host.ArrayHunk;
import com.volmit.host.ModuleRegistry;
import com.volmit.host.FeatureDescriptor;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import org.junit.jupiter.api.Test;
@@ -40,25 +36,12 @@ class FeatureContractTest {
}
@Test
void registryBindsDecodedOptionsToTheCorrectModifier() {
var host = new ModuleRegistry();
host.register(FillOptions.class, Integer.class, FillModifier::new);
var registration = host.freeze().generation(FillOptions.class, Integer.class);
var modifier = registration.configure(ResourceId.parse("test:fill/0"), new FillOptions());
var output = new ArrayHunk<>(Integer.class, 1, 1, 1, 0);
modifier.modify(TestContexts.generation(), output);
assertEquals(12, output.get(0, 0, 0));
}
private static class FillModifier extends GenerationModifier<Integer> {
private final FillOptions options;
FillModifier(FillOptions options) {
this.options = options;
}
public String id() { return "example:fill-modifier"; }
public void modify(GenerationContext context, Hunk<Integer> volume) {
volume.set(0, 0, 0, options.value);
}
void descriptorReadsFeatureIdentityAndAttachment() {
var descriptor = FeatureDescriptor.of(FillOptions.class);
assertEquals(ResourceId.parse("example:fill"), descriptor.id());
assertEquals("fill", descriptor.attachment().field());
assertEquals(java.util.Set.of(FeatureAttachment.Target.BIOME), descriptor.attachment().targets());
assertEquals(1, descriptor.options().options().size());
}
static class InvalidOptions {
@@ -1,54 +0,0 @@
package com.volmit.generation;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class DependenciesTest {
@Test
void accumulatesAndDeduplicatesWithoutMutatingEarlierDeclarations() {
var original = Dependencies.requires("iris:terrain", "iris:terrain");
var result = original.andRequires("iris:carving")
.afterIfPresent("example:caves").afterIfPresent("example:lakes")
.beforeIfPresent("iris:ores").beforeIfPresent("iris:ores", "iris:objects");
assertEquals(Set.of("iris:terrain"), original.required());
assertTrue(original.after().isEmpty());
assertTrue(original.before().isEmpty());
assertEquals(Set.of("iris:terrain", "iris:carving"), result.required());
assertEquals(Set.of("example:caves", "example:lakes"), result.after());
assertEquals(Set.of("iris:ores", "iris:objects"), result.before());
}
@Test
void copiesInputsAndExposesImmutableSets() {
var ids = new HashSet<>(Set.of("iris:terrain"));
var result = new Dependencies(ids, ids, ids);
ids.clear();
assertEquals(Set.of("iris:terrain"), result.required());
assertThrows(UnsupportedOperationException.class, () -> result.required().clear());
assertThrows(UnsupportedOperationException.class, () -> result.after().clear());
assertThrows(UnsupportedOperationException.class, () -> result.before().clear());
String[] input = {"iris:terrain"};
var fromArray = Dependencies.requires(input);
input[0] = "iris:ores";
assertEquals(Set.of("iris:terrain"), fromArray.required());
}
@Test
void supportsEmptyAndOptionalOnlyDeclarations() {
assertEquals(new Dependencies(Set.of(), Set.of(), Set.of()), Dependencies.none());
assertEquals(Dependencies.none(), Dependencies.requires());
assertEquals(Set.of("iris:ores"), Dependencies.none().beforeIfPresent("iris:ores").before());
}
@Test
void rejectsNullAndBlankIds() {
assertThrows(IllegalArgumentException.class, () -> Dependencies.requires(" "));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().afterIfPresent(""));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().beforeIfPresent("\n"));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String) null));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String[]) null));
assertThrows(NullPointerException.class, () -> new Dependencies(null, Set.of(), Set.of()));
}
}
@@ -1,85 +0,0 @@
package com.volmit.host;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class GenerationPlanTest {
private static ResourceId id(String path) { return ResourceId.parse("test:" + path); }
private static ConfiguredModifier<String> binding(String occurrence, String name, Dependencies dependencies) {
return new ConfiguredModifier<>(id(occurrence), String.class, new Modifier(name, dependencies));
}
private static class Modifier extends GenerationModifier<String> {
private final String name;
private final Dependencies dependencies;
Modifier(String name, Dependencies dependencies) { this.name = name; this.dependencies = dependencies; }
public String id() { return "test:" + name; }
public Dependencies depends() { return dependencies; }
public void modify(GenerationContext context, Hunk<String> output) {}
}
@Test
void orderingIsIndependentOfDiscoveryAndIncludesRepeatedOccurrences() {
var first = binding("terrain/1", "terrain", Dependencies.none());
var second = binding("terrain/0", "terrain", Dependencies.none());
var caves = binding("caves/0", "caves", Dependencies.requires("test:terrain"));
var decoration = binding("decoration/0", "decoration", Dependencies.requires("test:caves").beforeIfPresent("test:missing"));
var a = GenerationPlan.resolve(List.of(decoration, first, caves, second));
var b = GenerationPlan.resolve(List.of(second, caves, decoration, first));
var expected = List.of(id("terrain/0"), id("terrain/1"), id("caves/0"), id("decoration/0"));
assertEquals(expected, a.ordered().stream().map(ConfiguredModifier::occurrence).toList());
assertEquals(expected, b.ordered().stream().map(ConfiguredModifier::occurrence).toList());
var executed = new ArrayList<ResourceId>();
a.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) { executed.add(modifier.occurrence()); }
});
assertEquals(expected, executed);
assertThrows(UnsupportedOperationException.class, () -> a.ordered().clear());
}
@Test
void rejectsMissingRequirementsSelfEdgesAndCycles() {
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:missing"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.none().beforeIfPresent("test:a"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:b"), id("b"), Dependencies.requires("test:a"))));
}
@Test
void rejectsDuplicateOccurrencesAndConflictingImplementationsOrDeclarations() {
var a = binding("a/0", "a", Dependencies.none());
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, a)));
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a,
binding("a/1", "a", Dependencies.none().afterIfPresent("test:b")))));
var otherImplementation = new ConfiguredModifier<>(id("a/2"), String.class, new Modifier("a", Dependencies.none()) {});
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, otherImplementation)));
}
@Test
void repeatedEdgesAreCountedOnceAndIndependentIdsUseLexicalOrder() {
var graph = Map.of(id("a"), Dependencies.none(), id("z"), Dependencies.none(),
id("b"), Dependencies.requires("test:a").afterIfPresent("test:a"));
assertEquals(List.of(id("a"), id("b"), id("z")), DependencyOrder.resolve(graph));
}
@Test
void failuresStopDispatchAndNegativeReachFailsAtPackLoad() {
var plan = GenerationPlan.resolve(List.of(binding("a", "a", Dependencies.none()), binding("b", "b", Dependencies.none())));
var visited = new ArrayList<ResourceId>();
assertThrows(IllegalStateException.class, () -> plan.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) {
visited.add(modifier.id());
throw new IllegalStateException("Failed output");
}
}));
assertEquals(List.of(id("a")), visited);
assertThrows(IllegalArgumentException.class, () -> new ConfiguredModifier<>(id("negative"), String.class,
new Modifier("a", Dependencies.none()) { public int mantleRadius() { return -1; } }));
}
}
@@ -2,10 +2,10 @@ package com.volmit.host;
import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.*;
import com.volmit.placement.PlacementModifier;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import org.junit.jupiter.api.Test;
import java.io.DataInput;
import java.io.DataOutput;
@@ -23,54 +23,34 @@ class ModuleRegistryTest {
static class Collision implements IrisFeature {}
@Feature(id = "test:one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION)
static class Duplicate implements IrisFeature {}
@Feature(id = "test:placement", name = "Placement", field = "foundation", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static class Placement implements IrisFeature {}
static class MissingAnnotation implements IrisFeature {}
@Feature(id = "test:abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME)
abstract static class AbstractFeature implements IrisFeature {}
private static GenerationModifier<String> modifier(IrisFeature ignored) {
return new GenerationModifier<>() {
public String id() { return "test:modifier"; }
public void modify(GenerationContext context, Hunk<String> output) {}
};
}
@Test
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
var registry = new ModuleRegistry();
registry.register(One.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.register(Collision.class, String.class, ModuleRegistryTest::modifier));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
registry.registerSettings(One.class);
registry.registerSettings(One.class);
assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Collision.class, ignored -> context -> null));
registry.registerObject(Two.class, ignored -> context -> null);
assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Duplicate.class, ignored -> context -> null));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.registerObject(One.class, ignored -> context -> null));
var catalog = registry.freeze();
assertEquals(List.of("test:one", "test:two"), catalog.generation().stream().map(value -> value.descriptor().id().toString()).toList());
assertThrows(IllegalArgumentException.class, () -> catalog.generation(One.class, Integer.class));
assertEquals(List.of("test:one"), catalog.settings().stream().map(value -> value.id().toString()).toList());
assertEquals(List.of("test:two"), catalog.objects().stream().map(value -> value.descriptor().id().toString()).toList());
}
@Test
void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(MissingAnnotation.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(AbstractFeature.class, String.class, ModuleRegistryTest::modifier));
assertThrows(NullPointerException.class, () -> registry.register(Two.class, String.class, null));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
}
@Test
void placementMustAttachToPlacementAndFreezeEndsRegistration() {
var registry = new ModuleRegistry();
assertThrows(IllegalArgumentException.class, () -> registry.registerPlacement(One.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
}));
registry.registerPlacement(Placement.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
});
assertEquals(1, registry.freeze().placement().size());
assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(One.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(MissingAnnotation.class));
assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(AbstractFeature.class));
assertThrows(NullPointerException.class, () -> registry.registerObject(Two.class, null));
registry.registerObject(Two.class, ignored -> context -> null);
assertSame(registry.freeze(), registry.freeze());
assertThrows(IllegalStateException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalStateException.class, () -> registry.registerSettings(One.class));
}
@Test
@@ -85,6 +65,24 @@ class ModuleRegistryTest {
assertEquals(1, registry.freeze().mantle().size());
}
@Test
void loadingModulesCatalogsStageSettingsAndRegistrationsTogether() {
var conditioned = new IrisModule() {
static final PlacementStage<Void> WORK = Stage.placement("test:conditioned/work");
public ModuleInfo info() { return ModuleInfo.of("test:conditioned", "1"); }
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); }
public void register(FeatureRegistry registry) { registry.registerObject(Two.class, ignored -> context -> null); }
};
var loaded = LoadedModules.load(List.of(conditioned), Map.of());
assertEquals(List.of("test:one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
assertEquals(1, loaded.catalog().objects().size());
assertEquals(1, loaded.placement().stages().size());
assertTrue(loaded.chunk().stages().isEmpty());
var reserved = Map.of(FeatureAttachment.Target.BIOME, Set.of("shared"));
assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(conditioned), reserved));
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
@@ -1,259 +0,0 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.*;
import com.volmit.object.*;
import com.volmit.placement.*;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class PlacementPipelineTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState AIR = new BlockState("minecraft:air");
private static ResourceId id(String name) { return ResourceId.parse("test:" + name); }
private static PlacementRequest request() {
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(1, 0, 0),
List.of(new ObjectBlock(new BlockPosition(1, 0, 0), STONE), new ObjectBlock(new BlockPosition(0, 0, 0), STONE)),
List.of(new ObjectMarker(new BlockPosition(1, 0, 0), id("owner"), Map.of("name", "column"))));
return new PlacementRequest(id("attempt"), object, new BlockPosition(-2, -60, -3));
}
private static ConfiguredPlacementModifier configured(PlacementModifier modifier) {
return new ConfiguredPlacementModifier(ResourceId.parse(modifier.id() + "/0"), modifier);
}
@Test
void validatesCompletePlanBeforeWritesAndAfterHooksSeeOverlayAndActualBounds() {
var events = new ArrayList<String>();
var modifier = new PlacementModifier() {
public String id() { return "test:foundation"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) {
events.add("prepare"); return Optional.of(request);
}
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
events.add("map");
return block.position().x() == -3 ? Optional.empty() : Optional.of(block);
}
public boolean validate(PlacementContext context, PlacementPlan plan) {
events.add("validate");
assertEquals(1, plan.blocks().size());
return true;
}
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
events.add("before");
assertEquals(AIR, access.get(-2, -60, -3));
}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {
events.add("after");
assertEquals(STONE, access.get(-2, -60, -3));
assertEquals(new BlockBox(-2, -60, -3, -1, -59, -2), written.writtenBounds().orElseThrow());
assertFalse(access instanceof PlacementEdit);
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
}
};
var pipeline = PlacementPipeline.resolve(List.of(configured(modifier)));
var edit = new RecordingEdit(events);
var result = pipeline.place(request(), edit, ignored -> TestContexts.placement(), plan -> {
events.add("host-validate"); assertEquals(0, edit.mutations); return true;
});
assertTrue(result.isPresent());
assertEquals(List.of("prepare", "map", "map", "host-validate", "validate", "before", "write", "marker", "after", "write", "commit", "close"), events);
assertEquals(2, edit.published.size());
assertEquals(1, edit.publishedMarkers.size());
assertThrows(IllegalStateException.class, () -> edit.get(-2, -60, -3));
}
@Test
void validationRejectionPublishesNothingAndDoesNotStartMutating() {
var modifier = new PlacementModifier() {
public String id() { return "test:reject"; }
public boolean validate(PlacementContext context, PlacementPlan plan) { return false; }
};
var edit = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, edit.mutations);
assertTrue(edit.published.isEmpty());
assertTrue(edit.closed);
}
@Test
void failureAfterBufferedObjectWritesDiscardsEntireAttempt() {
var modifier = new PlacementModifier() {
public String id() { return "test:failure"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
throw new IllegalStateException("Foundation failed");
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(edit.mutations > 0);
assertTrue(edit.published.isEmpty());
assertTrue(edit.publishedMarkers.isEmpty());
assertTrue(edit.closed);
}
@Test
void prepareRejectionAndFailedCommitCloseWithoutPublication() {
var rejection = new PlacementModifier() {
public String id() { return "test:prepare-reject"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.empty(); }
};
var rejected = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(rejection)))
.place(request(), rejected, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, rejected.mutations);
var failed = new RecordingEdit(new ArrayList<>());
failed.failCommit = true;
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of())
.place(request(), failed, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(failed.closed);
assertTrue(failed.published.isEmpty());
}
@Test
void rejectsMappedBoundsDuplicateWritesAndInsufficientPreparedReachBeforeMutation() {
var escape = new PlacementModifier() {
public String id() { return "test:escape"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(new BlockPosition(5, -60, -3), block.state(), block.blockEntity()));
}
};
var escaped = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(escape)))
.place(request(), escaped, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, escaped.mutations);
var radius = new PlacementModifier() {
public String id() { return "test:radius"; }
public int writeRadius() { return 32; }
};
var unprepared = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(radius)))
.place(request(), unprepared, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, unprepared.mutations);
}
@Test
void hooksCannotWriteBeyondReachOrRetainUsableViews() {
var retained = new AtomicReference<PlacementAccess>();
var retainedLayer = new AtomicReference<MantleLayer<String>>();
var modifier = new PlacementModifier() {
public String id() { return "test:bounded"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
retained.set(access);
retainedLayer.set(access.mantle().layer(new MantleKey<>("test:owner", String.class)));
assertThrows(IndexOutOfBoundsException.class, () -> access.set(new PlacedBlock(new BlockPosition(5, -60, -3), STONE, Optional.empty())));
assertThrows(UnsupportedOperationException.class, () -> access.mantle().edit());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle().layer(new MantleKey<>("test:owner", String.class)).get(5, -60, -3));
}
};
var edit = new RecordingEdit(new ArrayList<>());
PlacementPipeline.resolve(List.of(configured(modifier))).place(request(), edit, ignored -> TestContexts.placement(), ignored -> true);
assertThrows(IllegalStateException.class, () -> retained.get().get(-2, -60, -3));
assertThrows(IllegalStateException.class, () -> retainedLayer.get().get(-2, -60, -3));
}
@Test
void placementDependenciesStayInTheirOwnGraphAndRejectConflicts() {
var first = new PlacementModifier() { public String id() { return "test:first"; } };
var second = new PlacementModifier() {
public String id() { return "test:second"; }
public Dependencies depends() { return Dependencies.requires("test:first"); }
};
assertEquals(List.of(ResourceId.parse("test:first"), ResourceId.parse("test:second")),
PlacementPipeline.resolve(List.of(configured(second), configured(first))).ordered().stream().map(ConfiguredPlacementModifier::id).toList());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(second))));
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(first), configured(first))));
}
@Test
void mappedWritesOutsideReachFailBeforeMutationAndEachHookKeepsItsOwnReach() {
var moved = new PlacementModifier() {
public String id() { return "test:moved"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(block.position().add(new BlockPosition(8, 0, 0)), block.state(), block.blockEntity()));
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(moved)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, edit.mutations);
var large = new PlacementModifier() {
public String id() { return "test:large"; }
public int writeRadius() { return 2; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertEquals(AIR, access.get(0, -60, -3));
assertEquals(new BlockBox(-5, -64, -5, 1, 320, 0), access.mantle().bounds());
assertNull(access.mantle().layer(new MantleKey<>("test:owner", String.class))
.get(0, -60, -3));
}
};
var small = new PlacementModifier() {
public String id() { return "test:small"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertThrows(IndexOutOfBoundsException.class, () -> access.get(0, -60, -3));
assertEquals(new BlockBox(-3, -64, -3, -1, 320, -2), access.mantle().bounds());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle()
.layer(new MantleKey<>("test:owner", String.class)).get(0, -60, -3));
}
};
assertTrue(PlacementPipeline.resolve(List.of(configured(small), configured(large)))
.place(request(), new RecordingEdit(new ArrayList<>()), ignored -> TestContexts.placement(), ignored -> true).isPresent());
}
/** In-memory transactional test adapter; production storage/persistence is deliberately absent. */
private static class RecordingEdit implements PlacementEdit {
final List<String> events;
final Map<BlockPosition, BlockState> pending = new HashMap<>();
final Map<BlockPosition, BlockState> published = new HashMap<>();
final List<PlacedMarker> pendingMarkers = new ArrayList<>();
final List<PlacedMarker> publishedMarkers = new ArrayList<>();
boolean closed;
boolean failCommit;
int mutations;
RecordingEdit(List<String> events) { this.events = events; }
private void checkOpen() { if (closed) throw new IllegalStateException("Closed edit"); }
public BlockBox bounds() { checkOpen(); return new BlockBox(-16, -64, -16, 16, 320, 16); }
public BlockState get(int x, int y, int z) { checkOpen(); return pending.getOrDefault(new BlockPosition(x, y, z), AIR); }
public void set(PlacedBlock block) { checkOpen(); mutations++; events.add("write"); pending.put(block.position(), block.state()); }
public void marker(PlacedMarker marker) { checkOpen(); mutations++; events.add("marker"); pendingMarkers.add(marker); }
public Mantle mantle() {
checkOpen();
return new Mantle() {
public BlockBox bounds() { return RecordingEdit.this.bounds(); }
public MantleEdit edit() { throw new UnsupportedOperationException(); }
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return new MantleLayer<>() {
public T get(int x, int y, int z) { checkOpen(); return null; }
public void set(int x, int y, int z, T value) { throw new AssertionError("Unused mantle mutation"); }
public void remove(int x, int y, int z) { throw new AssertionError("Unused mantle mutation"); }
public void clear(BlockBox area) { throw new AssertionError("Unused mantle mutation"); }
public void visit(BlockBox area, MantleVisitor<T> visitor) { checkOpen(); }
};
}
};
}
public void commit() {
checkOpen();
if (failCommit) throw new IllegalStateException("Commit failed");
events.add("commit"); published.putAll(pending); publishedMarkers.addAll(pendingMarkers); closed = true;
}
public void close() {
if (!events.contains("close")) events.add("close");
closed = true; pending.clear(); pendingMarkers.clear();
}
}
}
@@ -0,0 +1,415 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.block.BlockState;
import com.volmit.config.Feature;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacementEdit;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.ResourceId;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.ChunkStage;
import com.volmit.stage.Pipeline;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.stage.StageRef;
import com.volmit.support.MemoryEdit;
import com.volmit.support.TestContexts;
import com.volmit.support.TestTerrain;
import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
class StageGraphTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
@Feature(id = "test:toggle", name = "Toggle", field = "toggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static final class Toggle implements IrisFeature {}
static final class Unannotated implements IrisFeature {}
private static IrisModule module(String id, Consumer<StageGraph> install) {
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "1"); }
public void install(StageGraph graph) { install.accept(graph); }
};
}
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
var builder = new StageGraphBuilder();
for (var module : modules) builder.install(module);
return builder.resolve(pipeline);
}
private static List<String> order(ResolvedGraph graph) {
return graph.stages().stream().map(stage -> stage.stage().id().toString()).toList();
}
private static List<List<String>> passes(ResolvedGraph graph) {
return graph.blockPasses().stream().map(pass -> pass.stream().map(ResourceId::toString).toList()).toList();
}
private static PlacementRequest twoBlockRequest() {
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(0, 0, 0),
List.of(new ObjectBlock(new BlockPosition(0, 0, 0), STONE), new ObjectBlock(new BlockPosition(1, 0, 0), STONE)),
List.of());
return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0));
}
private static MemoryEdit flatEdit() {
return new MemoryEdit(new TestTerrain((x, z) -> 5));
}
private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings) {
return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), settings);
}
@Test
void adjacentBlockStagesShareOnePassAndRunPerBlockInOrder() {
var first = Stage.placementBlock("test:first");
var second = Stage.placementBlock("test:second");
var events = new ArrayList<String>();
var graph = resolve(Pipeline.PLACEMENT, module("test:blocks", stages -> {
stages.define(second).requires(first).run(context -> events.add("second@" + context.block().position().x()));
stages.define(first).run(context -> events.add("first@" + context.block().position().x()));
}));
assertEquals(List.of(List.of("test:first", "test:second")), passes(graph));
assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced());
assertEquals(List.of("first@0", "second@0", "first@1", "second@1"), events);
}
@Test
void requiredInvocationStageBetweenBlockStagesSplitsThePass() {
var collect = Stage.placementBlock("test:collect", Counter.class);
var middle = Stage.placement("test:middle", Integer.class);
var paint = Stage.placementBlock("test:paint");
var events = new ArrayList<String>();
var graph = resolve(Pipeline.PLACEMENT, module("test:split", stages -> {
stages.define(collect).accumulate(Counter::new, (context, counter) -> {
counter.count++;
events.add("collect");
});
stages.define(middle).requires(collect).produce(context -> {
events.add("middle");
return context.output(collect).count;
});
stages.define(paint).requires(middle).run(context -> events.add("paint:" + context.output(middle)));
}));
assertEquals(List.of(List.of("test:collect"), List.of("test:paint")), passes(graph));
assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced());
assertEquals(List.of("collect", "collect", "middle", "paint:2", "paint:2"), events);
}
@Test
void unrelatedInvocationStagesRunOutsideBlockPassesSoTheyDoNotSplitThem() {
var graph = resolve(Pipeline.PLACEMENT, module("test:fusion", stages -> {
stages.define(Stage.placementBlock("test:a")).run(context -> {});
stages.define(Stage.placement("test:b")).run(context -> {});
stages.define(Stage.placementBlock("test:c")).run(context -> {});
}));
assertEquals(List.of("test:b", "test:a", "test:c"), order(graph));
assertEquals(List.of(List.of("test:a", "test:c")), passes(graph));
}
@Test
void unorderedStagesFollowLexicalIdsRegardlessOfInstallOrder() {
var zebra = module("zeta:module", stages -> stages.define(Stage.placement("zeta:work")).run(context -> {}));
var alpha = module("alpha:module", stages -> stages.define(Stage.placement("alpha:work")).run(context -> {}));
var forward = resolve(Pipeline.PLACEMENT, zebra, alpha);
var reversed = resolve(Pipeline.PLACEMENT, alpha, zebra);
assertEquals(List.of("alpha:work", "zeta:work"), order(forward));
assertEquals(forward.describe(), reversed.describe());
assertEquals(List.of(new ResolvedGraph.UnorderedPair(ResourceId.parse("alpha:work"), ResourceId.parse("zeta:work"))),
forward.unorderedPairs());
}
@Test
void softEdgesOrderOnlyInstalledStagesAndReportAbsentTargets() {
var late = Stage.placement("test:late");
var early = Stage.placement("test:early");
var graph = resolve(Pipeline.PLACEMENT, module("test:soft", stages -> {
stages.define(early).softAfter(StageRef.of("test:late")).run(context -> {});
stages.define(late).softBefore(StageRef.of("other:missing")).run(context -> {});
}));
assertEquals(List.of("test:late", "test:early"), order(graph));
var earlyStage = graph.stages().get(1);
assertEquals(List.of(new StageEdge(late.id(), early.id(), StageEdge.Kind.SOFT)), earlyStage.incoming());
assertEquals(List.of(StageRef.of("other:missing")), graph.stages().get(0).absentSoftTargets());
assertTrue(graph.describe().contains("absent soft targets other:missing"));
assertTrue(graph.unorderedPairs().isEmpty());
}
@Test
void missingRequirementNamesBothStagesAndTheirModules() {
var absent = Stage.placement("other:absent");
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:needy", stages -> stages.define(Stage.placement("test:needy/work")).requires(absent).run(context -> {}))));
assertEquals("Stage test:needy/work (module test:needy) requires other:absent, which no installed module "
+ "defines (expected a module in namespace 'other')", error.getMessage());
}
@Test
void requirementMustBeTheOwnersDeclarationNotACopyWithTheSameId() {
var owned = Stage.placement("test:owned");
var copy = Stage.placement("test:owned");
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:owner", stages -> stages.define(owned).run(context -> {})),
module("test:user", stages -> stages.define(Stage.placement("test:user/work")).requires(copy).run(context -> {}))));
assertTrue(error.getMessage().contains("different declaration of test:owned (module test:owner)"), error.getMessage());
}
@Test
void cyclesListEveryStageWithItsModuleAndEdgeKind() {
var a = Stage.placement("test:a");
var b = Stage.placement("other:b");
var c = Stage.placement("test:c");
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:first", stages -> {
stages.define(a).requires(b).run(context -> {});
stages.define(c).requires(a).run(context -> {});
}),
module("other:second", stages -> stages.define(b).softAfter(c.ref()).run(context -> {}))));
assertEquals("Stage cycle in pipeline PLACEMENT: other:b (module other:second) -[required]-> "
+ "test:a (module test:first) -[required]-> test:c (module test:first) -[soft]-> "
+ "other:b (module other:second)", error.getMessage());
}
@Test
void stageNamespaceMustMatchItsModuleAndDefinitionsAreUnique() {
var foreign = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:module", stages -> stages.define(Stage.placement("iris:stolen")).run(context -> {}))));
assertTrue(foreign.getMessage().contains("must use namespace 'test'"), foreign.getMessage());
var shared = Stage.placement("test:shared");
var duplicate = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:one", stages -> stages.define(shared).run(context -> {})),
module("test:two", stages -> stages.define(shared).run(context -> {}))));
assertTrue(duplicate.getMessage().contains("already defined by module test:one"), duplicate.getMessage());
var module = module("test:twice", stages -> {});
var builder = new StageGraphBuilder();
builder.install(module);
assertThrows(IllegalArgumentException.class, () -> builder.install(module));
}
@Test
void dependenciesCannotCrossPipelines() {
var placementStage = Stage.placement("test:placed");
ChunkStage<Void> chunkStage = Stage.chunk("test:chunk");
var hard = module("test:hard", stages -> {
stages.define(placementStage).run(context -> {});
stages.define(chunkStage).requires(placementStage).run(context -> {});
});
var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, hard));
assertTrue(error.getMessage().contains("in pipeline CHUNK depends on test:placed (module test:hard) in pipeline PLACEMENT"),
error.getMessage());
var soft = module("test:soft", stages -> {
stages.define(Stage.placement("test:soft/placed")).run(context -> {});
stages.define(Stage.chunk("test:soft/chunk")).softAfter(StageRef.of("test:soft/placed")).run(context -> {});
});
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, soft));
}
@Test
void definitionsNeedExactlyOneBodyOfTheRightKind() {
var withOutput = Stage.placement("test:output", Integer.class);
var withoutOutput = Stage.placement("test:plain");
var accumulating = Stage.placementBlock("test:acc", Counter.class);
var run = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:run", stages -> stages.define(withOutput).run(context -> {}))));
assertTrue(run.getMessage().contains("declares output Integer; define it with produce(...)"), run.getMessage());
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:produce", stages -> stages.define(withoutOutput).produce(context -> null))));
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:accrun", stages -> stages.define(accumulating).run(context -> {}))));
var missing = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT,
module("test:missing", stages -> stages.define(withoutOutput).requires())));
assertTrue(missing.getMessage().contains("has no body"), missing.getMessage());
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, module("test:again", stages -> {
var definition = stages.define(withoutOutput);
definition.run(context -> {});
definition.requires(withOutput);
})));
}
@Test
void invalidDeclarationsFailWhileInstalling() {
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:self", stages -> {
var self = Stage.placement("test:self/work");
stages.define(self).requires(self).run(context -> {});
})));
assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, module("test:twice", stages -> {
var definition = stages.define(Stage.placement("test:twice/work"));
definition.when(Toggle.class);
definition.when(Toggle.class);
})));
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:plain", stages ->
stages.define(Stage.placement("test:plain/work")).when(Unannotated.class).run((context, settings) -> {}))));
var retained = new ArrayList<StageGraph>();
new StageGraphBuilder().install(module("test:retained", retained::add));
assertThrows(IllegalStateException.class, () -> retained.getFirst().define(Stage.placement("test:retained/late")));
}
@Test
void outputsAreReadableOnlyThroughTransitiveRequirementsAndAfterTheirPass() {
var height = Stage.placement("test:height", Integer.class);
var offset = Stage.placement("test:offset", Integer.class);
var counted = Stage.placementBlock("test:counted", Counter.class);
var observed = new ArrayList<Object>();
var graph = resolve(Pipeline.PLACEMENT, module("test:outputs", stages -> {
stages.define(height).produce(context -> 10);
stages.define(offset).requires(height).produce(context -> context.output(height) + 1);
stages.define(counted).requires(offset).accumulate(Counter::new, (context, counter) -> {
counter.count++;
observed.add(context.output(height));
});
stages.define(Stage.placementBlock("test:peek")).requires(counted).run(context -> observed.add(
assertThrows(IllegalStateException.class, () -> context.output(counted)).getMessage()));
stages.define(Stage.placement("test:reader")).requires(counted).run(context -> observed.add(context.output(counted).count));
stages.define(Stage.placement("test:snoop")).run(context -> observed.add(
assertThrows(IllegalStateException.class, () -> context.output(height)).getMessage()));
}));
assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced());
assertEquals(10, observed.get(1));
assertTrue(observed.get(2).toString().contains("before it completed"), observed.get(2).toString());
assertTrue(observed.contains(2));
assertTrue(observed.contains("Stage test:snoop read the output of test:height without requiring it; "
+ "add requires(test:height) to its definition"));
}
@Test
void nullOutputsFailTheInvocation() {
var graph = resolve(Pipeline.PLACEMENT, module("test:nulls", stages ->
stages.define(Stage.placement("test:nulls/value", Integer.class)).produce(context -> null)));
var edit = flatEdit();
assertThrows(NullPointerException.class, () -> place(graph, edit, ConfiguredSettings.none()));
assertEquals(MemoryEdit.Status.CLOSED, edit.status());
assertFalse(edit.committed());
}
@Test
void conditionalStagesCascadeToDependentsWithoutAnyError() {
var toggled = Stage.placement("test:toggled", Integer.class);
var dependent = Stage.placement("test:dependent");
var unrelated = Stage.placement("test:unrelated");
var events = new ArrayList<String>();
var graph = resolve(Pipeline.PLACEMENT, module("test:cascade", stages -> {
stages.define(toggled).when(Toggle.class).produce((context, toggle) -> {
events.add("toggled");
return 1;
});
stages.define(dependent).requires(toggled).run(context -> events.add("dependent:" + context.output(toggled)));
stages.define(unrelated).run(context -> events.add("unrelated"));
}));
place(graph, flatEdit(), ConfiguredSettings.none());
assertEquals(List.of("unrelated"), events);
events.clear();
place(graph, flatEdit(), ConfiguredSettings.of(new Toggle()));
assertEquals(List.of("toggled", "dependent:1", "unrelated"), events);
}
@Test
void skippedBlocksAreHiddenFromLaterStagesOfThePass() {
var written = new ArrayList<Integer>();
var graph = resolve(Pipeline.PLACEMENT, module("test:skip", stages -> {
var filter = Stage.placementBlock("test:filter");
stages.define(filter).run(context -> {
if (context.block().position().x() == 0) context.skip();
});
stages.define(Stage.placementBlock("test:write")).requires(filter).run(context -> written.add(context.block().position().x()));
}));
place(graph, flatEdit(), ConfiguredSettings.none());
assertEquals(List.of(1), written);
}
@Test
void rejectionStopsTheAttemptAndCommitsNothing() {
var events = new ArrayList<String>();
var graph = resolve(Pipeline.PLACEMENT, module("test:reject", stages -> {
var write = Stage.placementBlock("test:write");
stages.define(write).run(context -> {
events.add("write");
context.access().set(new PlacedBlock(new BlockPosition(0, 10, 0), STONE, Optional.empty()));
context.reject("blocked");
context.reject("ignored");
});
stages.define(Stage.placement("test:after")).requires(write).run(context -> events.add("after"));
}));
var edit = flatEdit();
var outcome = place(graph, edit, ConfiguredSettings.none());
assertEquals(PlacementOutcome.Status.REJECTED, outcome.status());
assertEquals(Optional.of("blocked"), outcome.rejection());
assertEquals(List.of("write"), events);
assertFalse(edit.committed());
assertEquals(MemoryEdit.Status.CLOSED, edit.status());
}
@Test
void stagesGetBufferedAccessWithoutTransactionOwnershipAndViewsExpire() {
var retained = new ArrayList<com.volmit.placement.PlacementAccess>();
var graph = resolve(Pipeline.PLACEMENT, module("test:access", stages ->
stages.define(Stage.placement("test:access/write")).run(context -> {
assertFalse(context.access() instanceof PlacementEdit);
assertThrows(IllegalStateException.class, () -> ((BlockStageContext) context).block());
context.access().set(new PlacedBlock(new BlockPosition(1, 10, 1), STONE, Optional.empty()));
assertEquals(STONE, context.access().get(1, 10, 1));
retained.add(context.access());
})));
var edit = flatEdit();
assertTrue(place(graph, edit, ConfiguredSettings.none()).isPlaced());
assertEquals(STONE, edit.publishedAt(1, 10, 1));
assertThrows(IllegalStateException.class, () -> retained.getFirst().get(1, 10, 1));
}
@Test
void failuresDiscardBufferedWrites() {
var graph = resolve(Pipeline.PLACEMENT, module("test:fail", stages ->
stages.define(Stage.placement("test:fail/work")).run(context -> {
context.access().set(new PlacedBlock(new BlockPosition(1, 10, 1), STONE, Optional.empty()));
throw new IllegalStateException("boom");
})));
var edit = flatEdit();
assertThrows(IllegalStateException.class, () -> place(graph, edit, ConfiguredSettings.none()));
assertFalse(edit.committed());
assertEquals(MemoryEdit.Status.CLOSED, edit.status());
}
@Test
void runnersOnlyAcceptTheirOwnPipeline() {
var empty = resolve(Pipeline.CHUNK);
assertThrows(IllegalArgumentException.class, () -> new PlacementRunner(empty));
assertThrows(IllegalArgumentException.class, () -> new ChunkRunner(resolve(Pipeline.PLACEMENT)));
assertTrue(empty.describe().contains("CHUNK pipeline: 0 stages, 0 block passes"));
}
static final class Counter {
int count;
}
}
@@ -0,0 +1,93 @@
package com.volmit.support;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.mantle.Mantle;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementEdit;
import com.volmit.world.BlockPosition;
import com.volmit.world.BlockView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** In-memory transactional test adapter over a base view; production storage is absent. */
public final class MemoryEdit implements PlacementEdit {
public enum Status { OPEN, COMMITTED, CLOSED }
private final BlockView base;
private final Map<BlockPosition, BlockState> pending = new HashMap<>();
private final Map<BlockPosition, BlockState> published = new HashMap<>();
private final List<PlacedMarker> pendingMarkers = new ArrayList<>();
private final List<PlacedMarker> publishedMarkers = new ArrayList<>();
private Status status = Status.OPEN;
private boolean committed;
public MemoryEdit(BlockView base) {
this.base = base;
}
public boolean committed() { return committed; }
public Status status() { return status; }
public Map<BlockPosition, BlockState> published() { return Map.copyOf(published); }
public List<PlacedMarker> publishedMarkers() { return List.copyOf(publishedMarkers); }
public BlockState publishedAt(int x, int y, int z) {
return published.getOrDefault(new BlockPosition(x, y, z), base.get(x, y, z));
}
@Override
public BlockBox bounds() {
checkOpen();
return base.bounds();
}
@Override
public BlockState get(int x, int y, int z) {
checkOpen();
return pending.getOrDefault(new BlockPosition(x, y, z), base.get(x, y, z));
}
@Override
public void set(PlacedBlock block) {
checkOpen();
var position = block.position();
if (!base.bounds().contains(position.x(), position.y(), position.z())) {
throw new IndexOutOfBoundsException("Write outside prepared area: " + position);
}
pending.put(position, block.state());
}
@Override
public void marker(PlacedMarker marker) {
checkOpen();
pendingMarkers.add(marker);
}
@Override
public Mantle mantle() {
throw new AssertionError("Unused mantle");
}
@Override
public void commit() {
checkOpen();
published.putAll(pending);
publishedMarkers.addAll(pendingMarkers);
committed = true;
status = Status.COMMITTED;
}
@Override
public void close() {
pending.clear();
pendingMarkers.clear();
status = Status.CLOSED;
}
private void checkOpen() {
if (status != Status.OPEN) throw new IllegalStateException("Edit is " + status);
}
}
@@ -2,44 +2,61 @@ package com.volmit.support;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.GenerationContext;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementContext;
import com.volmit.resource.PackResources;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
import java.util.Map;
import java.util.Random;
import java.util.random.RandomGenerator;
/** Tests needing no platform facilities fail loudly if code starts using one. */
public final class TestContexts {
public static final long SEED = 42;
private TestContexts() {}
public static GenerationContext generation() {
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks) {
return new GenerationContext() {
private final RandomGenerator random = new Random(42);
private final RandomGenerator random = new Random(SEED);
public int originX() { return 0; }
public int originY() { return -64; }
public int originZ() { return 0; }
public long worldSeed() { return 42; }
public long worldSeed() { return SEED; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public Mantle mantle() { throw new AssertionError("Unused mantle"); }
@SuppressWarnings("unchecked")
public <T> Hunk<T> hunk(Class<T> type) {
var hunk = hunks.get(type);
if (hunk == null) throw new IllegalArgumentException("No hunk of " + type.getName());
return (Hunk<T>) hunk;
}
};
}
public static PlacementContext placement() {
return placement(null);
}
public static PlacementContext placement(BlockView blocks) {
return new PlacementContext() {
private final RandomGenerator random = new Random(42);
public long worldSeed() { return 42; }
private final RandomGenerator random = new Random(SEED);
public long worldSeed() { return SEED; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
public BlockView blocks() { throw new AssertionError("Unused blocks"); }
public BlockView blocks() {
if (blocks == null) throw new AssertionError("Unused blocks");
return blocks;
}
};
}
}
@@ -0,0 +1,30 @@
package com.volmit.support;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockView;
import java.util.function.IntBinaryOperator;
/** Prepared pre-placement blocks: stone below a per-column ground height, air above. */
public final class TestTerrain implements BlockView {
public static final BlockState STONE = new BlockState("minecraft:stone");
public static final BlockState AIR = new BlockState("minecraft:air");
public static final BlockBox BOUNDS = new BlockBox(-16, 0, -16, 16, 32, 16);
private final IntBinaryOperator groundHeight;
public TestTerrain(IntBinaryOperator groundHeight) {
this.groundHeight = groundHeight;
}
@Override
public BlockBox bounds() {
return BOUNDS;
}
@Override
public BlockState get(int x, int y, int z) {
if (!BOUNDS.contains(x, y, z)) throw new IndexOutOfBoundsException("Outside test terrain: " + x + "," + y + "," + z);
return y < groundHeight.applyAsInt(x, z) ? STONE : AIR;
}
}