Batch 4 of the API review: api and host artifacts, ModuleLoadException

- Split into Gradle subprojects api (com.volmit:iris-api) and host
  (com.volmit:iris-host). ExposedPackages never exposes com.volmit.host.
- One unchecked ModuleLoadException(moduleId, origin, message, cause)
  for every load error; messages unchanged.
- PlacementAccess.set(x, y, z, state) next to set(PlacedBlock).
- BlockState: precompiled patterns, withProperty copies once.
- Mantle and layer views are made once per invocation.
- Hunk getters are width(), height(), depth().
- Held types and host types are deprecated for removal at the cut-over.
- Docs: artifacts, one-or-more modules per jar, no option shorthand.
This commit is contained in:
piexel committed 2026-10-24 04:19:39 +02:00
1 parent 3a307b5b8e
commit b6c2992752
309 files changed
+547 -178

No files matched your search

@@ -0,0 +1,67 @@
package com.volmit;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.ObjectGeneratorFactory;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Service;
import com.volmit.stage.StageGraph;
import com.volmit.validation.Validator;
/** Host implementation collects non-stage registrations before loading pack configuration.
* Feature IDs must be unique. JSON keys must be unique per {@link com.volmit.config.Level}, including the
* settings types stages name in {@code when(...)}. Feature IDs, mantle keys and resource kind ids a module
* registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}.
*/
public interface FeatureRegistry {
/** Registers a layer before pack loading. Null arguments throw NullPointerException;
* duplicate IDs and negative codec versions throw IllegalArgumentException.
* Only the owner registers a shared layer; consumers refer to its key. The host must
* preserve unknown persisted layers or fail explicitly, never silently discard them.
* GENERATION layers also require codecs.
*/
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec);
<F extends IrisFeature> void registerObject(Class<F> featureType, ObjectGeneratorFactory<F> factory);
/** Catalogs settings types that no stage names in {@code when(...)}, such as ones read only
* through {@link com.volmit.config.FeatureSettings#at}, so the host decodes them and studio
* describes them: {@code registerSettings(WindSettings.class, GustSettings.class)}. Settings that a
* stage names are catalogued without this; registering them as well changes nothing. Each type's
* feature id must be this module's id or start with it and {@code /}. Once registered, other
* modules may name the types in {@code when(...)} (see {@link StageGraph}).
*/
void registerSettings(Class<? extends IrisFeature>... settingsTypes);
/** Describes a class that Iris's own classes hold, such as the clamp of an object placement, so studio shows
* its fields as this class declares them. The class must be one the host loads: a built-in module's class, or a
* class of a package the host exposes to pack modules (a pack module's own classes could never be a field of
* one of the host's classes, so registering one fails the load). The host reads the class
* with its fields in pack JSON, and the class follows the rules of settings classes. Registering a class twice
* changes nothing.
*
* @deprecated Transitional, until the cut-over: only while Iris's own classes still hold built-in module types.
* Removed once they do not.
*/
@Deprecated(forRemoval = true)
void registerHeldType(Class<?> type);
/** Declares a kind of pack resource this module reads: the JSON files under the kind's folder, served through
* {@link com.volmit.resource.PackResources} by the kind's type and described for studio from its class like
* settings. The pack load fails when another kind has the same id, type or folder, or the folder is one the
* host reads itself; the error names both owners.
*/
<T> void registerResourceKind(ResourceKind<T> kind);
/** Adds a check the host runs over the whole pack wherever it validates packs. */
void registerValidator(Validator validator);
/** Adds hooks the host calls when it loads the pack and starts or stops a world with it. */
void registerLifecycle(ModuleLifecycle lifecycle);
/** Provides {@code service}, an interface marked {@link Service}, with {@code provider}. A service whose providers
* are {@link com.volmit.service.Providers#ONE} fails the pack load when a second module provides it, naming both.
*/
<S> void registerService(Class<S> service, S provider);
}
@@ -0,0 +1,6 @@
package com.volmit;
/** A configured feature instance. @Feature declares identity and attachment;
* annotated fields define settings. Each configuration occurrence is decoded separately.
*/
public interface IrisFeature {}
@@ -0,0 +1,18 @@
package com.volmit;
/** A unit of world-generation behavior. The core engine is an ordinary module too.
*
* <p>In a pack's module jar this class is the entry point. The jar names it in
* {@code META-INF/services/com.volmit.IrisModule}, one entry class per line, and it needs a public no-argument
* constructor. A jar holds one or more modules.
*/
public interface IrisModule {
ModuleInfo info();
/** Defines this module's stages and registers its other contributions (geometry generators, mantle layers,
* settings no stage names, pack resource kinds, validators, lifecycle hooks and services), before settings are
* decoded or generation starts. Called once per pack load, in any order relative to other modules; stage bodies
* must not capture per-invocation state.
*/
void setup(ModuleSetup setup);
}
@@ -0,0 +1,97 @@
package com.volmit;
import com.volmit.resource.ResourceId;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/** Module identity. Every stage a module defines has an id that starts with the module id and
* {@code /}, such as {@code iris:stilt/fill} for module {@code iris:stilt}, so a module id has no
* {@code /} of its own: {@code iris:stilt/extra} would own stages under {@code iris:stilt}'s path.
* Settings ids, object feature ids and mantle keys the module owns are its id or start with it and
* {@code /}, such as {@code iris:stilt} or {@code iris:stilt/depth}. The name is for
* people, for example in load logs; the id is what the host and other modules match on. Name and
* version must fit on one log line, so they reject control characters such as line breaks.
*
* <p>Optional packages are packages, with their subpackages, whose classes the module's jar uses
* but expects may be absent at runtime, typically optional integrations of a library it bundles.
* The pack load does not warn about missing classes in them. They never excuse a class that Iris
* hides from modules or one missing from a package Iris exposes; those still fail the load.
*/
public record ModuleInfo(ResourceId id, String name, String version, List<PackageName> optionalPackages) {
private static final String STAGE_SEPARATOR = "/";
public ModuleInfo {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(version, "version");
requireSingleSegment(id);
requireOneLineText(id, "name", name);
requireOneLineText(id, "version", version);
optionalPackages = List.copyOf(optionalPackages);
}
public static ModuleInfo of(String id, String name, String version) {
return new ModuleInfo(ResourceId.parse(id), name, version, List.of());
}
/** This identity with {@code packages} as its optional packages, replacing any declared before.
* A trailing dot is accepted; anything that is not a package name, such as a wildcard, is rejected.
*/
public ModuleInfo withOptionalPackages(String... packages) {
var parsed = Arrays.stream(packages).map(this::requireOptionalPackage).toList();
return new ModuleInfo(id, name, version, parsed);
}
private PackageName requireOptionalPackage(String packageName) {
Objects.requireNonNull(packageName, "optional package");
return PackageName.tryParse(packageName).orElseThrow(() -> new IllegalArgumentException("Optional package '"
+ packageName + "' of module " + id + " is not a package name; name a package such as org.slf4j,"
+ " which covers that package and its subpackages"));
}
/** Whether {@code stageId} may name a stage of this module: it starts with this module's id and '/'. */
public boolean ownsStage(ResourceId stageId) {
return stageId.namespace().equals(id.namespace()) && stageId.path().startsWith(childPathPrefix());
}
/** Whether {@code featureId} may name settings, an object generator or a mantle layer of this
* module: it is this module's id or starts with it and '/'.
*/
public boolean ownsId(ResourceId featureId) {
return featureId.equals(id) || ownsStage(featureId);
}
/** What every stage id of this module, and every other id below it, starts with, such as {@code iris:stilt/}. */
public String idPrefix() {
return id.namespace() + ":" + childPathPrefix();
}
private String childPathPrefix() {
return id.path() + STAGE_SEPARATOR;
}
private static void requireSingleSegment(ResourceId id) {
if (!id.path().contains(STAGE_SEPARATOR)) return;
throw new IllegalArgumentException("Module id " + id + " must not contain '" + STAGE_SEPARATOR
+ "': stage ids are a module id, '" + STAGE_SEPARATOR + "' and a name, so " + id
+ " would name stages under another module's id");
}
private static void requireOneLineText(ResourceId id, String field, String value) {
if (value.isBlank()) {
throw new IllegalArgumentException("Blank module " + field + ": " + id);
}
if (value.chars().anyMatch(ModuleInfo::breaksLogLine)) {
throw new IllegalArgumentException("Module " + field + " of " + id
+ " contains a line break or other control character");
}
}
private static boolean breaksLogLine(int character) {
var type = Character.getType(character);
return Character.isISOControl(character)
|| type == Character.LINE_SEPARATOR
|| type == Character.PARAGRAPH_SEPARATOR;
}
}
@@ -0,0 +1,47 @@
package com.volmit;
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, then {@link #warmUp} (a slow worldStarted the host may
* run off the main thread), 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 set up and its resources can be read: {@code pack} gives the resources, every settings
* entry of every dimension, region and biome of the pack (as validators see them) and the module's log. A hook that
* throws stops the pack's worlds from starting, naming its module.
*/
default void packLoaded(PackContext pack) {}
/** {@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} started: builds the caches that make its first chunks fast, which may be slow. Runs after
* {@link #worldStarted} of every module. The host may run it off the main thread: synchronously for a server's
* worlds, in the background for studio. It waits for every module's warm-up before the world's first generation, so
* a hook that is slow delays that, not the start of the world. A world that stops before its warm-up runs may skip it.
*
* <p>Only build caches in the module's world state ({@link PackWorld#state}): nothing here may change what the world
* generates, because the module also works when the warm-up never ran. A hook that throws does not stop the world;
* the host reports the failure, naming the module, and the cache is built when first needed.
*/
default void warmUp(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) {}
}
@@ -0,0 +1,35 @@
package com.volmit;
/** The log of one module. The host labels every line with the module's id, such as {@code [iris:decorant]}, and writes it
* to its own log, so a module never needs a logging library of its own and its lines are easy to find. Each module has
* its own: reach it as {@code context.log()} in stage bodies and generators
* ({@link com.volmit.generation.InvocationContext#log}), as {@link com.volmit.world.PackWorld#log} in services and
* lifecycle hooks, and as {@link ModuleSetup#log} during the module's setup.
*
* <p>Safe to use from any thread. A message is plain text, not a format string.
*/
public interface ModuleLog {
/** Detail for people debugging the module. The host writes it only when its debug setting is on, so building the
* message costs time even when nobody reads it: guard a message that is expensive to build, or leave it out.
*/
void debug(String message);
/** Something worth telling the server owner once in a while, such as what the module did at startup. */
void info(String message);
/** Something is wrong or unusual, but the module carries on. */
void warn(String message);
/** Warns the first time {@code key} is used on this log and writes {@code message} at {@link #debug} level every
* time after, for a condition worth stating once that is met per block, per sample or per chunk. Keys belong to the
* module: two modules can use the same key and each warns once. The key space must be bounded, so never put a
* coordinate in it; the host stops claiming new keys beyond a few hundred and then only debugs.
*/
void warnOnce(String key, String message);
/** Logs {@code message} as an error and reports {@code cause} the way the host reports its own failures, such as
* to its error tracker. Use it for a failure the module caught but cannot recover from. A null {@code cause}
* only logs the message.
*/
void error(String message, Throwable cause);
}
@@ -0,0 +1,16 @@
package com.volmit;
import com.volmit.stage.StageGraph;
/** What a module gets in {@link IrisModule#setup}: the stage graph it defines its stages in, the registry for
* everything else, and its own log. Stages and registrations are accepted only while {@code setup} runs; the log
* may be kept and used later, such as from lifecycle hooks.
*/
public interface ModuleSetup {
StageGraph stages();
FeatureRegistry registry();
/** This module's log, the same one its stages and lifecycle hooks see through their world. */
ModuleLog log();
}
@@ -0,0 +1,18 @@
package com.volmit;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
/** A pack snapshot the host loaded, as {@link ModuleLifecycle#packLoaded} sees it. Do not retain it after the hook
* returns: what a module builds from it for a world belongs in that world's state.
*/
public interface PackContext {
/** The snapshot's resources. */
PackResources resources();
/** Every settings entry of every dimension, region and biome of the pack, as validators see them. */
PackSettings settings();
/** The log of the module the hook belongs to, labelled with its id. */
ModuleLog log();
}
@@ -0,0 +1,51 @@
package com.volmit;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
/** A Java package name that stands for the package and all its subpackages. Only whole package
* names match: {@code com.volmit} contains {@code com.volmit.stage.Stage} but not
* {@code com.volmitx.Fake}.
*/
public record PackageName(String name) implements Comparable<PackageName> {
private static final char SEPARATOR = '.';
private static final String SEPARATOR_PATTERN = "\\.";
public PackageName {
Objects.requireNonNull(name, "name");
if (!isPackageName(name)) throw new IllegalArgumentException("'" + name + "' is not a package name");
}
/** The package {@code name} denotes, if it is a package name. A trailing dot is accepted; blank
* names, wildcards and anything else that is not a package name give an empty result.
*/
public static Optional<PackageName> tryParse(String name) {
Objects.requireNonNull(name, "name");
var withoutTrailingDot = name.endsWith(String.valueOf(SEPARATOR)) ? name.substring(0, name.length() - 1) : name;
return isPackageName(withoutTrailingDot) ? Optional.of(new PackageName(withoutTrailingDot)) : Optional.empty();
}
/** Whether the class with this binary name is in this package or one of its subpackages. */
public boolean contains(String binaryName) {
return binaryName.startsWith(name)
&& binaryName.length() > name.length()
&& binaryName.charAt(name.length()) == SEPARATOR;
}
@Override
public String toString() { return name; }
@Override
public int compareTo(PackageName other) { return name.compareTo(other.name); }
private static boolean isPackageName(String name) {
return Arrays.stream(name.split(SEPARATOR_PATTERN, -1)).allMatch(PackageName::isIdentifier);
}
private static boolean isIdentifier(String segment) {
return !segment.isEmpty()
&& Character.isJavaIdentifierStart(segment.codePointAt(0))
&& segment.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
}
}
@@ -0,0 +1,3 @@
package com.volmit.block;
public enum BlockFace { UP, DOWN, NORTH, SOUTH, EAST, WEST }
@@ -0,0 +1,12 @@
package com.volmit.block;
import com.volmit.random.WorldRandom;
/** Resolved, immutable palette. X and Z are world coordinates, Y is the height above the
* dimension's bottom (0 = bottom); selection uses only the given stream.
* An empty/unresolvable palette is a pack-load error. Implementations must support concurrent calls.
*/
@FunctionalInterface
public interface BlockPalette {
BlockState select(int worldX, int y, int worldZ, WorldRandom random);
}
@@ -0,0 +1,54 @@
package com.volmit.block;
import com.volmit.object.BlockEntityData;
import com.volmit.resource.ResourceId;
import java.util.Optional;
/** Host adapter for resolved states and cached behavior. No native platform objects escape.
* Unknown materials, unsupported properties, and malformed states throw IllegalArgumentException.
* Methods are safe for concurrent generation calls; predicates must not read the live world.
*/
public interface BlockRegistry {
BlockState resolve(String key);
default BlockState resolve(BlockState state) { return resolve(state.key()); }
/** The state {@code spec} names, resolved the way packs expect, so it never throws for a block the platform lacks:
* a block of the pack's {@code blocks} folder with the spec's properties over its own, else the platform's block
* (a key without a namespace is {@code minecraft:}) with the spec's properties, else the backup resolved the same
* way, else air.
*/
BlockState resolve(BlockSpec spec);
/** The block entity {@code spec}'s {@code tileData} describes, in the host's format; empty when the spec has none
* or its resolved block has no block entity.
*/
Optional<BlockEntityData> blockEntity(BlockSpec spec);
/** The picker for {@code spec}: every block counts as often as its weight, and the entry at a position is chosen by
* the style's noise at (x, y, z) divided by the zoom, so the palette changes smoothly over the world; a palette of
* one block always gives it. Blocks resolve as {@link #resolve(BlockSpec)}. Seed the noise like
* {@link com.volmit.noise.NoiseFactory#sampler}: from the world seed when the palette must line up across chunks.
* The host keeps what it builds for the pack snapshot, so asking again for the same palette and seed is cheap.
*
* @throws IllegalArgumentException when no block of the palette has a weight above zero, which includes an empty list
*/
PaletteSampler palette(PaletteSpec spec, long seed);
/** The ore that suits the {@code rock} it is placed in, which the platform decides: an ore placed in deepslate is its
* deepslate variant, one placed in other rock its ordinary one. {@code ore} itself when it has no variant, and by
* default for a registry that knows none.
*/
default BlockState oreFor(BlockState rock, BlockState ore) {
return ore;
}
boolean hasTrait(BlockState state, BlockTrait trait);
boolean inTag(BlockState state, ResourceId tag);
/** Whether state can attach to the specified face of support, ignoring other neighbors. */
boolean canAttach(BlockState state, BlockState support, BlockFace face);
/** Whether {@code state} can stand on {@code below}: the support rule the host checks before it writes a
* decoration, such as a flower on grass but not on stone. Only the kinds of block count, not their properties.
*/
boolean canPlaceOn(BlockState state, BlockState below);
}
@@ -0,0 +1,121 @@
package com.volmit.block;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.Required;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/** A block as packs write it in settings, such as {@code {"block": "iron_ore"}} or
* {@code {"block": "minecraft:oak_log", "data": {"axis": "y"}, "backup": {"block": "stone"}}}. Settings hold it
* where a pack picks a block it may not be able to name exactly: a key without a namespace, a custom block of
* the pack's {@code blocks} folder, or a block that only some versions or mods have.
*
* <p>The host resolves it with {@link BlockRegistry#resolve(BlockSpec)} and its block entity with
* {@link BlockRegistry#blockEntity(BlockSpec)}. A spec is a value: the host creates it with the no-argument
* constructor and reads the JSON into it, and nothing changes it afterwards. Property values are text however the
* pack writes them, so {@code "waterlogged": true} reads as {@code "true"}.
*/
@Desc("A block, with optional properties, block entity data and a backup for platforms without it")
public final class BlockSpec {
private static final String AIR = "air";
@Required
@Ref(Reference.BLOCK)
@Desc("The block to use. A key without a namespace is a Minecraft block or a block of the pack's blocks folder.")
private String block = AIR;
@Desc("Optional properties for this block, such as 'waterlogged': true")
private Map<String, String> data = Map.of();
@MinNumber(1)
@MaxNumber(1000)
@Desc("The weight of this block in a list it is picked from. A weight of two is as if the block were in the list twice.")
private int weight = 1;
@Desc("If the block cannot be created on this platform, this block is used instead.")
private BlockSpec backup;
@Desc("Optional block entity data for this block, such as a spawner's SpawnData")
private Map<String, Object> tileData = Map.of();
private BlockSpec() {
}
private BlockSpec(String block, Map<String, String> data, int weight, BlockSpec backup, Map<String, Object> tileData) {
this.block = Objects.requireNonNull(block, "block");
this.data = Map.copyOf(data);
this.weight = weight;
this.backup = backup;
this.tileData = Collections.unmodifiableMap(new LinkedHashMap<>(tileData));
}
/** The block {@code block}, such as {@code minecraft:stone} or {@code stone}, without properties, weight 1. */
public static BlockSpec of(String block) {
return new BlockSpec(block, Map.of(), 1, null, Map.of());
}
/** This spec with the property {@code name} set to {@code value}. */
public BlockSpec withProperty(String name, String value) {
var changed = new LinkedHashMap<>(data());
changed.put(name, value);
return new BlockSpec(block, changed, weight, backup, tileData());
}
public BlockSpec withWeight(int weight) {
return new BlockSpec(block, data(), weight, backup, tileData());
}
public BlockSpec withBackup(BlockSpec backup) {
return new BlockSpec(block, data(), weight, backup, tileData());
}
public BlockSpec withTileData(Map<String, Object> tileData) {
return new BlockSpec(block, data(), weight, backup, tileData);
}
/** The block key as the pack wrote it. */
public String block() {
return block == null ? AIR : block;
}
/** The properties as the pack wrote them, as text. */
public Map<String, String> data() {
return data == null ? Map.of() : Collections.unmodifiableMap(data);
}
public int weight() {
return weight;
}
public Optional<BlockSpec> backup() {
return Optional.ofNullable(backup);
}
/** The block entity data as the pack wrote it: JSON objects as maps, arrays as lists, numbers as {@code Double}. */
public Map<String, Object> tileData() {
return tileData == null ? Map.of() : Collections.unmodifiableMap(tileData);
}
@Override
public boolean equals(Object other) {
return other instanceof BlockSpec spec && block().equals(spec.block()) && data().equals(spec.data())
&& weight == spec.weight && Objects.equals(backup, spec.backup) && tileData().equals(spec.tileData());
}
@Override
public int hashCode() {
return Objects.hash(block(), data(), weight, backup, tileData());
}
@Override
public String toString() {
return "BlockSpec[" + block() + (data().isEmpty() ? "" : " " + data()) + "]";
}
}
@@ -0,0 +1,107 @@
package com.volmit.block;
import com.volmit.resource.ResourceId;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/** Immutable, platform-neutral block description with value equality.
* Construction validates syntax, not platform availability or valid material properties.
* Resolve through BlockRegistry before writing. Custom-content IDs are allowed.
*/
public record BlockState(ResourceId material, Map<String, String> properties) {
private static final String PROPERTIES_START = "[";
private static final String PROPERTIES_END = "]";
private static final String PROPERTY_SEPARATOR = ",";
private static final Pattern PROPERTY_NAME = Pattern.compile("[a-z0-9_]+");
private static final Pattern PROPERTY_VALUE = Pattern.compile("[a-z0-9_.-]+");
public BlockState {
Objects.requireNonNull(material, "material");
if (!(properties instanceof CheckedProperties)) {
var copy = new TreeMap<String, String>();
properties.forEach((name, value) -> copy.put(requireValid(name, value), value));
properties = new CheckedProperties(copy);
}
}
public BlockState(String material) { this(ResourceId.parse(material), Map.of()); }
/** Reads what {@link #key()} writes: {@code minecraft:oak_log} or {@code minecraft:oak_log[axis=y]}. */
public static BlockState parse(String key) {
Objects.requireNonNull(key, "key");
int open = key.indexOf(PROPERTIES_START);
if (open < 0) return new BlockState(key);
if (!key.endsWith(PROPERTIES_END)) throw new IllegalArgumentException("Unclosed block properties: " + key);
var properties = new TreeMap<String, String>();
var list = key.substring(open + 1, key.length() - 1);
for (var property : list.isEmpty() ? new String[0] : list.split(PROPERTY_SEPARATOR, -1)) {
int equals = property.indexOf('=');
if (equals < 0) throw new IllegalArgumentException("Block property without value: " + property + " in " + key);
if (properties.put(property.substring(0, equals), property.substring(equals + 1)) != null) {
throw new IllegalArgumentException("Block property set twice: " + property + " in " + key);
}
}
return new BlockState(ResourceId.parse(key.substring(0, open)), properties);
}
/** This state with {@code name} set to {@code value}. Copies the properties once and checks only the new one. */
public BlockState withProperty(String name, String value) {
var changed = new TreeMap<>(properties);
changed.put(requireValid(name, value), value);
return new BlockState(material, new CheckedProperties(changed));
}
/** Stable representation with properties in lexical order. */
public String key() {
if (properties.isEmpty()) return material.toString();
return material + properties.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining(PROPERTY_SEPARATOR, PROPERTIES_START, PROPERTIES_END));
}
/** Returns {@code name} once it and {@code value} are a valid property. */
private static String requireValid(String name, String value) {
if (name == null || value == null) throw new NullPointerException("Block property");
if (!PROPERTY_NAME.matcher(name).matches() || !PROPERTY_VALUE.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid block property: " + name + "=" + value);
}
return name;
}
/** Validated properties in key order that nobody can change. Only this class makes them, so the constructor takes
* them as they are instead of checking and copying them again.
*/
private static final class CheckedProperties extends AbstractMap<String, String> {
private final Map<String, String> sorted;
private CheckedProperties(TreeMap<String, String> sorted) {
this.sorted = Collections.unmodifiableMap(sorted);
}
@Override
public Set<Entry<String, String>> entrySet() {
return sorted.entrySet();
}
@Override
public String get(Object key) {
return sorted.get(key);
}
@Override
public boolean containsKey(Object key) {
return sorted.containsKey(key);
}
@Override
public int size() {
return sorted.size();
}
}
}
@@ -0,0 +1,9 @@
package com.volmit.block;
/** Host-defined block behavior; tags provide extensible material groups. {@code VINE} is a block that hangs from or
* clings to the faces around it, such as vines and glow lichen.
*/
public enum BlockTrait {
AIR, SOLID, OCCLUDING, FLUID, WATER, GRAVITY, FOLIAGE, DECORATION, VINE,
LOG, LEAVES, ORE, INVENTORY, BLOCK_ENTITY, CUSTOM, NEEDS_UPDATE
}
@@ -0,0 +1,10 @@
package com.volmit.block;
/** The block a {@link PaletteSpec} picks at a position, built by the host ({@link BlockRegistry#palette}). The
* coordinates are the noise's input and follow the API's coordinate rule: world X and Z, and Y as the height above the
* dimension's bottom (0 = bottom block). The same position always gives the same block. Safe for concurrent calls.
*/
@FunctionalInterface
public interface PaletteSampler {
BlockState at(double x, double y, double z);
}
@@ -0,0 +1,94 @@
package com.volmit.block;
import com.volmit.config.Desc;
import com.volmit.config.MinItems;
import com.volmit.config.MinNumber;
import com.volmit.config.Required;
import com.volmit.config.Snippet;
import com.volmit.noise.NoiseStyle;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/** A palette of blocks as packs write it in settings, such as
* {@code {"style": "SIMPLEX", "zoom": 8, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}]}}, or a
* snippet under {@code snippet/palette/}. The blocks are picked by noise: the host picks the entry the style's noise
* at the position over {@code zoom} selects, each block counting {@link BlockSpec#weight() weight} times.
*
* <p>A palette is a description, not a picker: the host builds the picker
* ({@link BlockRegistry#palette(PaletteSpec, long)}). It is a value the host creates with the no-argument
* constructor and reads the JSON into; nothing changes it afterwards.
*/
@Snippet("palette")
@Desc("A palette of materials")
public final class PaletteSpec {
private static final String DEFAULT_STYLE = "STATIC";
private static final double DEFAULT_ZOOM = 5;
private static final String DEFAULT_BLOCK = "stone";
@Desc("The style of noise")
private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE);
@MinNumber(0.0001)
@Desc("The terrain zoom mostly for zooming in on a wispy palette")
private double zoom = DEFAULT_ZOOM;
@Required
@MinItems(1)
@Desc("The palette of blocks to be used in this layer")
private List<BlockSpec> palette = List.of(BlockSpec.of(DEFAULT_BLOCK));
private PaletteSpec() {
}
private PaletteSpec(NoiseStyle style, double zoom, List<BlockSpec> palette) {
this.style = Objects.requireNonNull(style, "style");
this.zoom = zoom;
this.palette = List.copyOf(palette);
}
/** A palette of {@code blocks} with the default style and zoom. */
public static PaletteSpec of(List<BlockSpec> blocks) {
return new PaletteSpec(NoiseStyle.of(DEFAULT_STYLE), DEFAULT_ZOOM, blocks);
}
public PaletteSpec withStyle(NoiseStyle style) {
return new PaletteSpec(style, zoom, palette());
}
/** This palette with zoom {@code zoom}: above 1 stretches the noise that picks the blocks, below 1 squeezes it. */
public PaletteSpec withZoom(double zoom) {
return new PaletteSpec(style(), zoom, palette());
}
/** The noise that picks the blocks; the default {@code STATIC} style where the pack wrote none. */
public NoiseStyle style() {
return style == null ? NoiseStyle.of(DEFAULT_STYLE) : style;
}
/** The factor the position is divided by before it is looked up in the noise. */
public double zoom() {
return zoom;
}
/** The blocks to pick from, as the pack wrote them. */
public List<BlockSpec> palette() {
return palette == null ? List.of() : Collections.unmodifiableList(palette);
}
@Override
public boolean equals(Object other) {
return other instanceof PaletteSpec spec && style().equals(spec.style())
&& Double.compare(zoom, spec.zoom) == 0 && palette().equals(spec.palette());
}
@Override
public int hashCode() {
return Objects.hash(style(), zoom, palette());
}
@Override
public String toString() {
return "PaletteSpec[" + palette() + ", " + style() + ", zoom " + zoom + "]";
}
}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Human-readable documentation for a settings type or field. */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface Desc {
String value();
}
@@ -0,0 +1,28 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Identity and JSON attachment for an IrisFeature configuration class. The {@code id}, such as
* {@code "example:moss"}, is the feature's identity in the stage graph, logs and lookups by class. Packs write
* the settings under the short {@code key}, such as {@code "moss": {...}}, at each of the targets, the {@link Level}s
* of a pack's dimension, region, biome or object placement files.
*
* <p>The key is a plain JSON field name: not blank, no ':'. It is unique per target across all loaded modules
* and the JSON fields the host itself uses at that target, so it must not be a field of a biome, region or
* dimension; a clash refuses the pack load, naming both claimants.
*
* <p>The JSON under the key is an object of the class's options, unless {@code root} names an option. Then the
* key holds exactly that option's value, such as a list, and an object is not accepted: with
* {@code @Feature(id = "iris:deposit", key = "deposits", root = "generators", ...)} a pack writes
* {@code "deposits": [...]}. The class has no other option then, since nothing could set it.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Feature {
String id();
String name();
String key();
String root() default "";
/** The levels packs may write the settings at. */
Level[] targets();
}
@@ -0,0 +1,75 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import com.volmit.generation.ChunkContext;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
/** Invocation-scoped lookup of the settings that apply at one world column.
*
* <p>Every level that declares the settings contributes its own entry: the dimension, the region and
* the biome of the column, and in a placement the placement itself. Levels stack: nothing is merged or
* overridden, and a module decides what several entries mean, such as running a deposit once per
* entry. The biome is the column's surface biome; cave biomes are not a level. Values must be treated as
* read-only. Bounds and lifetime match the invocation's sampler.
*
* <p>Something that spans several columns, such as a chunk-wide pass or a placed object, reads the
* settings at one column it treats as its origin; per-chunk behaviour reads the chunk's centre column
* ({@link ChunkContext#centreX()}, {@link ChunkContext#centreZ()}).
*/
public interface FeatureSettings {
/** The entries of {@code featureType} at this column, in level order; empty when no level declares it. */
<F extends IrisFeature> SettingsStack<F> at(Class<F> featureType, int worldX, int worldZ);
/** Every distinct entry of {@code featureType} at the 16 by 16 columns of chunk {@code chunkX}, {@code chunkZ}, in
* level order; entries of one level in the order their first column was found, columns by X and then Z. Entries are
* distinct by level and source. The chunk and mantle runners decide with it whether a conditioned stage runs in a
* chunk. The default asks {@link #at} for every column; a host that knows which regions and biomes a chunk holds
* answers it from them.
*/
default <F extends IrisFeature> SettingsStack<F> declaredInChunk(Class<F> featureType, int chunkX, int chunkZ) {
var declarations = new HashSet<Declaration>();
var distinct = new ArrayList<Entry<F>>();
int originX = chunkX * ChunkContext.CHUNK_WIDTH;
int originZ = chunkZ * ChunkContext.CHUNK_WIDTH;
for (int x = 0; x < ChunkContext.CHUNK_WIDTH; x++) {
for (int z = 0; z < ChunkContext.CHUNK_WIDTH; z++) {
for (var entry : at(featureType, originX + x, originZ + z)) {
if (declarations.add(new Declaration(entry.level(), entry.source()))) {
distinct.add(entry);
}
}
}
}
return SettingsStack.of(distinct);
}
/** The settings {@code biome} declares itself, whichever column it is found at: for a biome that is not a column's
* surface biome, such as the cave biome of {@link com.volmit.world.BiomeSample#caveBiome()}, which is no level of
* {@link #at}. {@code biome} is an id as a {@code BiomeSample} gives it. Empty when the biome declares none, or the
* host knows no such biome.
*/
default <F extends IrisFeature> Optional<F> declaredBy(ResourceId biome, Class<F> featureType) {
return Optional.empty();
}
/** One level's declaration of the settings.
*
* @param level where the settings are declared: the dimension, a region, a biome or the placement
* @param source the resource that declares them, such as {@code overworld:biome/desert/dunes}
* @param value the decoded settings
*/
record Entry<F extends IrisFeature>(Level level, ResourceId source, F value) {
public Entry {
Objects.requireNonNull(level, "level");
Objects.requireNonNull(source, "source");
Objects.requireNonNull(value, "value");
}
}
}
/** What makes two entries of a chunk the same declaration. */
record Declaration(Level level, ResourceId source) {}
@@ -0,0 +1,7 @@
package com.volmit.config;
/** Where a pack declares settings, from the least to the most specific: the dimension, a region, a biome, and an
* object placement. {@link Feature#targets()} names the levels a feature may be written at, and every
* {@link FeatureSettings.Entry} carries the level that declared it. Settings stacks keep this order.
*/
public enum Level { DIMENSION, REGION, BIOME, PLACEMENT }
@@ -0,0 +1,39 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import java.util.Collection;
import java.util.Set;
/**
* Implemented by settings that make pack biomes part of a pack's layout besides the ones its regions list: the biome
* that a cave band puts underground, or the target of a floating island. The host asks the settings of every dimension
* and biome it reaches, without knowing the module behind them, so such a biome is loaded, registered and given its own
* settings like any other. Biomes are named by their ids, {@link PackResources#idOf} of the keys the settings hold; ids
* naming no biome of the pack are ignored.
*/
public interface LinkedBiomes {
/**
* Biomes that join the biome tree of every region the owner is part of, like the owner's children: the host registers
* them with the region, so their terrain generators take part in the region's terrain.
*
* @param pack the pack the settings belong to, which turns their keys into ids
*/
default Set<ResourceId> treeBiomes(PackResources pack) {
return Set.of();
}
/**
* Biomes the settings use besides, which a dimension reaches (their objects, decorators and settings take part in
* generation) without joining the region's biome tree.
*
* @param pack the pack the settings belong to, which turns their keys into ids
* @param dimension the settings the owner's dimension declares, for settings that name something the dimension
* declares, such as a band of its caves
*/
default Set<ResourceId> usedBiomes(PackResources pack, Collection<IrisFeature> dimension) {
return Set.of();
}
}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive numeric upper bound. Enforcement belongs to the configuration loader. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MaxNumber {
double value();
}
@@ -0,0 +1,12 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive lower bound on the length of a list, set or array option, such as a palette that needs a block. Studio
* shows it ({@code minItems}); like {@link MinNumber}, enforcement belongs to the configuration loader.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MinItems {
int value();
}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Inclusive numeric lower bound. Enforcement belongs to the configuration loader. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MinNumber {
double value();
}
@@ -0,0 +1,28 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import java.util.Optional;
/** Every settings declaration of the pack the host is loading, for what depends on the whole pack rather
* than one column, such as how far a mantle stage reaches ({@link com.volmit.stage.PackReach}).
*
* <p>The levels are those chunk and mantle stages see: the dimension being generated, and every region
* and biome it can reach. Placements are not a level here. Values must be treated as read-only and not
* retained.
*/
public interface PackSettings {
/** Every entry of {@code featureType} the pack declares, dimension first, then regions, then biomes;
* empty when nothing declares it.
*/
<F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType);
/**
* What the host offers for the pack it is loading beyond the API, as an object of {@code type}: empty when it offers
* no such thing. The same door as {@link com.volmit.world.PackWorld#extension}, for what is worked out from the
* settings before any world generates, such as a {@link com.volmit.stage.PackReach} that needs the size of the pack's
* objects from the host.
*/
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
}
@@ -0,0 +1,68 @@
package com.volmit.config;
import com.volmit.random.WorldRandom;
import java.util.Objects;
/** A span of numbers from {@code min} to {@code max}, both included, as packs write it: {@code {"min": 0, "max": 15}},
* or a snippet under {@code snippet/range/}. An omitted bound keeps its default, so give a settings field its own
* default with {@link #of}. A value the host creates with the no-argument constructor and reads the JSON into.
*/
@Snippet("range")
@Desc("Represents a range")
public final class Range {
@Desc("The minimum value")
private double min = 16;
@Desc("The maximum value")
private double max = 32;
private Range() {
}
private Range(double min, double max) {
this.min = min;
this.max = max;
}
public static Range of(double min, double max) {
return new Range(min, max);
}
public double min() {
return min;
}
public double max() {
return max;
}
/** Whether {@code value} lies between the bounds, both included. */
public boolean contains(double value) {
return value >= min && value <= max;
}
/** A number between the bounds drawn from {@code random}: {@code min + nextDouble() * (max - min)}, one draw,
* or {@code min} without a draw when the bounds are equal.
*/
public double pick(WorldRandom random) {
if (min == max) {
return min;
}
return min + random.nextDouble() * (max - min);
}
@Override
public boolean equals(Object other) {
return other instanceof Range that && Double.compare(min, that.min) == 0 && Double.compare(max, that.max) == 0;
}
@Override
public int hashCode() {
return Objects.hash(min, max);
}
@Override
public String toString() {
return "Range[" + min + ".." + max + "]";
}
}
@@ -0,0 +1,13 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Says what an option's text names, such as {@code @Ref(Reference.BLOCK) String block}. Allowed on
* {@code String} and {@link com.volmit.resource.ResourceId} options and on lists, sets and arrays of
* them, where it applies to every element. Anywhere else it fails the pack load.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ref {
Reference value();
}
@@ -0,0 +1,48 @@
package com.volmit.config;
/** What a text option names, so studio can offer the matching completion list. Platform kinds name
* entries of the server's registries, such as {@code minecraft:stone}, including those that data
* packs and mods add. Pack kinds name resources of the pack being edited. The set is closed: every
* kind is one the Iris host can list.
*/
public enum Reference {
/** A block type, such as {@code minecraft:stone}. {@link com.volmit.block.BlockState} options are block references without {@link Ref}. */
BLOCK,
/** An item type, such as {@code minecraft:stick}. */
ITEM,
/** An entity type, such as {@code minecraft:zombie}. */
ENTITY,
/** A platform biome, such as {@code minecraft:plains}; not a biome of the pack. */
BIOME,
/** A platform structure, such as {@code minecraft:village_plains}. */
STRUCTURE,
/** A platform structure or a prefix naming a family of them: {@code minecraft:village_plains},
* {@code minecraft:village} (every village) or {@code nova_structures:} (a whole namespace). */
STRUCTURE_PREFIX,
/** A platform structure set, such as {@code minecraft:villages}. */
STRUCTURE_SET,
/** A platform jigsaw template pool, such as {@code minecraft:village/plains/town_centers}. */
TEMPLATE_POOL,
/** A potion effect type, such as {@code minecraft:speed}. */
POTION_EFFECT,
/** An enchantment, such as {@code minecraft:sharpness}. */
ENCHANTMENT,
/** A loot table of the platform, such as {@code minecraft:chests/simple_dungeon}; not a loot table of the pack. */
LOOT_TABLE,
/** A mob of another plugin or content provider, such as {@code mythicmobs:skeleton_king}. */
SPECIAL_ENTITY,
/** A biome of the pack. */
PACK_BIOME,
/** A region of the pack. */
PACK_REGION,
/** An object of the pack. */
PACK_OBJECT,
/** One of the host's noise styles, such as {@code SIMPLEX}; see {@link com.volmit.noise.NoiseStyle}. */
NOISE_STYLE,
/** An expression of the pack. */
PACK_EXPRESSION,
/** An image map of the pack. */
PACK_IMAGE_MAP,
/** A jigsaw structure of the pack. */
PACK_STRUCTURE
}
@@ -0,0 +1,8 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Declares that a field must be supplied in configuration. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Required {}
@@ -0,0 +1,14 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Says that an option names a resource of the module resource kind read into {@code value}, by its key in the
* pack, such as {@code @ResourceRef(Pool.class) String startPool = "castle/start"}. Studio then offers the keys
* of that kind's files. Allowed on {@code String} options and lists, sets and arrays of them; the class must be
* the type of a resource kind some module of the pack registers. Anywhere else it fails the pack load.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ResourceRef {
Class<?> value();
}
@@ -0,0 +1,105 @@
package com.volmit.config;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** The entries of one settings type that apply somewhere, in {@link Level} order: what a column stacks
* ({@link FeatureSettings#at}), what a chunk or a placement configures ({@link com.volmit.stage.StageContext#configured})
* or what a pack declares ({@link PackSettings#declared}). Levels stack and nothing is merged, so a module picks what it
* needs: every entry, the dimension's, the most specific one. Several entries may share a level, such as the biomes of
* a chunk or of a pack; they keep the order they were found in.
*
* <p>An immutable value; equal when the entries are equal. Hosts build it with {@link #of}.
*/
public final class SettingsStack<F extends IrisFeature> implements Iterable<Entry<F>> {
private static final SettingsStack<?> EMPTY = new SettingsStack<>(List.of());
private static final Comparator<Entry<?>> LEVEL_ORDER = Comparator.comparing(Entry::level);
private final List<Entry<F>> entries;
private final List<F> values;
private SettingsStack(List<Entry<F>> entries) {
this.entries = entries;
this.values = entries.stream().map(Entry::value).toList();
}
@SuppressWarnings("unchecked") // The empty stack holds no entry of any type.
public static <F extends IrisFeature> SettingsStack<F> empty() {
return (SettingsStack<F>) EMPTY;
}
/** These entries in level order; entries of one level keep the order given. */
public static <F extends IrisFeature> SettingsStack<F> of(List<? extends Entry<F>> entries) {
Objects.requireNonNull(entries, "entries");
if (entries.isEmpty()) {
return empty();
}
var sorted = new ArrayList<Entry<F>>(entries);
sorted.forEach(entry -> Objects.requireNonNull(entry, "entry"));
sorted.sort(LEVEL_ORDER);
return new SettingsStack<>(List.copyOf(sorted));
}
public boolean isEmpty() {
return entries.isEmpty();
}
/** Every entry, in level order. */
public List<Entry<F>> entries() {
return entries;
}
/** Every entry's value, in level order. */
public List<F> values() {
return values;
}
/** The dimension's value; empty when the dimension declares none. */
public Optional<F> dimension() {
return level(Level.DIMENSION);
}
/** The first value declared at {@code level}; empty when that level declares none. */
public Optional<F> level(Level level) {
Objects.requireNonNull(level, "level");
for (var entry : entries) {
if (entry.level() == level) {
return Optional.of(entry.value());
}
}
return Optional.empty();
}
/** The value of the last entry, the most specific level's (a placement before a biome before a region before the
* dimension); empty when the stack is.
*/
public Optional<F> mostSpecific() {
return entries.isEmpty() ? Optional.empty() : Optional.of(entries.getLast().value());
}
@Override
public Iterator<Entry<F>> iterator() {
return entries.iterator();
}
@Override
public boolean equals(Object other) {
return other instanceof SettingsStack<?> stack && entries.equals(stack.entries);
}
@Override
public int hashCode() {
return entries.hashCode();
}
@Override
public String toString() {
return "SettingsStack" + entries;
}
}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Identifies a reusable settings snippet. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Snippet {
String value();
}
@@ -0,0 +1,110 @@
package com.volmit.entity;
import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* An entity a module decided to spawn, with every random choice made: the host creates it on the platform and applies
* what is set. Names are as authored in the pack, with {@code &} colour codes.
*
* @param type the entity type's key, such as {@code minecraft:zombie}; ignored when {@code specialType} is set
* @param specialType a mob of another plugin, written {@code PluginName:MobName}; empty for an entity of the platform
* @param reason the platform's spawn reason by name; empty for a natural spawn
* @param customName the name shown above the entity; empty for none
* @param flags the settings that every entity kind understands
* @param equipment what the entity wears and holds
* @param passengers entities that ride this one
* @param attributes attribute modifiers to apply
* @param lootTables the pack's loot tables the entity drops, instead of the platform's drops, when it dies
* @param lootShuffleSeed seeds how the drops of {@code lootTables} are shuffled
* @param leashHolder the entity that holds this one on a leash; empty for none
* @param spawnEffect an effect to show when the entity appears; empty for none
* @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near
* @param pandaMainGene for pandas the main gene by name; empty to leave it to the platform
* @param pandaHiddenGene for pandas the hidden gene by name; empty to leave it to the platform
* @param applySettingsToSpecial whether the settings also apply to a mob of another plugin
* @param commands console commands to run where the entity appears
*/
public record EntitySpec(Optional<String> type, Optional<String> specialType, Optional<String> reason, Optional<String> customName,
Flags flags, Equipment equipment, List<EntitySpec> passengers, List<ItemAttribute> attributes,
List<ResourceId> lootTables, long lootShuffleSeed, Optional<EntitySpec> leashHolder,
Optional<SpawnEffect> spawnEffect, boolean riseOutOfGround, Optional<String> pandaMainGene,
Optional<String> pandaHiddenGene, boolean applySettingsToSpecial, List<Command> commands) {
public EntitySpec {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(specialType, "specialType");
Objects.requireNonNull(reason, "reason");
Objects.requireNonNull(customName, "customName");
Objects.requireNonNull(flags, "flags");
Objects.requireNonNull(equipment, "equipment");
passengers = List.copyOf(passengers);
attributes = List.copyOf(attributes);
lootTables = List.copyOf(lootTables);
Objects.requireNonNull(leashHolder, "leashHolder");
Objects.requireNonNull(spawnEffect, "spawnEffect");
Objects.requireNonNull(pandaMainGene, "pandaMainGene");
Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene");
commands = List.copyOf(commands);
}
/** Whether the entity is a mob of another plugin. */
public boolean isSpecial() {
return specialType.isPresent();
}
/** What an entity can be set to be, whatever its kind; the host applies the ones its kind has. */
public record Flags(boolean customNameVisible, boolean aware, boolean ai, boolean glowing, boolean gravity,
boolean invulnerable, boolean silent, boolean pickupItems, boolean removable,
boolean keepEntity, boolean baby) {
}
/** The items an entity wears and holds; empty for an empty slot. */
public record Equipment(Optional<ItemDrop> helmet, Optional<ItemDrop> chestplate, Optional<ItemDrop> leggings,
Optional<ItemDrop> boots, Optional<ItemDrop> mainHand, Optional<ItemDrop> offHand) {
public static final Equipment NONE = new Equipment(Optional.empty(), Optional.empty(), Optional.empty(),
Optional.empty(), Optional.empty(), Optional.empty());
public Equipment {
Objects.requireNonNull(helmet, "helmet");
Objects.requireNonNull(chestplate, "chestplate");
Objects.requireNonNull(leggings, "leggings");
Objects.requireNonNull(boots, "boots");
Objects.requireNonNull(mainHand, "mainHand");
Objects.requireNonNull(offHand, "offHand");
}
}
/**
* Sound and particles shown around an entity that appears. Offsets and the randomness of the particle motion are
* as in an effect of the pack; the host makes the random choices.
*
* @param sound the platform's sound key; empty for no sound
* @param particle the platform's particle key; empty for no particles
*/
public record SpawnEffect(Optional<String> sound, int soundDistance, double minPitch, double maxPitch, double volume,
Optional<String> particle, int particleOffset, int particleCount, double altX, double altY,
double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) {
public SpawnEffect {
Objects.requireNonNull(sound, "sound");
Objects.requireNonNull(particle, "particle");
}
}
/**
* Console commands run when an entity appears. {@code {x}}, {@code {y}} and {@code {z}} stand for its block position.
*
* @param commands the commands
* @param delay server ticks to wait before running them
* @param repeat whether to run them again and again until the server stops
* @param repeatDelay server ticks between repeats
*/
public record Command(List<String> commands, long delay, boolean repeat, long repeatDelay) {
public Command {
commands = List.copyOf(commands);
}
}
}
@@ -0,0 +1,52 @@
package com.volmit.generation;
import com.volmit.config.FeatureSettings;
import com.volmit.mantle.BlockBox;
import com.volmit.world.TerrainSampler;
/** What chunk and mantle invocations share: the chunk they run for, its terrain and its settings. X and Z are world
* coordinates; heights are above the dimension's bottom. Must not be retained after execution.
*/
public interface ChunkContext extends InvocationContext {
/** The width of a chunk along X and Z, in blocks. */
int CHUNK_WIDTH = 16;
/** The local X and Z of a chunk's centre column, where something that happens once per chunk reads its settings. */
int CENTRE_COLUMN = 7;
/** The chunk's first block along X, in world coordinates. */
int originX();
/** The chunk's first block along Z, in world coordinates. */
int originZ();
TerrainSampler terrain();
FeatureSettings settings();
/** The chunk's X in chunk coordinates. */
default int chunkX() {
return Math.floorDiv(originX(), CHUNK_WIDTH);
}
/** The chunk's Z in chunk coordinates. */
default int chunkZ() {
return Math.floorDiv(originZ(), CHUNK_WIDTH);
}
/** The world X of the chunk's centre column (local 7). */
default int centreX() {
return originX() + CENTRE_COLUMN;
}
/** The world Z of the chunk's centre column (local 7). */
default int centreZ() {
return originZ() + CENTRE_COLUMN;
}
/** The chunk's 16 by 16 columns in world coordinates, at the full height the terrain covers. */
default BlockBox area() {
var bounds = terrain().bounds();
return new BlockBox(originX(), bounds.minY(), originZ(), originX() + CHUNK_WIDTH, bounds.maxY(), originZ() + CHUNK_WIDTH);
}
}
@@ -0,0 +1,37 @@
package com.volmit.generation;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.world.TerrainSampler;
/** Per-invocation chunk generation inputs. Must not be retained after execution. */
public interface GenerationContext extends ChunkContext {
/** World coordinates of the local volume's first column. The volume starts at the dimension's bottom:
* local y is the height above it (0 = bottom block).
*/
@Override
int originX();
@Override
int originZ();
/** The terrain of the chunk and of the 16 blocks around it on every side, at full height: a chunk stage writes only
* its own chunk, but may look at its neighbors' terrain, such as their heights.
*/
@Override
TerrainSampler terrain();
/** Non-null mantle access scoped to this invocation; the host owns its lifetime. Like {@link #terrain()} it covers
* the chunk and the 16 blocks around it, so a stage that places something against a neighbor can see what the mantle
* holds there. A chunk stage writes module layers inside its own chunk's columns only, such as markers it derives
* from the chunk's finished blocks: the mantle pipeline has finished around the chunk, and a neighbor may already
* be generated, so writes outside the chunk throw UnsupportedOperationException, as do writes to
* {@link Mantle#blocks()} and {@link Mantle#edit()}.
*/
Mantle mantle();
/** The host-owned local volume of the given value type, shared by all stages of this
* invocation. Unsupported types throw IllegalArgumentException.
*/
<T> Hunk<T> hunk(Class<T> type);
}
@@ -0,0 +1,33 @@
package com.volmit.generation;
import com.volmit.ModuleLog;
import com.volmit.world.PackWorld;
import java.util.Optional;
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
*
* <p>There is no shared random stream. A stage draws from {@link com.volmit.stage.StageContext#random()},
* a stream of its own, and an object generator from {@link com.volmit.object.ObjectGenerationContext#random()}.
*/
public interface InvocationContext {
/** The world this invocation generates: its seed, the pack snapshot's resources, its settings and the state modules
* keep for it ({@link PackWorld#state}). Every invocation has one. A placement a tool makes outside a world the host
* generates, such as a studio paste, gets a world of its own that lives for that placement.
*/
PackWorld world();
/** The log of the module this invocation runs for, labelled with the module's id. The same as {@code world().log()}. */
default ModuleLog log() {
return world().log();
}
/**
* What the host offers for this one invocation beyond the API, as an object of {@code type}: empty when the host
* offers no such thing. The per invocation counterpart of {@link PackWorld#extension}: a host hands its own modules
* inputs that belong to one placement or one chunk this way, such as what Iris knows about the placement that is
* running. The host fills it for each invocation; like every input it must not be kept after the invocation.
*/
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
}
@@ -0,0 +1,17 @@
package com.volmit.generation;
import com.volmit.mantle.Mantle;
import com.volmit.world.TerrainSampler;
/** Per-invocation inputs of the mantle pipeline for one chunk. Must not be retained after execution. */
public interface MantleGenerationContext extends ChunkContext {
/** The terrain of the chunk and of the larger of the stage's reach and 16 blocks around it on every side, at full
* height: a mantle stage writes only the mantle, but may look at the terrain around its chunk, such as the heights
* a cave blends over its borders.
*/
@Override
TerrainSampler terrain();
/** The mantle of the chunk widened by the pipeline's reach, full height (heights 0 up to the dimension height). Writes outside it throw. */
Mantle mantle();
}
@@ -0,0 +1,16 @@
package com.volmit.hunk;
/** Dense local volume. Coordinates range from zero inclusive to each dimension exclusive.
* Reads/writes outside that range throw IndexOutOfBoundsException. Null values are forbidden;
* block volumes represent empty space with an air state.
* A chunk's volume starts at the dimension's bottom: its local y is the height above
* the dimension's bottom (0 = bottom). Invocation-owned hunks must not escape.
* This is a new minimal contract, not a copy of Iris's full Hunk implementation.
*/
public interface Hunk<T> {
int width();
int height();
int depth();
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
}
@@ -0,0 +1,18 @@
package com.volmit.item;
import java.util.Objects;
/** An attribute modifier of an {@link ItemDrop} or an entity, with the amount the module decided. The host creates a
* modifier under an id it makes unique from {@code name}, for every equipment slot.
*
* @param attribute the platform attribute's key, such as {@code max_health} or {@code minecraft:armor}
* @param name identifies the modifier among those of one item or entity; not shown to players
* @param operation {@code ADD_NUMBER}, {@code ADD_SCALAR} or {@code MULTIPLY_SCALAR_1}
*/
public record ItemAttribute(String attribute, String name, String operation, double amount) {
public ItemAttribute {
Objects.requireNonNull(attribute, "attribute");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(operation, "operation");
}
}
@@ -0,0 +1,70 @@
package com.volmit.item;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/**
* One stack of items a module decided to give: what a loot entry, a block's drops or an entity's equipment turned into
* after the module made every random choice. The host creates the stack on the platform. Names and lore are as authored
* in the pack, with {@code &} colour codes; the host translates and wraps them.
*
* @param item the item's key as the pack wrote it, see {@link ItemRegistry}
* @param amount how many, at least 1
* @param displayName the item's name; empty keeps the platform's
* @param lore lines of text under the name
* @param enchantments applied in order
* @param attributes attribute modifiers applied in order
* @param unbreakable whether the item never breaks
* @param flags platform item flags to set, by name; names the platform lacks are ignored
* @param customModel custom model number; empty for none
* @param damage the fraction of the item's durability already used, 0 to 1; empty leaves it undamaged
* @param leatherColor colour of leather armour as {@code #rrggbb}; empty for none
* @param dyeColor dye colour name; empty for none
* @param customNbt custom data the platform stores on the item, or an empty map
* @param source where the item came from, present only when the host asked for it to be shown (debug loot)
*/
public record ItemDrop(String item, int amount, Optional<String> displayName, List<String> lore, List<ItemEnchantment> enchantments,
List<ItemAttribute> attributes, boolean unbreakable, List<String> flags, OptionalInt customModel,
OptionalDouble damage, Optional<String> leatherColor, Optional<String> dyeColor, Map<String, Object> customNbt,
Optional<Source> source) {
public ItemDrop {
Objects.requireNonNull(item, "item");
if (amount < 1) throw new IllegalArgumentException("Item amount must be at least 1: " + amount);
Objects.requireNonNull(displayName, "displayName");
lore = List.copyOf(lore);
enchantments = List.copyOf(enchantments);
attributes = List.copyOf(attributes);
flags = List.copyOf(flags);
Objects.requireNonNull(customModel, "customModel");
Objects.requireNonNull(damage, "damage");
Objects.requireNonNull(leatherColor, "leatherColor");
Objects.requireNonNull(dyeColor, "dyeColor");
customNbt = Collections.unmodifiableMap(new LinkedHashMap<>(customNbt));
Objects.requireNonNull(source, "source");
}
/** {@code amount} items of kind {@code item} and nothing else. */
public static ItemDrop of(String item, int amount) {
return new ItemDrop(item, amount, Optional.empty(), List.of(), List.of(), List.of(), false, List.of(), OptionalInt.empty(),
OptionalDouble.empty(), Optional.empty(), Optional.empty(), Map.of(), Optional.empty());
}
/**
* Where a shown item came from: the loot table, when it came from one, and the 1-in-N chances it passed.
*
* @param table the table's name; empty for an item that came from no table
* @param tableRarity the table's rarity, 1 in this many
* @param entryRarity the entry's rarity within the table
*/
public record Source(Optional<String> table, int tableRarity, int entryRarity) {
public Source {
Objects.requireNonNull(table, "table");
}
}
}
@@ -0,0 +1,13 @@
package com.volmit.item;
import java.util.Objects;
/** An enchantment of an {@link ItemDrop}, named by the key the platform's registry knows ({@code sharpness},
* {@code mymod:vorpal}) with the level the module decided.
*/
public record ItemEnchantment(String key, int level) {
public ItemEnchantment {
Objects.requireNonNull(key, "key");
if (level < 1) throw new IllegalArgumentException("Enchantment level must be at least 1: " + level);
}
}
@@ -0,0 +1,15 @@
package com.volmit.item;
import java.util.OptionalInt;
/** What a module may ask the platform about items, so that its decisions follow the item they concern. Item keys are
* written as in packs: {@code diamond_sword}, {@code minecraft:diamond_sword}, or a custom item of a provider such as
* {@code itemsadder:ruby}. Safe for concurrent use.
*/
public interface ItemRegistry {
/**
* The most damage an item of this kind takes before it breaks, 0 for an item that cannot be damaged; empty when no
* item is known by {@code key}.
*/
OptionalInt maxDurability(String key);
}
@@ -0,0 +1,26 @@
package com.volmit.mantle;
import java.util.Objects;
/** Block bounds, minimum inclusive and maximum exclusive. Empty boxes are valid. X and Z are world coordinates;
* Y is the height above the dimension's bottom (0 = bottom). Boxes of local volumes, such as an object's
* bounds, use that volume's own coordinates.
*/
public record BlockBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
public BlockBox {
if (minX > maxX || minY > maxY || minZ > maxZ) {
throw new IllegalArgumentException("Inverted block bounds");
}
}
public boolean contains(int x, int y, int z) {
return x >= minX && x < maxX && y >= minY && y < maxY && z >= minZ && z < maxZ;
}
public boolean contains(BlockBox area) {
Objects.requireNonNull(area, "area");
return area.minX >= minX && area.maxX <= maxX
&& area.minY >= minY && area.maxY <= maxY
&& area.minZ >= minZ && area.maxZ <= maxZ;
}
}
@@ -0,0 +1,45 @@
package com.volmit.mantle;
import com.volmit.block.BlockState;
/**
* Invocation-scoped access to typed mantle data. X and Z are world block coordinates; Y is
* the height above the dimension's bottom (0 = bottom), so it is never negative. The host translates
* them to storage coordinates.
*
* <p>The host owns chunk acquisition, release, persistence and the permitted access area.
* Out-of-area access throws IndexOutOfBoundsException. Access after the invocation ends
* throws IllegalStateException. Do not retain this interface or use it from detached tasks.
* Concurrent use of one instance is not supported unless the host explicitly permits it.
*
* <p>Only registered layers are supported. Unknown IDs or mismatched registered types throw
* IllegalArgumentException. Null arguments are rejected. Layer views share this view's lifetime.
*
* <p>Writes affect generation storage, not necessarily the current chunk Hunk or live world.
* Direct writes have no rollback guarantee. Use edit() to buffer multi-layer changes.
* The host must serialize overlapping writes; read-modify-write is not independently atomic.
*/
public interface Mantle {
BlockBox bounds();
<T> MantleLayer<T> layer(MantleKey<T> key);
/** The blocks the mantle holds for chunks to take over: what placements wrote, such as objects and structures.
* A chunk stage copies them into its chunk (Iris's {@code iris:matter}); absent positions read null, and air a
* placement wrote is a block like any other. The host owns this layer, so it needs no registration. Stages read
* it only, and writes throw UnsupportedOperationException: placements write blocks with
* {@link com.volmit.placement.PlacementAccess#set}. A dimension that keeps no mantle holds none.
*/
MantleLayer<BlockState> blocks();
/** Whether the mantle holds a carved void at the position for the chunk to take over: a cave's air or fluid, planned
* before the chunks were generated. Also true where the chunk's own blocks show no void, such as under a dimension
* stacked above. The host owns the carving; stages only ask. A dimension that keeps no mantle carves nothing.
*/
boolean isCarved(int x, int y, int z);
/** Only one edit may be active per view. Parent reads remain allowed, but parent
* mutations are prohibited until the edit ends (IllegalStateException).
*/
MantleEdit edit();
}
@@ -0,0 +1,18 @@
package com.volmit.mantle;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/** Value serialization. Host frames payloads and stores key ID and version separately.
* Implementations must support concurrent calls, must not close streams, and must reject
* malformed data or unsupported stored versions with IOException. Values cannot be null.
*/
public interface MantleCodec<T> {
/** Nonnegative format version, stable for the registration lifetime. */
int version();
void write(DataOutput output, T value) throws IOException;
T read(DataInput input, int storedVersion) throws IOException;
}
@@ -0,0 +1,19 @@
package com.volmit.mantle;
/** Buffered changes across layers, with the parent's bounds and registrations.
* Reads and visits include buffered replacements/removals over the unchanged parent.
* Nested edits are unsupported: edit() throws UnsupportedOperationException.
* The host excludes competing writers; this is not a concurrent or disk transaction.
*/
public interface MantleEdit extends Mantle, AutoCloseable {
/** Publishes all changes to the parent or leaves it unchanged on failure.
* Successful commit ends the edit and invalidates its layer views. On failure the
* edit can only be closed. Repeated commit throws IllegalStateException.
* This guarantee applies to generation storage, not crash recovery or world writes.
*/
void commit();
/** Discards uncommitted changes and invalidates edit views. Idempotent after commit/close. */
@Override
void close();
}
@@ -0,0 +1,17 @@
package com.volmit.mantle;
import java.util.Objects;
/** Stable storage identity. Different IDs may use the same value class without sharing data. */
public record MantleKey<T>(String id, Class<T> type) {
public MantleKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Expected a namespaced mantle ID: " + id);
}
if (type.isPrimitive()) {
throw new IllegalArgumentException("Mantle values require a reference type");
}
}
}
@@ -0,0 +1,25 @@
package com.volmit.mantle;
/** A registered layer bounded by its owning Mantle view and sharing its lifetime.
* Values must be non-null and treated as immutable. Wrong value types are rejected with
* IllegalArgumentException; null arguments with NullPointerException.
*/
public interface MantleLayer<T> {
/** Returns null on absence, without allocating a storage section. */
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
/** Removing an absent entry is a no-op. */
void remove(int x, int y, int z);
/** Visits stored entries only, in ascending x, then y, then z order.
* Area must be fully within bounds (no silent clipping). Callbacks must not mutate
* this layer directly. An edit may buffer changes while visiting its parent layer.
* Callback exceptions propagate and stop traversal. No snapshot allocation is required.
*/
void visit(BlockBox area, MantleVisitor<T> visitor);
/** Removes all entries in the fully bounded area; other layers are untouched. */
void clear(BlockBox area);
}
@@ -0,0 +1,8 @@
package com.volmit.mantle;
public enum MantleLifetime {
/** May be removed only after all generation consumers, including neighbors, finish. */
GENERATION,
/** Survives generation cleanup; explicit removal is still permitted. */
PERSISTENT
}
@@ -0,0 +1,6 @@
package com.volmit.mantle;
@FunctionalInterface
public interface MantleVisitor<T> {
void accept(int x, int y, int z, T value);
}
@@ -0,0 +1,18 @@
package com.volmit.noise;
/** Builds noise from styles a pack describes. Noise is the host's: modules describe it with {@link NoiseStyle} in
* their settings and get samplers from here ({@link com.volmit.resource.PackResources#noise()}), never the host's
* noise classes. Safe for concurrent calls.
*/
public interface NoiseFactory {
/** The noise {@code style} describes, seeded with {@code seed}. The same style and seed give the same values
* in every world of the pack, so derive the seed from the world seed ({@code context.world().seed()}), not from a
* stage's random stream, when the noise must line up across chunks. The host keeps what it builds for the pack
* snapshot, so asking again for the same style and seed is cheap.
*
* <p>A style name the host does not know samples as {@link NoiseStyle#FLAT}, and an expression the pack does not
* have falls back to the base style, as packs have always been read. An image map the pack does not have, or cannot
* use as noise, throws {@link IllegalArgumentException}.
*/
NoiseSampler sampler(NoiseStyle style, long seed);
}
@@ -0,0 +1,56 @@
package com.volmit.noise;
/** Immutable, seeded noise the host built from a {@link NoiseStyle} ({@link NoiseFactory#sampler}). X and Z are
* world coordinates; Y is the height above the dimension's bottom (0 = bottom). The host's own styles give values
* from 0 to 1; expressions and image maps give what they compute. Two-dimensional and three-dimensional samples
* are separate fields, so {@code sample(x, z)} is not {@code sample(x, 0, z)}. Safe for concurrent calls.
*/
public interface NoiseSampler {
double sample(double worldX, double worldZ);
double sample(double worldX, double y, double worldZ);
/** {@link #sample(double, double)} mapped from 0..1 to -1..1 ({@code sample * 2 - 1}), for noise that is added up
* and compared around zero. A host may answer a repeated read of the same coordinates from a per-thread memo, so a
* caller that samples the same field at the same points again and again (a carver testing densities) should read
* this instead of mapping {@link #sample(double, double)} itself.
*/
default double signed(double worldX, double worldZ) {
return sample(worldX, worldZ) * 2D - 1D;
}
/** The three-dimensional counterpart of {@link #signed(double, double)}. */
default double signed(double worldX, double y, double worldZ) {
return sample(worldX, y, worldZ) * 2D - 1D;
}
/** This noise with its coordinates multiplied by {@code factor}: a factor above 1 squeezes the pattern, below 1
* stretches it. A host folds the factor into the generator's own scale, so the result is the very noise the style
* would give with that extra scale (same values and float rounding), and builds it without touching this sampler.
* The default multiplies the coordinates before sampling, which may round differently.
*/
default NoiseSampler scaled(double factor) {
NoiseSampler source = this;
return new NoiseSampler() {
@Override
public double sample(double worldX, double worldZ) {
return source.sample(worldX * factor, worldZ * factor);
}
@Override
public double sample(double worldX, double y, double worldZ) {
return source.sample(worldX * factor, y * factor, worldZ * factor);
}
@Override
public double signed(double worldX, double worldZ) {
return source.signed(worldX * factor, worldZ * factor);
}
@Override
public double signed(double worldX, double y, double worldZ) {
return source.signed(worldX * factor, y * factor, worldZ * factor);
}
};
}
}
@@ -0,0 +1,164 @@
package com.volmit.noise;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinNumber;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.Snippet;
import java.util.Objects;
import java.util.Optional;
/** How noise is shaped, as packs write it: {@code {"style": "SIMPLEX", "zoom": 4}}, or a snippet under
* {@code snippet/style/}. The style names one of the host's noise generators ({@link Reference#NOISE_STYLE}); an
* expression or image map of the pack replaces it. A zoom stretches the noise, an exponent bends it, a fracture
* style distorts its coordinates and a cellular frequency turns it into cells.
*
* <p>A style is a description, not noise: the host builds the noise ({@link NoiseFactory#sampler}). It is a value
* the host creates with the no-argument constructor and reads the JSON into; nothing changes it afterwards.
*/
@Snippet("style")
@Desc("A noise style: one of the host's noise generators, or an expression or image map of the pack, shaped by zoom, exponent, fracture and cells")
public final class NoiseStyle {
/** The style without noise, the default. */
public static final String FLAT = "FLAT";
@Ref(Reference.NOISE_STYLE)
@Desc("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style.")
private String style = FLAT;
@Desc("If set above 0, this style will be cellularized")
private double cellularFrequency = 0;
@Desc("Cell zooms")
private double cellularZoom = 1;
@MinNumber(0.00001)
@Desc("The zoom of this style")
private double zoom = 1;
@Ref(Reference.PACK_EXPRESSION)
@Desc("Instead of using the style property, use a custom expression to represent this style.")
private String expression;
@Ref(Reference.PACK_IMAGE_MAP)
@Desc("Use an Image map instead of a generated value")
private String imageMap;
@MinNumber(0.00001)
@Desc("The Output multiplier. Only used if parent is fracture.")
private double multiplier = 1;
@Desc("Apply a generator to the coordinate field fed into this parent generator. I.e. Distort your generator with another generator.")
private NoiseStyle fracture;
@MinNumber(0.01562)
@MaxNumber(64)
@Desc("The exponent")
private double exponent = 1;
@MinNumber(0)
@MaxNumber(8192)
@Desc("If the cache size is set above 0, this generator will be cached")
private int cacheSize = 0;
private NoiseStyle() {
}
private NoiseStyle(NoiseStyle copy) {
style = copy.style;
cellularFrequency = copy.cellularFrequency;
cellularZoom = copy.cellularZoom;
zoom = copy.zoom;
expression = copy.expression;
imageMap = copy.imageMap;
multiplier = copy.multiplier;
fracture = copy.fracture;
exponent = copy.exponent;
cacheSize = copy.cacheSize;
}
/** The host's noise style {@code style}, such as {@code SIMPLEX}, with every other option at its default. */
public static NoiseStyle of(String style) {
var created = new NoiseStyle();
created.style = Objects.requireNonNull(style, "style");
return created;
}
/** This style with zoom {@code zoom}: above 1 stretches the noise, below 1 squeezes it. */
public NoiseStyle withZoom(double zoom) {
var changed = new NoiseStyle(this);
changed.zoom = zoom;
return changed;
}
/** The base style's name; {@link #FLAT} where the pack wrote none. */
public String style() {
return style == null ? FLAT : style;
}
public double cellularFrequency() {
return cellularFrequency;
}
public double cellularZoom() {
return cellularZoom;
}
public double zoom() {
return zoom;
}
/** The key of the pack expression that replaces the base style. */
public Optional<String> expression() {
return Optional.ofNullable(expression);
}
/** The key of the pack image map that replaces the base style when there is no expression. */
public Optional<String> imageMap() {
return Optional.ofNullable(imageMap);
}
public double multiplier() {
return multiplier;
}
public Optional<NoiseStyle> fracture() {
return Optional.ofNullable(fracture);
}
public double exponent() {
return exponent;
}
public int cacheSize() {
return cacheSize;
}
/** Whether the style gives no noise: the {@link #FLAT} base style without an expression or image map. */
public boolean isFlat() {
return FLAT.equals(style()) && expression == null && imageMap == null;
}
@Override
public boolean equals(Object other) {
return other instanceof NoiseStyle that && style().equals(that.style())
&& Double.compare(cellularFrequency, that.cellularFrequency) == 0
&& Double.compare(cellularZoom, that.cellularZoom) == 0 && Double.compare(zoom, that.zoom) == 0
&& Objects.equals(expression, that.expression) && Objects.equals(imageMap, that.imageMap)
&& Double.compare(multiplier, that.multiplier) == 0 && Objects.equals(fracture, that.fracture)
&& Double.compare(exponent, that.exponent) == 0 && cacheSize == that.cacheSize;
}
@Override
public int hashCode() {
return Objects.hash(style(), cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture,
exponent, cacheSize);
}
@Override
public String toString() {
return "NoiseStyle[" + style() + expression().map(key -> ", expression " + key).orElse("")
+ imageMap().map(key -> ", image map " + key).orElse("") + ", zoom " + zoom + "]";
}
}
@@ -0,0 +1,85 @@
package com.volmit.noise;
import com.volmit.config.Desc;
import com.volmit.config.Snippet;
import java.util.Objects;
/** A number between {@code min} and {@code max} that a noise style picks per column, as packs write it:
* {@code {"min": 4, "max": 12, "style": {"style": "SIMPLEX"}}}, or a snippet under {@code snippet/style-range/}.
* A value the host creates with the no-argument constructor and reads the JSON into.
*/
@Snippet("style-range")
@Desc("Represents a range styled with a custom generator")
public final class StyledRange {
private static final String DEFAULT_STYLE = "STATIC";
@Desc("The minimum value")
private double min = 16;
@Desc("The maximum value")
private double max = 32;
@Desc("The style to pick the range")
private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE);
private StyledRange() {
}
private StyledRange(double min, double max, NoiseStyle style) {
this.min = min;
this.max = max;
this.style = Objects.requireNonNull(style, "style");
}
public static StyledRange of(double min, double max, NoiseStyle style) {
return new StyledRange(min, max, style);
}
public double min() {
return min;
}
public double max() {
return max;
}
/** The style; {@link NoiseStyle#FLAT} where the pack wrote {@code null}. */
public NoiseStyle style() {
return style == null ? NoiseStyle.of(NoiseStyle.FLAT) : style;
}
/** Whether every column gets the same value: the bounds are equal or the style is flat. */
public boolean isFlat() {
return min == max || style().isFlat();
}
/** The value at column {@code worldX}, {@code worldZ}: {@code min} when the bounds are equal, halfway between
* them when the style is flat, otherwise {@code min + (max - min) * noise} of the style's noise seeded with
* {@code seed}.
*/
public double at(NoiseFactory noise, long seed, double worldX, double worldZ) {
if (min == max) {
return min;
}
if (style().isFlat()) {
return (min + max) / 2;
}
return min + (max - min) * noise.sampler(style(), seed).sample(worldX, worldZ);
}
@Override
public boolean equals(Object other) {
return other instanceof StyledRange that && Double.compare(min, that.min) == 0
&& Double.compare(max, that.max) == 0 && style().equals(that.style());
}
@Override
public int hashCode() {
return Objects.hash(min, max, style());
}
@Override
public String toString() {
return "StyledRange[" + min + ".." + max + ", " + style() + "]";
}
}
@@ -0,0 +1,34 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import java.util.Arrays;
import java.util.Objects;
/** Immutable versioned payload. The host's adapter owns interpretation and size limits.
* Unsupported formats/versions fail explicitly; native objects and mutable buffers never escape.
*/
public final class BlockEntityData {
private final ResourceId format;
private final int version;
private final byte[] payload;
public BlockEntityData(ResourceId format, int version, byte[] payload) {
this.format = Objects.requireNonNull(format, "format");
if (version < 0) throw new IllegalArgumentException("Negative block entity format version");
this.version = version;
this.payload = Objects.requireNonNull(payload, "payload").clone();
}
public ResourceId format() { return format; }
public int version() { return version; }
public byte[] payload() { return payload.clone(); }
@Override
public boolean equals(Object other) {
return other instanceof BlockEntityData data && format.equals(data.format)
&& version == data.version && Arrays.equals(payload, data.payload);
}
@Override
public int hashCode() { return 31 * Objects.hash(format, version) + Arrays.hashCode(payload); }
}
@@ -0,0 +1,36 @@
package com.volmit.object;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockPosition;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/** Immutable sparse geometry, safe to cache per pack snapshot.
* Bounds are local, minima inclusive/maxima exclusive, and include blocks and markers.
* The anchor may lie outside the bounds. Placement aligns it with a requested world position.
* Blocks are sorted by x/y/z; duplicates fail. Marker order at an equal position is declaration
* order. This value contains no placement settings, random state, or native platform objects.
*/
public record GeneratedObject(BlockBox bounds, BlockPosition anchor,
List<ObjectBlock> blocks, List<ObjectMarker> markers) {
public GeneratedObject {
Objects.requireNonNull(bounds, "bounds");
Objects.requireNonNull(anchor, "anchor");
blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(ObjectBlock::position)).toList();
markers = List.copyOf(markers).stream().sorted(Comparator.comparing(ObjectMarker::position)).toList();
var positions = new HashSet<BlockPosition>();
for (var block : blocks) {
checkPosition(bounds, block.position());
if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate object block: " + block.position());
}
for (var marker : markers) checkPosition(bounds, marker.position());
}
private static void checkPosition(BlockBox bounds, BlockPosition position) {
if (!bounds.contains(position.x(), position.y(), position.z())) {
throw new IllegalArgumentException("Object entry outside bounds: " + position);
}
}
}
@@ -0,0 +1,17 @@
package com.volmit.object;
import com.volmit.block.BlockState;
import com.volmit.world.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** One sparse block in object-local coordinates. Absence is distinct from an explicit air block. */
public record ObjectBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
public ObjectBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
}
public ObjectBlock(BlockPosition position, BlockState state) { this(position, state, Optional.empty()); }
}
@@ -0,0 +1,12 @@
package com.volmit.object;
import com.volmit.generation.InvocationContext;
import com.volmit.random.WorldRandom;
/** Geometry-only invocation. The host chooses the variant seed and enforces size limits.
* Placement and terrain adaptation happen later; generators return reusable local geometry.
*/
public interface ObjectGenerationContext extends InvocationContext {
/** This generation's stream, seeded from the variant seed the host chose. Do not retain it. */
WorldRandom random();
}
@@ -0,0 +1,9 @@
package com.volmit.object;
/** Configured geometry generator. Snapshot settings; concurrent calls use only invocation-local
* state. Return a non-null object. The host owns variant selection and snapshot-scoped caching.
*/
@FunctionalInterface
public interface ObjectGenerator {
GeneratedObject generate(ObjectGenerationContext context);
}
@@ -0,0 +1,8 @@
package com.volmit.object;
import com.volmit.IrisFeature;
@FunctionalInterface
public interface ObjectGeneratorFactory<F extends IrisFeature> {
ObjectGenerator create(F feature);
}
@@ -0,0 +1,15 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Map;
import java.util.Objects;
/** Immutable, named metadata in object-local coordinates. The registered host/module owns meaning. */
public record ObjectMarker(BlockPosition position, ResourceId type, Map<String, String> attributes) {
public ObjectMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(type, "type");
attributes = Map.copyOf(attributes);
}
}
@@ -0,0 +1,20 @@
package com.volmit.object;
/** Requested transform. The host owns rasterization, property orientation and interpolation.
* Rotation is in degrees about the object's anchor; mirrors precede scale, then X/Y/Z rotation.
* Unsupported transformations fail rather than silently changing the request.
*/
public record ObjectTransform(double rotationX, double rotationY, double rotationZ,
double scaleX, double scaleY, double scaleZ,
boolean mirrorX, boolean mirrorY, boolean mirrorZ) {
public ObjectTransform {
for (double angle : new double[]{rotationX, rotationY, rotationZ}) {
if (!Double.isFinite(angle)) throw new IllegalArgumentException("Non-finite rotation");
}
for (double scale : new double[]{scaleX, scaleY, scaleZ}) {
if (!Double.isFinite(scale) || scale <= 0) throw new IllegalArgumentException("Scale must be finite and positive");
}
}
public static ObjectTransform identity() { return new ObjectTransform(0, 0, 0, 1, 1, 1, false, false, false); }
}
@@ -0,0 +1,9 @@
package com.volmit.object;
/** Host adapter returning immutable transformed geometry with updated bounds, block properties,
* block entities and markers. Cache keys include pack snapshot, source geometry and transform.
*/
@FunctionalInterface
public interface ObjectTransformer {
GeneratedObject transform(GeneratedObject object, ObjectTransform transform);
}
@@ -0,0 +1,18 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.object.BlockEntityData;
import com.volmit.world.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** A proposed or buffered write, including its block entity payload. The position has world X and Z and a
* Y that is the height above the dimension's bottom (0 = bottom).
*/
public record PlacedBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
public PlacedBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
}
}
@@ -0,0 +1,17 @@
package com.volmit.placement;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Map;
import java.util.Objects;
/** Marker metadata. The position has world X and Z and a Y that is the height above the dimension's bottom
* (0 = bottom).
*/
public record PlacedMarker(BlockPosition position, ResourceId type, Map<String, String> attributes) {
public PlacedMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(type, "type");
attributes = Map.copyOf(attributes);
}
}
@@ -0,0 +1,21 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.mantle.Mantle;
import com.volmit.world.BlockView;
/** Buffered access for placement stages, without ownership of commit/close. X and Z are world coordinates;
* Y is the height above the dimension's bottom (0 = bottom).
* Reads include the overlay. Bounds are the host-prepared placement area.
* Block/entity/marker/mantle writes share the host edit.
* Out-of-area access throws; nested mantle edits are unsupported. Do not retain this view.
*/
public interface PlacementAccess extends BlockView {
/** Writes {@code state} without a block entity, replacing any block entity buffered there. The per-block write. */
void set(int x, int y, int z, BlockState state);
/** Writes a block with its block entity, if it has one. */
void set(PlacedBlock block);
void marker(PlacedMarker marker);
Mantle mantle();
}
@@ -0,0 +1,18 @@
package com.volmit.placement;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.InvocationContext;
import com.volmit.object.ObjectTransformer;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
/** Host-supplied, read-only inputs of one placement attempt. Working state is carried by stage
* outputs, never stored on a module or stage body. Context lifetime ends with the placement.
*/
public interface PlacementContext extends InvocationContext {
TerrainSampler terrain();
FeatureSettings settings();
ObjectTransformer objects();
/** Prepared blocks before this placement. Use stage access for reads of buffered changes. */
BlockView blocks();
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
/** Host-owned buffered placement writes, with world X and Z and Y as the height above the
* dimension's bottom (0 = bottom), including cross-chunk writes.
* All reads see the overlay. Block/entity/marker/mantle mutations participate in one commit.
* Out-of-bounds access fails, never clips. The host excludes competing writers and handles
* block entity replacement/removal when states change. Nested mantle edits are unsupported.
* Successful commit ends the edit; failure leaves the parent unchanged and permits only close.
* Close is idempotent and discards uncommitted work. Views expire when this edit ends.
* This is a generation-storage transaction, not live-world or disk/crash atomicity.
*/
public interface PlacementEdit extends PlacementAccess, AutoCloseable {
void commit();
@Override void close();
}
@@ -0,0 +1,37 @@
package com.volmit.placement;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Objects;
/** One placement attempt. Geometry is already transformed; anchor is a world block position (world X and Z, Y as the height
* above the dimension's bottom).
* World position = local position - object anchor + request anchor. Arithmetic never wraps.
* id identifies this attempt within the host's generation plan.
*/
public record PlacementRequest(ResourceId id, GeneratedObject object, BlockPosition anchor) {
public PlacementRequest {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(object, "object");
Objects.requireNonNull(anchor, "anchor");
}
public BlockPosition worldPosition(BlockPosition local) {
return new BlockPosition(translate(local.x(), object.anchor().x(), anchor.x()),
translate(local.y(), object.anchor().y(), anchor.y()),
translate(local.z(), object.anchor().z(), anchor.z()));
}
public BlockBox footprint() {
var bounds = object.bounds();
var min = worldPosition(new BlockPosition(bounds.minX(), bounds.minY(), bounds.minZ()));
var max = worldPosition(new BlockPosition(bounds.maxX(), bounds.maxY(), bounds.maxZ()));
return new BlockBox(min.x(), min.y(), min.z(), max.x(), max.y(), max.z());
}
private static int translate(int local, int objectAnchor, int worldAnchor) {
return Math.toIntExact((long) local - objectAnchor + worldAnchor);
}
}
@@ -0,0 +1,264 @@
package com.volmit.random;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;
/** A random stream whose every value is defined here, so the same seed gives the same draws on
* every machine and every JDK. World generation draws from it: stages through
* {@link com.volmit.stage.StageContext#random()}, object generators through
* {@link com.volmit.object.ObjectGenerationContext#random()}.
*
* <p>It deliberately does not implement {@link java.util.random.RandomGenerator}: that interface's
* default methods, and any a later JDK adds, use algorithms the JDK may change, which would change
* existing worlds. Only the methods below exist, and each is specified exactly.
*
* <p><b>Algorithm.</b> The state is one {@code long}, initially the seed. {@link #nextLong()} is
* SplitMix64 (Steele, Lea and Flood, 2014): add {@code 0x9e3779b97f4a7c15} to the state, then return
* {@code mix(state)}, where {@code mix} is the finalizer
* {@code z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >>> 27)) * 0x94d049bb133111eb; z ^ (z >>> 31)}.
* Every other method is defined on {@code nextLong()} values:
* <ul>
* <li>{@code nextInt()}: the high 32 bits of one value;</li>
* <li>{@code nextBoolean()}: whether one value is negative (its highest bit);</li>
* <li>{@code nextFloat()}: the high 24 bits of one value times 2<sup>-24</sup>;</li>
* <li>{@code nextDouble()}: the high 53 bits of one value times 2<sup>-53</sup>;</li>
* <li>bounded integers: Lemire's multiply-and-reject method, which is unbiased. For a range of
* {@code n} values, {@code ints} take the high 32 bits {@code x} of one value and compute the
* 64-bit product {@code x * n}, {@code longs} take one value {@code x} and compute the
* 128-bit product; when the product's low half is below 2<sup>32</sup> (or 2<sup>64</sup>)
* {@code mod n}, they draw again; the result is the product's high half plus the origin;</li>
* <li>bounded doubles: {@code origin + nextDouble() * (bound - origin)}, a result that rounds up
* to {@code bound} replaced by the largest double below it (see {@link #nextDouble(double, double)}
* for ranges wider than the largest double);</li>
* <li>{@code nextGaussian()}: Marsaglia's polar method on pairs of {@code nextDouble()} values,
* using {@link StrictMath}, whose results are fixed;</li>
* <li>{@code chance(p)}: {@code nextDouble() < p};</li>
* <li>{@code pick(items)}: {@code items.get(nextInt(items.size()))};</li>
* <li>{@code shuffle(items)}: Fisher-Yates, for {@code i} from {@code size - 1} down to {@code 1}
* swapping index {@code i} with {@code nextInt(i + 1)}.</li>
* </ul>
* Methods without rejection draw exactly one value. {@code nextInt(0, n)} equals {@code nextInt(n)}
* and {@code nextLong(0, n)} equals {@code nextLong(n)}.
*
* <p>Not thread-safe. One stage uses its stream within one invocation; do not share or retain it.
*/
public final class WorldRandom {
private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
private static final int INT_BITS = 32;
private static final long UNSIGNED_INT_MASK = 0xffff_ffffL;
private static final long INT_RANGE = 1L << INT_BITS;
private static final int FLOAT_SHIFT = Long.SIZE - 24;
private static final float FLOAT_UNIT = 0x1.0p-24f;
private static final int DOUBLE_SHIFT = Long.SIZE - 53;
private static final double DOUBLE_UNIT = 0x1.0p-53;
private long state;
public WorldRandom(long seed) {
state = seed;
}
/** A uniformly distributed {@code long}: the next SplitMix64 output. */
public long nextLong() {
state += GOLDEN_GAMMA;
return mix(state);
}
/** A uniformly distributed {@code long} in {@code [0, bound)}. Throws if {@code bound <= 0}. */
public long nextLong(long bound) {
if (bound <= 0) throw new IllegalArgumentException("bound must be positive: " + bound);
return boundedLong(bound);
}
/** A uniformly distributed {@code long} in {@code [origin, bound)}, for any {@code origin < bound},
* including ranges wider than {@code Long.MAX_VALUE}. Throws if {@code origin >= bound}.
*/
public long nextLong(long origin, long bound) {
if (origin >= bound) throw invalidRange(origin, bound);
return origin + boundedLong(bound - origin);
}
/** A uniformly distributed {@code int}: the high 32 bits of {@link #nextLong()}. */
public int nextInt() {
return (int) (nextLong() >>> INT_BITS);
}
/** A uniformly distributed {@code int} in {@code [0, bound)}. Throws if {@code bound <= 0}. */
public int nextInt(int bound) {
if (bound <= 0) throw new IllegalArgumentException("bound must be positive: " + bound);
return (int) boundedInt(bound);
}
/** A uniformly distributed {@code int} in {@code [origin, bound)}, for any {@code origin < bound},
* including ranges wider than {@code Integer.MAX_VALUE}. Throws if {@code origin >= bound}.
*/
public int nextInt(int origin, int bound) {
if (origin >= bound) throw invalidRange(origin, bound);
return (int) (origin + boundedInt((long) bound - origin));
}
/** {@code true} or {@code false} with equal probability: whether {@link #nextLong()} is negative. */
public boolean nextBoolean() {
return nextLong() < 0;
}
/** A uniformly distributed {@code float} in {@code [0, 1)}, a multiple of 2<sup>-24</sup>. */
public float nextFloat() {
return (nextLong() >>> FLOAT_SHIFT) * FLOAT_UNIT;
}
/** A uniformly distributed {@code double} in {@code [0, 1)}, a multiple of 2<sup>-53</sup>. */
public double nextDouble() {
return (nextLong() >>> DOUBLE_SHIFT) * DOUBLE_UNIT;
}
/** A {@code double} in {@code [0, bound)}: {@code nextDouble() * bound}, never {@code bound} itself.
* Throws unless {@code bound} is positive and finite.
*/
public double nextDouble(double bound) {
if (!(bound > 0 && bound < Double.POSITIVE_INFINITY)) {
throw new IllegalArgumentException("bound must be positive and finite: " + bound);
}
return belowBound(nextDouble() * bound, bound);
}
/** A {@code double} in {@code [origin, bound)}, never {@code bound} itself:
* {@code origin + nextDouble() * (bound - origin)}. When {@code bound - origin} exceeds the largest
* double, the range is halved first: {@code 2 * (origin / 2 + nextDouble() * (bound / 2 - origin / 2))}.
* Throws unless both are finite and {@code origin < bound}.
*/
public double nextDouble(double origin, double bound) {
if (!(origin < bound && Double.isFinite(origin) && Double.isFinite(bound))) {
throw new IllegalArgumentException("origin and bound must be finite with origin < bound: [" + origin + ", " + bound + ")");
}
double unit = nextDouble();
double width = bound - origin;
double value = Double.isFinite(width) ? origin + unit * width : 2 * (origin / 2 + unit * (bound / 2 - origin / 2));
return belowBound(value, bound);
}
/** A normally distributed {@code double} with mean 0 and standard deviation 1, by Marsaglia's polar
* method: draw {@code u = 2 * nextDouble() - 1} and {@code v = 2 * nextDouble() - 1} until
* {@code s = u * u + v * v} is in {@code (0, 1)}, then return
* {@code u * StrictMath.sqrt(-2 * StrictMath.log(s) / s)}. The second value of the pair is discarded.
*/
public double nextGaussian() {
double u;
double s;
do {
u = 2 * nextDouble() - 1;
double v = 2 * nextDouble() - 1;
s = u * u + v * v;
} while (s >= 1 || s == 0);
return u * StrictMath.sqrt(-2 * StrictMath.log(s) / s);
}
/** Whether an event of the given probability happens: {@code nextDouble() < probability}. Always
* draws one value, so {@code chance(0)} is never and {@code chance(1)} always true. Throws unless
* {@code probability} is in {@code [0, 1]}.
*/
public boolean chance(double probability) {
if (!(probability >= 0 && probability <= 1)) {
throw new IllegalArgumentException("probability must be in [0, 1]: " + probability);
}
return nextDouble() < probability;
}
/** One element chosen uniformly: {@code items.get(nextInt(items.size()))}, so it draws exactly what
* {@link #nextInt(int)} draws. Throws if {@code items} is empty.
*/
public <T> T pick(List<T> items) {
if (items.isEmpty()) throw new IllegalArgumentException("cannot pick from an empty list");
return items.get(nextInt(items.size()));
}
/** Shuffles {@code items} in place by Fisher-Yates: for {@code i} from {@code size - 1} down to
* {@code 1}, swap the elements at {@code i} and {@code nextInt(i + 1)}. A list of {@code n >= 2}
* elements takes {@code n - 1} {@code nextInt} calls; a shorter list draws nothing and is not touched.
*
* <p>{@link RandomAccess} lists are swapped through {@link List#set}. Other lists, such as
* {@link java.util.LinkedList}, are copied to an array, shuffled there and written back through
* their {@link ListIterator}, like {@link Collections#shuffle}; the result is the same. A list that
* does not support {@code set} throws its {@link UnsupportedOperationException} before any element
* changes.
*/
public void shuffle(List<?> items) {
if (items.size() < 2) return;
if (items instanceof RandomAccess) {
fisherYates(items.size(), (i, j) -> Collections.swap(items, i, j));
return;
}
shuffleThroughArray(items);
}
private void shuffleThroughArray(List<?> items) {
Object[] copy = items.toArray();
fisherYates(copy.length, (i, j) -> {
Object swapped = copy[i];
copy[i] = copy[j];
copy[j] = swapped;
});
@SuppressWarnings("unchecked")
ListIterator<Object> writer = (ListIterator<Object>) items.listIterator();
for (Object item : copy) {
writer.next();
writer.set(item);
}
}
/** The one place the shuffle order is defined, so both list kinds give the same result. */
private void fisherYates(int size, IndexSwap swap) {
for (int i = size - 1; i > 0; i--) swap.swap(i, nextInt(i + 1));
}
/** Lemire's method for {@code range} in {@code [1, 2^32]}: high half of a 32-by-32-bit product. */
private long boundedInt(long range) {
long product = (nextLong() >>> INT_BITS) * range;
long low = product & UNSIGNED_INT_MASK;
if (low < range) {
long threshold = (INT_RANGE - range) % range;
while (low < threshold) {
product = (nextLong() >>> INT_BITS) * range;
low = product & UNSIGNED_INT_MASK;
}
}
return product >>> INT_BITS;
}
/** Lemire's method for {@code range} in {@code [1, 2^64)}, read as unsigned: high half of a
* 64-by-64-bit product.
*/
private long boundedLong(long range) {
long value = nextLong();
long low = value * range;
if (Long.compareUnsigned(low, range) < 0) {
long threshold = Long.remainderUnsigned(-range, range);
while (Long.compareUnsigned(low, threshold) < 0) {
value = nextLong();
low = value * range;
}
}
return Math.unsignedMultiplyHigh(value, range);
}
private static double belowBound(double value, double bound) {
return value < bound ? value : Math.nextDown(bound);
}
private static IllegalArgumentException invalidRange(long origin, long bound) {
return new IllegalArgumentException("origin must be below bound: [" + origin + ", " + bound + ")");
}
@FunctionalInterface
private interface IndexSwap {
void swap(int i, int j);
}
private static long mix(long value) {
value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L;
value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL;
return value ^ (value >>> 31);
}
}
@@ -0,0 +1,64 @@
package com.volmit.resource;
import com.volmit.block.BlockRegistry;
import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory;
import com.volmit.object.GeneratedObject;
import com.volmit.world.PackBiome;
import com.volmit.world.PackRegion;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
/** Immutable view of one loaded pack snapshot, safe for concurrent reads.
* Reload produces a different snapshotId, even for the same pack. Resources must be immutable
* or explicitly thread-safe. A resource is named by its kind and its id, so one id can name
* both a biome and a region. Hosts serve the kinds {@link #BIOMES}, {@link #REGIONS} and {@link #OBJECTS}
* and every {@link ResourceKind} the pack's modules register; an id the pack lacks for that kind returns empty,
* and a kind the host does not serve throws IllegalArgumentException. Broken resources fail loading rather than
* appearing absent. The host owns resolution, imports, native handles and caches; no filesystem paths escape.
*/
public interface PackResources {
/** The pack's biomes, as the host reads them from its own folder. */
ResourceKind<PackBiome> BIOMES = ResourceKind.of("host:biome", "biomes", PackBiome.class);
/** The pack's regions, as the host reads them from its own folder. */
ResourceKind<PackRegion> REGIONS = ResourceKind.of("host:region", "regions", PackRegion.class);
/** The pack's objects as geometry, as the host reads them from its own folder. */
ResourceKind<GeneratedObject> OBJECTS = ResourceKind.of("host:object", "objects", GeneratedObject.class);
ResourceId packId();
UUID snapshotId();
BlockRegistry blocks();
/** Asks the platform about items, such as how much damage one takes. */
ItemRegistry items();
/** Builds the noise of the {@link com.volmit.noise.NoiseStyle}s the pack's settings describe. */
NoiseFactory noise();
/** The resource of {@code kind} the pack has under {@code id}; empty when it has none. */
<T> Optional<T> find(ResourceKind<T> kind, ResourceId id);
/** The ids of every resource of {@code kind}, in id order. A kind the host does not serve throws
* IllegalArgumentException, as in {@link #find}.
*/
List<ResourceId> ids(ResourceKind<?> kind);
/** The id of the resource the pack's files name by {@code key} (the file path inside the kind's folder, without
* {@code .json}), such as {@code overworld:dungeon/chest} for {@code dungeon/chest}; see
* {@link ResourceId#ofPackKey}. Settings that name a resource, such as a {@link com.volmit.config.ResourceRef}, or a
* biome's key in a region, hold such a key. Characters an id cannot hold are replaced the way the host does for its
* own ids, so use this and not {@code new ResourceId(packId().namespace(), key)}.
*/
default ResourceId idOf(String key) {
return ResourceId.ofPackKey(packId().namespace(), key);
}
/** {@link #find} for a resource that must exist: a missing one throws NoSuchElementException naming kind and id. */
default <T> T require(ResourceKind<T> kind, ResourceId id) {
return find(kind, id).orElseThrow(() -> new NoSuchElementException("Missing " + kind.id() + " resource: " + id));
}
}
@@ -0,0 +1,50 @@
package com.volmit.resource;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;
/** Case-sensitive namespaced identity. Parsing never supplies an implicit namespace. */
public record ResourceId(String namespace, String path) implements Comparable<ResourceId> {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private static final Pattern NOT_PATH = Pattern.compile("[^a-z0-9_./-]");
private static final String PATH_REPLACEMENT = "_";
public ResourceId {
Objects.requireNonNull(namespace, "namespace");
Objects.requireNonNull(path, "path");
if (!isNamespace(namespace) || !PATH.matcher(path).matches()) {
throw new IllegalArgumentException("Invalid resource ID: " + namespace + ":" + path);
}
}
/** Whether {@code value} is a valid namespace on its own, such as {@code iris}. */
public static boolean isNamespace(String value) {
return NAMESPACE.matcher(value).matches();
}
public static ResourceId parse(String value) {
Objects.requireNonNull(value, "value");
int separator = value.indexOf(':');
if (separator < 0) throw new IllegalArgumentException("Expected a namespaced ID: " + value);
return new ResourceId(value.substring(0, separator), value.substring(separator + 1));
}
/**
* The id a pack gives the resource its files name by {@code key}, such as {@code dungeon/chest} for
* {@code loot/dungeon/chest.json}: the pack's namespace and the key as the path, lower-cased, with every
* character outside {@code [a-z0-9_./-]} replaced by {@code _}. Keys that differ only in such characters share
* an id.
*/
public static ResourceId ofPackKey(String namespace, String key) {
Objects.requireNonNull(key, "key");
return new ResourceId(namespace, NOT_PATH.matcher(key.toLowerCase(Locale.ROOT)).replaceAll(PATH_REPLACEMENT));
}
@Override
public String toString() { return namespace + ":" + path; }
@Override
public int compareTo(ResourceId other) { return toString().compareTo(other.toString()); }
}
@@ -0,0 +1,55 @@
package com.volmit.resource;
import java.lang.reflect.Modifier;
import java.util.Objects;
import java.util.regex.Pattern;
/** A kind of resource read from the pack: every JSON file below {@code <pack>/<folder>/}, each read
* into a new instance of {@code type}. A file's key is its path below the folder without {@code .json}, such as
* {@code castle/keep}, and its id is {@code <pack namespace>:<key>}, the form {@link PackResources} uses for
* every pack resource. A resource is found by its kind and its id, {@link PackResources#find}{@code (kind, id)};
* the host tells kinds apart by {@code type}, so each kind has a class of its own. The host's own kinds are the
* constants of {@link PackResources}.
*
* <p>Modules register kinds with {@link com.volmit.FeatureRegistry#registerResourceKind}. The id names the kind
* in errors and studio and follows the module id like every other id the module owns: {@code iris:structure}
* owns {@code iris:structure/pool}. The folder is one folder name directly below the pack root, chosen by the
* module; one folder holds one kind, and the host's own folders belong to the host.
*
* <p>The host creates each resource with the type's no-argument constructor and reads the file's JSON into it,
* the way it reads settings, so an omitted field keeps its default. Resources are values: the host reads each
* once per pack load and hands every caller the same instance, so nobody may change one after it is read.
*/
public record ResourceKind<T>(ResourceId id, String folder, Class<T> type) {
private static final Pattern FOLDER = Pattern.compile("[a-z0-9_.-]+");
public ResourceKind {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(folder, "folder");
Objects.requireNonNull(type, "type");
requireFolderName(id, folder);
requireConcreteClass(id, type);
}
public static <T> ResourceKind<T> of(String id, String folder, Class<T> type) {
return new ResourceKind<>(ResourceId.parse(id), folder, type);
}
/** Whether {@code name} may name a kind's folder: one folder name of lowercase letters, digits, '-', '_' and '.'. */
public static boolean isFolderName(String name) {
return FOLDER.matcher(name).matches() && !name.equals(".") && !name.equals("..");
}
private static void requireFolderName(ResourceId id, String folder) {
if (isFolderName(folder)) return;
throw new IllegalArgumentException("Folder '" + folder + "' of resource kind " + id + " is not a folder name;"
+ " a kind reads one folder directly below the pack root, named with lowercase letters, digits, '-', '_' and '.'");
}
private static void requireConcreteClass(ResourceId id, Class<?> type) {
if (type.isPrimitive() || type.isArray() || type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException("Resource kind " + id + " reads into " + type.getName()
+ ", which the host cannot create; use a concrete class with a no-argument constructor");
}
}
}
@@ -0,0 +1,100 @@
package com.volmit.service;
import com.volmit.entity.EntitySpec;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The ambient effects of an area: sounds, particles, potion effects and commands that play around the players who stay
* in it. The host asks, now and then, for the players it keeps; the module says which effects of the area are due, and
* every random choice that goes with them (where the sound seems to come from, how the particles scatter, how long the
* potion lasts), so that the host only has to carry them out. An effect is due only now and then, as its interval and
* chance say, so most answers are empty. The host asks every provider and carries out all answers.
*/
@Service(Providers.ALL)
public interface AmbientEffects {
/**
* The effects due for a player standing at {@code at}.
*
* @param at world X and Z, Y the height above the dimension's bottom
*/
List<Effect> due(PackWorld world, BlockPosition at);
/**
* One effect that plays now. The host carries out the parts it has, in the order sound, particles, commands, potion.
* A part the platform lacks, such as an unknown sound, is skipped.
*
* @param sound a sound to play; empty for none
* @param particles particles to show; empty for none
* @param commands console commands to run, none when the effect has no commands that may run now
* @param potion a potion effect to give; empty for none
*/
record Effect(Optional<Sound> sound, Optional<Particles> particles, List<Command> commands, Optional<Potion> potion) {
public Effect {
Objects.requireNonNull(sound, "sound");
Objects.requireNonNull(particles, "particles");
commands = List.copyOf(commands);
Objects.requireNonNull(potion, "potion");
}
}
/**
* A sound played to the player.
*
* @param key the platform's sound key
* @param offsetX blocks from the player where the sound seems to come from, as the other offsets
* @param volume the sound's volume
* @param pitch the sound's pitch
*/
record Sound(String key, int offsetX, int offsetY, int offsetZ, float volume, float pitch) {
public Sound {
Objects.requireNonNull(key, "key");
}
}
/**
* Particles shown to the player. They appear {@code forward} blocks ahead of the player, {@code sideways} blocks to
* the right (negative for the left) and on the surface at that spot, one block up, moved by {@code jitterX} and
* {@code jitterZ} and by {@code lift} blocks up.
*
* @param key the platform's particle key
* @param count how many particles; none makes {@code altX}, {@code altY} and {@code altZ} their motion
* @param altX the particles' offset or motion, as the other two
* @param extra an extra value some particles take; 0 for none
*/
record Particles(String key, double forward, double sideways, double jitterX, double jitterZ, int lift, int count,
double altX, double altY, double altZ, double extra) {
public Particles {
Objects.requireNonNull(key, "key");
}
}
/**
* A command to run where the effect plays.
*
* @param command the commands, their delay and repeats; {@code {x}}, {@code {y}} and {@code {z}} stand for the block
* position
* @param offsetX blocks from the player where the command runs, as the other two
*/
record Command(EntitySpec.Command command, double offsetX, double offsetY, double offsetZ) {
public Command {
Objects.requireNonNull(command, "command");
}
}
/**
* A potion effect for the player. A player who has the same potion effect with a stronger amplifier keeps it.
*
* @param key the platform's potion effect key
* @param strength the amplifier
* @param ticks how long it lasts, in server ticks
*/
record Potion(String key, int strength, int ticks) {
public Potion {
Objects.requireNonNull(key, "key");
}
}
}
@@ -0,0 +1,44 @@
package com.volmit.service;
import com.volmit.block.BlockState;
import com.volmit.item.ItemDrop;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
/**
* Items a module drops when a block breaks, in addition to or instead of the platform's. The host asks every provider
* when a player breaks a block in a world generated with the pack, drops the items of all answers where the block was
* and keeps the platform's own drops unless an answer replaces them.
*/
@Service(Providers.ALL)
public interface BlockDrops {
/** What this module drops for the block {@code broken}; {@link Result#NONE} when it does nothing for that block. */
Result drops(PackWorld world, Broken broken);
/**
* The block that was broken.
*
* @param position world X and Z, Y the height above the dimension's bottom
* @param block the block as it was
*/
record Broken(BlockPosition position, BlockState block) {
public Broken {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(block, "block");
}
}
/**
* @param drops the items to drop
* @param replacesVanillaDrops whether the platform's own drops of the block are not dropped
*/
record Result(List<ItemDrop> drops, boolean replacesVanillaDrops) {
public static final Result NONE = new Result(List.of(), false);
public Result {
drops = List.copyOf(drops);
}
}
}
@@ -0,0 +1,29 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* Which biome a module puts underground. The host places the cave biome of a position itself, from the biome its regions give
* the column and its terrain; this service tells it where a module overrides that and where a cave biome gives way to the
* surface's. A pack has one provider, since two modules deciding the biome of the same cave could not both be right.
*/
@Service(Providers.ONE)
public interface CaveBiomes {
/**
* The pack biome the module puts at the position whatever the regions say, such as a band of the deep dark. Empty where it
* overrides nothing.
*
* @param y the height above the dimension's bottom
* @return the biome's pack id
*/
Optional<ResourceId> overriddenBiome(PackWorld world, int x, int y, int z);
/**
* How many blocks below the surface a position must lie for the pack biome {@code biome} to be the cave biome there;
* nearer the surface the surface's biome is. 0 for a biome that has no such limit. The answer depends on the world and the
* biome only: the host asks once per biome and keeps it while the world runs.
*/
int minDepthBelowSurface(PackWorld world, ResourceId biome);
}
@@ -0,0 +1,127 @@
package com.volmit.service;
import com.volmit.entity.EntitySpec;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The entities a module spawns in the world over time: spawners the dimension, region and biomes list, and the spawners
* markers in the world name. The host decides when and where to look, asks the providers, and spawns what the first
* answer plans, after checking the conditions of the platform that come with it (light, the surface below, free space).
* It tells the module how many entities appeared so that the module can keep its limits on how often a spawner fires.
*/
@Service(Providers.ALL)
public interface EntitySpawns {
/** What the module plans to spawn in the chunk or at the marker, or empty to spawn nothing. */
Optional<Plan> plan(PackWorld world, Site site);
/** Called with the number of entities of {@code plan} that appeared, so the spawner's rate limits count them. */
void spawned(PackWorld world, Plan plan, int count);
/** The pack's entity {@code entity} as this module would spawn it, for tools that spawn one on request; empty for an unknown one. */
Optional<EntitySpec> entity(PackWorld world, ResourceId entity);
/** What a marker in the world means for spawning; empty for a marker this module does not know. */
Optional<MarkerRule> marker(PackWorld world, String tag);
/** Where entities may spawn. */
sealed interface Site permits Chunk, Marker {
}
/**
* An ambient spawn in a chunk.
*
* @param chunkX chunk coordinates
* @param livingEntities how many living entities the chunk already holds
* @param initial whether this is the spawn of a chunk that was just generated
*/
record Chunk(int chunkX, int chunkZ, int livingEntities, boolean initial) implements Site {
}
/**
* A spawn at a marker.
*
* @param position the marker's block: world X and Z, Y the height above the dimension's bottom
* @param marker the marker's tag
* @param spawner the pack's spawner chosen among the marker's
* @param initial whether the spawner's initial spawns are used rather than its ordinary ones
*/
record Marker(BlockPosition position, String marker, ResourceId spawner, boolean initial) implements Site {
public Marker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(marker, "marker");
Objects.requireNonNull(spawner, "spawner");
}
}
/**
* What a marker does.
*
* @param spawners the pack's spawners at the marker
* @param emptyAbove whether it only counts with free space above it
* @param removeOnChange whether it goes away when its block changes
*/
record MarkerRule(List<ResourceId> spawners, boolean emptyAbove, boolean removeOnChange) {
public MarkerRule {
spawners = List.copyOf(spawners);
}
}
/**
* Entities to spawn, tried one after the other.
*
* @param spawner the pack's spawner that planned them
* @param chunkX the chunk they spawn in, where the spawner's per-chunk limit counts them
* @param exhaustsMarker whether the marker that led here is used up and should be removed
* @param attempts the spawns to try
*/
record Plan(ResourceId spawner, int chunkX, int chunkZ, boolean exhaustsMarker, List<Attempt> attempts) {
public Plan {
Objects.requireNonNull(spawner, "spawner");
attempts = List.copyOf(attempts);
}
}
/**
* One entity to spawn at a block. The host spawns it only if the block's light level lies in the range (when the
* range is restricted) and, when {@code checkSurface}, the block below suits the entity's {@code surface} and the
* space the entity needs is free.
*
* @param at world X and Z, Y the height above the dimension's bottom
* @param entity what to spawn
* @param surface the kind of ground or fluid the entity needs below it
* @param minLight lowest light level allowed, 0 for any
* @param maxLight highest light level allowed, 15 for any
* @param checkSurface whether to check the surface and the free space
*/
record Attempt(BlockPosition at, EntitySpec entity, Surface surface, int minLight, int maxLight, boolean checkSurface) {
public Attempt {
Objects.requireNonNull(at, "at");
Objects.requireNonNull(entity, "entity");
Objects.requireNonNull(surface, "surface");
}
/** Whether the light level matters. */
public boolean restrictsLight() {
return minLight > 0 || maxLight < 15;
}
}
/** The ground or fluid an entity spawns on. */
enum Surface {
/** Solid ground. */
LAND,
/** Ground animals spawn on, such as grass, dirt and podzol. */
ANIMAL,
/** Within water. */
WATER,
/** Solid ground or water. */
OVERWORLD,
/** Within lava. */
LAVA
}
}
@@ -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,67 @@
package com.volmit.service;
import com.volmit.block.BlockState;
import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The loot a module gives containers and mobs. The host asks in two steps so that it, and plugins listening to it, can
* see and change which tables are used: {@link #tables} names the tables a container draws from, {@link #items} turns
* one table into items. The host asks every provider and puts the answers together; a provider answers {@link #items}
* only for the tables it knows. A container is filled with items the host creates on the platform, in the order of the
* tables.
*/
@Service(Providers.ALL)
public interface Loot {
/**
* The tables the container at {@code site} draws from, in the order their items are added. Empty when the module
* gives that container nothing.
*/
List<Source> tables(PackWorld world, Site site);
/** The items the pack's table {@code table} gives at {@code site}; empty for a table this module does not know. */
List<ItemDrop> items(PackWorld world, Site site, ResourceId table);
/**
* Where loot is given.
*
* @param position the container, or the mob's spawn spot: world X and Z, Y the height above the dimension's
* bottom
* @param container the container's block when it is a storage chest the module may give the loot of the object
* placed there; empty for any other spot
* @param nativeLootDefined whether the platform already gave the container a loot table of its own
* @param debug whether items should say where they came from ({@link ItemDrop#source()})
*/
record Site(BlockPosition position, Optional<BlockState> container, boolean nativeLootDefined, boolean debug) {
public Site {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(container, "container");
}
}
/** Where a container's items come from. */
sealed interface Source permits Table, PlatformTable {
}
/** A loot table of the pack, by the id {@link com.volmit.resource.PackResources#idOf} gives its key. */
record Table(ResourceId id) implements Source {
public Table {
Objects.requireNonNull(id, "id");
}
}
/**
* A loot table of the platform, such as {@code minecraft:chests/simple_dungeon}. The host draws it with {@code seed}
* so that the same container always gets the same items.
*/
record PlatformTable(String key, long seed) implements Source {
public PlatformTable {
Objects.requireNonNull(key, "key");
}
}
}
@@ -0,0 +1,42 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld;
import java.util.Objects;
import java.util.Set;
/** Which pack objects a module places, predicted without generating anything. The host's object search and its
* studio tools ask every provider and use all the answers together.
*/
@Service(Providers.ALL)
public interface ObjectsAt {
/**
* The ids 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), as {@link com.volmit.resource.PackResources#idOf} gives them. 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<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ);
/**
* The biomes and regions of {@code world}'s layout whose own settings make this module place the object
* {@code object}. The host finds the areas where the object can appear from these: a biome counts for the areas
* it generates in and, through its children, for the areas of the biomes inside it, so a provider names only the
* layout entries that place the object themselves. Only biomes and regions the dimension can reach are named.
*/
PlacedBy placedBy(PackWorld world, ResourceId object);
/** Layout entries that place an object, by their pack ids. */
record PlacedBy(Set<ResourceId> biomes, Set<ResourceId> regions) {
public static final PlacedBy NOTHING = new PlacedBy(Set.of(), Set.of());
public PlacedBy {
biomes = Set.copyOf(Objects.requireNonNull(biomes, "biomes"));
regions = Set.copyOf(Objects.requireNonNull(regions, "regions"));
}
public boolean isEmpty() {
return biomes.isEmpty() && regions.isEmpty();
}
}
}
@@ -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,82 @@
package com.volmit.service;
import com.volmit.block.BlockState;
import com.volmit.placement.PlacedBlock;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Trees a module grows when a sapling or mushroom grows in a world generated with the pack, and which objects it
* counts as trees. The host asks every provider in order when something grows and uses the first {@link Growth}; no
* answer leaves the growth to the platform. The module decides what grows and the blocks it consists of; the host
* clears the sapling, places the blocks on the right thread and tells listeners.
*/
@Service(Providers.ALL)
public interface SaplingGrowth {
/**
* The tree that replaces the growth at {@code sapling}, or empty to leave it to the platform. Reads the world around
* the sapling through {@code surroundings}, which is only valid during the call and sees the saplings that are
* growing as air.
*/
Optional<Growth> grow(PackWorld world, Sapling sapling, Surroundings surroundings);
/** The objects of the pack this module places as trees, for tools that tell trees from other objects. */
TreeObjects treeObjects(PackWorld world);
/**
* What grows.
*
* @param at where the growth happened: world X and Z, Y the height above the dimension's bottom
* @param center the middle of the plane of saplings that grow together, the same way
* @param species the platform's name for the kind of tree that would grow, such as {@code TREE} or {@code JUNGLE}
*/
record Sapling(BlockPosition at, BlockPosition center, String species) {
public Sapling {
Objects.requireNonNull(at, "at");
Objects.requireNonNull(center, "center");
Objects.requireNonNull(species, "species");
}
}
/** The world around a growing sapling, read where the tree is placed. X and Z are world coordinates, Y the height above the dimension's bottom. */
interface Surroundings {
/** The height of the topmost block at the column, ignoring fluids when {@code ignoreFluid}. */
int highest(int x, int z, boolean ignoreFluid);
BlockState blockAt(int x, int y, int z);
}
/**
* The tree to place.
*
* @param object the id of the object the tree comes from, as {@link com.volmit.resource.PackResources#idOf} gives it
* for the object's key
* @param blocks the blocks to place, in order, later ones over earlier ones
*/
record Growth(ResourceId object, List<PlacedBlock> blocks) {
public Growth {
Objects.requireNonNull(object, "object");
blocks = List.copyOf(blocks);
}
}
/**
* Objects a module places as trees, by the ids {@link com.volmit.resource.PackResources#idOf} gives their keys.
*
* @param objects pack objects its placements mark as trees
* @param procedural the objects its procedural trees generate, one per variant
*/
record TreeObjects(Set<ResourceId> objects, Set<ResourceId> procedural) {
public static final TreeObjects NONE = new TreeObjects(Set.of(), Set.of());
public TreeObjects {
objects = Set.copyOf(objects);
procedural = Set.copyOf(procedural);
}
}
}
@@ -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,40 @@
package com.volmit.service;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
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
* ids: a pack's own structure by the id {@link PackResources#idOf} gives its key ({@code overworld:villages/plains}),
* a platform structure by the platform's id ({@code minecraft:ancient_city}). The host asks the providers in order and
* sends an id to the first that places it in the world ({@link #placed}).
*/
@Service(Providers.FIRST)
public interface StructureLocator {
/** Every structure 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<ResourceId> structures(PackResources pack);
/** 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<ResourceId> locatable(PackWorld world);
/** The structures {@link #locate} finds among those this module places in {@code world}, locatable or not: its own
* structures, the platform structures it starts itself and the platform structures its own stand in for. Commands
* report them and send a search for one of them here. By default the {@link #locatable} ones.
*/
default Set<ResourceId> placed(PackWorld world) {
return locatable(world);
}
/**
* The start of {@code structure} 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 an id from {@link #placed}. May take long; the
* host calls it off the server's main thread.
*/
LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks);
}
@@ -0,0 +1,38 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.DecorationStep;
import com.volmit.world.PackWorld;
import java.util.Optional;
/**
* A module's say over the platform's own placed features in the pack's worlds: the ores, trees, plants, springs and other
* decorations Minecraft, data packs and mods declare for a biome. By default the platform runs none of them over the pack's
* terrain. The host asks every provider, in module id order: it runs the platform's feature pass in a world when any
* provider turns it on with {@link #generates}, and then skips a decoration step or a feature that any provider refuses.
*
* <p>Every answer is decided from the world alone (its settings and resources), never from a position: the host asks once
* per world, and once per world and step or feature, and keeps the answer while the world runs. Every method may be
* called from any thread, concurrently.
*/
@Service(Providers.ALL)
public interface VanillaFeatures {
/** Whether the platform runs its placed features over the terrain of {@code world}. False when the module has no part in it. */
default boolean generates(PackWorld world) {
return false;
}
/**
* Whether the platform places the features of decoration step {@code step} in {@code world}: empty for a step of a newer
* platform the API does not know yet. True when the module has no part in it.
*/
default boolean generatesStep(PackWorld world, Optional<DecorationStep> step) {
return true;
}
/** Whether the platform places the feature {@code feature}, such as {@code minecraft:ore_diamond}, in {@code world}. True when the module has no part in it. */
default boolean generatesFeature(PackWorld world, ResourceId feature) {
return true;
}
}
@@ -0,0 +1,129 @@
package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.vanilla.PlatformStart;
import com.volmit.vanilla.StartMemo;
import com.volmit.vanilla.StartReach;
import com.volmit.vanilla.StructureFit;
import com.volmit.vanilla.VanillaStructureContext;
import com.volmit.vanilla.VanillaStructureRule;
import com.volmit.vanilla.VanillaStructureSetup;
import com.volmit.vanilla.VanillaStructureStart;
import com.volmit.vanilla.VanillaStructureStartContext;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/** A module's say over the platform's own structures, the ones Minecraft, data packs and mods register, in the pack's
* worlds. The host asks every provider, in module id order:
*
* <ul>
* <li>{@link #rule} before the platform starts one of its structures, and when it locates one;</li>
* <li>{@link #starts} for every chunk, for the starts modules place where the platform would not;</li>
* <li>{@link #shift} before it publishes a start the platform made itself, and {@link #reach} before it publishes any
* start;</li>
* <li>{@link #beforePieces} and {@link #afterPieces} around the platform placing the starts' pieces in a chunk;</li>
* <li>{@link #setup} before a world of the dimension exists, when the platform sets up its structures and when the
* host installs data packs.</li>
* </ul>
*
* <p>The host asks {@link #rule} once per world, structure and pack snapshot and keeps the answer, so a rule is decided
* from the pack (its settings and resources) and never from where a start would be. Rules combine with
* {@link VanillaStructureRule#and}: any module may block the platform's starts. Shifts add up; reaches are all covered;
* setups combine with {@link VanillaStructureSetup#and}. Every method may be called from any thread, concurrently, but
* one chunk's {@link StructureFit} is used on one thread.
*/
@Service(Providers.ALL)
public interface VanillaStructures {
/** What this module wants for the platform structure {@code structure}, such as {@code minecraft:village_plains},
* in the world {@code context} describes. {@link VanillaStructureRule#GENERATE} when the module has no part in it.
*/
default VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) {
return VanillaStructureRule.GENERATE;
}
/** The platform structures this module starts in chunk {@code chunkX, chunkZ}: starts the platform generates from
* that chunk, wherever its own placement rules would put them. At most one start per structure and chunk counts;
* the host keeps the first, in module id order. Decided from the world and the chunk only, so the same chunk always
* gets the same starts: the host asks again when it locates structures and when it checks a start it finds in
* the world.
*/
default List<VanillaStructureStart> starts(int chunkX, int chunkZ, VanillaStructureStartContext context) {
return List.of();
}
/** How many blocks the platform's own start {@code start} moves up (negative: down) before the host publishes it.
* Decided from the start's place and the terrain only, so asking again for the same start gives the same answer:
* the host asks again when it predicts where the platform's starts end up. The host keeps the start inside the
* world, moving it less when it would leave it. 0 when the module has no part in it.
*/
default int shift(PlatformStart start, VanillaStructureContext context) {
return 0;
}
/** How far around its pieces this module changes the terrain for a start of {@code structure}: a start the module
* placed itself, with the {@code memo} it gave it, or one of the platform's own starts (no memo; {@code underground}
* says whether the platform generates the structure in one of its underground steps). The platform hands the start to
* every chunk the reach covers, so {@link #beforePieces} sees it there. {@link StartReach#PLATFORM} when the module
* changes no more than the platform's own terrain adaptation would.
*/
default StartReach reach(ResourceId structure, boolean underground, Optional<StartMemo> memo,
VanillaStructureContext context) {
return StartReach.PLATFORM;
}
/** Called once per chunk before the platform places any piece of {@code fit}'s starts there: the module fits the
* terrain to the starts it cares about, writing only inside {@link StructureFit#area()}.
*/
default void beforePieces(StructureFit fit) {
}
/** Called after the platform placed the pieces of {@code placed}, one of {@code fit}'s starts, in the chunk, before
* it places the next start's; the last call of a chunk is for the last of {@link StructureFit#starts()}.
*/
default void afterPieces(StructureFit fit, StructureFit.Start placed) {
}
/** What this module changes about how the platform sets up its structures for the dimension {@code context}
* describes. Protecting the platform's definitions in one dimension protects them in every data pack the host
* installs, since those are shared by every world. {@link VanillaStructureSetup#UNCHANGED} when the module has no
* part in it.
*/
default VanillaStructureSetup setup(VanillaStructureContext context) {
return VanillaStructureSetup.UNCHANGED;
}
/** The platform structures this module starts itself in {@code world} ({@link #starts}), wherever its own placements put
* them. The host's locate and structure commands send them to {@link #locateStart}.
*/
default Set<ResourceId> startedStructures(PackWorld world) {
return Set.of();
}
/** Those of {@link #startedStructures} whose starts {@link #locateStart} can find in {@code world}: a start whose
* placement can never start in the world's height, for one, cannot be searched for.
*/
default Set<ResourceId> locatableStarts(PackWorld world) {
return Set.of();
}
/**
* The start of the platform structure {@code structure} this module makes nearest to the column {@code fromX},
* {@code fromZ} (world coordinates), searched ring by ring outward through its placements' grids up to {@code maxRings}
* rings: the nearest start of the first ring that has one. The position is the start's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Only chunks {@code accepts} allows count; the host checks the start
* the platform made there and searches again without a chunk it refuses. An exception {@code accepts} throws ends the
* search and reaches the caller. Called with a structure from {@link #locatableStarts}, off the server's main thread.
*/
default LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings,
ChunkFilter accepts) {
return LocateResult.NOT_FOUND;
}
/** Which chunks a {@link #locateStart} search may answer with. */
@FunctionalInterface
interface ChunkFilter {
boolean accepts(int chunkX, int chunkZ);
}
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
@FunctionalInterface
public interface BlockCollector<O> {
void collect(BlockStageContext context, O accumulator);
}
@@ -0,0 +1,20 @@
package com.volmit.stage;
/** Runs once per object block of a placement. Block stages that are adjacent in the resolved
* order share one loop over the object's blocks; a placement stage between them splits the pass.
*/
public final class BlockStage<O> extends Stage<O> {
BlockStage(String id, Class<O> accumulatorType) {
super(id, accumulatorType);
}
@Override
public Pipeline pipeline() {
return Pipeline.PLACEMENT;
}
@Override
public StageKind kind() {
return StageKind.BLOCK;
}
}
@@ -0,0 +1,16 @@
package com.volmit.stage;
import com.volmit.object.ObjectBlock;
/** The current object block of a block pass, in object-local coordinates. Every pass starts
* from the request's object blocks; replacements and skips are visible only to later stages
* of the same pass for the same block.
*/
public interface BlockStageContext extends PlacementStageContext {
ObjectBlock block();
void replace(ObjectBlock block);
/** Later stages of this pass do not see the current block. */
void skip();
}
@@ -0,0 +1,40 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import java.util.function.Supplier;
/** Declares one per-block placement stage. Requiring another block stage orders the two per block within a fused
* pass. A block stage's accumulator becomes readable only after its pass. Edges work as on
* {@link PlacementStageDefinition}.
*/
public interface BlockStageDefinition<O> {
BlockStageDefinition<O> requires(Stage<?>... stages);
BlockStageDefinition<O> softAfter(Stage<?>... stages);
BlockStageDefinition<O> softAfter(StageRef... stages);
BlockStageDefinition<O> softBefore(Stage<?>... stages);
BlockStageDefinition<O> softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond the placed
* object's X/Z bounds. The host prepares that much around every placement. Leaving it out means 0.
*/
BlockStageDefinition<O> reach(int blocks);
/** Declares the mantle layers this stage writes; each must be registered by some module. */
BlockStageDefinition<O> writesMantle(MantleKey<?>... layers);
/** Activates the stage only where the placement declares the given settings; the body reads them with
* {@link StageContext#configured}. See {@link StageGraph} for who may name a settings type.
*/
BlockStageDefinition<O> when(Class<? extends IrisFeature> settingsType);
/** Body for a block stage without accumulator. */
void run(StageAction<BlockStageContext> action);
/** Body for a block stage whose accumulator, created once per placement, is its output. */
void accumulate(Supplier<O> initial, BlockCollector<O> collector);
}
@@ -0,0 +1,20 @@
package com.volmit.stage;
/** Runs once per chunk generation invocation and writes only its own chunk. It may read the mantle but
* not write it, and it declares no reach: such work belongs in a {@link MantleStage}.
*/
public final class ChunkStage<O> extends Stage<O> {
ChunkStage(String id, Class<O> outputType) {
super(id, outputType);
}
@Override
public Pipeline pipeline() {
return Pipeline.CHUNK;
}
@Override
public StageKind kind() {
return StageKind.INVOCATION;
}
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
import com.volmit.generation.GenerationContext;
/** One chunk generation invocation with access to the host's typed local hunks. */
public interface ChunkStageContext extends GenerationContext, StageContext {}
@@ -0,0 +1,31 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
/** Declares one chunk stage. A chunk stage writes only its own chunk, its blocks and its columns of the mantle, and
* reads the mantle around it, so it declares neither a reach nor mantle layers: work that writes the mantle beyond its
* chunk is a {@link MantleStage}. Edges work as on {@link PlacementStageDefinition}.
*/
public interface ChunkStageDefinition<O> {
ChunkStageDefinition<O> requires(Stage<?>... stages);
ChunkStageDefinition<O> softAfter(Stage<?>... stages);
ChunkStageDefinition<O> softAfter(StageRef... stages);
ChunkStageDefinition<O> softBefore(Stage<?>... stages);
ChunkStageDefinition<O> softBefore(StageRef... stages);
/** Activates the stage only where any column of the chunk configures the given settings; the body reads every
* distinct entry of those columns with {@link StageContext#configured}. See {@link StageGraph} for who may name a
* settings type.
*/
ChunkStageDefinition<O> when(Class<? extends IrisFeature> settingsType);
/** Body for a stage without output. */
void run(StageAction<ChunkStageContext> action);
/** Body for a stage with output; a null result fails the invocation. */
void produce(StageFunction<ChunkStageContext, O> function);
}
@@ -0,0 +1,22 @@
package com.volmit.stage;
/** Runs once per chunk in the mantle pipeline, before the chunks it reaches generate. Every mantle stage is
* its own pass: the host runs it for every chunk around a generating chunk before the next stage starts,
* so a stage sees what earlier stages wrote into neighboring chunks. Mantle stages therefore have no
* output; they pass data on through mantle layers.
*/
public final class MantleStage extends Stage<Void> {
MantleStage(String id) {
super(id, Void.class);
}
@Override
public Pipeline pipeline() {
return Pipeline.MANTLE;
}
@Override
public StageKind kind() {
return StageKind.INVOCATION;
}
}
@@ -0,0 +1,6 @@
package com.volmit.stage;
import com.volmit.generation.MantleGenerationContext;
/** One mantle invocation for one chunk: the mantle around it, without a block hunk. */
public interface MantleStageContext extends MantleGenerationContext, StageContext {}
@@ -0,0 +1,40 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
/** Declares one mantle stage. Mantle stages have no output: each runs as its own pass and passes data on through
* mantle layers. Edges work as on {@link PlacementStageDefinition}.
*/
public interface MantleStageDefinition {
MantleStageDefinition requires(Stage<?>... stages);
MantleStageDefinition softAfter(Stage<?>... stages);
MantleStageDefinition softAfter(StageRef... stages);
MantleStageDefinition softBefore(Stage<?>... stages);
MantleStageDefinition softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes mantle values beyond its chunk. The host prepares
* that much around every chunk the stage runs for. Leaving it out means 0.
*/
MantleStageDefinition reach(int blocks);
/** Declares a reach the host works out from the pack's settings when the pack loads, for a stage whose reach
* depends on the pack, such as the largest object any level configures.
*/
MantleStageDefinition reach(PackReach reach);
/** Declares the mantle layers this stage writes; each must be registered by some module. */
MantleStageDefinition writesMantle(MantleKey<?>... layers);
/** Activates the stage only where any column of the chunk configures the given settings; the body reads every
* distinct entry of those columns with {@link StageContext#configured}. See {@link StageGraph} for who may name a
* settings type.
*/
MantleStageDefinition when(Class<? extends IrisFeature> settingsType);
void run(StageAction<MantleStageContext> action);
}
@@ -0,0 +1,13 @@
package com.volmit.stage;
import com.volmit.config.PackSettings;
/** How far a mantle stage writes beyond its chunk, worked out when the pack loads, for work whose size
* depends on the pack, such as the largest object or the longest vein any level configures. The host
* calls it once per pack load, before generating, and prepares that much around every chunk.
*/
@FunctionalInterface
public interface PackReach {
/** Blocks along X and Z beyond the chunk's 16 by 16 columns; never negative. */
int blocks(PackSettings settings);
}
@@ -0,0 +1,17 @@
package com.volmit.stage;
/** Independent stage graphs. A stage belongs to exactly one pipeline; edges never cross them. */
public enum Pipeline {
/** Runs once per object placement attempt, against one buffered placement edit. */
PLACEMENT,
/** Runs once per chunk generation invocation, against host-owned local hunks. Its stages write only
* their own chunk and read the mantle.
*/
CHUNK,
/** Runs once per chunk before any chunk near it generates, against the mantle only: work that writes
* the mantle or reaches beyond its chunk. The host runs each stage as its own pass, in resolved order,
* around a chunk as far as that stage's reach plus every later stage's, so a chunk's mantle is
* complete when the chunk pipeline reads it.
*/
MANTLE
}
@@ -0,0 +1,18 @@
package com.volmit.stage;
/** Runs once per placement attempt. */
public final class PlacementStage<O> extends Stage<O> {
PlacementStage(String id, Class<O> outputType) {
super(id, outputType);
}
@Override
public Pipeline pipeline() {
return Pipeline.PLACEMENT;
}
@Override
public StageKind kind() {
return StageKind.INVOCATION;
}
}
Loaded 100 of 309 files, more files were not shown because too many files have changed in this diff. Show more