Give modules per-world state, lifecycle hooks and services: PackWorld with its state store, InvocationContext.world(), ModuleLifecycle, @Service with Providers ALL, FIRST and ONE, ObjectsAt and StructureLocator, and the host's WorldStates, LifecycleRunner and catalog lookups

This commit is contained in:
piexel committed 2026-10-09 14:32:54 +02:00
1 parent ef4b640867
commit b20a3cf719
29 files changed
+1286 -17

No files matched your search

@@ -5,6 +5,7 @@ import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Service;
import com.volmit.stage.StageGraph;
import com.volmit.validation.Validator;
@@ -42,4 +43,12 @@ public interface FeatureRegistry {
/** Adds a check the host runs over the whole pack wherever it validates packs. */
void registerValidator(Validator validator);
/** Adds hooks the host calls when it loads the pack and starts or stops a world with it. */
void registerLifecycle(ModuleLifecycle lifecycle);
/** Provides {@code service}, an interface marked {@link Service}, with {@code provider}. A service whose providers
* are {@link com.volmit.service.Providers#ONE} fails the pack load when a second module provides it, naming both.
*/
<S> void registerService(Class<S> service, S provider);
}
+1 -1
View File
@@ -17,7 +17,7 @@ public interface IrisModule {
void install(StageGraph graph);
/** Registers non-stage contributions: geometry generators, mantle layers, settings no stage names, pack
* resource kinds and validators.
* resource kinds, validators, lifecycle hooks and services.
*/
default void register(FeatureRegistry registry) {}
}
@@ -0,0 +1,37 @@
package com.volmit;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
/** What a module does when the host loads a pack and starts or stops a world with it. Every hook does nothing by
* default. Modules register it with {@link FeatureRegistry#registerLifecycle}; a module class may implement it and
* register itself.
*
* <p>Order: {@link #packLoaded} for a pack snapshot before the first world using it starts, then
* {@link #worldStarted} before that world generates anything, and {@link #worldStopped} when it stops. A hotload, or a
* reload of the pack's resources while worlds run, stops each world of the old snapshot, loads the new snapshot and
* starts its worlds again, with empty state (see {@link PackWorld}). The host calls the hooks of a pack's modules in
* module id order and stops them in reverse, one hook at a time, on the thread that starts or stops the world.
*
* <p>Hooks keep what they build in the world's state ({@link PackWorld#state}), never in fields: a module instance may
* serve several packs and worlds at once.
*/
public interface ModuleLifecycle {
/** The pack's modules are installed and its resources can be read. {@code settings} holds every entry of every
* dimension, region and biome of the pack, as validators see them. A hook that throws stops the pack's worlds from
* starting, naming its module.
*/
default void packLoaded(PackResources resources, PackSettings settings) {}
/** {@code world} starts, before it generates anything: the place to build state eagerly, such as caches a world
* would otherwise build on its first chunk. A hook that throws stops the world from starting, naming its module; the
* modules that had started it already get {@link #worldStopped}.
*/
default void worldStarted(PackWorld world) {}
/** {@code world} stops: it generates nothing more with this pack snapshot. Its state is still readable here and is
* closed afterwards. The host runs every module's hook even when one throws, then reports the failures.
*/
default void worldStopped(PackWorld world) {}
}
@@ -1,6 +1,7 @@
package com.volmit.generation;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
*
@@ -10,4 +11,9 @@ import com.volmit.resource.PackResources;
public interface InvocationContext {
long worldSeed();
PackResources resources();
/** The world this invocation generates, where modules keep their per-world state ({@link PackWorld#state}). An
* invocation outside any world, such as an object a studio tool pastes, throws IllegalStateException.
*/
PackWorld world();
}
@@ -6,6 +6,7 @@ import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
@@ -65,6 +66,11 @@ final class ChunkInvocation implements ChunkStageContext {
return inputs.worldSeed();
}
@Override
public PackWorld world() {
return inputs.world();
}
@Override
public PackResources resources() {
return inputs.resources();
@@ -1,16 +1,19 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Function;
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators are in module id order,
* so nothing depends on discovery. Factory, codec and validator implementations must themselves obey their
* concurrency contracts.
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators, lifecycle hooks and service
* providers are in module id order, each module's in the order it registered them, so nothing depends on discovery.
* Factory, codec, validator, hook and provider implementations must themselves obey their concurrency contracts.
*/
public final class FeatureCatalog {
private final Map<Class<?>, FeatureDescriptor<?>> settings;
@@ -18,20 +21,24 @@ public final class FeatureCatalog {
private final Map<String, MantleRegistration<?>> mantle;
private final List<ResourceKindRegistration> resourceKinds;
private final List<ValidatorRegistration> validators;
private final List<LifecycleRegistration> lifecycles;
private final List<ServiceRegistration> services;
FeatureCatalog(
Map<Class<?>, FeatureDescriptor<?>> settings,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<String, MantleRegistration<?>> mantle,
Collection<ResourceKindRegistration> resourceKinds,
List<ValidatorRegistration> validators) {
List<ValidatorRegistration> validators,
List<LifecycleRegistration> lifecycles,
List<ServiceRegistration> services) {
this.settings = Map.copyOf(settings);
this.objects = Map.copyOf(objects);
this.mantle = Map.copyOf(mantle);
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
this.validators = validators.stream()
.sorted(Comparator.comparing(registration -> registration.module().info().id()))
.toList();
this.validators = inModuleOrder(validators, ValidatorRegistration::module);
this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module);
this.services = inModuleOrder(services, ServiceRegistration::module);
}
/** Settings types that activate stages; the host decodes them from pack JSON. */
@@ -57,6 +64,47 @@ public final class FeatureCatalog {
return validators;
}
/** The lifecycle hooks modules registered, by module id, each module's in the order it registered them. */
public List<LifecycleRegistration> lifecycles() {
return lifecycles;
}
/** Every provider of {@code service}, an interface marked {@link Service}, in module id order and each module's in the
* order it registered them; empty when no module provides it.
*/
public <S> List<S> services(Class<S> service) {
requireService(service);
return services.stream()
.filter(registration -> registration.service() == service)
.map(registration -> service.cast(registration.provider()))
.toList();
}
/** The one provider of {@code service}, a service whose providers are {@link Providers#ONE}, if a module provides it. */
public <S> Optional<S> service(Class<S> service) {
if (requireService(service).value() != Providers.ONE) {
throw new IllegalArgumentException("Service " + service.getName() + " may have several providers; ask for all of"
+ " them with services(...)");
}
return services(service).stream().findFirst();
}
/** The {@link Service} annotation of {@code type}, which must be an interface carrying one. */
static Service requireService(Class<?> type) {
var service = type.isInterface() ? type.getAnnotation(Service.class) : null;
if (service == null) {
throw new IllegalArgumentException(type.getName() + " is not a service: services are interfaces marked @"
+ Service.class.getName());
}
return service;
}
private static <T> List<T> inModuleOrder(List<T> registrations, Function<? super T, DiscoveredModule> module) {
return registrations.stream()
.sorted(Comparator.comparing(registration -> module.apply(registration).info().id()))
.toList();
}
private static <T, K extends Comparable<? super K>> List<T> sorted(
Collection<T> registrations,
Function<? super T, ? extends K> key) {
@@ -0,0 +1,12 @@
package com.volmit.host;
import com.volmit.ModuleLifecycle;
import java.util.Objects;
/** Lifecycle hooks and the module that registered them, which the host names when a hook fails. */
public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule module) {
public LifecycleRegistration {
Objects.requireNonNull(lifecycle, "lifecycle");
Objects.requireNonNull(module, "module");
}
}
@@ -0,0 +1,95 @@
package com.volmit.host;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
/** Calls the lifecycle hooks of one pack's modules ({@link FeatureCatalog#lifecycles()}) the way
* {@link com.volmit.ModuleLifecycle} promises: loading and starting in module id order, stopping in reverse.
*
* <pre>{@code
* var lifecycles = new LifecycleRunner(pack.catalog());
* lifecycles.packLoaded(resources, packSettings); // once per pack snapshot, before its first world starts
* lifecycles.worldStarted(world); // before the world generates anything
* ...
* lifecycles.worldStopped(world); // then close the world's state
* }</pre>
*
* A failure names the module whose hook failed. The runner keeps no state: the host decides when a snapshot is loaded
* and which worlds run, and calls one method at a time per world.
*/
public final class LifecycleRunner {
private final List<LifecycleRegistration> lifecycles;
public LifecycleRunner(FeatureCatalog catalog) {
this.lifecycles = Objects.requireNonNull(catalog, "catalog").lifecycles();
}
/** Runs every {@code packLoaded} hook in order; the first that throws ends the run with an IllegalStateException
* naming its module, and the hooks after it do not run.
*/
public void packLoaded(PackResources resources, PackSettings settings) {
Objects.requireNonNull(resources, "resources");
Objects.requireNonNull(settings, "settings");
for (var registration : lifecycles) {
try {
registration.lifecycle().packLoaded(resources, settings);
} catch (RuntimeException failure) {
throw failed("loading pack " + resources.packId(), registration, failure);
}
}
}
/** Runs every {@code worldStarted} hook in order. When one throws, the modules started before it are stopped again,
* in reverse, and an IllegalStateException naming the failed module is thrown, with failures of those stops
* suppressed in it.
*/
public void worldStarted(PackWorld world) {
Objects.requireNonNull(world, "world");
for (int index = 0; index < lifecycles.size(); index++) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStarted(world);
} catch (RuntimeException failure) {
var startFailure = failed("starting a world", registration, failure);
stopInReverse(world, index - 1, startFailure);
throw startFailure;
}
}
}
/** Runs every {@code worldStopped} hook in reverse order, each even when an earlier one threw; afterwards throws the
* first failure, naming its module, with the later ones suppressed.
*/
public void worldStopped(PackWorld world) {
Objects.requireNonNull(world, "world");
IllegalStateException failure = stopInReverse(world, lifecycles.size() - 1, null);
if (failure != null) {
throw failure;
}
}
/** Stops the modules from {@code last} down to the first, collecting failures into {@code failure}. */
private IllegalStateException stopInReverse(PackWorld world, int last, IllegalStateException failure) {
for (int index = last; index >= 0; index--) {
var registration = lifecycles.get(index);
try {
registration.lifecycle().worldStopped(world);
} catch (RuntimeException stopFailure) {
var named = failed("stopping a world", registration, stopFailure);
if (failure == null) {
failure = named;
} else {
failure.addSuppressed(named);
}
}
}
return failure;
}
private static IllegalStateException failed(String action, LifecycleRegistration registration, RuntimeException cause) {
return new IllegalStateException("Module " + registration.module() + " failed while " + action + ": " + cause, cause);
}
}
@@ -5,6 +5,7 @@ import com.volmit.generation.MantleGenerationContext;
import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.stage.MantleStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler;
@@ -59,6 +60,11 @@ final class MantleInvocation implements MantleStageContext {
return inputs.worldSeed();
}
@Override
public PackWorld world() {
return inputs.world();
}
@Override
public PackResources resources() {
return inputs.resources();
@@ -4,12 +4,14 @@ import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleLifecycle;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Providers;
import com.volmit.validation.Validator;
import java.util.ArrayList;
import java.util.HashMap;
@@ -26,7 +28,8 @@ import java.util.Set;
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. A failed registration leaves the registry unchanged. A failed module callback
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
* are {@link Providers#ONE} has at most one. A failed registration leaves the registry unchanged. A failed module callback
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
* settings.
*/
@@ -40,6 +43,8 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Map<Field, String> fields = new HashMap<>();
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
private final List<ValidatorRegistration> validators = new ArrayList<>();
private final List<LifecycleRegistration> lifecycles = new ArrayList<>();
private final List<ServiceRegistration> services = new ArrayList<>();
private final Set<String> reservedFolders;
private final List<DiscoveredModule> registered = new ArrayList<>();
private FeatureCatalog catalog;
@@ -129,6 +134,32 @@ public final class ModuleRegistry implements FeatureRegistry {
validators.add(new ValidatorRegistration(validator, registering));
}
@Override
public void registerLifecycle(ModuleLifecycle lifecycle) {
checkOpen();
Objects.requireNonNull(lifecycle, "lifecycle");
requireRegistering("Lifecycle " + lifecycle);
lifecycles.add(new LifecycleRegistration(lifecycle, registering));
}
@Override
public <S> void registerService(Class<S> service, S provider) {
checkOpen();
Objects.requireNonNull(service, "service");
Objects.requireNonNull(provider, "provider");
requireRegistering("Provider of " + service.getName());
var providers = FeatureCatalog.requireService(service).value();
if (!service.isInstance(provider)) {
throw new IllegalArgumentException("Provider " + provider + " of module " + registering + " does not implement "
+ service.getName());
}
var added = new ServiceRegistration(service, provider, registering);
if (providers == Providers.ONE) {
requireNoProvider(added);
}
services.add(added);
}
/** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
* has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call
* it after every module has registered, so the owner is known.
@@ -149,7 +180,7 @@ public final class ModuleRegistry implements FeatureRegistry {
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators);
catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators, lifecycles, services);
}
return catalog;
}
@@ -179,6 +210,23 @@ public final class ModuleRegistry implements FeatureRegistry {
+ info.idPrefix() + ", the id of its registering module " + registering);
}
private void requireRegistering(String registration) {
if (registering == null) {
throw new IllegalStateException(registration + " registered outside IrisModule.register");
}
}
/** A service a pack has one provider of: a second provider, from this module or another, fails. */
private void requireNoProvider(ServiceRegistration added) {
for (var existing : services) {
if (existing.service() == added.service()) {
throw new IllegalArgumentException("Service " + added.service().getName() + " is provided by module "
+ existing.module() + " already, and module " + added.module() + " provides it too; a pack has"
+ " one provider of it (Providers.ONE), so remove one of them");
}
}
}
/** One id, one type and one folder per kind: the host finds resources by type and reads each folder as one kind. */
private void requireUnclaimedKind(ResourceKindRegistration added) {
var kind = added.kind();
@@ -8,6 +8,7 @@ import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import com.volmit.world.BlockView;
@@ -111,6 +112,11 @@ final class PlacementInvocation implements BlockStageContext {
return inputs.worldSeed();
}
@Override
public PackWorld world() {
return inputs.world();
}
@Override
public PackResources resources() {
return inputs.resources();
@@ -0,0 +1,17 @@
package com.volmit.host;
import java.util.Objects;
/** One provider of a service and the module that registered it. */
public record ServiceRegistration(Class<?> service, Object provider, DiscoveredModule module) {
public ServiceRegistration {
Objects.requireNonNull(service, "service");
Objects.requireNonNull(provider, "provider");
Objects.requireNonNull(module, "module");
}
@Override
public String toString() {
return "provider of " + service.getName() + " from module " + module;
}
}
@@ -0,0 +1,119 @@
package com.volmit.host;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/** The reference store behind {@link com.volmit.world.PackWorld#state}: one instance per type, created once, closed
* with the world. A host's world implementation keeps one per world and passes {@code state} calls on, binding the
* world into the factory.
*
* <p>Reads of existing state take no lock. Creation runs under the store's lock, so each type is created once even
* when threads race; a factory may ask for other state on its own thread (the lock is re-entrant), and a type asked
* for again while it is being created fails instead of recursing. {@link #close()} closes every {@link AutoCloseable}
* state, newest first, and ends the store.
*/
public final class WorldStates implements AutoCloseable {
private final Map<Class<?>, Object> states = new ConcurrentHashMap<>();
private final List<Object> createdInOrder = new ArrayList<>();
private final Deque<Class<?>> creating = new ArrayDeque<>();
private final Object lock = new Object();
private boolean closed;
/** The {@code type} state, created by {@code create} the first time it is asked for. See {@link com.volmit.world.PackWorld#state}. */
public <T> T state(Class<T> type, Supplier<? extends T> create) {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(create, "create");
Object existing = states.get(type);
if (existing != null) {
return type.cast(existing);
}
synchronized (lock) {
requireOpen(type);
existing = states.get(type);
if (existing != null) {
return type.cast(existing);
}
return create(type, create);
}
}
/** Closes every {@link AutoCloseable} state, the newest first, even when one fails, then throws the first failure
* with the others suppressed. Asking for state afterwards throws. Closing twice does nothing.
*/
@Override
public void close() {
List<Object> closing;
synchronized (lock) {
if (closed) {
return;
}
closed = true;
closing = new ArrayList<>(createdInOrder);
createdInOrder.clear();
states.clear();
}
RuntimeException failure = null;
for (int index = closing.size() - 1; index >= 0; index--) {
failure = closeState(closing.get(index), failure);
}
if (failure != null) {
throw failure;
}
}
private <T> T create(Class<T> type, Supplier<? extends T> create) {
if (creating.contains(type)) {
throw new IllegalStateException("World state " + type.getName() + " was asked for while it is being created: "
+ creationChain(type));
}
creating.push(type);
try {
T created = type.cast(Objects.requireNonNull(create.get(), () -> "The factory of world state " + type.getName()
+ " returned null"));
states.put(type, created);
createdInOrder.add(created);
return created;
} finally {
creating.pop();
}
}
private String creationChain(Class<?> repeated) {
var chain = new ArrayList<Class<?>>(creating);
Collections.reverse(chain);
chain.add(repeated);
return chain.stream().map(Class::getName).collect(Collectors.joining(" -> "));
}
private void requireOpen(Class<?> type) {
if (closed) {
throw new IllegalStateException("World state " + type.getName() + " was asked for after the world stopped");
}
}
private static RuntimeException closeState(Object state, RuntimeException failure) {
if (!(state instanceof AutoCloseable closeable)) {
return failure;
}
try {
closeable.close();
return failure;
} catch (Exception exception) {
var closeFailure = new IllegalStateException("World state " + state.getClass().getName() + " failed to close: "
+ exception, exception);
if (failure == null) {
return closeFailure;
}
failure.addSuppressed(closeFailure);
return failure;
}
}
}
@@ -0,0 +1,29 @@
package com.volmit.service;
import com.volmit.world.BlockPosition;
import java.util.Objects;
/** How a search for something in a world ended: found at a position, not there, or given up before covering the whole
* area asked for.
*/
public sealed interface LocateResult {
LocateResult NOT_FOUND = new NotFound();
LocateResult SEARCH_LIMIT_REACHED = new SearchLimitReached();
static LocateResult found(BlockPosition position) {
return new Found(position);
}
/** Found at {@code position}: world X and Z, and Y the height above the dimension's bottom. */
record Found(BlockPosition position) implements LocateResult {
public Found {
Objects.requireNonNull(position, "position");
}
}
/** The whole area was searched and holds none. */
record NotFound() implements LocateResult {}
/** The search stopped before covering the area, such as after checking as many candidates as it allows itself. */
record SearchLimitReached() implements LocateResult {}
}
@@ -0,0 +1,18 @@
package com.volmit.service;
import com.volmit.world.PackWorld;
import java.util.Set;
/** Which pack objects a module places in a chunk, predicted without generating it. The host's object search and its
* studio tools ask every provider and use all the keys together.
*/
@Service(Providers.ALL)
public interface ObjectsAt {
/**
* The keys of the pack objects this module would place in the chunk at {@code chunkX}, {@code chunkZ} (chunk
* coordinates, world X and Z divided by 16), in the form packs write them ({@code trees/oak}). It is a prediction:
* it may name an object whose placement the chunk's generation later rejects. Empty when the module places nothing
* there.
*/
Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ);
}
@@ -0,0 +1,16 @@
package com.volmit.service;
/** How the host combines the providers of one {@link Service}. A service chooses one; its javadoc says how the host
* uses the answers. Providers are always in module id order, each module's in the order it registered them, so the
* outcome never depends on how modules were discovered.
*/
public enum Providers {
/** The host asks every provider and combines their answers, such as the objects each module places in a chunk. */
ALL,
/** The host asks the providers in order until one answers, such as the module that knows a structure key. A provider
* that has no answer says so in the service's own terms (an empty result) and the next one is asked.
*/
FIRST,
/** A pack has at most one provider. A second module registering one fails the pack load, naming both modules. */
ONE
}
@@ -0,0 +1,25 @@
package com.volmit.service;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** Marks an interface as a service: a capability modules provide and the host looks up, such as finding a module's
* structures, instead of knowing the feature behind it. Modules register providers with
* {@link com.volmit.FeatureRegistry#registerService}; the host gets them from the pack's catalog.
*
* <p>Providers hold no state of their own: a provider is shared by every world, and the host may call it from any
* thread, also from several at once. A provider keeps what it needs in the world's state store
* ({@link com.volmit.world.PackWorld#state}), which is why service methods take the world. Services compute answers;
* they never act on the platform themselves: what should happen in the world comes back as a value the host carries out
* on the right thread.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Service {
/** How the host treats several modules providing this service. */
Providers value();
}
@@ -0,0 +1,30 @@
package com.volmit.service;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.Set;
/** Finds the structures a module places, for the host's structure commands and index. Structures are named by their
* keys, in the form packs write them ({@code castle}, {@code villages/plains}). The host asks the providers in order and
* sends a key to the first that can locate it in the world.
*/
@Service(Providers.FIRST)
public interface StructureLocator {
/** Every structure key of the pack this module knows, placed in a world or not, such as one per structure file. The
* host lists them in its index of the structures a pack has.
*/
Set<String> structures(PackResources pack);
/** The keys of the structures this module places in {@code world} and can find with {@link #locate}: commands offer
* them and send a search for one of them here. A structure no placement of the world uses is not among them.
*/
Set<String> locatable(PackWorld world);
/**
* The start of structure {@code key} nearest to the column {@code fromX}, {@code fromZ} (world coordinates), searched
* up to {@code maxRadiusChunks} chunks away from it. The position is the structure's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Called with a key from {@link #locatable}. May take long; the
* host calls it off the server's main thread.
*/
LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks);
}
@@ -0,0 +1,41 @@
package com.volmit.world;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import java.util.function.Function;
/** One world the host generates with a pack, for as long as the pack stays loaded: the world's seed, the pack's
* resources and settings, and the state modules keep for this world. Stage bodies reach it through
* {@link com.volmit.generation.InvocationContext#world()}, services as their first argument and lifecycle hooks as
* theirs ({@link com.volmit.ModuleLifecycle}).
*
* <p>A hotload ends the world: the host stops it ({@link com.volmit.ModuleLifecycle#worldStopped}) and starts a new
* one with the reloaded pack and an empty state store. So does a reload of the pack's resources while the world runs,
* such as after a tool rewrote some of its files. State therefore never outlives the resources it was built from.
* Invocations that began before the restart finish with the world they began with.
*
* <p>Safe to use from any thread.
*/
public interface PackWorld {
long seed();
/** The pack snapshot this world generates with. */
PackResources resources();
/** The settings of the world's dimension and of every region and biome it can reach, as mantle reaches see them. */
PackSettings settings();
/**
* The world's one {@code type} instance, created by {@code create} the first time anyone asks for it. Modules keep
* their caches and per-world workers here instead of in fields, since stage bodies and services are shared by every
* world and every invocation. Use a class of the module as {@code type}, so two modules never share an entry.
*
* <p>{@code create} runs once per world, even when several threads ask at once; the others wait for it and get the
* same instance. It may ask for other state of this world on its own thread, but must not wait for other threads
* that ask for state, and a type that is asked for again while it is being created fails with
* IllegalStateException. If {@code create} throws, nothing is kept and the next call tries again. A state that is
* {@link AutoCloseable} is closed after the world stops, once nothing generates with it any more. After the world
* stopped, asking for state throws IllegalStateException.
*/
<T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create);
}