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

+3 -11
View File
@@ -1,16 +1,13 @@
package com.volmit;
import com.volmit.generation.ModifierFactory;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.placement.PlacementModifierFactory;
/** Host implementation collects registrations before loading pack configuration.
* Feature IDs must be unique. JSON fields must be unique per attachment target.
* Modifiers own their IDs and dependency declarations, independently of feature IDs.
* All configured instances of a modifier follow the same ordering.
/** Host implementation collects non-stage registrations before loading pack configuration.
* Feature IDs must be unique. JSON fields must be unique per attachment target, including the
* settings types stages name in {@code when(...)}.
*/
public interface FeatureRegistry {
/** Registers a layer before pack loading. Null arguments throw NullPointerException;
@@ -21,10 +18,5 @@ public interface FeatureRegistry {
*/
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec);
<F extends IrisFeature, T> void register(Class<F> featureType,
Class<T> outputType, ModifierFactory<F, T> factory);
<F extends IrisFeature> void registerObject(Class<F> featureType, ObjectGeneratorFactory<F> factory);
<F extends IrisFeature> void registerPlacement(Class<F> featureType, PlacementModifierFactory<F> factory);
}
+10 -4
View File
@@ -1,10 +1,16 @@
package com.volmit;
import com.volmit.stage.StageGraph;
/** A unit of world-generation behavior. The core engine is an ordinary module too. */
public interface IrisModule {
ModuleInfo info();
String name();
/** Defines this module's stages, before settings are decoded or generation starts.
* Called once per pack load; stage bodies must not capture per-invocation state.
*/
void install(StageGraph graph);
String displayVersion();
/** Called during registration, before settings are decoded or generation starts. */
void register(FeatureRegistry registry);
/** Registers non-stage contributions: geometry generators and mantle layers. */
default void register(FeatureRegistry registry) {}
}
+19
View File
@@ -0,0 +1,19 @@
package com.volmit;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Module identity. Stages a module defines must use the namespace of its id. */
public record ModuleInfo(ResourceId id, String version) {
public ModuleInfo {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(version, "version");
if (version.isBlank()) {
throw new IllegalArgumentException("Blank module version: " + id);
}
}
public static ModuleInfo of(String id, String version) {
return new ModuleInfo(ResourceId.parse(id), version);
}
}
@@ -1,52 +0,0 @@
package com.volmit.generation;
import java.util.HashSet;
import java.util.Set;
import com.volmit.resource.ResourceId;
/** Immutable ordering declarations referencing modifier IDs, not feature IDs.
* Requirements must exist and finish first. Optional constraints apply only when present.
* Nothing here activates a feature. The host resolves and validates the graph at pack load.
*/
public record Dependencies(Set<String> required, Set<String> after, Set<String> before) {
public Dependencies {
required = validatedCopy(required);
after = validatedCopy(after);
before = validatedCopy(before);
}
public static Dependencies none() {
return new Dependencies(Set.of(), Set.of(), Set.of());
}
public static Dependencies requires(String... ids) {
return none().andRequires(ids);
}
/** Adds required predecessors without changing this declaration. */
public Dependencies andRequires(String... ids) {
return new Dependencies(adding(required, ids), after, before);
}
public Dependencies afterIfPresent(String... ids) {
return new Dependencies(required, adding(after, ids), before);
}
public Dependencies beforeIfPresent(String... ids) {
return new Dependencies(required, after, adding(before, ids));
}
private static Set<String> adding(Set<String> existing, String[] ids) {
var result = new HashSet<>(existing);
for (String id : ids) result.add(id);
return result;
}
private static Set<String> validatedCopy(Set<String> ids) {
var copy = Set.copyOf(ids);
for (String id : copy) {
ResourceId.parse(id);
}
return copy;
}
}
@@ -1,10 +1,11 @@
package com.volmit.generation;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.config.FeatureSettings;
import com.volmit.world.TerrainSampler;
/** Per-invocation state. Must not be retained by a modifier after execution. */
/** Per-invocation chunk generation inputs. Must not be retained after execution. */
public interface GenerationContext extends InvocationContext {
/** World block coordinates corresponding to local volume coordinates (0, 0, 0). */
int originX();
@@ -16,4 +17,9 @@ public interface GenerationContext extends InvocationContext {
/** Non-null mantle access scoped to this invocation; the host owns its lifetime. */
Mantle mantle();
/** The host-owned local volume of the given value type, shared by all stages of this
* invocation. Unsupported types throw IllegalArgumentException.
*/
<T> Hunk<T> hunk(Class<T> type);
}
@@ -1,34 +0,0 @@
package com.volmit.generation;
import com.volmit.hunk.Hunk;
/** Bound to one configured feature instance.
* Calls may occur concurrently for different volumes. Keep settings read-only and temporary
* state local to modify(). Exceptions propagate: the host must not publish partial output.
*/
public abstract class GenerationModifier<T> {
/** Stable, nonblank namespaced modifier identity, independent of feature identity.
* Configured instances of the same modifier share this ID and dependency declaration.
* Different modifier implementations must not claim the same ID.
*/
public abstract String id();
/** Stable requirements read at pack load, not per invocation. Constructors must not
* depend on prerequisite modifiers having run. Ordering does not guarantee that
* a prerequisite changed blocks at the current location.
*/
public Dependencies depends() {
return Dependencies.none();
}
/** Nonnegative horizontal reach in blocks beyond the output footprint; zero by default.
* Read once per configured instance at pack load. The host must prepare this area and
* required predecessor work before invocation, bound vertical access to the world, and
* serialize overlapping writes. It must reject negative or unsupported reach, not clip it.
*/
public int mantleRadius() {
return 0;
}
public abstract void modify(GenerationContext context, Hunk<T> output);
}
@@ -1,9 +0,0 @@
package com.volmit.generation;
import com.volmit.IrisFeature;
/** Connects a feature's decoded options to its executable modifier. */
@FunctionalInterface
public interface ModifierFactory<F extends IrisFeature, T> {
GenerationModifier<T> create(F feature);
}
@@ -0,0 +1,85 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.stage.BlockCollector;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.BlockStageDefinition;
import com.volmit.stage.ConditionalBlockStageDefinition;
import com.volmit.stage.SettingsAction;
import com.volmit.stage.SettingsBlockCollector;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageRef;
import java.util.Objects;
import java.util.function.Supplier;
/** Builder behind both block stage definition views; S is unused until when(...). */
final class BlockStageDraft<S extends IrisFeature, O>
implements BlockStageDefinition<O>, ConditionalBlockStageDefinition<S, O> {
private final StageDeclaration declaration;
BlockStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public BlockStageDraft<S, O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public BlockStageDraft<S, O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public BlockStageDraft<S, O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
@SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here.
public <N extends IrisFeature> BlockStageDraft<N, O> when(Class<N> settingsType) {
declaration.condition(settingsType);
return (BlockStageDraft<N, O>) (BlockStageDraft<?, ?>) this;
}
@Override
public void run(StageAction<BlockStageContext> action) {
Objects.requireNonNull(action, "action");
complete(null, (context, settings, accumulator) -> action.run(context));
}
@Override
public void accumulate(Supplier<O> initial, BlockCollector<O> collector) {
Objects.requireNonNull(collector, "collector");
complete(Objects.requireNonNull(initial, "initial"),
(context, settings, accumulator) -> collector.collect(context, cast(accumulator)));
}
@Override
public void run(SettingsAction<BlockStageContext, S> action) {
Objects.requireNonNull(action, "action");
complete(null, (context, settings, accumulator) -> action.run(context, cast(settings)));
}
@Override
public void accumulate(Supplier<O> initial, SettingsBlockCollector<S, O> collector) {
Objects.requireNonNull(collector, "collector");
complete(Objects.requireNonNull(initial, "initial"),
(context, settings, accumulator) -> collector.collect(context, cast(settings), cast(accumulator)));
}
private void complete(Supplier<?> initial, StageBody.BlockWork work) {
boolean accumulates = initial != null;
declaration.complete(new StageBody.Block(initial, work), accumulates, accumulates ? "run" : "accumulate");
}
@SuppressWarnings("unchecked") // The executor passes the settings and accumulator this stage was declared with.
private static <T> T cast(Object value) {
return (T) value;
}
}
@@ -0,0 +1,82 @@
package com.volmit.host;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.GenerationContext;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.resource.PackResources;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
import java.util.Objects;
import java.util.random.RandomGenerator;
/** The context every stage of one chunk invocation receives. */
final class ChunkInvocation implements ChunkStageContext {
private final StageInvocation stages;
private final GenerationContext inputs;
ChunkInvocation(StageInvocation stages, GenerationContext inputs) {
this.stages = stages;
this.inputs = Objects.requireNonNull(inputs, "inputs");
}
StageInvocation stages() {
return stages;
}
@Override
public <O> O output(Stage<O> stage) {
return stages.output(stage);
}
@Override
public int originX() {
return inputs.originX();
}
@Override
public int originY() {
return inputs.originY();
}
@Override
public int originZ() {
return inputs.originZ();
}
@Override
public TerrainSampler terrain() {
return inputs.terrain();
}
@Override
public FeatureSettings settings() {
return inputs.settings();
}
@Override
public Mantle mantle() {
return inputs.mantle();
}
@Override
public <T> Hunk<T> hunk(Class<T> type) {
return inputs.hunk(type);
}
@Override
public long worldSeed() {
return inputs.worldSeed();
}
@Override
public PackResources resources() {
return inputs.resources();
}
@Override
public RandomGenerator random() {
return inputs.random();
}
}
@@ -0,0 +1,27 @@
package com.volmit.host;
import com.volmit.generation.GenerationContext;
import com.volmit.stage.Pipeline;
import java.util.Objects;
/** Reference executor of a resolved chunk graph: active stages run once, in resolved order.
* It does not schedule neighbors or roll back hunks; a failed invocation must prevent the host
* from publishing the chunk.
*/
public final class ChunkRunner {
private final ResolvedGraph graph;
public ChunkRunner(ResolvedGraph graph) {
this.graph = Objects.requireNonNull(graph, "graph");
if (graph.pipeline() != Pipeline.CHUNK) {
throw new IllegalArgumentException("Expected a chunk graph, got " + graph.pipeline());
}
}
public void generate(GenerationContext inputs, ConfiguredSettings settings) {
var chunk = new ChunkInvocation(new StageInvocation(graph, settings), inputs);
for (int position = 0; position < graph.size(); position++) {
chunk.stages().runInvocationStage(position, chunk);
}
}
}
@@ -1,69 +0,0 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.generation.GenerationContext;
import com.volmit.generation.GenerationModifier;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Pack-load snapshot of modifier identity, requirements, type and prepared reach.
* The occurrence identifies one configuration, independent of its shared ordering identity.
*/
public final class ConfiguredModifier<T> {
private final ResourceId occurrence;
private final Class<T> outputType;
private final GenerationModifier<T> modifier;
private final ResourceId id;
private final Dependencies dependencies;
private final int mantleRadius;
public ConfiguredModifier(
ResourceId occurrence,
Class<T> outputType,
GenerationModifier<T> modifier) {
this.occurrence = Objects.requireNonNull(occurrence, "occurrence");
this.outputType = Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Output requires a reference type");
}
this.modifier = Objects.requireNonNull(modifier, "modifier");
id = ResourceId.parse(modifier.id());
dependencies = Objects.requireNonNull(modifier.depends(), "dependencies");
mantleRadius = modifier.mantleRadius();
if (mantleRadius < 0) {
throw new IllegalArgumentException("Negative mantle radius: " + id);
}
}
public ResourceId occurrence() {
return occurrence;
}
public Class<T> outputType() {
return outputType;
}
public ResourceId id() {
return id;
}
public Dependencies dependencies() {
return dependencies;
}
public int mantleRadius() {
return mantleRadius;
}
public Class<?> implementationType() {
return modifier.getClass();
}
/** Host must prepare views/predecessor work and abort publication if this throws. */
public void modify(GenerationContext context, Hunk<T> output) {
modifier.modify(
Objects.requireNonNull(context, "context"),
Objects.requireNonNull(output, "output"));
}
}
@@ -1,46 +0,0 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.placement.PlacementModifier;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Pack-load placement declaration snapshot. The configured modifier must be immutable. */
public final class ConfiguredPlacementModifier {
private final ResourceId occurrence;
private final PlacementModifier modifier;
private final ResourceId id;
private final Dependencies dependencies;
private final int writeRadius;
public ConfiguredPlacementModifier(ResourceId occurrence, PlacementModifier modifier) {
this.occurrence = Objects.requireNonNull(occurrence, "occurrence");
this.modifier = Objects.requireNonNull(modifier, "modifier");
id = ResourceId.parse(modifier.id());
dependencies = Objects.requireNonNull(modifier.depends(), "dependencies");
writeRadius = modifier.writeRadius();
if (writeRadius < 0) {
throw new IllegalArgumentException("Negative placement radius: " + id);
}
}
public ResourceId occurrence() {
return occurrence;
}
public PlacementModifier modifier() {
return modifier;
}
public ResourceId id() {
return id;
}
public Dependencies dependencies() {
return dependencies;
}
public int writeRadius() {
return writeRadius;
}
}
@@ -0,0 +1,41 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/** Feature settings configured for one invocation: the placement's settings, or the settings
* the host resolved for a chunk. At most one value per type; merging and precedence between
* dimension/region/biome/placement declarations stay host policy. Build once and reuse it for
* every invocation with the same configuration.
*/
public final class ConfiguredSettings {
private static final ConfiguredSettings NONE = new ConfiguredSettings(Map.of());
private final Map<Class<?>, IrisFeature> values;
private ConfiguredSettings(Map<Class<?>, IrisFeature> values) {
this.values = Map.copyOf(values);
}
public static ConfiguredSettings none() {
return NONE;
}
public static ConfiguredSettings of(IrisFeature... settings) {
var values = new HashMap<Class<?>, IrisFeature>();
for (var value : settings) {
Objects.requireNonNull(value, "settings");
if (values.putIfAbsent(value.getClass(), value) != null) {
throw new IllegalArgumentException("Settings configured twice: " + value.getClass().getName());
}
}
return new ConfiguredSettings(values);
}
public <S extends IrisFeature> Optional<S> find(Class<S> type) {
return Optional.ofNullable(type.cast(values.get(type)));
}
}
@@ -1,144 +0,0 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
/** Host-independent ordering of one complete modifier graph. Ready IDs use lexical order,
* independent of discovery. Required IDs must exist. Optional edges apply only when present.
* Self-dependencies and cycles fail. This graph never activates features or permits parallel writes.
*/
public final class DependencyOrder {
private DependencyOrder() {}
public static List<ResourceId> resolve(Map<ResourceId, Dependencies> declarations) {
var graph = Map.copyOf(declarations);
var incomingEdges = initializeIncomingEdges(graph.keySet());
var outgoingEdges = new HashMap<ResourceId, Set<ResourceId>>();
addDeclaredEdges(graph, incomingEdges, outgoingEdges);
return topologicalOrder(graph, incomingEdges, outgoingEdges);
}
private static Map<ResourceId, Integer> initializeIncomingEdges(Set<ResourceId> ids) {
var incomingEdges = new HashMap<ResourceId, Integer>();
ids.forEach(id -> incomingEdges.put(id, 0));
return incomingEdges;
}
private static void addDeclaredEdges(
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
graph.forEach((id, dependencies) -> {
Objects.requireNonNull(dependencies, "dependencies");
addRequiredEdges(id, dependencies, graph, incomingEdges, outgoingEdges);
addOptionalEdges(id, dependencies, graph, incomingEdges, outgoingEdges);
});
}
private static void addRequiredEdges(
ResourceId id,
Dependencies dependencies,
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
for (var name : dependencies.required()) {
var predecessor = ResourceId.parse(name);
if (!graph.containsKey(predecessor)) {
throw new IllegalArgumentException(id + " requires missing modifier " + predecessor);
}
addEdge(predecessor, id, incomingEdges, outgoingEdges);
}
}
private static void addOptionalEdges(
ResourceId id,
Dependencies dependencies,
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
for (var name : dependencies.after()) {
var predecessor = ResourceId.parse(name);
rejectSelf(id, predecessor);
if (graph.containsKey(predecessor)) {
addEdge(predecessor, id, incomingEdges, outgoingEdges);
}
}
for (var name : dependencies.before()) {
var successor = ResourceId.parse(name);
rejectSelf(id, successor);
if (graph.containsKey(successor)) {
addEdge(id, successor, incomingEdges, outgoingEdges);
}
}
}
private static List<ResourceId> topologicalOrder(
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
var ready = new PriorityQueue<ResourceId>();
incomingEdges.forEach((id, count) -> {
if (count == 0) {
ready.add(id);
}
});
var ordered = new ArrayList<ResourceId>(graph.size());
while (!ready.isEmpty()) {
var id = ready.remove();
ordered.add(id);
releaseSuccessors(id, outgoingEdges, incomingEdges, ready);
}
if (ordered.size() != graph.size()) {
throw cycleException(graph.keySet(), ordered);
}
return List.copyOf(ordered);
}
private static void releaseSuccessors(
ResourceId id,
Map<ResourceId, Set<ResourceId>> outgoingEdges,
Map<ResourceId, Integer> incomingEdges,
PriorityQueue<ResourceId> ready) {
for (var successor : outgoingEdges.getOrDefault(id, Set.of())) {
int remainingEdges = incomingEdges.compute(successor, (ignored, count) -> count - 1);
if (remainingEdges == 0) {
ready.add(successor);
}
}
}
private static IllegalArgumentException cycleException(Set<ResourceId> ids, List<ResourceId> ordered) {
var unresolved = new TreeSet<>(ids);
unresolved.removeAll(ordered);
return new IllegalArgumentException("Modifier dependency cycle: " + unresolved);
}
private static void rejectSelf(ResourceId id, ResourceId other) {
if (id.equals(other)) {
throw new IllegalArgumentException("Self-dependency: " + id);
}
}
private static void addEdge(
ResourceId from,
ResourceId to,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
rejectSelf(from, to);
if (outgoingEdges.computeIfAbsent(from, ignored -> new HashSet<>()).add(to)) {
incomingEdges.compute(to, (ignored, count) -> count + 1);
}
}
}
@@ -0,0 +1,27 @@
package com.volmit.host;
import com.volmit.stage.Stage;
/** Execution data of one resolved stage. Indices are positions in the resolved order.
* readableStages/readablePositions are the transitive requirements whose outputs it may read.
* settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS.
*/
record ExecutableStage(
Stage<?> stage,
StageBody body,
int[] requirements,
Stage<?>[] readableStages,
int[] readablePositions,
int settingsSlot) {
static final int NO_SETTINGS = -1;
static final int NOT_READABLE = -1;
int readablePosition(Stage<?> requested) {
for (int index = 0; index < readableStages.length; index++) {
if (readableStages[index] == requested) {
return readablePositions[index];
}
}
return NOT_READABLE;
}
}
@@ -12,34 +12,28 @@ import java.util.function.Function;
* Factory and codec implementations must themselves obey their concurrency contracts.
*/
public final class FeatureCatalog {
private final Map<Class<?>, GenerationRegistration<?, ?>> generation;
private final Map<Class<?>, FeatureDescriptor<?>> settings;
private final Map<Class<?>, ObjectRegistration<?>> objects;
private final Map<Class<?>, PlacementRegistration<?>> placement;
private final Map<String, MantleRegistration<?>> mantle;
FeatureCatalog(
Map<Class<?>, GenerationRegistration<?, ?>> generation,
Map<Class<?>, FeatureDescriptor<?>> settings,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<Class<?>, PlacementRegistration<?>> placement,
Map<String, MantleRegistration<?>> mantle) {
this.generation = Map.copyOf(generation);
this.settings = Map.copyOf(settings);
this.objects = Map.copyOf(objects);
this.placement = Map.copyOf(placement);
this.mantle = Map.copyOf(mantle);
}
public List<GenerationRegistration<?, ?>> generation() {
return sorted(generation.values(), registration -> registration.descriptor().id());
/** Settings types that activate stages; the host decodes them from pack JSON. */
public List<FeatureDescriptor<?>> settings() {
return sorted(settings.values(), FeatureDescriptor::id);
}
public List<ObjectRegistration<?>> objects() {
return sorted(objects.values(), registration -> registration.descriptor().id());
}
public List<PlacementRegistration<?>> placement() {
return sorted(placement.values(), registration -> registration.descriptor().id());
}
public List<MantleRegistration<?>> mantle() {
return sorted(mantle.values(), registration -> registration.key().id());
}
@@ -52,20 +46,6 @@ public final class FeatureCatalog {
.toList();
}
@SuppressWarnings("unchecked") // The registry key and output type establish the generic pairing.
public <F extends IrisFeature, T> GenerationRegistration<F, T> generation(
Class<F> type,
Class<T> outputType) {
var registration = generation.get(type);
if (registration == null) {
throw new NoSuchElementException("No generation feature: " + type.getName());
}
if (!registration.outputType().equals(outputType)) {
throw new IllegalArgumentException("Output type mismatch: " + type.getName());
}
return (GenerationRegistration<F, T>) registration;
}
@SuppressWarnings("unchecked") // The registry key is the factory's feature type.
public <F extends IrisFeature> ObjectRegistration<F> object(Class<F> type) {
var registration = objects.get(type);
@@ -74,13 +54,4 @@ public final class FeatureCatalog {
}
return (ObjectRegistration<F>) registration;
}
@SuppressWarnings("unchecked") // The registry key is the factory's feature type.
public <F extends IrisFeature> PlacementRegistration<F> placement(Class<F> type) {
var registration = placement.get(type);
if (registration == null) {
throw new NoSuchElementException("No placement feature: " + type.getName());
}
return (PlacementRegistration<F>) registration;
}
}
@@ -2,11 +2,14 @@ package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.OptionsMetadata;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Modifier;
import java.util.Objects;
import java.util.Set;
/** Validated registration metadata. It describes configuration, not executable ordering. */
/** Validated settings metadata. It describes configuration, not executable ordering. */
public record FeatureDescriptor<F extends IrisFeature>(
ResourceId id,
String name,
@@ -23,4 +26,31 @@ public record FeatureDescriptor<F extends IrisFeature>(
Objects.requireNonNull(attachment, "attachment");
Objects.requireNonNull(options, "options");
}
/** Reads the @Feature declaration of a concrete settings class. */
public static <F extends IrisFeature> FeatureDescriptor<F> of(Class<F> type) {
Objects.requireNonNull(type, "featureType");
requireConcreteFeature(type);
var annotation = type.getDeclaredAnnotation(Feature.class);
if (annotation == null) {
throw new IllegalArgumentException("Missing @Feature: " + type.getName());
}
return new FeatureDescriptor<>(
ResourceId.parse(annotation.id()),
annotation.name(),
type,
new FeatureAttachment(annotation.field(), Set.of(annotation.targets())),
OptionsMetadata.inspect(type));
}
private static void requireConcreteFeature(Class<?> type) {
if (!IrisFeature.class.isAssignableFrom(type)
|| type.isInterface()
|| Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException(
"Feature type must be a concrete IrisFeature: " + type.getName());
}
}
}
@@ -1,91 +0,0 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Immutable pack-load ordering across output types. Instances sharing a modifier ID must
* have the same implementation, output type and dependencies. Occurrence IDs must be unique.
* Instances within one identity use lexical occurrence order. Resolve once, dispatch many times.
* The host includes its built-in lifecycle steps in this graph and rejects incompatible edges.
*/
public final class GenerationPlan {
private final List<ConfiguredModifier<?>> ordered;
private GenerationPlan(List<ConfiguredModifier<?>> ordered) {
this.ordered = List.copyOf(ordered);
}
public static GenerationPlan resolve(List<? extends ConfiguredModifier<?>> modifiers) {
List<ConfiguredModifier<?>> instances = new ArrayList<>(modifiers);
var declarations = collectDeclarations(instances);
var modifierIds = DependencyOrder.resolve(declarations);
var orderedOccurrences = OccurrenceOrder.order(
modifierIds,
instances,
ConfiguredModifier::id,
ConfiguredModifier::occurrence);
return new GenerationPlan(orderedOccurrences);
}
private static Map<ResourceId, Dependencies> collectDeclarations(List<ConfiguredModifier<?>> instances) {
var representatives = new HashMap<ResourceId, ConfiguredModifier<?>>();
var occurrences = new HashSet<ResourceId>();
var declarations = new HashMap<ResourceId, Dependencies>();
for (var modifier : instances) {
checkUniqueOccurrence(modifier, occurrences);
checkCompatibleIdentity(modifier, representatives);
declarations.put(modifier.id(), modifier.dependencies());
}
return declarations;
}
private static void checkUniqueOccurrence(
ConfiguredModifier<?> modifier,
Set<ResourceId> occurrences) {
if (!occurrences.add(modifier.occurrence())) {
throw new IllegalArgumentException("Duplicate occurrence: " + modifier.occurrence());
}
}
private static void checkCompatibleIdentity(
ConfiguredModifier<?> modifier,
Map<ResourceId, ConfiguredModifier<?>> representatives) {
var previous = representatives.putIfAbsent(modifier.id(), modifier);
if (previous == null || isCompatible(previous, modifier)) {
return;
}
throw new IllegalArgumentException("Conflicting modifier identity: " + modifier.id());
}
private static boolean isCompatible(ConfiguredModifier<?> first, ConfiguredModifier<?> second) {
return first.implementationType().equals(second.implementationType())
&& first.outputType().equals(second.outputType())
&& first.dependencies().equals(second.dependencies());
}
public List<ConfiguredModifier<?>> ordered() {
return ordered;
}
/** Sequential dispatch only. Executor prepares/releases a dedicated context and typed output
* for each applicable occurrence; applicability is host-owned. Failures stop dispatch.
* This reference planner does not implement chunk scheduling, rollback or lifecycle bridging.
*/
public void execute(Executor executor) {
java.util.Objects.requireNonNull(executor, "executor");
for (var modifier : ordered) {
executor.execute(modifier);
}
}
public interface Executor {
<T> void execute(ConfiguredModifier<T> modifier);
}
}
@@ -1,25 +0,0 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.generation.ModifierFactory;
import com.volmit.resource.ResourceId;
import java.util.Objects;
public record GenerationRegistration<F extends IrisFeature, T>(
FeatureDescriptor<F> descriptor,
Class<T> outputType,
ModifierFactory<F, T> factory) {
public GenerationRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Output requires a reference type");
}
Objects.requireNonNull(factory, "factory");
}
public ConfiguredModifier<T> configure(ResourceId occurrence, F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return new ConfiguredModifier<>(occurrence, outputType, factory.create(configuredFeature));
}
}
@@ -0,0 +1,87 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import com.volmit.stage.StageKind;
import java.util.List;
import java.util.stream.Collectors;
/** Text rendering of a resolved graph for pack authors and logs. */
final class GraphDescription {
private static final String INDENT = " ";
private static final String DETAIL_INDENT = " ";
private GraphDescription() {}
static String describe(ResolvedGraph graph) {
var text = new StringBuilder();
var passes = graph.blockPasses();
text.append(graph.pipeline()).append(" pipeline: ")
.append(graph.stages().size()).append(" stages, ")
.append(passes.size()).append(passes.size() == 1 ? " block pass\n" : " block passes\n");
appendOrder(text, graph, passes);
appendBlockPasses(text, passes);
appendUnorderedPairs(text, graph.unorderedPairs());
return text.toString();
}
private static void appendOrder(StringBuilder text, ResolvedGraph graph, List<List<ResourceId>> passes) {
text.append("order:\n");
var stages = graph.stages();
for (int position = 0; position < stages.size(); position++) {
var stage = stages.get(position);
text.append(INDENT).append(position + 1).append(". ").append(stage.stage().id())
.append(" [").append(kindLabel(stage, passes)).append("] module ").append(stage.module());
stage.settings().ifPresent(settings -> text.append(" when ").append(settings.id()));
text.append('\n');
appendEdges(text, stage.incoming(), StageEdge.Kind.REQUIRED, "requires ");
appendEdges(text, stage.incoming(), StageEdge.Kind.SOFT, "soft after ");
if (!stage.absentSoftTargets().isEmpty()) {
text.append(DETAIL_INDENT).append("absent soft targets ").append(joined(stage.absentSoftTargets())).append('\n');
}
}
}
private static String kindLabel(ResolvedStage stage, List<List<ResourceId>> passes) {
if (stage.stage().kind() == StageKind.INVOCATION) {
return "invocation";
}
for (int pass = 0; pass < passes.size(); pass++) {
if (passes.get(pass).contains(stage.stage().id())) {
return "block pass " + (pass + 1);
}
}
throw new IllegalStateException("Block stage outside every pass: " + stage.stage());
}
private static void appendEdges(StringBuilder text, List<StageEdge> edges, StageEdge.Kind kind, String label) {
var sources = edges.stream().filter(edge -> edge.kind() == kind).map(StageEdge::from).toList();
if (sources.isEmpty()) {
return;
}
text.append(DETAIL_INDENT).append(label).append(joined(sources)).append('\n');
}
private static void appendBlockPasses(StringBuilder text, List<List<ResourceId>> passes) {
text.append("block passes:\n");
if (passes.isEmpty()) {
text.append(INDENT).append("none\n");
}
for (int pass = 0; pass < passes.size(); pass++) {
text.append(INDENT).append("pass ").append(pass + 1).append(": ").append(joined(passes.get(pass))).append('\n');
}
}
private static void appendUnorderedPairs(StringBuilder text, List<ResolvedGraph.UnorderedPair> pairs) {
text.append("mutually unordered:\n");
if (pairs.isEmpty()) {
text.append(INDENT).append("none\n");
}
for (var pair : pairs) {
text.append(INDENT).append(pair.first()).append(" <-> ").append(pair.second()).append('\n');
}
}
private static String joined(List<?> values) {
return values.stream().map(Object::toString).collect(Collectors.joining(", "));
}
}
@@ -0,0 +1,269 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage;
import com.volmit.stage.StageKind;
import com.volmit.stage.StageRef;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
/** Validates and orders the stages of one pipeline. Nodes are numbered in lexical id order,
* which makes every choice below independent of module install order.
*/
final class GraphResolver {
private final Pipeline pipeline;
private final Map<ResourceId, StageDeclaration> installed = new HashMap<>();
private final List<StageDeclaration> nodes;
private final Map<ResourceId, Integer> nodeById = new HashMap<>();
private final List<Map<Integer, StageEdge.Kind>> predecessors = new ArrayList<>();
private final List<List<StageRef>> absentSoftTargets = new ArrayList<>();
private GraphResolver(Pipeline pipeline, Collection<StageDeclaration> declarations) {
this.pipeline = pipeline;
declarations.forEach(declaration -> installed.put(declaration.stage().id(), declaration));
nodes = declarations.stream()
.filter(declaration -> declaration.stage().pipeline() == pipeline)
.sorted(Comparator.comparing(declaration -> declaration.stage().id()))
.toList();
for (int node = 0; node < nodes.size(); node++) {
nodeById.put(nodes.get(node).stage().id(), node);
predecessors.add(new TreeMap<>());
absentSoftTargets.add(new ArrayList<>());
}
}
static ResolvedGraph resolve(Pipeline pipeline, Collection<StageDeclaration> declarations) {
var resolver = new GraphResolver(pipeline, declarations);
resolver.addDeclaredEdges();
return resolver.toResolvedGraph(resolver.executionOrder());
}
private void addDeclaredEdges() {
for (int node = 0; node < nodes.size(); node++) {
addRequiredEdges(node);
addSoftEdges(node);
}
}
private void addRequiredEdges(int node) {
var declaration = nodes.get(node);
for (var required : declaration.requirements()) {
var target = findRequired(declaration, required);
addEdge(nodeById.get(target.stage().id()), node, StageEdge.Kind.REQUIRED);
}
}
private void addSoftEdges(int node) {
var declaration = nodes.get(node);
for (var reference : declaration.softAfter()) {
findSoftTarget(declaration, reference).ifPresentOrElse(
target -> addEdge(target, node, StageEdge.Kind.SOFT),
() -> absentSoftTargets.get(node).add(reference));
}
for (var reference : declaration.softBefore()) {
findSoftTarget(declaration, reference).ifPresentOrElse(
target -> addEdge(node, target, StageEdge.Kind.SOFT),
() -> absentSoftTargets.get(node).add(reference));
}
}
private StageDeclaration findRequired(StageDeclaration dependent, Stage<?> required) {
var target = installed.get(required.id());
if (target == null) {
throw new IllegalArgumentException("Stage " + dependent + " requires " + required
+ ", which no installed module defines (expected a module in namespace '"
+ required.id().namespace() + "')");
}
requireSamePipeline(dependent, target);
if (target.stage() != required) {
throw new IllegalArgumentException("Stage " + dependent + " requires a different declaration of "
+ target + "; reference the owning module's stage constant");
}
return target;
}
private Optional<Integer> findSoftTarget(StageDeclaration dependent, StageRef reference) {
var target = installed.get(reference.id());
if (target == null) {
return Optional.empty();
}
requireSamePipeline(dependent, target);
return Optional.of(nodeById.get(reference.id()));
}
private void requireSamePipeline(StageDeclaration dependent, StageDeclaration target) {
if (target.stage().pipeline() == pipeline) {
return;
}
throw new IllegalArgumentException("Stage " + dependent + " in pipeline " + pipeline
+ " depends on " + target + " in pipeline " + target.stage().pipeline()
+ "; dependencies cannot cross pipelines");
}
private void addEdge(int from, int to, StageEdge.Kind kind) {
predecessors.get(to).merge(from, kind, StageEdge.Kind::strongest);
}
private int[] executionOrder() {
int[] waitingOn = new int[nodes.size()];
var successors = successors();
var ready = new ReadyStages();
for (int node = 0; node < nodes.size(); node++) {
waitingOn[node] = predecessors.get(node).size();
if (waitingOn[node] == 0) {
ready.add(node, kind(node));
}
}
int[] order = new int[nodes.size()];
int ordered = 0;
while (!ready.isEmpty()) {
int node = ready.next();
order[ordered++] = node;
for (int successor : successors.get(node)) {
if (--waitingOn[successor] == 0) {
ready.add(successor, kind(successor));
}
}
}
if (ordered != nodes.size()) {
throw cycleError(waitingOn);
}
return order;
}
private List<List<Integer>> successors() {
var successors = new ArrayList<List<Integer>>();
nodes.forEach(ignored -> successors.add(new ArrayList<>()));
for (int node = 0; node < nodes.size(); node++) {
for (int predecessor : predecessors.get(node).keySet()) {
successors.get(predecessor).add(node);
}
}
return successors;
}
private StageKind kind(int node) {
return nodes.get(node).stage().kind();
}
private IllegalArgumentException cycleError(int[] waitingOn) {
var cycle = findCycle(waitingOn);
var description = new StringBuilder(nodes.get(cycle.getFirst()).toString());
for (int index = 0; index < cycle.size(); index++) {
int from = cycle.get(index);
int to = cycle.get((index + 1) % cycle.size());
var kind = predecessors.get(to).get(from).name().toLowerCase();
description.append(" -[").append(kind).append("]-> ").append(nodes.get(to));
}
return new IllegalArgumentException("Stage cycle in pipeline " + pipeline + ": " + description);
}
/** Every unordered node still waits on an unordered predecessor, so walking predecessors
* from any of them must revisit a node; the revisited stretch is a cycle.
*/
private List<Integer> findCycle(int[] waitingOn) {
int current = firstWaiting(waitingOn);
var walk = new ArrayList<Integer>();
var walkIndex = new HashMap<Integer, Integer>();
while (!walkIndex.containsKey(current)) {
walkIndex.put(current, walk.size());
walk.add(current);
current = firstWaitingPredecessor(current, waitingOn);
}
var cycle = new ArrayList<>(walk.subList(walkIndex.get(current), walk.size()));
Collections.reverse(cycle);
Collections.rotate(cycle, -cycle.indexOf(Collections.min(cycle)));
return cycle;
}
private static int firstWaiting(int[] waitingOn) {
for (int node = 0; node < waitingOn.length; node++) {
if (waitingOn[node] > 0) {
return node;
}
}
throw new IllegalStateException("No stage is waiting");
}
private int firstWaitingPredecessor(int node, int[] waitingOn) {
return predecessors.get(node).keySet().stream()
.filter(predecessor -> waitingOn[predecessor] > 0)
.findFirst()
.orElseThrow();
}
private ResolvedGraph toResolvedGraph(int[] order) {
int[] position = new int[order.length];
for (int index = 0; index < order.length; index++) {
position[order[index]] = index;
}
var stages = new ArrayList<ResolvedStage>(order.length);
var executables = new ExecutableStage[order.length];
var readable = new BitSet[order.length];
var settingsTypes = new ArrayList<Class<?>>();
for (int index = 0; index < order.length; index++) {
int node = order[index];
var declaration = nodes.get(node);
int[] requirements = requiredPositions(node, position);
readable[index] = transitiveRequirements(requirements, readable);
executables[index] = new ExecutableStage(
declaration.stage(),
declaration.body(),
requirements,
readable[index].stream().mapToObj(readablePosition -> nodes.get(order[readablePosition]).stage())
.toArray(Stage<?>[]::new),
readable[index].stream().toArray(),
settingsSlot(declaration, settingsTypes));
stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(),
incomingEdges(node, position), absentSoftTargets.get(node)));
}
return new ResolvedGraph(pipeline, stages, List.of(executables), settingsTypes);
}
private int[] requiredPositions(int node, int[] position) {
return predecessors.get(node).entrySet().stream()
.filter(edge -> edge.getValue() == StageEdge.Kind.REQUIRED)
.mapToInt(edge -> position[edge.getKey()])
.sorted()
.toArray();
}
private static BitSet transitiveRequirements(int[] requirements, BitSet[] readable) {
var result = new BitSet();
for (int required : requirements) {
result.set(required);
result.or(readable[required]);
}
return result;
}
private static int settingsSlot(StageDeclaration declaration, List<Class<?>> settingsTypes) {
if (declaration.settings().isEmpty()) {
return ExecutableStage.NO_SETTINGS;
}
var type = declaration.settings().orElseThrow().type();
if (!settingsTypes.contains(type)) {
settingsTypes.add(type);
}
return settingsTypes.indexOf(type);
}
private List<StageEdge> incomingEdges(int node, int[] position) {
var target = nodes.get(node).stage().id();
return predecessors.get(node).entrySet().stream()
.sorted(Comparator.comparingInt(edge -> position[edge.getKey()]))
.map(edge -> new StageEdge(nodes.get(edge.getKey()).stage().id(), target, edge.getValue()))
.toList();
}
}
@@ -0,0 +1,87 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.stage.ConditionalStageDefinition;
import com.volmit.stage.SettingsAction;
import com.volmit.stage.SettingsFunction;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageContext;
import com.volmit.stage.StageDefinition;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
import java.util.Objects;
/** Builder behind both invocation stage definition views; S is unused until when(...). */
final class InvocationStageDraft<C extends StageContext, S extends IrisFeature, O>
implements StageDefinition<C, O>, ConditionalStageDefinition<C, S, O> {
private final StageDeclaration declaration;
InvocationStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public InvocationStageDraft<C, S, O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public InvocationStageDraft<C, S, O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public InvocationStageDraft<C, S, O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
@SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here.
public <N extends IrisFeature> InvocationStageDraft<C, N, O> when(Class<N> settingsType) {
declaration.condition(settingsType);
return (InvocationStageDraft<C, N, O>) (InvocationStageDraft<?, ?, ?>) this;
}
@Override
public void run(StageAction<C> action) {
Objects.requireNonNull(action, "action");
complete(false, "produce", (context, settings) -> {
action.run(cast(context));
return null;
});
}
@Override
public void produce(StageFunction<C, O> function) {
Objects.requireNonNull(function, "function");
complete(true, "run", (context, settings) -> function.run(cast(context)));
}
@Override
public void run(SettingsAction<C, S> action) {
Objects.requireNonNull(action, "action");
complete(false, "produce", (context, settings) -> {
action.run(cast(context), cast(settings));
return null;
});
}
@Override
public void produce(SettingsFunction<C, S, O> function) {
Objects.requireNonNull(function, "function");
complete(true, "run", (context, settings) -> function.run(cast(context), cast(settings)));
}
private void complete(boolean producesOutput, String alternativeMethod, StageBody.InvocationWork work) {
declaration.complete(new StageBody.Invocation(work), producesOutput, alternativeMethod);
}
@SuppressWarnings("unchecked") // The executor passes the context and settings this stage was declared with.
private static <T> T cast(Object value) {
return (T) value;
}
}
@@ -0,0 +1,34 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisModule;
import com.volmit.stage.Pipeline;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/** Everything one pack load derives from its modules: the frozen feature catalog (including the
* settings types stages are conditioned on) and one resolved graph per pipeline.
*/
public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, ResolvedGraph chunk) {
public LoadedModules {
Objects.requireNonNull(catalog, "catalog");
Objects.requireNonNull(placement, "placement");
Objects.requireNonNull(chunk, "chunk");
}
/** Module discovery and version gating stay host work; pass the accepted modules here. */
public static LoadedModules load(
List<? extends IrisModule> modules,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields) {
var registry = new ModuleRegistry(reservedHostFields);
var stages = new StageGraphBuilder();
for (var module : modules) {
stages.install(module);
module.register(registry);
}
stages.settingsTypes().forEach(registry::registerSettings);
return new LoadedModules(registry.freeze(), stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK));
}
}
@@ -3,16 +3,11 @@ package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.OptionsMetadata;
import com.volmit.generation.ModifierFactory;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.placement.PlacementModifierFactory;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -26,9 +21,8 @@ import java.util.Set;
* This does not decode JSON, discover modules or instantiate settings.
*/
public final class ModuleRegistry implements FeatureRegistry {
private final Map<Class<?>, GenerationRegistration<?, ?>> generation = new HashMap<>();
private final Map<Class<?>, FeatureDescriptor<?>> settings = new HashMap<>();
private final Map<Class<?>, ObjectRegistration<?>> objects = new HashMap<>();
private final Map<Class<?>, PlacementRegistration<?>> placement = new HashMap<>();
private final Map<String, MantleRegistration<?>> mantle = new HashMap<>();
private final Set<ResourceId> featureIds = new HashSet<>();
private final Set<Class<?>> featureTypes = new HashSet<>();
@@ -43,42 +37,17 @@ public final class ModuleRegistry implements FeatureRegistry {
reserveHostFields(reservedFields);
}
@Override
public <F extends IrisFeature, T> void register(
Class<F> featureType,
Class<T> outputType,
ModifierFactory<F, T> factory) {
var descriptor = describe(featureType);
var registration = new GenerationRegistration<>(descriptor, outputType, factory);
claim(descriptor);
generation.put(featureType, registration);
}
@Override
public <F extends IrisFeature> void registerObject(
Class<F> featureType,
ObjectGeneratorFactory<F> factory) {
var descriptor = describe(featureType);
checkOpen();
var descriptor = FeatureDescriptor.of(featureType);
var registration = new ObjectRegistration<>(descriptor, factory);
claim(descriptor);
objects.put(featureType, registration);
}
@Override
public <F extends IrisFeature> void registerPlacement(
Class<F> featureType,
PlacementModifierFactory<F> factory) {
var descriptor = describe(featureType);
if (!isPlacementFeature(descriptor)) {
throw new IllegalArgumentException(
"Placement modifiers must attach only to OBJECT_PLACEMENT: " + descriptor.id());
}
var registration = new PlacementRegistration<>(descriptor, factory);
claim(descriptor);
placement.put(featureType, registration);
}
@Override
public <T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec) {
checkOpen();
@@ -91,9 +60,20 @@ public final class ModuleRegistry implements FeatureRegistry {
}
}
/** Claims a settings type named by a stage's when(...). Several stages may share one type. */
public void registerSettings(Class<? extends IrisFeature> settingsType) {
checkOpen();
if (settings.containsKey(settingsType)) {
return;
}
var descriptor = FeatureDescriptor.of(settingsType);
claim(descriptor);
settings.put(settingsType, descriptor);
}
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(generation, objects, placement, mantle);
catalog = new FeatureCatalog(settings, objects, mantle);
}
return catalog;
}
@@ -111,37 +91,6 @@ public final class ModuleRegistry implements FeatureRegistry {
fields.put(new Field(target, name), "host");
}
private <F extends IrisFeature> FeatureDescriptor<F> describe(Class<F> type) {
checkOpen();
Objects.requireNonNull(type, "featureType");
validateFeatureType(type);
var annotation = type.getDeclaredAnnotation(Feature.class);
if (annotation == null) {
throw new IllegalArgumentException("Missing @Feature: " + type.getName());
}
return new FeatureDescriptor<>(
ResourceId.parse(annotation.id()),
annotation.name(),
type,
new FeatureAttachment(annotation.field(), Set.of(annotation.targets())),
OptionsMetadata.inspect(type));
}
private static void validateFeatureType(Class<? extends IrisFeature> type) {
if (!IrisFeature.class.isAssignableFrom(type)
|| type.isInterface()
|| Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException(
"Feature type must be a concrete IrisFeature: " + type.getName());
}
}
private static boolean isPlacementFeature(FeatureDescriptor<?> descriptor) {
return descriptor.attachment().targets().equals(Set.of(FeatureAttachment.Target.OBJECT_PLACEMENT));
}
private void claim(FeatureDescriptor<?> descriptor) {
validateClaim(descriptor);
recordClaim(descriptor);
@@ -1,45 +0,0 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/** Orders configured occurrences by dependency identity, then by occurrence ID. */
final class OccurrenceOrder {
private OccurrenceOrder() {}
static <T> List<T> order(
List<ResourceId> orderedIds,
List<T> occurrences,
Function<? super T, ResourceId> identity,
Function<? super T, ResourceId> occurrenceId) {
Map<ResourceId, List<T>> occurrencesByIdentity = groupByIdentity(occurrences, identity);
var ordered = new ArrayList<T>(occurrences.size());
for (var id : orderedIds) {
var group = occurrencesByIdentity.get(id);
if (group == null) {
continue;
}
group.sort((left, right) -> occurrenceId.apply(left).compareTo(occurrenceId.apply(right)));
ordered.addAll(group);
}
return List.copyOf(ordered);
}
private static <T> Map<ResourceId, List<T>> groupByIdentity(
List<T> occurrences,
Function<? super T, ResourceId> identity) {
var occurrencesByIdentity = new HashMap<ResourceId, List<T>>();
for (var occurrence : occurrences) {
occurrencesByIdentity.computeIfAbsent(identity.apply(occurrence), ignored -> new ArrayList<>())
.add(occurrence);
}
return occurrencesByIdentity;
}
}
@@ -0,0 +1,149 @@
package com.volmit.host;
import com.volmit.config.FeatureSettings;
import com.volmit.object.ObjectBlock;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.PackResources;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.BlockView;
import com.volmit.world.TerrainSampler;
import java.util.Objects;
import java.util.random.RandomGenerator;
/** The context every stage of one placement attempt receives. Block accessors work only while
* a block pass is running.
*/
final class PlacementInvocation implements BlockStageContext {
private enum Progress { RUNNING, REJECTED }
private enum BlockStatus { OUTSIDE_PASS, VISIBLE, SKIPPED }
private final StageInvocation stages;
private final PlacementRequest request;
private final PlacementContext inputs;
private final PlacementAccess access;
private Progress progress = Progress.RUNNING;
private String rejection;
private BlockStatus blockStatus = BlockStatus.OUTSIDE_PASS;
private ObjectBlock block;
PlacementInvocation(StageInvocation stages, PlacementRequest request, PlacementContext inputs, PlacementAccess access) {
this.stages = stages;
this.request = Objects.requireNonNull(request, "request");
this.inputs = Objects.requireNonNull(inputs, "inputs");
this.access = access;
}
StageInvocation stages() {
return stages;
}
boolean isRejected() {
return progress == Progress.REJECTED;
}
String rejection() {
return rejection;
}
void beginBlock(ObjectBlock next) {
block = next;
blockStatus = BlockStatus.VISIBLE;
}
boolean isBlockSkipped() {
return blockStatus == BlockStatus.SKIPPED;
}
void endBlockPass() {
block = null;
blockStatus = BlockStatus.OUTSIDE_PASS;
}
@Override
public <O> O output(Stage<O> stage) {
return stages.output(stage);
}
@Override
public PlacementRequest request() {
return request;
}
@Override
public PlacementAccess access() {
return access;
}
@Override
public void reject(String reason) {
Objects.requireNonNull(reason, "reason");
if (progress == Progress.RUNNING) {
progress = Progress.REJECTED;
rejection = reason;
}
}
@Override
public ObjectBlock block() {
requireBlockPass();
return block;
}
@Override
public void replace(ObjectBlock replacement) {
requireBlockPass();
block = Objects.requireNonNull(replacement, "block");
}
@Override
public void skip() {
requireBlockPass();
blockStatus = BlockStatus.SKIPPED;
}
@Override
public long worldSeed() {
return inputs.worldSeed();
}
@Override
public PackResources resources() {
return inputs.resources();
}
@Override
public RandomGenerator random() {
return inputs.random();
}
@Override
public TerrainSampler terrain() {
return inputs.terrain();
}
@Override
public FeatureSettings settings() {
return inputs.settings();
}
@Override
public ObjectTransformer objects() {
return inputs.objects();
}
@Override
public BlockView blocks() {
return inputs.blocks();
}
private void requireBlockPass() {
if (blockStatus == BlockStatus.OUTSIDE_PASS) {
throw new IllegalStateException("The current block is only available to block stages");
}
}
}
@@ -0,0 +1,29 @@
package com.volmit.host;
import java.util.Objects;
import java.util.Optional;
/** Result of one placement attempt. A rejected attempt committed nothing. */
public record PlacementOutcome(Status status, Optional<String> rejection) {
public enum Status { PLACED, REJECTED }
public PlacementOutcome {
Objects.requireNonNull(status, "status");
Objects.requireNonNull(rejection, "rejection");
if ((status == Status.REJECTED) != rejection.isPresent()) {
throw new IllegalArgumentException("Only rejected placements carry a rejection reason");
}
}
static PlacementOutcome placed() {
return new PlacementOutcome(Status.PLACED, Optional.empty());
}
static PlacementOutcome rejected(String reason) {
return new PlacementOutcome(Status.REJECTED, Optional.of(reason));
}
public boolean isPlaced() {
return status == Status.PLACED;
}
}
@@ -1,374 +0,0 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.BlockBox;
import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementEdit;
import com.volmit.placement.PlacementModifier;
import com.volmit.placement.PlacementPlan;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/** Reference placement orchestration, resolved at pack load. Same-ID instances must agree on
* implementation and dependencies; occurrences are unique and sorted lexically within an ID.
* The host supplies prepared, serialized storage and enforces platform/placement policies.
* This runner buffers all mapped candidates; host validation must reject collisions or unsupported
* writes before execution. It does not silently skip writes, transform geometry or place live blocks.
*/
public final class PlacementPipeline {
private final List<ConfiguredPlacementModifier> ordered;
private PlacementPipeline(List<ConfiguredPlacementModifier> ordered) {
this.ordered = List.copyOf(ordered);
}
public static PlacementPipeline resolve(List<ConfiguredPlacementModifier> modifiers) {
var instances = List.copyOf(modifiers);
var declarations = collectDeclarations(instances);
var modifierIds = DependencyOrder.resolve(declarations);
var orderedOccurrences = OccurrenceOrder.order(
modifierIds,
instances,
ConfiguredPlacementModifier::id,
ConfiguredPlacementModifier::occurrence);
return new PlacementPipeline(orderedOccurrences);
}
private static Map<ResourceId, Dependencies> collectDeclarations(
List<ConfiguredPlacementModifier> instances) {
var representatives = new HashMap<ResourceId, ConfiguredPlacementModifier>();
var occurrences = new HashSet<ResourceId>();
var declarations = new HashMap<ResourceId, Dependencies>();
for (var modifier : instances) {
checkUniqueOccurrence(modifier, occurrences);
checkCompatibleIdentity(modifier, representatives);
declarations.put(modifier.id(), modifier.dependencies());
}
return declarations;
}
private static void checkUniqueOccurrence(
ConfiguredPlacementModifier modifier,
Set<ResourceId> occurrences) {
if (!occurrences.add(modifier.occurrence())) {
throw new IllegalArgumentException("Duplicate placement occurrence: " + modifier.occurrence());
}
}
private static void checkCompatibleIdentity(
ConfiguredPlacementModifier modifier,
Map<ResourceId, ConfiguredPlacementModifier> representatives) {
var previous = representatives.putIfAbsent(modifier.id(), modifier);
if (previous == null || isCompatible(previous, modifier)) {
return;
}
throw new IllegalArgumentException("Conflicting placement identity: " + modifier.id());
}
private static boolean isCompatible(
ConfiguredPlacementModifier first,
ConfiguredPlacementModifier second) {
return first.modifier().getClass().equals(second.modifier().getClass())
&& first.dependencies().equals(second.dependencies());
}
public List<ConfiguredPlacementModifier> ordered() {
return ordered;
}
public int writeRadius() {
return ordered.stream()
.mapToInt(ConfiguredPlacementModifier::writeRadius)
.max()
.orElse(0);
}
/** Takes ownership of a fresh edit, closing it on success, rejection or exception.
* Contexts are opened once per occurrence and must use dedicated RNGs from one pack snapshot.
* The caller releases those invocation views after this call. The host must prepare the full
* footprint plus declared reach; a prepare hook that moves outside it fails without clipping.
* hostValidation must be read-only and covers collisions, support, protection, state/payload
* validity and any policies beyond modifier validation. Callbacks must not commit the edit.
*/
public Optional<PlacementPlan> place(
PlacementRequest request,
PlacementEdit edit,
Function<ConfiguredPlacementModifier, PlacementContext> contexts,
Predicate<PlacementPlan> hostValidation) {
Objects.requireNonNull(edit, "edit");
try (edit) {
requireInputs(request, contexts, hostValidation);
var invocations = openInvocations(contexts);
var preparedRequest = prepareAll(request, invocations);
if (preparedRequest.isEmpty()) {
return Optional.empty();
}
var prepared = preparedRequest.orElseThrow();
checkPreparedArea(prepared, edit);
var plan = createPlan(prepared, invocations, edit);
if (!validatePlan(plan, invocations, hostValidation)) {
return Optional.empty();
}
var hooks = openHookInvocations(prepared, invocations, edit);
runBeforeHooks(plan, hooks);
writePlan(plan, edit);
runAfterHooks(plan, hooks);
edit.commit();
return Optional.of(plan);
}
}
private static void requireInputs(
PlacementRequest request,
Function<ConfiguredPlacementModifier, PlacementContext> contexts,
Predicate<PlacementPlan> hostValidation) {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(contexts, "contexts");
Objects.requireNonNull(hostValidation, "hostValidation");
}
private List<PlacementInvocation> openInvocations(
Function<ConfiguredPlacementModifier, PlacementContext> contexts) {
var invocations = new ArrayList<PlacementInvocation>(ordered.size());
for (var modifier : ordered) {
var context = Objects.requireNonNull(contexts.apply(modifier), "context");
invocations.add(new PlacementInvocation(modifier, context));
}
return List.copyOf(invocations);
}
private static Optional<PlacementRequest> prepareAll(
PlacementRequest initialRequest,
List<PlacementInvocation> invocations) {
var attemptId = initialRequest.id();
var request = initialRequest;
for (var invocation : invocations) {
var prepared = Objects.requireNonNull(
invocation.modifier().modifier().prepare(invocation.context(), request),
"prepared request");
if (prepared.isEmpty()) {
return Optional.empty();
}
request = prepared.orElseThrow();
if (!request.id().equals(attemptId)) {
throw new IllegalArgumentException("Prepare must preserve placement attempt ID");
}
}
return Optional.of(request);
}
private PlacementPlan createPlan(
PlacementRequest request,
List<PlacementInvocation> invocations,
PlacementEdit edit) {
var blocks = mapBlocks(request, invocations);
var markers = mapMarkers(request);
var plan = new PlacementPlan(request, blocks, markers);
// Compute checked half-open bounds before any mutation, including integer extremes.
plan.writtenBounds();
validateMappedPositions(plan, request, edit, writeRadius());
return plan;
}
private static List<PlacedBlock> mapBlocks(
PlacementRequest request,
List<PlacementInvocation> invocations) {
var mappedBlocks = new ArrayList<PlacedBlock>();
for (var block : request.object().blocks()) {
var mapped = mapBlock(request, block, invocations);
mapped.ifPresent(mappedBlocks::add);
}
return mappedBlocks;
}
private static Optional<PlacedBlock> mapBlock(
PlacementRequest request,
ObjectBlock block,
List<PlacementInvocation> invocations) {
Optional<PlacedBlock> mapped = Optional.of(new PlacedBlock(
request.worldPosition(block.position()),
block.state(),
block.blockEntity()));
for (var invocation : invocations) {
var modifier = invocation.modifier().modifier();
var next = Objects.requireNonNull(
modifier.mapBlock(invocation.context(), mapped.orElseThrow()),
"mapped block");
if (next.isEmpty()) {
return Optional.empty();
}
mapped = next;
}
return mapped;
}
private static List<PlacedMarker> mapMarkers(PlacementRequest request) {
var markers = new ArrayList<PlacedMarker>();
for (var marker : request.object().markers()) {
markers.add(new PlacedMarker(
request.worldPosition(marker.position()),
marker.type(),
marker.attributes()));
}
return markers;
}
private static void validateMappedPositions(
PlacementPlan plan,
PlacementRequest request,
PlacementEdit edit,
int radius) {
for (var block : plan.blocks()) {
checkPosition(block.position(), request.footprint(), edit.bounds(), radius);
}
for (var marker : plan.markers()) {
checkPosition(marker.position(), request.footprint(), edit.bounds(), radius);
}
}
private static boolean validatePlan(
PlacementPlan plan,
List<PlacementInvocation> invocations,
Predicate<PlacementPlan> hostValidation) {
if (!hostValidation.test(plan)) {
return false;
}
for (var invocation : invocations) {
if (!invocation.modifier().modifier().validate(invocation.context(), plan)) {
return false;
}
}
return true;
}
private List<HookInvocation> openHookInvocations(
PlacementRequest request,
List<PlacementInvocation> invocations,
PlacementEdit edit) {
var hooks = new ArrayList<HookInvocation>(invocations.size());
for (var invocation : invocations) {
var access = hookAccess(invocation.modifier(), request, edit);
hooks.add(new HookInvocation(invocation, access));
}
return List.copyOf(hooks);
}
private static void runBeforeHooks(PlacementPlan plan, List<HookInvocation> hooks) {
for (var hook : hooks) {
hook.invocation().modifier().modifier().beforePlace(
hook.invocation().context(),
hook.access(),
plan);
}
}
private static void writePlan(PlacementPlan plan, PlacementEdit edit) {
for (var block : plan.blocks()) {
edit.set(block);
}
for (var marker : plan.markers()) {
edit.marker(marker);
}
}
private static void runAfterHooks(PlacementPlan plan, List<HookInvocation> hooks) {
for (var hook : hooks) {
hook.invocation().modifier().modifier().afterPlace(
hook.invocation().context(),
hook.access(),
plan);
}
}
private static PlacementAccess hookAccess(
ConfiguredPlacementModifier modifier,
PlacementRequest request,
PlacementEdit edit) {
var footprint = request.footprint();
int radius = modifier.writeRadius();
var bounds = new BlockBox(
Math.subtractExact(footprint.minX(), radius),
edit.bounds().minY(),
Math.subtractExact(footprint.minZ(), radius),
Math.addExact(footprint.maxX(), radius),
edit.bounds().maxY(),
Math.addExact(footprint.maxZ(), radius));
return PlacementViews.restrict(edit, bounds);
}
private void checkPreparedArea(PlacementRequest request, PlacementEdit edit) {
var footprint = request.footprint();
var preparedBounds = edit.bounds();
if (!preparedBounds.contains(footprint)
|| !containsHorizontalReach(preparedBounds, footprint, writeRadius())) {
throw new IndexOutOfBoundsException("Placement footprint/reach outside prepared bounds");
}
}
private static void checkPosition(
BlockPosition position,
BlockBox footprint,
BlockBox preparedBounds,
int radius) {
if (!preparedBounds.contains(position.x(), position.y(), position.z())
|| !isWithinHorizontalReach(position.x(), position.z(), footprint, radius)) {
throw new IndexOutOfBoundsException("Mapped placement write outside declared reach: " + position);
}
}
private static boolean containsHorizontalReach(BlockBox outer, BlockBox footprint, int radius) {
return containsReachOnAxis(outer.minX(), outer.maxX(), footprint.minX(), footprint.maxX(), radius)
&& containsReachOnAxis(outer.minZ(), outer.maxZ(), footprint.minZ(), footprint.maxZ(), radius);
}
private static boolean isWithinHorizontalReach(
int x,
int z,
BlockBox footprint,
int radius) {
return isWithinReachOnAxis(x, footprint.minX(), footprint.maxX(), radius)
&& isWithinReachOnAxis(z, footprint.minZ(), footprint.maxZ(), radius);
}
private static boolean containsReachOnAxis(
int outerMin,
int outerMax,
int footprintMin,
int footprintMax,
int radius) {
return (long) footprintMin - radius >= outerMin
&& (long) footprintMax + radius <= outerMax;
}
private static boolean isWithinReachOnAxis(int position, int min, int max, int radius) {
return position >= (long) min - radius && position < (long) max + radius;
}
private record PlacementInvocation(
ConfiguredPlacementModifier modifier,
PlacementContext context) {}
private record HookInvocation(PlacementInvocation invocation, PlacementAccess access) {}
}
@@ -1,20 +0,0 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.placement.PlacementModifierFactory;
import com.volmit.resource.ResourceId;
import java.util.Objects;
public record PlacementRegistration<F extends IrisFeature>(
FeatureDescriptor<F> descriptor,
PlacementModifierFactory<F> factory) {
public PlacementRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(factory, "factory");
}
public ConfiguredPlacementModifier configure(ResourceId occurrence, F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return new ConfiguredPlacementModifier(occurrence, factory.create(configuredFeature));
}
}
@@ -0,0 +1,91 @@
package com.volmit.host;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementEdit;
import com.volmit.placement.PlacementRequest;
import com.volmit.stage.Pipeline;
import java.util.Objects;
/** Reference executor of a resolved placement graph. It runs active stages in resolved order;
* each fused block pass loops once over the request object's blocks and runs every active stage
* of the pass for a block before moving to the next block. A rejection stops the attempt after
* the current stage or block; the edit is committed only when no stage rejects or throws.
*/
public final class PlacementRunner {
private final ResolvedGraph graph;
public PlacementRunner(ResolvedGraph graph) {
this.graph = Objects.requireNonNull(graph, "graph");
if (graph.pipeline() != Pipeline.PLACEMENT) {
throw new IllegalArgumentException("Expected a placement graph, got " + graph.pipeline());
}
}
/** Takes ownership of a fresh edit and closes it on success, rejection or exception.
* The host prepares the edit area, the read-only inputs (with a dedicated RNG) and the
* settings configured for this placement. Stages never receive commit/close rights.
*/
public PlacementOutcome place(
PlacementRequest request,
PlacementEdit edit,
PlacementContext inputs,
ConfiguredSettings settings) {
Objects.requireNonNull(edit, "edit");
try (edit) {
var stages = new StageInvocation(graph, settings);
var access = PlacementViews.restrict(edit, edit.bounds());
var placement = new PlacementInvocation(stages, request, inputs, access);
runSegments(placement);
if (placement.isRejected()) {
return PlacementOutcome.rejected(placement.rejection());
}
edit.commit();
return PlacementOutcome.placed();
}
}
private void runSegments(PlacementInvocation placement) {
for (var segment : graph.segments()) {
if (placement.isRejected()) {
return;
}
switch (segment.kind()) {
case INVOCATION -> placement.stages().runInvocationStage(segment.start(), placement);
case BLOCK -> runBlockPass(segment, placement);
}
}
}
private static void runBlockPass(Segment segment, PlacementInvocation placement) {
var stages = placement.stages();
int[] active = stages.activePositions(segment);
if (active.length == 0) {
return;
}
var accumulators = new Object[active.length];
for (int index = 0; index < active.length; index++) {
accumulators[index] = stages.newAccumulator(active[index]);
}
for (var block : placement.request().object().blocks()) {
placement.beginBlock(block);
runBlockStages(active, accumulators, placement);
if (placement.isRejected()) {
return;
}
}
placement.endBlockPass();
for (int index = 0; index < active.length; index++) {
stages.complete(active[index], accumulators[index]);
}
}
private static void runBlockStages(int[] active, Object[] accumulators, PlacementInvocation placement) {
for (int index = 0; index < active.length; index++) {
placement.stages().runBlockStage(active[index], placement, accumulators[index]);
if (placement.isRejected() || placement.isBlockSkipped()) {
return;
}
}
}
}
@@ -13,7 +13,7 @@ import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementEdit;
import java.util.Objects;
/** Internal hook views: limit horizontal reach and hide transaction ownership. */
/** Internal stage views: bound access to an area and hide transaction ownership. */
final class PlacementViews {
private PlacementViews() {}
@@ -0,0 +1,39 @@
package com.volmit.host;
import com.volmit.stage.StageKind;
import java.util.PriorityQueue;
/** Choice among stages whose predecessors have all run. Node numbers follow lexical stage id
* order, so each queue yields the lexically smallest ready stage. To keep block passes fused,
* an open pass continues while a block stage is ready, and ready invocation stages run before
* a new pass opens. The choice depends only on ids and edges, never on install order.
*/
final class ReadyStages {
private final PriorityQueue<Integer> invocation = new PriorityQueue<>();
private final PriorityQueue<Integer> block = new PriorityQueue<>();
private boolean blockPassOpen;
void add(int node, StageKind kind) {
queue(kind).add(node);
}
boolean isEmpty() {
return invocation.isEmpty() && block.isEmpty();
}
int next() {
if (blockPassOpen && !block.isEmpty()) {
return block.remove();
}
if (!invocation.isEmpty()) {
blockPassOpen = false;
return invocation.remove();
}
blockPassOpen = true;
return block.remove();
}
private PriorityQueue<Integer> queue(StageKind kind) {
return kind == StageKind.BLOCK ? block : invocation;
}
}
@@ -0,0 +1,144 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline;
import com.volmit.stage.StageKind;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
/** Immutable, validated order of one pipeline, resolved once per pack load. Adjacent block
* stages form one fused block pass; any invocation stage between them splits the pass, even
* when that stage is inactive for a particular invocation. Execution never sorts or hashes.
*/
public final class ResolvedGraph {
private final Pipeline pipeline;
private final List<ResolvedStage> stages;
private final List<ExecutableStage> executables;
private final List<Class<?>> settingsTypes;
private final List<Segment> segments;
ResolvedGraph(
Pipeline pipeline,
List<ResolvedStage> stages,
List<ExecutableStage> executables,
List<Class<?>> settingsTypes) {
this.pipeline = Objects.requireNonNull(pipeline, "pipeline");
this.stages = List.copyOf(stages);
this.executables = List.copyOf(executables);
this.settingsTypes = List.copyOf(settingsTypes);
segments = segments(this.executables);
}
public Pipeline pipeline() {
return pipeline;
}
/** Stages in execution order. */
public List<ResolvedStage> stages() {
return stages;
}
/** Each fused block pass as stage ids in execution order. */
public List<List<ResourceId>> blockPasses() {
return segments.stream()
.filter(segment -> segment.kind() == StageKind.BLOCK)
.map(segment -> stages.subList(segment.start(), segment.end()).stream()
.map(stage -> stage.stage().id())
.toList())
.toList();
}
/** Pairs with no path between them in either direction, first stage earlier in the order.
* Their relative order comes only from the deterministic tie-break, so a pack author should
* check that they do not conflict.
*/
public List<UnorderedPair> unorderedPairs() {
var reachable = reachability();
var pairs = new ArrayList<UnorderedPair>();
for (int first = 0; first < stages.size(); first++) {
for (int second = first + 1; second < stages.size(); second++) {
if (!reachable[first].get(second)) {
pairs.add(new UnorderedPair(id(first), id(second)));
}
}
}
return pairs;
}
/** Human-readable order, owners, edges, block passes and unordered pairs. */
public String describe() {
return GraphDescription.describe(this);
}
int size() {
return executables.size();
}
ExecutableStage executable(int position) {
return executables.get(position);
}
List<Segment> segments() {
return segments;
}
List<Class<?>> settingsTypes() {
return settingsTypes;
}
private ResourceId id(int position) {
return stages.get(position).stage().id();
}
/** Edges always point forward in the order, so a reverse sweep completes each stage's
* reachable set before any predecessor merges it.
*/
private BitSet[] reachability() {
var positions = new HashMap<ResourceId, Integer>();
var reachable = new BitSet[stages.size()];
for (int position = 0; position < stages.size(); position++) {
positions.put(id(position), position);
reachable[position] = new BitSet();
}
for (int position = stages.size() - 1; position >= 0; position--) {
for (var edge : stages.get(position).incoming()) {
int predecessor = positions.get(edge.from());
reachable[predecessor].set(position);
reachable[predecessor].or(reachable[position]);
}
}
return reachable;
}
private static List<Segment> segments(List<ExecutableStage> executables) {
var segments = new ArrayList<Segment>();
int position = 0;
while (position < executables.size()) {
int end = segmentEnd(executables, position);
segments.add(new Segment(executables.get(position).stage().kind(), position, end));
position = end;
}
return List.copyOf(segments);
}
private static int segmentEnd(List<ExecutableStage> executables, int start) {
if (executables.get(start).stage().kind() != StageKind.BLOCK) {
return start + 1;
}
int end = start + 1;
while (end < executables.size() && executables.get(end).stage().kind() == StageKind.BLOCK) {
end++;
}
return end;
}
public record UnorderedPair(ResourceId first, ResourceId second) {
public UnorderedPair {
Objects.requireNonNull(first, "first");
Objects.requireNonNull(second, "second");
}
}
}
@@ -0,0 +1,27 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Stage;
import com.volmit.stage.StageRef;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** Diagnostic view of one stage at its resolved position. incoming lists every edge into this
* stage, including soft edges other stages declared; absentSoftTargets lists this stage's soft
* references that matched no installed stage and therefore add no ordering.
*/
public record ResolvedStage(
Stage<?> stage,
ResourceId module,
Optional<FeatureDescriptor<?>> settings,
List<StageEdge> incoming,
List<StageRef> absentSoftTargets) {
public ResolvedStage {
Objects.requireNonNull(stage, "stage");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(settings, "settings");
incoming = List.copyOf(incoming);
absentSoftTargets = List.copyOf(absentSoftTargets);
}
}
@@ -0,0 +1,8 @@
package com.volmit.host;
import com.volmit.stage.StageKind;
/** Positions [start, end) of the resolved order. An INVOCATION segment holds one stage;
* a BLOCK segment is one fused block pass.
*/
record Segment(StageKind kind, int start, int end) {}
@@ -0,0 +1,24 @@
package com.volmit.host;
import com.volmit.stage.BlockStageContext;
import java.util.function.Supplier;
/** Type-erased stage work. Drafts build the body matching their stage kind, so executors may
* rely on invocation stages carrying Invocation bodies and block stages carrying Block bodies.
*/
sealed interface StageBody {
record Invocation(InvocationWork work) implements StageBody {}
/** initial is null for block stages without an accumulator. */
record Block(Supplier<?> initial, BlockWork work) implements StageBody {}
@FunctionalInterface
interface InvocationWork {
Object run(Object context, Object settings);
}
@FunctionalInterface
interface BlockWork {
void run(BlockStageContext context, Object settings, Object accumulator);
}
}
@@ -0,0 +1,126 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Stage;
import com.volmit.stage.StageRef;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** One stage as declared during install. It becomes immutable once its body is set. */
final class StageDeclaration {
private final Stage<?> stage;
private final ResourceId module;
private final List<Stage<?>> requirements = new ArrayList<>();
private final List<StageRef> softAfter = new ArrayList<>();
private final List<StageRef> softBefore = new ArrayList<>();
private FeatureDescriptor<?> settings;
private StageBody body;
StageDeclaration(Stage<?> stage, ResourceId module) {
this.stage = Objects.requireNonNull(stage, "stage");
this.module = Objects.requireNonNull(module, "module");
}
void require(Stage<?>... stages) {
checkOpen();
for (var required : stages) {
Objects.requireNonNull(required, "required stage");
rejectSelfReference(required.id());
requirements.add(required);
}
}
void softAfter(StageRef... references) {
addSoftReferences(softAfter, references);
}
void softBefore(StageRef... references) {
addSoftReferences(softBefore, references);
}
void condition(Class<? extends IrisFeature> settingsType) {
checkOpen();
if (settings != null) {
throw new IllegalStateException("Stage " + this + " already has a when(...) condition");
}
settings = FeatureDescriptor.of(settingsType);
}
/** Sets the only body. alternativeMethod names the builder method for the other output kind. */
void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) {
checkOpen();
Objects.requireNonNull(body, "body");
if (bodyProducesOutput != stage.producesOutput()) {
throw new IllegalStateException(bodyMismatch(alternativeMethod));
}
this.body = body;
}
boolean isComplete() {
return body != null;
}
Stage<?> stage() {
return stage;
}
ResourceId module() {
return module;
}
List<Stage<?>> requirements() {
return List.copyOf(requirements);
}
List<StageRef> softAfter() {
return List.copyOf(softAfter);
}
List<StageRef> softBefore() {
return List.copyOf(softBefore);
}
Optional<FeatureDescriptor<?>> settings() {
return Optional.ofNullable(settings);
}
StageBody body() {
return body;
}
@Override
public String toString() {
return stage.id() + " (module " + module + ")";
}
private void addSoftReferences(List<StageRef> target, StageRef... references) {
checkOpen();
for (var reference : references) {
Objects.requireNonNull(reference, "stage reference");
rejectSelfReference(reference.id());
target.add(reference);
}
}
private void rejectSelfReference(ResourceId id) {
if (stage.id().equals(id)) {
throw new IllegalArgumentException("Stage " + this + " cannot depend on itself");
}
}
private String bodyMismatch(String alternativeMethod) {
var declared = stage.producesOutput()
? "declares output " + stage.outputType().getSimpleName()
: "declares no output";
return "Stage " + this + " " + declared + "; define it with " + alternativeMethod + "(...)";
}
private void checkOpen() {
if (body != null) {
throw new IllegalStateException("Stage " + this + " is already complete");
}
}
}
@@ -0,0 +1,24 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** A resolved ordering edge: from runs before to. */
public record StageEdge(ResourceId from, ResourceId to, Kind kind) {
public enum Kind {
/** Declared with requires(...): orders, exposes output and cascades deactivation. */
REQUIRED,
/** Declared with softAfter/softBefore against an installed stage: ordering only. */
SOFT;
Kind strongest(Kind other) {
return this == REQUIRED || other == REQUIRED ? REQUIRED : SOFT;
}
}
public StageEdge {
Objects.requireNonNull(from, "from");
Objects.requireNonNull(to, "to");
Objects.requireNonNull(kind, "kind");
}
}
@@ -0,0 +1,125 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.resource.ResourceId;
import com.volmit.stage.BlockStage;
import com.volmit.stage.BlockStageDefinition;
import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Pipeline;
import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.Stage;
import com.volmit.stage.StageDefinition;
import com.volmit.stage.StageGraph;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/** Reference host collection of module stages. Install every module, then resolve each pipeline
* once per pack load. Install order never affects the result. If a module's install throws,
* discard the whole builder: it may hold a partial module.
*/
public final class StageGraphBuilder implements StageGraph {
private final Map<ResourceId, StageDeclaration> declarations = new HashMap<>();
private final Set<ResourceId> modules = new HashSet<>();
private ResourceId installingModule;
public void install(IrisModule module) {
Objects.requireNonNull(module, "module");
var moduleId = Objects.requireNonNull(module.info(), "module info").id();
claimModule(moduleId);
installingModule = moduleId;
try {
module.install(this);
} finally {
installingModule = null;
}
requireCompleteDefinitions(moduleId);
}
@Override
public <O> StageDefinition<PlacementStageContext, O> define(PlacementStage<O> stage) {
return new InvocationStageDraft<>(declare(stage));
}
@Override
public <O> BlockStageDefinition<O> define(BlockStage<O> stage) {
return new BlockStageDraft<>(declare(stage));
}
@Override
public <O> StageDefinition<ChunkStageContext, O> define(ChunkStage<O> stage) {
return new InvocationStageDraft<>(declare(stage));
}
public ResolvedGraph resolve(Pipeline pipeline) {
Objects.requireNonNull(pipeline, "pipeline");
return GraphResolver.resolve(pipeline, declarations.values());
}
/** Settings types named by when(...), ordered by feature id. */
public List<Class<? extends IrisFeature>> settingsTypes() {
return declarations.values().stream()
.flatMap(declaration -> declaration.settings().stream())
.distinct()
.sorted(Comparator.comparing(FeatureDescriptor::id))
.<Class<? extends IrisFeature>>map(FeatureDescriptor::type)
.toList();
}
private void claimModule(ResourceId moduleId) {
if (installingModule != null) {
throw new IllegalStateException("Module " + moduleId + " installed during " + installingModule);
}
if (!modules.add(moduleId)) {
throw new IllegalArgumentException("Duplicate module: " + moduleId);
}
}
private StageDeclaration declare(Stage<?> stage) {
Objects.requireNonNull(stage, "stage");
var module = requireInstallingModule(stage);
requireModuleNamespace(stage, module);
var declaration = new StageDeclaration(stage, module);
var previous = declarations.putIfAbsent(stage.id(), declaration);
if (previous != null) {
throw new IllegalArgumentException("Duplicate definition of stage " + stage.id() + " by module "
+ module + "; already defined by module " + previous.module());
}
return declaration;
}
private ResourceId requireInstallingModule(Stage<?> stage) {
if (installingModule == null) {
throw new IllegalStateException("Stage " + stage + " defined outside IrisModule.install");
}
return installingModule;
}
private static void requireModuleNamespace(Stage<?> stage, ResourceId module) {
if (!stage.id().namespace().equals(module.namespace())) {
throw new IllegalArgumentException("Stage " + stage + " must use namespace '"
+ module.namespace() + "' of its defining module " + module);
}
}
private void requireCompleteDefinitions(ResourceId moduleId) {
declarations.values().stream()
.filter(declaration -> declaration.module().equals(moduleId))
.filter(declaration -> !declaration.isComplete())
.map(StageDeclaration::toString)
.sorted()
.findFirst()
.ifPresent(incomplete -> {
throw new IllegalStateException("Stage " + incomplete
+ " has no body; end its definition with run, produce or accumulate");
});
}
}
@@ -0,0 +1,144 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.IntStream;
/** Pipeline-independent state of one invocation: activation, settings and stage outputs, all
* indexed by resolved position. Activation is computed once up front in resolved order: a stage
* is active when its settings are configured (or it has no condition) and every stage it
* requires is active, so inactivity cascades to dependents. Cost is one pass over stages and
* requirement edges plus one settings lookup per distinct settings type.
*/
final class StageInvocation {
private static final Object PENDING = new Object();
private static final int NO_STAGE = -1;
private final ResolvedGraph graph;
private final Object[] settingsBySlot;
private final boolean[] active;
private final Object[] outputs;
private int current = NO_STAGE;
StageInvocation(ResolvedGraph graph, ConfiguredSettings settings) {
this.graph = graph;
settingsBySlot = lookUpSettings(graph, Objects.requireNonNull(settings, "settings"));
active = activation(graph, settingsBySlot);
outputs = new Object[graph.size()];
Arrays.fill(outputs, PENDING);
}
boolean isActive(int position) {
return active[position];
}
int[] activePositions(Segment segment) {
return IntStream.range(segment.start(), segment.end())
.filter(position -> active[position])
.toArray();
}
void runInvocationStage(int position, Object context) {
if (!active[position]) {
return;
}
var executable = graph.executable(position);
var work = ((StageBody.Invocation) executable.body()).work();
current = position;
var output = work.run(context, settings(executable));
current = NO_STAGE;
complete(position, requireDeclaredOutput(executable, output));
}
Object newAccumulator(int position) {
var initial = ((StageBody.Block) graph.executable(position).body()).initial();
if (initial == null) {
return null;
}
return Objects.requireNonNull(initial.get(), () -> "Stage " + graph.executable(position).stage()
+ " created a null accumulator");
}
void runBlockStage(int position, BlockStageContext context, Object accumulator) {
var executable = graph.executable(position);
var work = ((StageBody.Block) executable.body()).work();
current = position;
work.run(context, settings(executable), accumulator);
current = NO_STAGE;
}
void complete(int position, Object output) {
outputs[position] = output;
}
@SuppressWarnings("unchecked") // Bodies are typed by their stage, so the stored output matches O.
<O> O output(Stage<O> stage) {
Objects.requireNonNull(stage, "stage");
var reader = currentStage();
int position = reader.readablePosition(stage);
if (position == ExecutableStage.NOT_READABLE) {
throw new IllegalStateException("Stage " + reader.stage() + " read the output of " + stage
+ " without requiring it; add requires(" + stage + ") to its definition");
}
if (outputs[position] == PENDING) {
throw new IllegalStateException("Stage " + reader.stage() + " read the output of " + stage
+ " before it completed; block stage outputs are available after their block pass");
}
return (O) outputs[position];
}
private ExecutableStage currentStage() {
if (current == NO_STAGE) {
throw new IllegalStateException("Stage outputs can only be read while a stage runs");
}
return graph.executable(current);
}
private Object settings(ExecutableStage executable) {
int slot = executable.settingsSlot();
return slot == ExecutableStage.NO_SETTINGS ? null : settingsBySlot[slot];
}
private static Object requireDeclaredOutput(ExecutableStage executable, Object output) {
if (output == null && executable.stage().producesOutput()) {
throw new NullPointerException("Stage " + executable.stage() + " produced a null output");
}
return output;
}
@SuppressWarnings("unchecked") // Settings types come from when(Class<? extends IrisFeature>).
private static Object[] lookUpSettings(ResolvedGraph graph, ConfiguredSettings settings) {
var types = graph.settingsTypes();
var values = new Object[types.size()];
for (int slot = 0; slot < values.length; slot++) {
values[slot] = settings.find((Class<? extends IrisFeature>) types.get(slot)).orElse(null);
}
return values;
}
private static boolean[] activation(ResolvedGraph graph, Object[] settingsBySlot) {
var active = new boolean[graph.size()];
for (int position = 0; position < active.length; position++) {
var executable = graph.executable(position);
active[position] = isConfigured(executable, settingsBySlot) && requirementsActive(executable, active);
}
return active;
}
private static boolean isConfigured(ExecutableStage executable, Object[] settingsBySlot) {
int slot = executable.settingsSlot();
return slot == ExecutableStage.NO_SETTINGS || settingsBySlot[slot] != null;
}
private static boolean requirementsActive(ExecutableStage executable, boolean[] active) {
for (int requirement : executable.requirements()) {
if (!active[requirement]) {
return false;
}
}
return true;
}
}
@@ -3,9 +3,9 @@ package com.volmit.placement;
import com.volmit.mantle.Mantle;
import com.volmit.world.BlockView;
/** Buffered world-space access for placement hooks, without ownership of commit/close.
* Reads include the overlay. Bounds cover the object's footprint plus declared horizontal reach
* and host-authorized vertical area. Block/entity/marker/mantle writes share the host edit.
/** Buffered world-space access for placement stages, without ownership of commit/close.
* Reads include the overlay. Bounds are the host-prepared placement area.
* Block/entity/marker/mantle writes share the host edit.
* Out-of-area access throws; nested mantle edits are unsupported. Do not retain this view.
*/
public interface PlacementAccess extends BlockView {
@@ -6,13 +6,13 @@ import com.volmit.object.ObjectTransformer;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
/** Read-only inputs to placement hooks. Working state is carried by returned immutable requests
* and blocks, never stored on a configured modifier. Context lifetime ends with placement.
/** Host-supplied, read-only inputs of one placement attempt. Working state is carried by stage
* outputs, never stored on a module or stage body. Context lifetime ends with the placement.
*/
public interface PlacementContext extends InvocationContext {
TerrainSampler terrain();
FeatureSettings settings();
ObjectTransformer objects();
/** Prepared blocks before this placement. Use hook access for reads of buffered changes. */
/** Prepared blocks before this placement. Use stage access for reads of buffered changes. */
BlockView blocks();
}
@@ -1,24 +0,0 @@
package com.volmit.placement;
import com.volmit.generation.Dependencies;
import java.util.Optional;
/** Configured placement behavior. IDs are namespaced; dependencies refer only to placement
* modifier IDs, not chunk modifiers. Snapshot settings; calls may occur concurrently.
* The host runs prepare for all modifiers, mapBlock for each candidate, then validate for all
* modifiers before buffering any write. beforePlace runs after validation but before object
* writes, for boring/preparation. afterPlace runs only after all accepted blocks and
* markers are buffered, allowing vacuum/stilts to observe the final footprint and overlay.
* Exceptions discard the attempt. Empty prepare rejects it; empty mapBlock skips one block.
*/
public abstract class PlacementModifier {
public abstract String id();
public Dependencies depends() { return Dependencies.none(); }
/** Horizontal access beyond the resulting object footprint; nonnegative, read at pack load. */
public int writeRadius() { return 0; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.of(request); }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) { return Optional.of(block); }
public boolean validate(PlacementContext context, PlacementPlan plan) { return true; }
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan proposed) {}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {}
}
@@ -1,8 +0,0 @@
package com.volmit.placement;
import com.volmit.IrisFeature;
@FunctionalInterface
public interface PlacementModifierFactory<F extends IrisFeature> {
PlacementModifier create(F feature);
}
@@ -1,37 +0,0 @@
package com.volmit.placement;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockPosition;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** Complete proposed writes, constructed before validation or mutation.
* Block positions are unique and ordered x/y/z. writtenBounds describes block writes only;
* markers and the original object's declared footprint are tracked separately.
*/
public record PlacementPlan(PlacementRequest request, List<PlacedBlock> blocks, List<PlacedMarker> markers) {
public PlacementPlan {
Objects.requireNonNull(request, "request");
blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(PlacedBlock::position)).toList();
markers = List.copyOf(markers).stream().sorted(Comparator.comparing(PlacedMarker::position)).toList();
var positions = new HashSet<BlockPosition>();
for (var block : blocks) {
if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate placement write: " + block.position());
}
}
public Optional<BlockBox> writtenBounds() {
if (blocks.isEmpty()) return Optional.empty();
int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE;
for (var block : blocks) {
var position = block.position();
minX = Math.min(minX, position.x()); minY = Math.min(minY, position.y()); minZ = Math.min(minZ, position.z());
maxX = Math.max(maxX, position.x()); maxY = Math.max(maxY, position.y()); maxZ = Math.max(maxZ, position.z());
}
return Optional.of(new BlockBox(minX, minY, minZ, Math.addExact(maxX, 1), Math.addExact(maxY, 1), Math.addExact(maxZ, 1)));
}
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface BlockCollector<O> {
void collect(BlockStageContext context, O accumulator);
}
@@ -0,0 +1,20 @@
package com.volmit.stage;
/** Runs once per object block of a placement. Block stages that are adjacent in the resolved
* order share one loop over the object's blocks; a placement stage between them splits the pass.
*/
public final class BlockStage<O> extends Stage<O> {
BlockStage(String id, Class<O> accumulatorType) {
super(id, accumulatorType);
}
@Override
public Pipeline pipeline() {
return Pipeline.PLACEMENT;
}
@Override
public StageKind kind() {
return StageKind.BLOCK;
}
}
@@ -0,0 +1,16 @@
package com.volmit.stage;
import com.volmit.object.ObjectBlock;
/** The current object block of a block pass, in object-local coordinates. Every pass starts
* from the request's object blocks; replacements and skips are visible only to later stages
* of the same pass for the same block.
*/
public interface BlockStageContext extends PlacementStageContext {
ObjectBlock block();
void replace(ObjectBlock block);
/** Later stages of this pass do not see the current block. */
void skip();
}
@@ -0,0 +1,23 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import java.util.function.Supplier;
/** Declares one per-block placement stage. Requiring another block stage orders the two per
* block within a fused pass. A block stage's accumulator becomes readable only after its pass.
*/
public interface BlockStageDefinition<O> {
BlockStageDefinition<O> requires(Stage<?>... stages);
BlockStageDefinition<O> softAfter(StageRef... stages);
BlockStageDefinition<O> softBefore(StageRef... stages);
<S extends IrisFeature> ConditionalBlockStageDefinition<S, O> when(Class<S> settingsType);
/** Body for a block stage without accumulator. */
void run(StageAction<BlockStageContext> action);
/** Body for a block stage whose accumulator, created once per placement, is its output. */
void accumulate(Supplier<O> initial, BlockCollector<O> collector);
}
@@ -0,0 +1,18 @@
package com.volmit.stage;
/** Runs once per chunk generation invocation. */
public final class ChunkStage<O> extends Stage<O> {
ChunkStage(String id, Class<O> outputType) {
super(id, outputType);
}
@Override
public Pipeline pipeline() {
return Pipeline.CHUNK;
}
@Override
public StageKind kind() {
return StageKind.INVOCATION;
}
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
import com.volmit.generation.GenerationContext;
/** One chunk generation invocation with access to the host's typed local hunks. */
public interface ChunkStageContext extends GenerationContext, StageContext {}
@@ -0,0 +1,16 @@
package com.volmit.stage;
import java.util.function.Supplier;
/** A block stage active only where its settings are configured; bodies receive them. */
public interface ConditionalBlockStageDefinition<S, O> {
ConditionalBlockStageDefinition<S, O> requires(Stage<?>... stages);
ConditionalBlockStageDefinition<S, O> softAfter(StageRef... stages);
ConditionalBlockStageDefinition<S, O> softBefore(StageRef... stages);
void run(SettingsAction<BlockStageContext, S> action);
void accumulate(Supplier<O> initial, SettingsBlockCollector<S, O> collector);
}
@@ -0,0 +1,14 @@
package com.volmit.stage;
/** An invocation stage active only where its settings are configured; bodies receive them. */
public interface ConditionalStageDefinition<C extends StageContext, S, O> {
ConditionalStageDefinition<C, S, O> requires(Stage<?>... stages);
ConditionalStageDefinition<C, S, O> softAfter(StageRef... stages);
ConditionalStageDefinition<C, S, O> softBefore(StageRef... stages);
void run(SettingsAction<C, S> action);
void produce(SettingsFunction<C, S, O> function);
}
@@ -0,0 +1,9 @@
package com.volmit.stage;
/** Independent stage graphs. A stage belongs to exactly one pipeline; edges never cross them. */
public enum Pipeline {
/** Runs once per object placement attempt, against one buffered placement edit. */
PLACEMENT,
/** Runs once per chunk generation invocation, against host-owned local hunks. */
CHUNK
}
@@ -0,0 +1,18 @@
package com.volmit.stage;
/** Runs once per placement attempt. */
public final class PlacementStage<O> extends Stage<O> {
PlacementStage(String id, Class<O> outputType) {
super(id, outputType);
}
@Override
public Pipeline pipeline() {
return Pipeline.PLACEMENT;
}
@Override
public StageKind kind() {
return StageKind.INVOCATION;
}
}
@@ -0,0 +1,20 @@
package com.volmit.stage;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
/** One placement attempt. Writes go to a buffered edit committed only if no stage rejects
* and none throws. All stages of an attempt share its inputs, including the RNG, in resolved order.
*/
public interface PlacementStageContext extends PlacementContext, StageContext {
PlacementRequest request();
/** Buffered access bounded by the prepared edit; reads include earlier writes. */
PlacementAccess access();
/** Stops the attempt after the current stage (or current block); nothing is committed.
* The first reason is kept.
*/
void reject(String reason);
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface SettingsAction<C, S> {
void run(C context, S settings);
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface SettingsBlockCollector<S, O> {
void collect(BlockStageContext context, S settings, O accumulator);
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface SettingsFunction<C, S, O> {
O run(C context, S settings);
}
+73
View File
@@ -0,0 +1,73 @@
package com.volmit.stage;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** A unit of pipeline work, declared as a constant by the module that defines it.
* The id is namespaced and its namespace must match the defining module. Identity is this
* declaration object: other modules require or read the owner's constant, never a copy.
* The output type is Void for stages that only act; otherwise dependents read it through
* {@link StageContext#output(Stage)}. Block stages accumulate their output across the pass.
*/
public abstract sealed class Stage<O> permits PlacementStage, BlockStage, ChunkStage {
private final ResourceId id;
private final Class<O> outputType;
Stage(String id, Class<O> outputType) {
this.id = ResourceId.parse(id);
this.outputType = Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Stage output requires a reference type: " + id);
}
}
public static PlacementStage<Void> placement(String id) {
return new PlacementStage<>(id, Void.class);
}
public static <O> PlacementStage<O> placement(String id, Class<O> outputType) {
return new PlacementStage<>(id, outputType);
}
public static BlockStage<Void> placementBlock(String id) {
return new BlockStage<>(id, Void.class);
}
/** The accumulator type is created once per placement and becomes the stage output. */
public static <O> BlockStage<O> placementBlock(String id, Class<O> accumulatorType) {
return new BlockStage<>(id, accumulatorType);
}
public static ChunkStage<Void> chunk(String id) {
return new ChunkStage<>(id, Void.class);
}
public static <O> ChunkStage<O> chunk(String id, Class<O> outputType) {
return new ChunkStage<>(id, outputType);
}
public final ResourceId id() {
return id;
}
public final Class<O> outputType() {
return outputType;
}
public final boolean producesOutput() {
return outputType != Void.class;
}
public final StageRef ref() {
return new StageRef(id);
}
public abstract Pipeline pipeline();
public abstract StageKind kind();
@Override
public final String toString() {
return id.toString();
}
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface StageAction<C> {
void run(C context);
}
@@ -0,0 +1,10 @@
package com.volmit.stage;
/** Per-invocation view handed to one stage body. Do not retain it after the body returns. */
public interface StageContext {
/** The output the given stage produced in this invocation. Only stages the current stage
* transitively requires are readable; anything else throws IllegalStateException, as does
* reading a block stage's accumulator before its block pass has finished.
*/
<O> O output(Stage<O> stage);
}
@@ -0,0 +1,25 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
/** Declares one invocation stage. requires(...) is a hard dependency on another module's
* stage constant: it orders this stage after it, allows reading its output, and deactivates
* this stage wherever the requirement is inactive. Soft edges only order, and only when the
* referenced stage is installed in the same pipeline. There is deliberately no hard "before".
*/
public interface StageDefinition<C extends StageContext, O> {
StageDefinition<C, O> requires(Stage<?>... stages);
StageDefinition<C, O> softAfter(StageRef... stages);
StageDefinition<C, O> softBefore(StageRef... stages);
/** Activates the stage only where the given feature settings are configured. */
<S extends IrisFeature> ConditionalStageDefinition<C, S, O> when(Class<S> settingsType);
/** Body for a stage without output. */
void run(StageAction<C> action);
/** Body for a stage with output; null results fail the invocation. */
void produce(StageFunction<C, O> function);
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface StageFunction<C, O> {
O run(C context);
}
@@ -0,0 +1,15 @@
package com.volmit.stage;
/** Collects the stages a module defines during {@code IrisModule.install}. Each define call must
* end with exactly one body (run, produce or accumulate). The graph is resolved once at pack load:
* missing requirements, cycles, duplicate definitions, foreign namespaces and cross-pipeline
* edges are load errors. Bodies are shared by concurrent invocations and must not capture
* invocation state; everything per-invocation arrives through the context and outputs.
*/
public interface StageGraph {
<O> StageDefinition<PlacementStageContext, O> define(PlacementStage<O> stage);
<O> BlockStageDefinition<O> define(BlockStage<O> stage);
<O> StageDefinition<ChunkStageContext, O> define(ChunkStage<O> stage);
}
@@ -0,0 +1,9 @@
package com.volmit.stage;
/** How often a stage runs within one pipeline invocation. */
public enum StageKind {
/** Once per placement or chunk. */
INVOCATION,
/** Once per object block, inside a fused block pass. Placement pipeline only. */
BLOCK
}
@@ -0,0 +1,20 @@
package com.volmit.stage;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** A stage named by id only, for soft ordering against stages that may not be installed. */
public record StageRef(ResourceId id) {
public StageRef {
Objects.requireNonNull(id, "id");
}
public static StageRef of(String id) {
return new StageRef(ResourceId.parse(id));
}
@Override
public String toString() {
return id.toString();
}
}