mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-03 03:31:32 +00:00
Merge wave1/a1
This commit is contained in:
commit
adb848bf9f
29 files changed
+1286
-17
No files matched your search
@@ -29,6 +29,9 @@ types that carry them and lists what the Iris adapter still owes.
|
|||||||
| Pack-scoped resolution | `ResourceId`, `ResourceKey<T>`, `PackResources` (`find`, `ids`), `PackBiome`, `PackRegion` |
|
| Pack-scoped resolution | `ResourceId`, `ResourceKey<T>`, `PackResources` (`find`, `ids`), `PackBiome`, `PackRegion` |
|
||||||
| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` |
|
| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` |
|
||||||
| Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` |
|
| Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` |
|
||||||
|
| Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` |
|
||||||
|
| Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` |
|
||||||
|
| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`) |
|
||||||
| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` |
|
| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` |
|
||||||
| Dense chunk output | `Hunk<T>`, `GenerationContext.hunk`, reference `ArrayHunk<T>` |
|
| Dense chunk output | `Hunk<T>`, `GenerationContext.hunk`, reference `ArrayHunk<T>` |
|
||||||
| Sparse geometry and transforms | `ObjectGenerator`, `GeneratedObject`, `ObjectTransform`, `ObjectTransformer` |
|
| Sparse geometry and transforms | `ObjectGenerator`, `GeneratedObject`, `ObjectTransform`, `ObjectTransformer` |
|
||||||
@@ -70,6 +73,12 @@ naming the jar and the classes. A class nobody has (an optional dependency) only
|
|||||||
its package is one the module declares optional with `ModuleInfo.withOptionalPackages(...)`
|
its package is one the module declares optional with `ModuleInfo.withOptionalPackages(...)`
|
||||||
(`PackageName`). That declaration never excuses a load error.
|
(`PackageName`). That declaration never excuses a load error.
|
||||||
|
|
||||||
|
Stage bodies and service providers keep no state; what a module keeps for a world lives in that world's state store,
|
||||||
|
created once per type and world. A world's state lives while the world runs with one pack snapshot: a hotload or a
|
||||||
|
reload of the pack's resources starts the world again with empty state. A service names how its providers combine
|
||||||
|
(`ALL`, `FIRST`, `ONE`); a second provider of a `ONE` service fails the pack load, naming both modules. Services
|
||||||
|
return values and never act on the platform.
|
||||||
|
|
||||||
A resource kind reads one folder directly below the pack root, with a class no other kind uses; a folder two
|
A resource kind reads one folder directly below the pack root, with a class no other kind uses; a folder two
|
||||||
kinds claim, or one the host reads itself, fails the pack load naming both owners. Resources of a kind are
|
kinds claim, or one the host reads itself, fails the pack load naming both owners. Resources of a kind are
|
||||||
values, read once per pack snapshot. Validators only report: an `ERROR` blocks the pack, a `WARNING` is shown.
|
values, read once per pack snapshot. Validators only report: an `ERROR` blocks the pack, a `WARNING` is shown.
|
||||||
@@ -151,6 +160,20 @@ running Iris is the pack publisher's responsibility.
|
|||||||
`ERROR` blocks the pack, a `WARNING` is shown; show each problem with its subject. A validator that throws is an
|
`ERROR` blocks the pack, a `WARNING` is shown; show each problem with its subject. A validator that throws is an
|
||||||
error naming its module, and the others still run.
|
error naming its module, and the others still run.
|
||||||
|
|
||||||
|
- Keep one `PackWorld` per world and pack snapshot and pass it to every invocation of the world
|
||||||
|
(`InvocationContext.world()`), to service calls and to hooks. Use `WorldStates` (or the same rules) for its store.
|
||||||
|
- Call the hooks with `LifecycleRunner`: `packLoaded` once per pack snapshot before its first world starts,
|
||||||
|
`worldStarted` before the world generates anything, `worldStopped` when it stops. On a hotload, and when the pack's
|
||||||
|
resources are read again while worlds run, stop each world, load the new snapshot and start the world again with
|
||||||
|
a new store. Close a stopped world's store only once no invocation uses it any more.
|
||||||
|
- A failed `packLoaded` or `worldStarted` keeps the world from starting and names the module; report `worldStopped`
|
||||||
|
failures without skipping the other modules.
|
||||||
|
- Ask modules through services instead of reading their features: combine `ALL` providers, ask `FIRST` providers in
|
||||||
|
catalog order until one answers, and use `service(type)` for `ONE`. Call providers from any thread, but long
|
||||||
|
searches off the server's main thread, and carry out what they return on the thread the platform needs.
|
||||||
|
- Read a `StructureLocator` position's Y as a height above the dimension's bottom and convert it to the platform's Y
|
||||||
|
at the boundary, like every other IrisApi height.
|
||||||
|
|
||||||
## Open
|
## Open
|
||||||
|
|
||||||
- Terrain/biome providers, pack transformations, structure assembly and the runtime family.
|
- Terrain/biome providers, pack transformations, structure assembly and the runtime family.
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Status: pack module loading (`LoadedPack`), the stage graph, per-stage random streams, both
|
Status: pack module loading (`LoadedPack`), the stage graph, per-stage random streams, both
|
||||||
pipelines' reference executors, settings catalog and its description for studio, geometry,
|
pipelines' reference executors, settings catalog and its description for studio, geometry,
|
||||||
resources, module resource kinds, validators and typed storage contracts
|
resources, module resource kinds, validators, per-world state, lifecycle hooks, services and typed storage contracts
|
||||||
exist and are tested without the Iris
|
exist and are tested without the Iris
|
||||||
engine. Provider and runtime families at the end are design notes, not Java interfaces.
|
engine. Provider and runtime families at the end are design notes, not Java interfaces.
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@ phase or hook has special status in the API.
|
|||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
Modules[Built-in and addon modules] --> Install[install: define stages]
|
Modules[Built-in and addon modules] --> Install[install: define stages]
|
||||||
Modules --> Register[register: geometry, mantle layers, resource kinds, validators]
|
Modules --> Register[register: geometry, mantle layers, resource kinds, validators, hooks, services]
|
||||||
Install --> Resolve[Resolve per pipeline at pack load]
|
Install --> Resolve[Resolve per pipeline at pack load]
|
||||||
Install --> Settings[when settings types]
|
Install --> Settings[when settings types]
|
||||||
Settings --> Catalog[Frozen feature catalog]
|
Settings --> Catalog[Frozen feature catalog]
|
||||||
@@ -782,6 +782,70 @@ host shows the subject with the message. A validator that throws fails the pack'
|
|||||||
naming its module; the other validators still run. `FeatureCatalog.validators()` lists them by module id, each
|
naming its module; the other validators still run. `FeatureCatalog.validators()` lists them by module id, each
|
||||||
module's in registration order, so the order never depends on discovery.
|
module's in registration order, so the order never depends on discovery.
|
||||||
|
|
||||||
|
## World state and lifecycle
|
||||||
|
|
||||||
|
Iris kept the caches of its features itself: decoration streams in the biome complex, a warm-up pass over feature
|
||||||
|
data when an engine starts, per-runtime workers in a map only built-in stages reached. A module could not do the
|
||||||
|
same, because stage bodies are shared by every world and every invocation and must keep no state. The API now gives
|
||||||
|
each world a state store and tells modules when worlds start and stop.
|
||||||
|
|
||||||
|
- **The world.** `PackWorld` is one world generating with one pack snapshot: seed, resources, the settings of its
|
||||||
|
dimension and of the regions and biomes it can reach (what mantle reaches see), and `state(type, create)`.
|
||||||
|
`InvocationContext.world()` hands it to every stage; services take it as their first argument; hooks get it. A
|
||||||
|
placement outside any world, such as a studio paste, has none and throws.
|
||||||
|
- **The store.** One instance per type, keyed by class: a class is compile-checked and module-owned, so two modules
|
||||||
|
never share an entry by accident, and it matches the internal `state(Class, factory)` Iris already used. A factory
|
||||||
|
runs once per type even when threads race (the others wait and get the same instance); it may ask for other state
|
||||||
|
on its own thread, since creation holds one re-entrant lock, and asking for the type being created fails naming the
|
||||||
|
chain instead of recursing or deadlocking. A factory that throws keeps nothing. Reads of existing state take no lock.
|
||||||
|
`WorldStates` is the reference store hosts use.
|
||||||
|
- **Hooks.** `ModuleLifecycle` has `packLoaded(resources, settings)`, `worldStarted(world)` and `worldStopped(world)`,
|
||||||
|
each a no-op by default, registered with `FeatureRegistry.registerLifecycle` like validators, so the host knows the
|
||||||
|
owning module for errors and orders hooks by module id. A module class may implement it and register itself.
|
||||||
|
`packLoaded` runs once per snapshot before its first world starts; a pack that is only validated or edited in studio
|
||||||
|
is not loaded in this sense. The settings it gets are the whole pack's, as validators see them.
|
||||||
|
- **Hotload semantics.** A world's state lives as long as the world runs with one pack snapshot. A hotload stops the
|
||||||
|
world and starts a new one with the reloaded pack; so does a reload of the pack's resources while the world runs,
|
||||||
|
such as a tool rewriting structure files. State therefore never outlives the resources it was built from, and
|
||||||
|
modules need no invalidation calls of their own. An invocation keeps the world it began with; the host closes the
|
||||||
|
old world's `AutoCloseable` states once nothing generates with it.
|
||||||
|
- **Failures.** A failing `packLoaded` or `worldStarted` keeps the world from starting, naming the module, and the
|
||||||
|
modules that had started get `worldStopped`. Every `worldStopped` runs even when one fails; the failures are reported
|
||||||
|
together. `LifecycleRunner` implements these rules for hosts.
|
||||||
|
- **Threading.** Hooks of one world run one at a time on the thread that starts or stops it, in module id order and
|
||||||
|
stops in reverse. State is safe from any thread.
|
||||||
|
- **Not added (yet):** a pack-level store shared by the worlds of one snapshot. Every known consumer (decoration
|
||||||
|
streams, warm-up, placement workers, structure indexes) is per world; per-world state built from pack data costs
|
||||||
|
a little duplication when several worlds share a pack.
|
||||||
|
|
||||||
|
## Services
|
||||||
|
|
||||||
|
Iris core still asks feature classes directly: which objects a chunk gets, where a structure is, which tree grows
|
||||||
|
from a sapling, which drops a block has. A module answers such questions through a service instead.
|
||||||
|
|
||||||
|
- **Shape.** A service is an interface marked `@Service`. Its methods take the `PackWorld` they concern (or the
|
||||||
|
`PackResources` for a question about the pack alone) and return values. A provider is registered once per pack with
|
||||||
|
`FeatureRegistry.registerService(type, provider)` and holds no state: it reaches the world's store. Services compute;
|
||||||
|
what should happen in the world (an entity spawned, items dropped) comes back as a value the host carries out on the
|
||||||
|
thread the platform needs, so no platform type ever appears in a service.
|
||||||
|
- **Several providers.** Each service chooses with `@Service(Providers.X)`: `ALL`, the host asks every provider and
|
||||||
|
combines the answers (objects in a chunk); `FIRST`, the host asks in order until one answers (the module that knows a
|
||||||
|
structure key); `ONE`, at most one provider per pack, and a second module providing it fails the pack load naming
|
||||||
|
both. Order is module id order and, within a module, registration order, so it never depends on discovery.
|
||||||
|
- **Lookup.** The host asks the pack's catalog: `services(type)` for every provider, `service(type)` for the one
|
||||||
|
provider of a `ONE` service. Looking up a type that is not marked fails, and so does `service` for a service that may
|
||||||
|
have several providers.
|
||||||
|
- **Threading.** The host may call a provider from any thread, several at once. A provider that searches long
|
||||||
|
(`StructureLocator.locate`) is called off the server's main thread.
|
||||||
|
- **Services now.** `ObjectsAt` (`ALL`): pack object keys a module would place in a chunk, predicted without
|
||||||
|
generating it. `StructureLocator` (`FIRST`): every structure key a module knows, the ones a world places, and the
|
||||||
|
nearest start of one as a `LocateResult` (`Found`, `NotFound`, `SearchLimitReached`; a sealed interface, so callers
|
||||||
|
switch over every outcome). Keys are pack keys as packs write them and match without regard to case.
|
||||||
|
- **Why not per-world provider instances.** A factory per world (`world -> provider`) would let a provider hold its
|
||||||
|
world, but every service method would then hide which world it answers for, and a host could not ask a pack-level
|
||||||
|
question without a world. Passing the world keeps providers stateless like stage bodies and puts all per-world data
|
||||||
|
in one place.
|
||||||
|
|
||||||
## Not implemented
|
## Not implemented
|
||||||
|
|
||||||
- Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and
|
- Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and
|
||||||
@@ -825,7 +889,8 @@ This is an inventory of where each existing family should land, not a claim that
|
|||||||
- Image maps and expressions should compile into pack resources before a snapshot is published.
|
- Image maps and expressions should compile into pack resources before a snapshot is published.
|
||||||
- Runtime features need their own family with read-only event inputs and requested actions that
|
- Runtime features need their own family with read-only event inputs and requested actions that
|
||||||
host adapters perform on the right scheduler. Generation hunks, RNGs and views never leak into
|
host adapters perform on the right scheduler. Generation hunks, RNGs and views never leak into
|
||||||
runtime work.
|
runtime work. Services are that family's seam: a service takes the world and an event value and returns the
|
||||||
|
actions (see Services).
|
||||||
|
|
||||||
Exact signatures for these families should follow their first real port.
|
Exact signatures for these families should follow their first real port.
|
||||||
|
|
||||||
|
|||||||
@@ -51,8 +51,8 @@ public final class MossModule implements IrisModule {
|
|||||||
The stream is a `WorldRandom` (see Random streams below).
|
The stream is a `WorldRandom` (see Random streams below).
|
||||||
|
|
||||||
`IrisModule.register(FeatureRegistry)` stays for non-stage contributions: geometry generators,
|
`IrisModule.register(FeatureRegistry)` stays for non-stage contributions: geometry generators,
|
||||||
mantle layers, settings no stage names (see Settings for studio), pack resource kinds and validators
|
mantle layers, settings no stage names (see Settings for studio), pack resource kinds, validators,
|
||||||
(see below). Their feature ids, mantle keys and kind ids are the module id or start with it and `/`,
|
lifecycle hooks and services (see below). Their feature ids, mantle keys and kind ids are the module id or start with it and `/`,
|
||||||
like stage ids: `iris:snow` or `iris:snow/depth` for module `iris:snow`. A settings type named in `when(...)` needs a feature id that at least one
|
like stage ids: `iris:snow` or `iris:snow/depth` for module `iris:snow`. A settings type named in `when(...)` needs a feature id that at least one
|
||||||
module naming it owns in that sense, or its owner must have registered it, so another module may
|
module naming it owns in that sense, or its owner must have registered it, so another module may
|
||||||
still condition its stages on it, as moss does on `iris:snow`.
|
still condition its stages on it, as moss does on `iris:snow`.
|
||||||
@@ -204,6 +204,88 @@ every dimension, region and biome of the pack. It reports each `Problem` with a
|
|||||||
resource id or a file below the pack root. An `ERROR` stops the pack from loading; a `WARNING` is only shown.
|
resource id or a file below the pack root. An `ERROR` stops the pack from loading; a `WARNING` is only shown.
|
||||||
A validator reports and returns; one that throws fails the pack's validation, naming its module.
|
A validator reports and returns; one that throws fails the pack's validation, naming its module.
|
||||||
|
|
||||||
|
## World state and lifecycle
|
||||||
|
|
||||||
|
Stage bodies and services are shared by every world and every invocation, so a module keeps nothing in fields. What
|
||||||
|
it builds for one world, such as a cache or a worker, it keeps in that world's state store:
|
||||||
|
|
||||||
|
```java
|
||||||
|
private static void plant(ChunkStageContext context) {
|
||||||
|
planted(context.world()).add(context.originX() >> 4, context.originZ() >> 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
static PlantedChunks planted(PackWorld world) {
|
||||||
|
return world.state(PlantedChunks.class, PlantedChunks::new); // one per world, created on first use
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `ctx.world()` is the `PackWorld` an invocation generates: its seed, the pack snapshot's resources, the settings of
|
||||||
|
its dimension and the regions and biomes it can reach, and `state(type, create)`. Every stage context has it; a
|
||||||
|
placement outside any world, such as a studio paste, throws.
|
||||||
|
- `state` creates each type once per world, even when threads race, and hands every caller the same instance. A
|
||||||
|
factory may ask for other state; asking for the type being created fails instead of recursing. A factory that throws
|
||||||
|
keeps nothing. Use a class of the module as the type.
|
||||||
|
- A state that is `AutoCloseable` is closed after the world stops, once nothing generates with it.
|
||||||
|
|
||||||
|
A module that wants to act when the host loads a pack or starts or stops a world registers a `ModuleLifecycle`. Every
|
||||||
|
hook does nothing by default, and a module class may implement it and register itself:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public final class RuinsModule implements IrisModule, ModuleLifecycle {
|
||||||
|
public void register(FeatureRegistry registry) {
|
||||||
|
registry.registerLifecycle(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void worldStarted(PackWorld world) {
|
||||||
|
planted(world); // build the state now instead of on the world's first chunk
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `packLoaded(resources, settings)` runs once per pack snapshot, before the first world using it starts; `settings`
|
||||||
|
holds every entry of the whole pack.
|
||||||
|
- `worldStarted(world)` runs before the world generates anything, `worldStopped(world)` when it stops; its state is
|
||||||
|
still readable there.
|
||||||
|
- A hotload, or a reload of the pack's resources while worlds run (a tool rewrote files), stops each world, loads the
|
||||||
|
new snapshot and starts the worlds again with empty state. State never outlives the resources it was built from.
|
||||||
|
- Hooks run in module id order, stops in reverse. A failing `packLoaded` or `worldStarted` stops the world from
|
||||||
|
starting, naming the module (modules that had started get `worldStopped`); every `worldStopped` runs even when one
|
||||||
|
fails.
|
||||||
|
|
||||||
|
## Services
|
||||||
|
|
||||||
|
The host asks modules for what only they know, such as which objects a chunk gets or where a structure is, through
|
||||||
|
services: small interfaces marked `@Service` in `com.volmit.service`. A module registers a provider; the host looks
|
||||||
|
them up in the pack's catalog instead of knowing the feature.
|
||||||
|
|
||||||
|
```java
|
||||||
|
public void register(FeatureRegistry registry) {
|
||||||
|
registry.registerService(ObjectsAt.class, RuinsModule::objectsAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) {
|
||||||
|
return planted(world).contains(chunkX, chunkZ) ? Set.of("ruins/arch") : Set.of();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Providers hold no state: a provider serves every world and the host may call it from any thread, several at once.
|
||||||
|
Service methods take the world, and the provider keeps what it needs in the world's state store.
|
||||||
|
- Services compute; they never act on the platform. What should happen in the world comes back as a value the host
|
||||||
|
carries out on the right thread.
|
||||||
|
- Each service says how several providers combine, with `@Service(Providers.X)`: `ALL` (the host asks every provider
|
||||||
|
and combines the answers), `FIRST` (the host asks in order until one answers) or `ONE` (at most one provider per
|
||||||
|
pack; a second fails the pack load, naming both modules). Providers are in module id order, each module's in
|
||||||
|
registration order.
|
||||||
|
|
||||||
|
| Service | Providers | What the host asks |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `ObjectsAt` | `ALL` | The pack objects a module would place in a chunk, predicted without generating it (object search, studio tools). |
|
||||||
|
| `StructureLocator` | `FIRST` | Every structure key the module knows (the structure index), the ones a world places (commands complete them), and the nearest start of one, as a `LocateResult`: `Found(position)`, `NotFound` or `SearchLimitReached`. Keys match without regard to case. |
|
||||||
|
|
||||||
|
```
|
||||||
|
Service example.Clock is provided by module example:alpha from modules/alpha.jar already, and module example:beta from modules/beta.jar provides it too; a pack has one provider of it (Providers.ONE), so remove one of them
|
||||||
|
```
|
||||||
|
|
||||||
## Module jars
|
## Module jars
|
||||||
|
|
||||||
A pack loads its modules from `<pack>/modules/*.jar`. A jar holds one or more modules. Each module's
|
A pack loads its modules from `<pack>/modules/*.jar`. A jar holds one or more modules. Each module's
|
||||||
@@ -497,6 +579,20 @@ schema, after a module jar changes.
|
|||||||
`PlacementRunner` owns the edit for one attempt. It commits once if no stage rejects or throws
|
`PlacementRunner` owns the edit for one attempt. It commits once if no stage rejects or throws
|
||||||
and closes the edit in every case. Stages get buffered `PlacementAccess` without commit rights.
|
and closes the edit in every case. Stages get buffered `PlacementAccess` without commit rights.
|
||||||
|
|
||||||
|
The host keeps one `PackWorld` per world and pack snapshot. `WorldStates` is the reference store behind
|
||||||
|
`PackWorld.state`, and `LifecycleRunner` calls a pack's hooks the way `ModuleLifecycle` promises:
|
||||||
|
|
||||||
|
```java
|
||||||
|
var lifecycles = new LifecycleRunner(pack.catalog());
|
||||||
|
lifecycles.packLoaded(resources, packSettings); // once per snapshot, before its first world starts
|
||||||
|
lifecycles.worldStarted(world); // then hand world to every invocation of the world
|
||||||
|
...
|
||||||
|
lifecycles.worldStopped(world); // then close the world's WorldStates
|
||||||
|
|
||||||
|
List<ObjectsAt> providers = pack.catalog().services(ObjectsAt.class); // in module id order
|
||||||
|
Optional<Clock> clock = pack.catalog().service(Clock.class); // a Providers.ONE service only
|
||||||
|
```
|
||||||
|
|
||||||
## Values that stay
|
## Values that stay
|
||||||
|
|
||||||
- `ResourceId` requires a namespace. `ResourceKey<T>` pairs it with a public type.
|
- `ResourceId` requires a namespace. `ResourceKey<T>` pairs it with a public type.
|
||||||
@@ -514,7 +610,8 @@ and closes the edit in every case. Stages get buffered `PlacementAccess` without
|
|||||||
`@MaxNumber`, `@Snippet`, `@Ref`) and `OptionsMetadata` describe settings.
|
`@MaxNumber`, `@Snippet`, `@Ref`) and `OptionsMetadata` describe settings.
|
||||||
|
|
||||||
Invocation views and random streams expire when the invocation ends. Stage bodies are shared by
|
Invocation views and random streams expire when the invocation ends. Stage bodies are shared by
|
||||||
concurrent invocations and must not keep views, streams or mutable state.
|
concurrent invocations and must not keep views, streams or mutable state; what a module keeps per world lives in the
|
||||||
|
world's state store (`PackWorld.state`).
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
@@ -544,7 +641,13 @@ settings (and the load error when a pack module uses one), and the one-option sh
|
|||||||
`PackSchemaTest` also loads a module jar with a resource kind: the kind's files described from its class,
|
`PackSchemaTest` also loads a module jar with a resource kind: the kind's files described from its class,
|
||||||
`@ResourceRef` options as references to the kind, built-in kinds of host types, the load error for a pack kind
|
`@ResourceRef` options as references to the kind, built-in kinds of host types, the load error for a pack kind
|
||||||
of a host type, for a folder two kinds claim or the host reserves, and for a misplaced `@ResourceRef`.
|
of a host type, for a folder two kinds claim or the host reserves, and for a misplaced `@ResourceRef`.
|
||||||
`ModuleRegistryTest` checks kind ids, types and folders, and the validator order. `DiscoveredModuleTest`
|
`ModuleRegistryTest` checks kind ids, types and folders, the validator and lifecycle order, service providers in module
|
||||||
|
order, the load error for a second provider of a `ONE` service and for providers of unmarked interfaces or of the
|
||||||
|
wrong type. `WorldStatesTest` checks that each state is created once (also when threads race), nested creation, the
|
||||||
|
error for a type asked for while it is created, factories that fail or return null, and closing newest first past
|
||||||
|
failures. `LifecycleRunnerTest` checks hook order, stops in reverse, the stop of already started modules when a start
|
||||||
|
fails, and that every stop runs. `WorldStateExampleTest` (`example/world`) has a chunk stage, a service and a hook share
|
||||||
|
one world's state, and a new world start empty. `DiscoveredModuleTest`
|
||||||
checks that `info()` is read once. `LoadedPackTest` loads a pack with
|
checks that `info()` is read once. `LoadedPackTest` loads a pack with
|
||||||
built-ins and checks that a failed load and `close()` leave nothing open. `PackJarSnapshotTest` checks
|
built-ins and checks that a failed load and `close()` leave nothing open. `PackJarSnapshotTest` checks
|
||||||
that classes come from the copies, that the original can be replaced while loaded, that copies go
|
that classes come from the copies, that the original can be replaced while loaded, that copies go
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.volmit.mantle.MantleKey;
|
|||||||
import com.volmit.mantle.MantleLifetime;
|
import com.volmit.mantle.MantleLifetime;
|
||||||
import com.volmit.object.ObjectGeneratorFactory;
|
import com.volmit.object.ObjectGeneratorFactory;
|
||||||
import com.volmit.resource.ResourceKind;
|
import com.volmit.resource.ResourceKind;
|
||||||
|
import com.volmit.service.Service;
|
||||||
import com.volmit.stage.StageGraph;
|
import com.volmit.stage.StageGraph;
|
||||||
import com.volmit.validation.Validator;
|
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. */
|
/** Adds a check the host runs over the whole pack wherever it validates packs. */
|
||||||
void registerValidator(Validator validator);
|
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);
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@ public interface IrisModule {
|
|||||||
void install(StageGraph graph);
|
void install(StageGraph graph);
|
||||||
|
|
||||||
/** Registers non-stage contributions: geometry generators, mantle layers, settings no stage names, pack
|
/** 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) {}
|
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;
|
package com.volmit.generation;
|
||||||
|
|
||||||
import com.volmit.resource.PackResources;
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
|
|
||||||
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
|
/** 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 {
|
public interface InvocationContext {
|
||||||
long worldSeed();
|
long worldSeed();
|
||||||
PackResources resources();
|
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.mantle.Mantle;
|
||||||
import com.volmit.random.WorldRandom;
|
import com.volmit.random.WorldRandom;
|
||||||
import com.volmit.resource.PackResources;
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
import com.volmit.stage.ChunkStageContext;
|
import com.volmit.stage.ChunkStageContext;
|
||||||
import com.volmit.stage.Stage;
|
import com.volmit.stage.Stage;
|
||||||
import com.volmit.world.TerrainSampler;
|
import com.volmit.world.TerrainSampler;
|
||||||
@@ -65,6 +66,11 @@ final class ChunkInvocation implements ChunkStageContext {
|
|||||||
return inputs.worldSeed();
|
return inputs.worldSeed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PackWorld world() {
|
||||||
|
return inputs.world();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PackResources resources() {
|
public PackResources resources() {
|
||||||
return inputs.resources();
|
return inputs.resources();
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
package com.volmit.host;
|
package com.volmit.host;
|
||||||
|
|
||||||
import com.volmit.IrisFeature;
|
import com.volmit.IrisFeature;
|
||||||
|
import com.volmit.service.Providers;
|
||||||
|
import com.volmit.service.Service;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
|
|
||||||
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators are in module id order,
|
/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators, lifecycle hooks and service
|
||||||
* so nothing depends on discovery. Factory, codec and validator implementations must themselves obey their
|
* providers are in module id order, each module's in the order it registered them, so nothing depends on discovery.
|
||||||
* concurrency contracts.
|
* Factory, codec, validator, hook and provider implementations must themselves obey their concurrency contracts.
|
||||||
*/
|
*/
|
||||||
public final class FeatureCatalog {
|
public final class FeatureCatalog {
|
||||||
private final Map<Class<?>, FeatureDescriptor<?>> settings;
|
private final Map<Class<?>, FeatureDescriptor<?>> settings;
|
||||||
@@ -18,20 +21,24 @@ public final class FeatureCatalog {
|
|||||||
private final Map<String, MantleRegistration<?>> mantle;
|
private final Map<String, MantleRegistration<?>> mantle;
|
||||||
private final List<ResourceKindRegistration> resourceKinds;
|
private final List<ResourceKindRegistration> resourceKinds;
|
||||||
private final List<ValidatorRegistration> validators;
|
private final List<ValidatorRegistration> validators;
|
||||||
|
private final List<LifecycleRegistration> lifecycles;
|
||||||
|
private final List<ServiceRegistration> services;
|
||||||
|
|
||||||
FeatureCatalog(
|
FeatureCatalog(
|
||||||
Map<Class<?>, FeatureDescriptor<?>> settings,
|
Map<Class<?>, FeatureDescriptor<?>> settings,
|
||||||
Map<Class<?>, ObjectRegistration<?>> objects,
|
Map<Class<?>, ObjectRegistration<?>> objects,
|
||||||
Map<String, MantleRegistration<?>> mantle,
|
Map<String, MantleRegistration<?>> mantle,
|
||||||
Collection<ResourceKindRegistration> resourceKinds,
|
Collection<ResourceKindRegistration> resourceKinds,
|
||||||
List<ValidatorRegistration> validators) {
|
List<ValidatorRegistration> validators,
|
||||||
|
List<LifecycleRegistration> lifecycles,
|
||||||
|
List<ServiceRegistration> services) {
|
||||||
this.settings = Map.copyOf(settings);
|
this.settings = Map.copyOf(settings);
|
||||||
this.objects = Map.copyOf(objects);
|
this.objects = Map.copyOf(objects);
|
||||||
this.mantle = Map.copyOf(mantle);
|
this.mantle = Map.copyOf(mantle);
|
||||||
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
|
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
|
||||||
this.validators = validators.stream()
|
this.validators = inModuleOrder(validators, ValidatorRegistration::module);
|
||||||
.sorted(Comparator.comparing(registration -> registration.module().info().id()))
|
this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module);
|
||||||
.toList();
|
this.services = inModuleOrder(services, ServiceRegistration::module);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Settings types that activate stages; the host decodes them from pack JSON. */
|
/** Settings types that activate stages; the host decodes them from pack JSON. */
|
||||||
@@ -57,6 +64,47 @@ public final class FeatureCatalog {
|
|||||||
return validators;
|
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(
|
private static <T, K extends Comparable<? super K>> List<T> sorted(
|
||||||
Collection<T> registrations,
|
Collection<T> registrations,
|
||||||
Function<? super T, ? extends K> key) {
|
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.mantle.Mantle;
|
||||||
import com.volmit.random.WorldRandom;
|
import com.volmit.random.WorldRandom;
|
||||||
import com.volmit.resource.PackResources;
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
import com.volmit.stage.MantleStageContext;
|
import com.volmit.stage.MantleStageContext;
|
||||||
import com.volmit.stage.Stage;
|
import com.volmit.stage.Stage;
|
||||||
import com.volmit.world.TerrainSampler;
|
import com.volmit.world.TerrainSampler;
|
||||||
@@ -59,6 +60,11 @@ final class MantleInvocation implements MantleStageContext {
|
|||||||
return inputs.worldSeed();
|
return inputs.worldSeed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PackWorld world() {
|
||||||
|
return inputs.world();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PackResources resources() {
|
public PackResources resources() {
|
||||||
return inputs.resources();
|
return inputs.resources();
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ import com.volmit.FeatureAttachment;
|
|||||||
import com.volmit.FeatureRegistry;
|
import com.volmit.FeatureRegistry;
|
||||||
import com.volmit.IrisFeature;
|
import com.volmit.IrisFeature;
|
||||||
import com.volmit.IrisModule;
|
import com.volmit.IrisModule;
|
||||||
|
import com.volmit.ModuleLifecycle;
|
||||||
import com.volmit.mantle.MantleCodec;
|
import com.volmit.mantle.MantleCodec;
|
||||||
import com.volmit.mantle.MantleKey;
|
import com.volmit.mantle.MantleKey;
|
||||||
import com.volmit.mantle.MantleLifetime;
|
import com.volmit.mantle.MantleLifetime;
|
||||||
import com.volmit.object.ObjectGeneratorFactory;
|
import com.volmit.object.ObjectGeneratorFactory;
|
||||||
import com.volmit.resource.ResourceId;
|
import com.volmit.resource.ResourceId;
|
||||||
import com.volmit.resource.ResourceKind;
|
import com.volmit.resource.ResourceKind;
|
||||||
|
import com.volmit.service.Providers;
|
||||||
import com.volmit.validation.Validator;
|
import com.volmit.validation.Validator;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
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
|
* {@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}).
|
* 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
|
* 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
|
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
|
||||||
* settings.
|
* settings.
|
||||||
*/
|
*/
|
||||||
@@ -40,6 +43,8 @@ public final class ModuleRegistry implements FeatureRegistry {
|
|||||||
private final Map<Field, String> fields = new HashMap<>();
|
private final Map<Field, String> fields = new HashMap<>();
|
||||||
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
|
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
|
||||||
private final List<ValidatorRegistration> validators = new ArrayList<>();
|
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 Set<String> reservedFolders;
|
||||||
private final List<DiscoveredModule> registered = new ArrayList<>();
|
private final List<DiscoveredModule> registered = new ArrayList<>();
|
||||||
private FeatureCatalog catalog;
|
private FeatureCatalog catalog;
|
||||||
@@ -129,6 +134,32 @@ public final class ModuleRegistry implements FeatureRegistry {
|
|||||||
validators.add(new ValidatorRegistration(validator, registering));
|
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}
|
/** 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
|
* 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.
|
* it after every module has registered, so the owner is known.
|
||||||
@@ -149,7 +180,7 @@ public final class ModuleRegistry implements FeatureRegistry {
|
|||||||
|
|
||||||
public FeatureCatalog freeze() {
|
public FeatureCatalog freeze() {
|
||||||
if (catalog == null) {
|
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;
|
return catalog;
|
||||||
}
|
}
|
||||||
@@ -179,6 +210,23 @@ public final class ModuleRegistry implements FeatureRegistry {
|
|||||||
+ info.idPrefix() + ", the id of its registering module " + registering);
|
+ 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. */
|
/** 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) {
|
private void requireUnclaimedKind(ResourceKindRegistration added) {
|
||||||
var kind = added.kind();
|
var kind = added.kind();
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import com.volmit.placement.PlacementContext;
|
|||||||
import com.volmit.placement.PlacementRequest;
|
import com.volmit.placement.PlacementRequest;
|
||||||
import com.volmit.random.WorldRandom;
|
import com.volmit.random.WorldRandom;
|
||||||
import com.volmit.resource.PackResources;
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
import com.volmit.stage.BlockStageContext;
|
import com.volmit.stage.BlockStageContext;
|
||||||
import com.volmit.stage.Stage;
|
import com.volmit.stage.Stage;
|
||||||
import com.volmit.world.BlockView;
|
import com.volmit.world.BlockView;
|
||||||
@@ -111,6 +112,11 @@ final class PlacementInvocation implements BlockStageContext {
|
|||||||
return inputs.worldSeed();
|
return inputs.worldSeed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PackWorld world() {
|
||||||
|
return inputs.world();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PackResources resources() {
|
public PackResources resources() {
|
||||||
return inputs.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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package com.volmit.example.world;
|
||||||
|
|
||||||
|
import com.volmit.FeatureRegistry;
|
||||||
|
import com.volmit.IrisModule;
|
||||||
|
import com.volmit.ModuleInfo;
|
||||||
|
import com.volmit.ModuleLifecycle;
|
||||||
|
import com.volmit.host.ChunkRunner;
|
||||||
|
import com.volmit.host.DiscoveredModule;
|
||||||
|
import com.volmit.host.LifecycleRunner;
|
||||||
|
import com.volmit.host.LoadedModules;
|
||||||
|
import com.volmit.service.ObjectsAt;
|
||||||
|
import com.volmit.stage.ChunkStage;
|
||||||
|
import com.volmit.stage.ChunkStageContext;
|
||||||
|
import com.volmit.stage.Stage;
|
||||||
|
import com.volmit.stage.StageGraph;
|
||||||
|
import com.volmit.support.ColumnSettings;
|
||||||
|
import com.volmit.support.TestContexts;
|
||||||
|
import com.volmit.support.TestWorld;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
/** A module that remembers, per world, which chunks it planted ruins in: its chunk stage writes the world's state,
|
||||||
|
* its {@link ObjectsAt} service reads it, and its lifecycle builds the state when the world starts.
|
||||||
|
*/
|
||||||
|
class WorldStateExampleTest {
|
||||||
|
static final class RuinsModule implements IrisModule, ModuleLifecycle {
|
||||||
|
static final ChunkStage<Void> PLANT = Stage.chunk("example:ruins/plant");
|
||||||
|
|
||||||
|
/** What ruins keeps per world. A field of the module would be shared by every world. */
|
||||||
|
static final class PlantedChunks {
|
||||||
|
final long seed;
|
||||||
|
final Set<Long> chunks = ConcurrentHashMap.newKeySet();
|
||||||
|
|
||||||
|
PlantedChunks(PackWorld world) {
|
||||||
|
this.seed = world.seed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModuleInfo info() { return ModuleInfo.of("example:ruins", "Ruins", "1"); }
|
||||||
|
|
||||||
|
public void install(StageGraph graph) {
|
||||||
|
graph.define(PLANT).run(RuinsModule::plant);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void register(FeatureRegistry registry) {
|
||||||
|
registry.registerLifecycle(this);
|
||||||
|
registry.registerService(ObjectsAt.class, RuinsModule::objectsAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void worldStarted(PackWorld world) {
|
||||||
|
planted(world);
|
||||||
|
}
|
||||||
|
|
||||||
|
static PlantedChunks planted(PackWorld world) {
|
||||||
|
return world.state(PlantedChunks.class, PlantedChunks::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void plant(ChunkStageContext context) {
|
||||||
|
planted(context.world()).chunks.add(key(context.originX() >> 4, context.originZ() >> 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) {
|
||||||
|
return planted(world).chunks.contains(key(chunkX, chunkZ)) ? Set.of("ruins/arch") : Set.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long key(int chunkX, int chunkZ) {
|
||||||
|
return ((long) chunkX << 32) ^ (chunkZ & 0xFFFFFFFFL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void stagesServicesAndHooksShareTheStateOfTheirWorldAndANewWorldStartsEmpty() {
|
||||||
|
var pack = LoadedModules.load(List.of(DiscoveredModule.builtIn(new RuinsModule())), Map.of(), Set.of(), Set.of(), Set.of());
|
||||||
|
var lifecycles = new LifecycleRunner(pack.catalog());
|
||||||
|
ObjectsAt objects = pack.catalog().services(ObjectsAt.class).getFirst();
|
||||||
|
|
||||||
|
try (var world = new TestWorld()) {
|
||||||
|
lifecycles.worldStarted(world);
|
||||||
|
var startedWith = RuinsModule.planted(world);
|
||||||
|
assertEquals(TestContexts.SEED, startedWith.seed);
|
||||||
|
|
||||||
|
new ChunkRunner(pack.chunk()).generate(TestContexts.generation(Map.of(), ColumnSettings.NONE, null, world), TestContexts.SEED);
|
||||||
|
|
||||||
|
assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built");
|
||||||
|
assertEquals(Set.of("ruins/arch"), objects.objectsAt(world, 0, 0));
|
||||||
|
assertEquals(Set.of(), objects.objectsAt(world, 1, 0));
|
||||||
|
lifecycles.worldStopped(world);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (var reloaded = new TestWorld()) {
|
||||||
|
assertEquals(Set.of(), objects.objectsAt(reloaded, 0, 0), "a new world starts with empty state");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.volmit.host;
|
||||||
|
|
||||||
|
import com.volmit.FeatureRegistry;
|
||||||
|
import com.volmit.IrisModule;
|
||||||
|
import com.volmit.ModuleInfo;
|
||||||
|
import com.volmit.ModuleLifecycle;
|
||||||
|
import com.volmit.config.PackSettings;
|
||||||
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.stage.StageGraph;
|
||||||
|
import com.volmit.support.EmptyResources;
|
||||||
|
import com.volmit.support.TestWorld;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class LifecycleRunnerTest {
|
||||||
|
/** A module whose hooks record themselves into {@code calls} and throw on the named hook. */
|
||||||
|
private static IrisModule module(String id, List<String> calls, String failingHook) {
|
||||||
|
return new IrisModule() {
|
||||||
|
public ModuleInfo info() { return ModuleInfo.of(id, "Lifecycle " + id, "1"); }
|
||||||
|
public void install(StageGraph graph) {}
|
||||||
|
public void register(FeatureRegistry registry) {
|
||||||
|
registry.registerLifecycle(new ModuleLifecycle() {
|
||||||
|
public void packLoaded(PackResources resources, PackSettings settings) { record("loaded"); }
|
||||||
|
public void worldStarted(PackWorld world) { record("started"); }
|
||||||
|
public void worldStopped(PackWorld world) { record("stopped"); }
|
||||||
|
|
||||||
|
private void record(String hook) {
|
||||||
|
calls.add(hook + " " + id);
|
||||||
|
if (hook.equals(failingHook)) {
|
||||||
|
throw new IllegalStateException(id + " cannot be " + hook);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LifecycleRunner runner(IrisModule... modules) {
|
||||||
|
var discovered = Arrays.stream(modules).map(DiscoveredModule::builtIn).toList();
|
||||||
|
return new LifecycleRunner(LoadedModules.load(discovered, Map.of(), Set.of(), Set.of(), Set.of()).catalog());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void startsInModuleIdOrderAndStopsInReverse() {
|
||||||
|
var calls = new ArrayList<String>();
|
||||||
|
var runner = runner(module("test:zeta", calls, null), module("test:alpha", calls, null));
|
||||||
|
try (var world = new TestWorld()) {
|
||||||
|
runner.worldStarted(world);
|
||||||
|
runner.worldStopped(world);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(List.of("started test:alpha", "started test:zeta", "stopped test:zeta", "stopped test:alpha"), calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aFailedStartStopsTheModulesThatStartedAndNamesTheModule() {
|
||||||
|
var calls = new ArrayList<String>();
|
||||||
|
var runner = runner(module("test:alpha", calls, null), module("test:beta", calls, "started"), module("test:gamma", calls, null));
|
||||||
|
try (var world = new TestWorld()) {
|
||||||
|
var failure = assertThrows(IllegalStateException.class, () -> runner.worldStarted(world));
|
||||||
|
assertTrue(failure.getMessage().startsWith("Module test:beta from host classpath failed while starting a world"),
|
||||||
|
failure.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(List.of("started test:alpha", "started test:beta", "stopped test:alpha"), calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void everyModuleStopsEvenWhenOneFailsAndEveryFailureIsReported() {
|
||||||
|
var calls = new ArrayList<String>();
|
||||||
|
var runner = runner(module("test:alpha", calls, "stopped"), module("test:beta", calls, null), module("test:gamma", calls, "stopped"));
|
||||||
|
try (var world = new TestWorld()) {
|
||||||
|
var failure = assertThrows(IllegalStateException.class, () -> runner.worldStopped(world));
|
||||||
|
assertTrue(failure.getMessage().startsWith("Module test:gamma from host classpath failed while stopping a world"),
|
||||||
|
failure.getMessage());
|
||||||
|
assertEquals(1, failure.getSuppressed().length);
|
||||||
|
assertTrue(failure.getSuppressed()[0].getMessage().startsWith("Module test:alpha"));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(List.of("stopped test:gamma", "stopped test:beta", "stopped test:alpha"), calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aFailedPackLoadNamesTheModuleAndSkipsTheRest() {
|
||||||
|
var calls = new ArrayList<String>();
|
||||||
|
var runner = runner(module("test:alpha", calls, "loaded"), module("test:beta", calls, null));
|
||||||
|
PackResources resources = new EmptyResources();
|
||||||
|
|
||||||
|
var failure = assertThrows(IllegalStateException.class, () -> runner.packLoaded(resources, new TestWorld().settings()));
|
||||||
|
|
||||||
|
assertTrue(failure.getMessage().startsWith("Module test:alpha from host classpath failed while loading pack test:pack"),
|
||||||
|
failure.getMessage());
|
||||||
|
assertEquals(List.of("loaded test:alpha"), calls);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import com.volmit.*;
|
|||||||
import com.volmit.config.Feature;
|
import com.volmit.config.Feature;
|
||||||
import com.volmit.mantle.*;
|
import com.volmit.mantle.*;
|
||||||
import com.volmit.resource.ResourceKind;
|
import com.volmit.resource.ResourceKind;
|
||||||
|
import com.volmit.service.Providers;
|
||||||
|
import com.volmit.service.Service;
|
||||||
import com.volmit.validation.Validator;
|
import com.volmit.validation.Validator;
|
||||||
import com.volmit.stage.PlacementStage;
|
import com.volmit.stage.PlacementStage;
|
||||||
import com.volmit.stage.Stage;
|
import com.volmit.stage.Stage;
|
||||||
@@ -13,6 +15,7 @@ import java.io.DataInput;
|
|||||||
import java.io.DataOutput;
|
import java.io.DataOutput;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
@@ -248,6 +251,82 @@ class ModuleRegistryTest {
|
|||||||
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}), "registration has ended");
|
assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}), "registration has ended");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Service(Providers.ALL)
|
||||||
|
interface Greeting { String greet(); }
|
||||||
|
@Service(Providers.ONE)
|
||||||
|
interface Clock { long now(); }
|
||||||
|
interface NotAService { void run(); }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void lifecyclesAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() {
|
||||||
|
var registry = new ModuleRegistry();
|
||||||
|
ModuleLifecycle first = new ModuleLifecycle() {};
|
||||||
|
ModuleLifecycle second = new ModuleLifecycle() {};
|
||||||
|
ModuleLifecycle other = new ModuleLifecycle() {};
|
||||||
|
registerAs(registry, "test:zeta", hooks -> hooks.registerLifecycle(other));
|
||||||
|
registerAs(registry, "test:alpha", hooks -> {
|
||||||
|
hooks.registerLifecycle(first);
|
||||||
|
hooks.registerLifecycle(second);
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, () -> registry.registerLifecycle(new ModuleLifecycle() {}),
|
||||||
|
"registration outside IrisModule.register");
|
||||||
|
var catalog = registry.freeze();
|
||||||
|
assertEquals(List.of(first, second, other), catalog.lifecycles().stream().map(LifecycleRegistration::lifecycle).toList());
|
||||||
|
assertEquals("test:alpha", catalog.lifecycles().getFirst().module().info().id().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void serviceProvidersComeInModuleIdOrderAndEachModulesInRegistrationOrder() {
|
||||||
|
var registry = new ModuleRegistry();
|
||||||
|
Greeting zeta = () -> "zeta";
|
||||||
|
Greeting alphaFirst = () -> "alpha 1";
|
||||||
|
Greeting alphaSecond = () -> "alpha 2";
|
||||||
|
registerAs(registry, "test:zeta", services -> services.registerService(Greeting.class, zeta));
|
||||||
|
registerAs(registry, "test:alpha", services -> {
|
||||||
|
services.registerService(Greeting.class, alphaFirst);
|
||||||
|
services.registerService(Greeting.class, alphaSecond);
|
||||||
|
});
|
||||||
|
|
||||||
|
var catalog = registry.freeze();
|
||||||
|
assertEquals(List.of(alphaFirst, alphaSecond, zeta), catalog.services(Greeting.class));
|
||||||
|
assertEquals(List.of(), catalog.services(Clock.class), "a service nobody provides has no providers");
|
||||||
|
assertEquals(Optional.empty(), catalog.service(Clock.class));
|
||||||
|
var several = assertThrows(IllegalArgumentException.class, () -> catalog.service(Greeting.class));
|
||||||
|
assertTrue(several.getMessage().contains("services(...)"), several.getMessage());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> catalog.services(NotAService.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aServiceWithOneProviderFailsTheLoadWhenASecondModuleProvidesIt() {
|
||||||
|
var registry = new ModuleRegistry();
|
||||||
|
Clock clock = () -> 1L;
|
||||||
|
registerAs(registry, "test:alpha", services -> services.registerService(Clock.class, clock));
|
||||||
|
registerAs(registry, "test:zeta", services -> {
|
||||||
|
var duplicate = assertThrows(IllegalArgumentException.class, () -> services.registerService(Clock.class, () -> 2L));
|
||||||
|
assertTrue(duplicate.getMessage().contains("test:alpha from host classpath"), duplicate.getMessage());
|
||||||
|
assertTrue(duplicate.getMessage().contains("test:zeta from host classpath"), duplicate.getMessage());
|
||||||
|
});
|
||||||
|
|
||||||
|
assertEquals(Optional.of(clock), registry.freeze().service(Clock.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"}) // A raw class lets a provider of the wrong type reach the check.
|
||||||
|
void servicesMustBeMarkedInterfacesThatTheProviderImplements() {
|
||||||
|
var registry = new ModuleRegistry();
|
||||||
|
registerAs(registry, "test:alpha", services -> {
|
||||||
|
var unmarked = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> services.registerService(NotAService.class, () -> {}));
|
||||||
|
assertTrue(unmarked.getMessage().contains("@" + Service.class.getName()), unmarked.getMessage());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> services.registerService(Object.class, new Object()));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> services.registerService((Class) Greeting.class, (Clock) () -> 1L));
|
||||||
|
assertThrows(NullPointerException.class, () -> services.registerService(Greeting.class, null));
|
||||||
|
});
|
||||||
|
assertThrows(IllegalStateException.class, () -> registry.registerService(Greeting.class, () -> "outside"));
|
||||||
|
assertEquals(List.of(), registry.freeze().services(Greeting.class));
|
||||||
|
}
|
||||||
|
|
||||||
private static MantleCodec<String> codec(int version) {
|
private static MantleCodec<String> codec(int version) {
|
||||||
return new MantleCodec<>() {
|
return new MantleCodec<>() {
|
||||||
public int version() { return version; }
|
public int version() { return version; }
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package com.volmit.host;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class WorldStatesTest {
|
||||||
|
static final class Cache {}
|
||||||
|
static final class Index {
|
||||||
|
final Cache cache;
|
||||||
|
Index(Cache cache) { this.cache = cache; }
|
||||||
|
}
|
||||||
|
static final class Loop {}
|
||||||
|
static final class Other {}
|
||||||
|
|
||||||
|
record Closing(String name, List<String> closed, boolean fails) implements AutoCloseable {
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
closed.add(name);
|
||||||
|
if (fails) {
|
||||||
|
throw new IllegalStateException(name + " broke");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static final class ClosingA {}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createsEachTypeOnceAndHandsEveryCallerTheSameInstance() {
|
||||||
|
var states = new WorldStates();
|
||||||
|
var created = new AtomicInteger();
|
||||||
|
Cache first = states.state(Cache.class, () -> {
|
||||||
|
created.incrementAndGet();
|
||||||
|
return new Cache();
|
||||||
|
});
|
||||||
|
Cache second = states.state(Cache.class, () -> {
|
||||||
|
created.incrementAndGet();
|
||||||
|
return new Cache();
|
||||||
|
});
|
||||||
|
|
||||||
|
assertSame(first, second);
|
||||||
|
assertEquals(1, created.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void racingThreadsShareOneCreation() throws Exception {
|
||||||
|
var states = new WorldStates();
|
||||||
|
var created = new AtomicInteger();
|
||||||
|
var start = new CountDownLatch(1);
|
||||||
|
var threads = 8;
|
||||||
|
try (var executor = Executors.newFixedThreadPool(threads)) {
|
||||||
|
var results = new ArrayList<Future<Cache>>();
|
||||||
|
for (int thread = 0; thread < threads; thread++) {
|
||||||
|
results.add(executor.submit(() -> {
|
||||||
|
start.await();
|
||||||
|
return states.state(Cache.class, () -> {
|
||||||
|
created.incrementAndGet();
|
||||||
|
return new Cache();
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
start.countDown();
|
||||||
|
Cache shared = results.getFirst().get(10, TimeUnit.SECONDS);
|
||||||
|
for (var result : results) {
|
||||||
|
assertSame(shared, result.get(10, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(1, created.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aFactoryMayAskForOtherStateButNotForItself() {
|
||||||
|
var states = new WorldStates();
|
||||||
|
Index index = states.state(Index.class, () -> new Index(states.state(Cache.class, Cache::new)));
|
||||||
|
assertSame(index.cache, states.state(Cache.class, Cache::new));
|
||||||
|
|
||||||
|
var loop = assertThrows(IllegalStateException.class, () -> states.state(Loop.class, () -> {
|
||||||
|
states.state(Other.class, () -> {
|
||||||
|
states.state(Loop.class, Loop::new);
|
||||||
|
return new Other();
|
||||||
|
});
|
||||||
|
return new Loop();
|
||||||
|
}));
|
||||||
|
assertTrue(loop.getMessage().contains(Loop.class.getName() + " -> " + Other.class.getName() + " -> " + Loop.class.getName()),
|
||||||
|
loop.getMessage());
|
||||||
|
assertNotNull(states.state(Loop.class, Loop::new), "a failed creation keeps nothing, so the next call creates it");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void aFactoryThatFailsOrReturnsNullKeepsNothing() {
|
||||||
|
var states = new WorldStates();
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> states.state(Cache.class, () -> {
|
||||||
|
throw new IllegalArgumentException("not yet");
|
||||||
|
}));
|
||||||
|
var nothing = assertThrows(NullPointerException.class, () -> states.state(Cache.class, () -> null));
|
||||||
|
assertTrue(nothing.getMessage().contains(Cache.class.getName()), nothing.getMessage());
|
||||||
|
|
||||||
|
var cache = new Cache();
|
||||||
|
assertSame(cache, states.state(Cache.class, () -> cache));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void closingClosesEveryCloseableStateNewestFirstAndEndsTheStore() {
|
||||||
|
var states = new WorldStates();
|
||||||
|
var closed = new ArrayList<String>();
|
||||||
|
states.state(Closing.class, () -> new Closing("first", closed, false));
|
||||||
|
states.state(Cache.class, Cache::new);
|
||||||
|
states.state(ClosingA.class, ClosingA::new);
|
||||||
|
states.state(AutoCloseable.class, () -> () -> closed.add("second"));
|
||||||
|
|
||||||
|
states.close();
|
||||||
|
states.close();
|
||||||
|
|
||||||
|
assertEquals(List.of("second", "first"), closed);
|
||||||
|
var after = assertThrows(IllegalStateException.class, () -> states.state(Cache.class, Cache::new));
|
||||||
|
assertTrue(after.getMessage().contains("after the world stopped"), after.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void closingContinuesPastAFailureAndReportsEveryOne() {
|
||||||
|
var states = new WorldStates();
|
||||||
|
var closed = new ArrayList<String>();
|
||||||
|
states.state(Closing.class, () -> new Closing("first", closed, true));
|
||||||
|
states.state(AutoCloseable.class, () -> new Closing("second", closed, true));
|
||||||
|
|
||||||
|
var failure = assertThrows(IllegalStateException.class, states::close);
|
||||||
|
|
||||||
|
assertEquals(List.of("second", "first"), closed);
|
||||||
|
assertTrue(failure.getMessage().contains("second broke"), failure.getMessage());
|
||||||
|
assertEquals(1, failure.getSuppressed().length);
|
||||||
|
assertTrue(failure.getSuppressed()[0].getMessage().contains("first broke"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.volmit.support;
|
||||||
|
|
||||||
|
import com.volmit.block.BlockRegistry;
|
||||||
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.resource.ResourceId;
|
||||||
|
import com.volmit.resource.ResourceKey;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/** A pack {@code test:pack} without resources. */
|
||||||
|
public final class EmptyResources implements PackResources {
|
||||||
|
private final UUID snapshot = UUID.randomUUID();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResourceId packId() {
|
||||||
|
return new ResourceId("test", "pack");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UUID snapshotId() {
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BlockRegistry blocks() {
|
||||||
|
throw new AssertionError("Unused blocks");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> Optional<T> find(ResourceKey<T> key) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<ResourceId> ids(Class<?> type) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import com.volmit.placement.PlacementContext;
|
|||||||
import com.volmit.resource.PackResources;
|
import com.volmit.resource.PackResources;
|
||||||
import com.volmit.world.TerrainSampler;
|
import com.volmit.world.TerrainSampler;
|
||||||
import com.volmit.world.BlockView;
|
import com.volmit.world.BlockView;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/** Tests needing no platform facilities fail loudly if code starts using one. */
|
/** Tests needing no platform facilities fail loudly if code starts using one. */
|
||||||
@@ -24,11 +25,17 @@ public final class TestContexts {
|
|||||||
|
|
||||||
/** The chunk at the origin; a null {@code settings} or {@code mantle} fails when used. */
|
/** The chunk at the origin; a null {@code settings} or {@code mantle} fails when used. */
|
||||||
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks, FeatureSettings settings, Mantle mantle) {
|
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks, FeatureSettings settings, Mantle mantle) {
|
||||||
|
return generation(hunks, settings, mantle, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The chunk at the origin in {@code world}; a null {@code settings}, {@code mantle} or {@code world} fails when used. */
|
||||||
|
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks, FeatureSettings settings, Mantle mantle, PackWorld world) {
|
||||||
return new GenerationContext() {
|
return new GenerationContext() {
|
||||||
public int originX() { return 0; }
|
public int originX() { return 0; }
|
||||||
public int originZ() { return 0; }
|
public int originZ() { return 0; }
|
||||||
public long worldSeed() { return SEED; }
|
public long worldSeed() { return SEED; }
|
||||||
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
||||||
|
public PackWorld world() { return used(world, "world"); }
|
||||||
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
||||||
public FeatureSettings settings() { return used(settings, "settings"); }
|
public FeatureSettings settings() { return used(settings, "settings"); }
|
||||||
public Mantle mantle() { return used(mantle, "mantle"); }
|
public Mantle mantle() { return used(mantle, "mantle"); }
|
||||||
@@ -48,6 +55,7 @@ public final class TestContexts {
|
|||||||
public int originZ() { return originZ; }
|
public int originZ() { return originZ; }
|
||||||
public long worldSeed() { return SEED; }
|
public long worldSeed() { return SEED; }
|
||||||
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
||||||
|
public PackWorld world() { throw new AssertionError("Unused world"); }
|
||||||
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
||||||
public FeatureSettings settings() { return settings; }
|
public FeatureSettings settings() { return settings; }
|
||||||
public Mantle mantle() { return mantle; }
|
public Mantle mantle() { return mantle; }
|
||||||
@@ -62,6 +70,7 @@ public final class TestContexts {
|
|||||||
return new PlacementContext() {
|
return new PlacementContext() {
|
||||||
public long worldSeed() { return SEED; }
|
public long worldSeed() { return SEED; }
|
||||||
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
public PackResources resources() { throw new AssertionError("Unused resources"); }
|
||||||
|
public PackWorld world() { throw new AssertionError("Unused world"); }
|
||||||
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
|
||||||
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
|
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
|
||||||
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
|
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.volmit.support;
|
||||||
|
|
||||||
|
import com.volmit.IrisFeature;
|
||||||
|
import com.volmit.config.FeatureSettings.Entry;
|
||||||
|
import com.volmit.config.PackSettings;
|
||||||
|
import com.volmit.host.WorldStates;
|
||||||
|
import com.volmit.resource.PackResources;
|
||||||
|
import com.volmit.world.PackWorld;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
/** A world for tests: the test seed, no resources, no declared settings, and a real state store. */
|
||||||
|
public final class TestWorld implements PackWorld, AutoCloseable {
|
||||||
|
private final WorldStates states = new WorldStates();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long seed() {
|
||||||
|
return TestContexts.SEED;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PackResources resources() {
|
||||||
|
throw new AssertionError("Unused resources");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PackSettings settings() {
|
||||||
|
return new PackSettings() {
|
||||||
|
public <F extends IrisFeature> List<Entry<F>> declared(Class<F> featureType) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
|
||||||
|
return states.state(type, () -> create.apply(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
states.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user