Move noise runtime state into the engine pack runtime

- Add SeedTable for bounded per-seed lookups
- Add GeneratorRuntime and ExpressionRuntime for engine-derived generator and expression state
- Build style, noise layer, generator and expression state through PackRuntime tables
- Pass PackRuntime through noise, generator and expression sampling instead of IrisData and Engine
- Remove engine-keyed caches from IrisGeneratorStyle, IrisNoiseGenerator, IrisGenerator, IrisExpression, IrisExpressionFunction and IrisExpressionLoad
- Give export compilers and studio tools their own standalone runtime scope
- Drop the migrated noise entries from the pending ledger
- Update noise, expression and caller tests to the runtime API
This commit is contained in:
piexel committed 2026-11-26 18:35:40 +01:00
1 parent 43cc702a9e
commit 305dbd63e3
90 files changed
+1162 -1188

No files matched your search

@@ -3,6 +3,7 @@ package art.arcane.iris.generation.bake;
import art.arcane.iris.generation.noise.GeneratorProgram; import art.arcane.iris.generation.noise.GeneratorProgram;
import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.TerrainBatchScratch; import art.arcane.iris.generation.noise.TerrainBatchScratch;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.M;
import java.util.Arrays; import java.util.Arrays;
@@ -12,26 +13,28 @@ public final class TerrainProgram {
private static final int CONSTANT = 1; private static final int CONSTANT = 1;
private static final int ACTIVE = 2; private static final int ACTIVE = 2;
private final PackRuntime runtime;
private final IrisGenerator[][] generators; private final IrisGenerator[][] generators;
private final GeneratorProgram[][] programs; private final GeneratorProgram[][] programs;
private final long heightSeed; private final long heightSeed;
private TerrainProgram(IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) { private TerrainProgram(PackRuntime runtime, IrisGenerator[][] generators, GeneratorProgram[][] programs, long heightSeed) {
this.runtime = runtime;
this.generators = generators; this.generators = generators;
this.programs = programs; this.programs = programs;
this.heightSeed = heightSeed; this.heightSeed = heightSeed;
} }
public static TerrainProgram compile(IrisGenerator[][] generators, long heightSeed) { public static TerrainProgram compile(PackRuntime runtime, IrisGenerator[][] generators, long heightSeed) {
GeneratorProgram[][] programs = new GeneratorProgram[generators.length][]; GeneratorProgram[][] programs = new GeneratorProgram[generators.length][];
for (int group = 0; group < generators.length; group++) { for (int group = 0; group < generators.length; group++) {
programs[group] = new GeneratorProgram[generators[group].length]; programs[group] = new GeneratorProgram[generators[group].length];
for (int index = 0; index < generators[group].length; index++) { for (int index = 0; index < generators[group].length; index++) {
IrisGenerator generator = generators[group][index]; IrisGenerator generator = generators[group][index];
programs[group][index] = generator.supportsBatch() ? generator.compileProgram(heightSeed) : null; programs[group][index] = generator.supportsBatch() ? generator.compileProgram(runtime, heightSeed) : null;
} }
} }
return new TerrainProgram(generators, programs, heightSeed); return new TerrainProgram(runtime, generators, programs, heightSeed);
} }
public long heightSeed() { public long heightSeed() {
@@ -58,7 +61,7 @@ public final class TerrainProgram {
GeneratorProgram[] compiled = programs[group]; GeneratorProgram[] compiled = programs[group];
for (int member = 0; member < members.length; member++) { for (int member = 0; member < members.length; member++) {
GeneratorProgram program = compiled[member]; GeneratorProgram program = compiled[member];
double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(x, z, heightSeed); double noise = program != null ? program.height(scratch, x, z) : members[member].getHeight(runtime, x, z, heightSeed);
if (!Double.isFinite(noise)) { if (!Double.isFinite(noise)) {
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
+ " (generator=" + members[member].getLoadKey() + ", noise=" + noise + " (generator=" + members[member].getLoadKey() + ", noise=" + noise
@@ -148,7 +151,7 @@ public final class TerrainProgram {
program.heights(scratch, activeX, activeZ, activeCount, noise); program.heights(scratch, activeX, activeZ, activeCount, noise);
} else { } else {
for (int index = 0; index < activeCount; index++) { for (int index = 0; index < activeCount; index++) {
noise[index] = members[member].getHeight(activeX[index], activeZ[index], heightSeed); noise[index] = members[member].getHeight(runtime, activeX[index], activeZ[index], heightSeed);
} }
} }
for (int index = 0; index < activeCount; index++) { for (int index = 0; index < activeCount; index++) {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome; package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator; import art.arcane.iris.generation.decoration.IrisDecorator;
@@ -471,9 +472,10 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
public double getHeight(Engine xg, double x, double z, long seed) { public double getHeight(Engine xg, double x, double z, long seed) {
double height = 0; double height = 0;
PackRuntime runtime = PackRuntime.of(xg, xg.getData());
for (IrisBiomeGeneratorLink i : generators) { for (IrisBiomeGeneratorLink i : generators) {
height += i.getHeight(xg, x, z, seed); height += i.getHeight(runtime, x, z, seed);
} }
return Math.max(0, Math.min(height, xg.getHeight())); return Math.max(0, Math.min(height, xg.getHeight()));
@@ -512,7 +514,7 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
private CNG createBiomeGenerator(long seed, IrisData loader) { private CNG createBiomeGenerator(long seed, IrisData loader) {
int signature = 213949 + 228888 + getRarity() + getName().length(); int signature = 213949 + 228888 + getRarity() + getName().length();
return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), loader); return biomeStyle.createNoCache(new RNG(seed).nextParallelRNG(signature), PackRuntime.forContext(loader));
} }
public CNG getChildrenGenerator(RNG random, int sig, double scale) { public CNG getChildrenGenerator(RNG random, int sig, double scale) {
@@ -528,7 +530,7 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
} }
ChildGeneratorKey key = new ChildGeneratorKey(seed, scale, data, engine); ChildGeneratorKey key = new ChildGeneratorKey(seed, scale, data, engine);
CNG generator = childrenGenerators.computeIfAbsent(key, CNG generator = childrenGenerators.computeIfAbsent(key,
ignored -> getChildStyle().createScaledGenerator(new RNG(seed), data, scale)); ignored -> getChildStyle().createScaledGenerator(new RNG(seed), PackRuntime.of(engine, data), scale));
recentChildGenerator = new CachedChildGenerator(key, generator); recentChildGenerator = new CachedChildGenerator(key, generator);
return generator; return generator;
} }
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome; package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.cache.AtomicCache;
@@ -81,8 +82,8 @@ public class IrisBiomeGeneratorLink {
}); });
} }
public double getHeight(DataProvider xg, double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
double g = getCachedGenerator(xg).getHeight(x, z, seed); double g = getCachedGenerator(runtime::data).getHeight(runtime, x, z, seed);
g = g < 0 ? 0 : g; g = g < 0 ? 0 : g;
g = g > 1 ? 1 : g; g = g > 1 ? 1 : g;
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome; package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
@@ -155,7 +156,7 @@ public class IrisBiomePaletteLayer {
LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed); LayerGeneratorKey key = new LayerGeneratorKey(data, engine, generatorSeed);
CNG generator = layerGenerators.computeIfAbsent(key, CNG generator = layerGenerators.computeIfAbsent(key,
ignored -> style.create(new RNG(generatorSeed), data, engine)); ignored -> style.create(new RNG(generatorSeed), PackRuntime.of(engine, data)));
if (generator != null) { if (generator != null) {
recentLayerGenerators.setRelease(slot, new CachedLayerGenerator(key, generator)); recentLayerGenerators.setRelease(slot, new CachedLayerGenerator(key, generator));
} }
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.biome; package art.arcane.iris.generation.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveProfileSampler; import art.arcane.iris.generation.cave.IrisCaveProfileSampler;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
@@ -77,7 +78,7 @@ public class IrisFloatingChildBiomes implements Rarity {
private final transient AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>(); private final transient AtomicCache<IrisObjectScale> shrinkScaleCache = new AtomicCache<>();
public CNG getFootprintCng(long baseSeed, IrisData data) { public CNG getFootprintCng(long baseSeed, IrisData data) {
return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, data); return getFootprintStyle().create(baseSeed ^ 0xF007B17DL, PackRuntime.forContext(data));
} }
public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) { public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) {
@@ -93,7 +94,7 @@ public class IrisFloatingChildBiomes implements Rarity {
getEdgeTaperVariationAmplitude(), width); getEdgeTaperVariationAmplitude(), width);
IrisGeneratorStyle style = getEdgeTaperVariationStyle(); IrisGeneratorStyle style = getEdgeTaperVariationStyle();
CNG variation = amplitude > 0.0D && style != null CNG variation = amplitude > 0.0D && style != null
? style.create(baseSeed ^ 0xED6E7A9E5L, data) ? style.create(baseSeed ^ 0xED6E7A9E5L, PackRuntime.forContext(data))
: null; : null;
return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation); return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation);
}); });
@@ -102,19 +103,19 @@ public class IrisFloatingChildBiomes implements Rarity {
} }
public CNG getPickerCng(long baseSeed, IrisData data) { public CNG getPickerCng(long baseSeed, IrisData data) {
return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, data); return getPickerStyle().create(baseSeed ^ 0x91C4E72DL, PackRuntime.forContext(data));
} }
public CNG getAltitudeCng(long baseSeed, IrisData data) { public CNG getAltitudeCng(long baseSeed, IrisData data) {
return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, data); return getAltitudeStyle().create(baseSeed ^ 0xA17DEBBL, PackRuntime.forContext(data));
} }
public CNG getTopShapeCng(long baseSeed, IrisData data) { public CNG getTopShapeCng(long baseSeed, IrisData data) {
return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, data); return getTopShapeStyle().create(baseSeed ^ 0x70970601DEFL, PackRuntime.forContext(data));
} }
public CNG getBottomCng(long baseSeed, IrisData data) { public CNG getBottomCng(long baseSeed, IrisData data) {
return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, data); return getBottomStyle().create(baseSeed ^ 0xB0770075CAFEL, PackRuntime.forContext(data));
} }
public CNG getWallWarpCng(long baseSeed, IrisData data) { public CNG getWallWarpCng(long baseSeed, IrisData data) {
@@ -122,7 +123,7 @@ public class IrisFloatingChildBiomes implements Rarity {
if (style == null) { if (style == null) {
return null; return null;
} }
return style.create(baseSeed ^ 0xA117BA17E0FL, data); return style.create(baseSeed ^ 0xA117BA17E0FL, PackRuntime.forContext(data));
} }
public CNG getCarveCng(long baseSeed, IrisData data) { public CNG getCarveCng(long baseSeed, IrisData data) {
@@ -130,7 +131,7 @@ public class IrisFloatingChildBiomes implements Rarity {
if (style == null) { if (style == null) {
return null; return null;
} }
return style.create(baseSeed ^ 0xCA5EC1EE5EL, data); return style.create(baseSeed ^ 0xCA5EC1EE5EL, PackRuntime.forContext(data));
} }
public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) {
@@ -22,7 +22,7 @@ import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.generation.noise.IrisStyledRange; import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.M;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
@@ -52,18 +52,18 @@ public final class IrisCaveProfileSampler {
private final boolean hasModules; private final boolean hasModules;
public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) { public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) {
IrisData data = engine.getData(); PackRuntime runtime = PackRuntime.of(engine, engine.getData());
this.profile = profile; this.profile = profile;
List<ModuleState> moduleStates = new ArrayList<>(); List<ModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve()); RNG baseRng = new RNG(engine.getSeedManager().getCarve());
this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime);
this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime);
this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime);
IrisStyledRange threshold = profile.getDensityThreshold(); IrisStyledRange threshold = profile.getDensityThreshold();
thresholdMin = threshold.getMin(); thresholdMin = threshold.getMin();
thresholdMax = threshold.getMax(); thresholdMax = threshold.getMax();
thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat(); thresholdHasNoise = thresholdMin != thresholdMax && !threshold.getStyle().isFlat();
thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), data) : null; thresholdDensity = thresholdHasNoise ? threshold.getStyle().create(baseRng.nextParallelRNG(489_112), runtime) : null;
constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D); constantThreshold = thresholdMin == thresholdMax ? thresholdMin : M.lerp(thresholdMin, thresholdMax, 0.5D);
this.baseWeight = profile.getBaseWeight(); this.baseWeight = profile.getBaseWeight();
this.detailWeight = profile.getDetailWeight(); this.detailWeight = profile.getDetailWeight();
@@ -73,7 +73,7 @@ public final class IrisCaveProfileSampler {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight); double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0; int index = 0;
for (IrisCaveFieldModule module : profile.getModules()) { for (IrisCaveFieldModule module : profile.getModules()) {
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
ModuleState state = new ModuleState(module, moduleDensity); ModuleState state = new ModuleState(module, moduleDensity);
moduleStates.add(state); moduleStates.add(state);
weight += Math.abs(state.weight); weight += Math.abs(state.weight);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration; package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.cache.LazyBoundedCache;
@@ -133,13 +134,13 @@ public class IrisDecorator {
AtomicCache<CNG> cache = generators(rng, data).height; AtomicCache<CNG> cache = generators(rng, data).height;
CNG cached = cache.getIfPresent(); CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() -> return cached != null ? cached : cache.aquire(() ->
heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data)); heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), PackRuntime.forContext(data)));
} }
public CNG getGenerator(RNG rng, IrisData data) { public CNG getGenerator(RNG rng, IrisData data) {
AtomicCache<CNG> cache = generators(rng, data).layer; AtomicCache<CNG> cache = generators(rng, data).layer;
CNG cached = cache.getIfPresent(); CNG cached = cache.getIfPresent();
return cached != null ? cached : cache.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data)); return cached != null ? cached : cache.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), PackRuntime.forContext(data)));
} }
public CNG getVarianceGenerator(RNG rng, IrisData data) { public CNG getVarianceGenerator(RNG rng, IrisData data) {
@@ -161,7 +162,7 @@ public class IrisDecorator {
} }
private CNG createVarianceGenerator(RNG rng, IrisData data) { private CNG createVarianceGenerator(RNG rng, IrisData data) {
return variance.createNoCache(deriveVarianceSeed(rng, data), data).scale(1D / variance.getZoom()); return variance.createNoCache(deriveVarianceSeed(rng, data), PackRuntime.forContext(data)).scale(1D / variance.getZoom());
} }
RNG deriveVarianceSeed(RNG rng, IrisData data) { RNG deriveVarianceSeed(RNG rng, IrisData data) {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.decoration; package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisMaterialPalette;
@@ -95,7 +96,7 @@ public class IrisOreGenerator {
return recent.chance; return recent.chance;
} }
ChanceKey key = new ChanceKey(seed, data, engine); ChanceKey key = new ChanceKey(seed, data, engine);
OreChance selected = chanceCache.computeIfAbsent(key, ignored -> OreChance.of(chanceStyle.create(rng, data))); OreChance selected = chanceCache.computeIfAbsent(key, ignored -> OreChance.of(chanceStyle.create(rng, PackRuntime.of(engine, data))));
recentChance = new CachedChance(key, selected); recentChance = new CachedChance(key, selected);
return selected; return selected;
} }
@@ -60,7 +60,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource,
this.focus = complex.getFocusBiome(); this.focus = complex.getFocusBiome();
this.binding = Objects.requireNonNull(binding, "binding"); this.binding = Objects.requireNonNull(binding, "binding");
this.climate = settings.climate(); this.climate = settings.climate();
this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getData()) : null; this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getPackRuntime()) : null;
} }
@Override @Override
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.mantle; package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.GenerationCounter; import art.arcane.iris.generation.runtime.GenerationCounter;
@@ -78,6 +79,7 @@ public class IrisCaveCarver3D {
private final Engine engine; private final Engine engine;
private final IrisData data; private final IrisData data;
private final PackRuntime runtime;
private final IrisCaveProfile profile; private final IrisCaveProfile profile;
private final NoiseProgram baseDensity; private final NoiseProgram baseDensity;
private final NoiseProgram detailDensity; private final NoiseProgram detailDensity;
@@ -122,6 +124,7 @@ public class IrisCaveCarver3D {
this.engine = engine; this.engine = engine;
this.densityGrid = densityGrid; this.densityGrid = densityGrid;
this.data = engine.getData(); this.data = engine.getData();
this.runtime = PackRuntime.of(engine, data);
this.profile = profile; this.profile = profile;
this.carveAir = new MatterCavern(true, "", LIQUID_AIR); this.carveAir = new MatterCavern(true, "", LIQUID_AIR);
this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID);
@@ -130,10 +133,10 @@ public class IrisCaveCarver3D {
List<CaveFieldModuleState> moduleStates = new ArrayList<>(); List<CaveFieldModuleState> moduleStates = new ArrayList<>();
RNG baseRng = new RNG(engine.getSeedManager().getCarve()); RNG baseRng = new RNG(engine.getSeedManager().getCarve());
this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data)); this.baseDensity = NoiseProgram.compileSigned3D(profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), runtime));
this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data)); this.detailDensity = NoiseProgram.compileSigned3D(profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), runtime));
this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data)); this.warpDensity = NoiseProgram.compileSigned3D(profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), runtime));
this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), runtime);
this.thresholdRng = baseRng.nextParallelRNG(489_112); this.thresholdRng = baseRng.nextParallelRNG(489_112);
this.baseWeight = profile.getBaseWeight(); this.baseWeight = profile.getBaseWeight();
this.detailWeight = profile.getDetailWeight(); this.detailWeight = profile.getDetailWeight();
@@ -149,7 +152,7 @@ public class IrisCaveCarver3D {
double weight = Math.abs(baseWeight) + Math.abs(detailWeight); double weight = Math.abs(baseWeight) + Math.abs(detailWeight);
int index = 0; int index = 0;
for (IrisCaveFieldModule module : profile.getModules()) { for (IrisCaveFieldModule module : profile.getModules()) {
CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), runtime);
CaveFieldModuleState state = new CaveFieldModuleState(module, NoiseProgram.compileSigned3D(moduleDensity)); CaveFieldModuleState state = new CaveFieldModuleState(module, NoiseProgram.compileSigned3D(moduleDensity));
moduleStates.add(state); moduleStates.add(state);
weight += Math.abs(state.weight); weight += Math.abs(state.weight);
@@ -342,7 +345,7 @@ public class IrisCaveCarver3D {
} else if (densityThreshold.getStyle().isFlat()) { } else if (densityThreshold.getStyle().isFlat()) {
constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5);
} else { } else {
thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); thresholdDensity = densityThreshold.getStyle().create(thresholdRng, runtime);
} }
for (int lx = 0; lx < 16; lx++) { for (int lx = 0; lx < 16; lx++) {
@@ -24,9 +24,9 @@ import art.arcane.volmlib.util.math.RNG;
public class ExpressionNoise implements NoiseGenerator { public class ExpressionNoise implements NoiseGenerator {
private final RNG rng; private final RNG rng;
private final IrisExpression expression; private final ExpressionRuntime expression;
public ExpressionNoise(RNG rng, IrisExpression expression) { public ExpressionNoise(RNG rng, ExpressionRuntime expression) {
this.rng = rng; this.rng = rng;
this.expression = expression; this.expression = expression;
} }
@@ -0,0 +1,258 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import lombok.NonNull;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
/**
* An {@link IrisExpression} parsed for one runtime scope: its functions and variables read that scope's engine
* streams and seeded styles, so the parsed expression belongs to the scope and not to the pack object.
*/
public final class ExpressionRuntime {
private static final int SEED_CAPACITY = 8;
private static final int MAX_RETAINED_EVALUATION_DEPTH = 8;
private static final int MAX_RETAINED_ARGUMENTS = 256;
private static final ThreadLocal<EvaluationScratch> EVALUATION_SCRATCH =
ThreadLocal.withInitial(EvaluationScratch::new);
private final VariableRuntime[] variables;
private final Expression parsed;
private final SeedTable<ProceduralStream<Double>> streams;
public ExpressionRuntime(IrisExpression expression, PackRuntime runtime) {
this.variables = expression.getVariables().stream()
.map(variable -> new VariableRuntime(variable, runtime))
.toArray(VariableRuntime[]::new);
this.parsed = expression.parse(function -> new FunctionRuntime(function, runtime));
this.streams = new SeedTable<>(SEED_CAPACITY, seed -> {
RNG streamRng = new RNG(seed);
return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z),
(x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE);
});
}
public ProceduralStream<Double> stream(RNG rng) {
return streams.get(rng.getSeed());
}
public double evaluate(RNG rng, double x, double z) {
EvaluationScratch scratch = EVALUATION_SCRATCH.get();
double[] arguments = scratch.acquire(3 + variables.length);
try {
int index = 0;
for (VariableRuntime variable : variables) {
arguments[index++] = variable.value(rng, x, z);
}
arguments[index++] = x;
arguments[index++] = z;
arguments[index] = -1;
return parsed.evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public double evaluate(RNG rng, double x, double y, double z) {
EvaluationScratch scratch = EVALUATION_SCRATCH.get();
double[] arguments = scratch.acquire(3 + variables.length);
try {
int index = 0;
for (VariableRuntime variable : variables) {
arguments[index++] = variable.value(rng, x, y, z);
}
arguments[index++] = x;
arguments[index++] = y;
arguments[index] = z;
return parsed.evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public record FunctionContext(@NonNull RNG rng) implements Context {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
FunctionContext that = (FunctionContext) o;
return rng.getSeed() == that.rng.getSeed();
}
@Override
public int hashCode() {
return Long.hashCode(rng.getSeed());
}
}
private static Engine requireEngine(PackRuntime runtime, String kind, String name) {
Engine engine = runtime.engine();
if (engine == null) {
throw new IllegalStateException("Expression " + kind + " '" + name + "' requires an active Iris engine.");
}
return engine;
}
private static final class FunctionRuntime implements DynamicFunction {
private final IrisExpressionFunction function;
private final PackRuntime runtime;
private final SeedTable<Provider> providers;
private FunctionRuntime(IrisExpressionFunction function, PackRuntime runtime) {
this.function = function;
this.runtime = runtime;
this.providers = new SeedTable<>(SEED_CAPACITY, this::createProvider);
}
@Override
public int getArgNumber() {
return function.argumentCount();
}
@NotNull
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... doubles) {
return 0;
}
@Override
public double eval(@Nullable Context raw, double... args) {
FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context");
return providers.get(context.rng().getSeed()).eval(args);
}
private Provider createProvider(long seed) {
if (function.getEngineStreamValue() != null) {
Engine engine = requireEngine(runtime, "function", function.getName());
ProceduralStream<Double> stream = function.getEngineStreamValue().get(engine);
return coordinates -> stream.get(coordinates[0], coordinates[1]);
}
if (function.getStyleValue() != null) {
return function.getStyleValue().create(seed, runtime)::noise;
}
return coordinates -> Double.NaN;
}
}
@FunctionalInterface
private interface Provider {
double eval(double... args);
}
private static final class VariableRuntime {
private final IrisExpressionLoad variable;
private final PackRuntime runtime;
private final SeedTable<CNG> styles;
private volatile ProceduralStream<Double> engineStream;
private volatile Double engineValue;
private VariableRuntime(IrisExpressionLoad variable, PackRuntime runtime) {
this.variable = variable;
this.runtime = runtime;
this.styles = new SeedTable<>(SEED_CAPACITY,
seed -> variable.getStyleValue().createNoCache(new RNG(seed), runtime));
}
private double value(RNG rng, double x, double z) {
if (variable.getEngineValue() != null) {
return engineValue();
}
if (variable.getEngineStreamValue() != null) {
return engineStream().get(x, z);
}
if (variable.getStyleValue() != null) {
return styles.get(rng.getSeed()).noise(x, z);
}
return variable.getStaticValue();
}
private double value(RNG rng, double x, double y, double z) {
if (variable.getEngineValue() != null) {
return engineValue();
}
if (variable.getEngineStreamValue() != null) {
return engineStream().get(x, z);
}
if (variable.getStyleValue() != null) {
return styles.get(rng.getSeed()).noise(x, y, z);
}
return variable.getStaticValue();
}
private double engineValue() {
Double value = engineValue;
if (value == null) {
value = variable.getEngineValue().get(requireEngine(runtime, "variable", variable.getName()));
engineValue = value;
}
return value;
}
private ProceduralStream<Double> engineStream() {
ProceduralStream<Double> stream = engineStream;
if (stream == null) {
stream = variable.getEngineStreamValue().get(requireEngine(runtime, "variable", variable.getName()));
engineStream = stream;
}
return stream;
}
}
private static final class EvaluationScratch {
private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][];
private int depth;
private double[] acquire(int length) {
double[] arguments;
if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) {
arguments = new double[length];
} else {
arguments = retained[depth];
if (arguments == null || arguments.length != length) {
arguments = new double[length];
retained[depth] = arguments;
}
}
depth++;
return arguments;
}
private void release() {
depth--;
}
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.interpolation.IrisInterpolation; import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import java.util.Arrays; import java.util.Arrays;
@@ -21,9 +22,14 @@ public final class GeneratorProgram {
private final double cliffHeightMin; private final double cliffHeightMin;
private final double cliffHeightMax; private final double cliffHeightMax;
private final boolean cellCracks; private final boolean cellCracks;
private final PackRuntime runtime;
private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes;
GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity, NoiseLayerProgram cliffs) { GeneratorProgram(IrisGenerator generator, long superSeed, NoiseLayerProgram[] layers, double totalOpacity,
NoiseLayerProgram cliffs, PackRuntime runtime) {
this.generator = generator; this.generator = generator;
this.runtime = runtime;
this.surfaceStripes = runtime.generator(generator).surfaceStripes();
this.superSeed = superSeed; this.superSeed = superSeed;
this.layers = layers; this.layers = layers;
this.totalOpacity = totalOpacity; this.totalOpacity = totalOpacity;
@@ -69,7 +75,7 @@ public final class GeneratorProgram {
double lowerZ = Math.floor(z / SURFACE_GRID) * SURFACE_GRID; double lowerZ = Math.floor(z / SURFACE_GRID) * SURFACE_GRID;
double dx = (x - lowerX) / SURFACE_GRID; double dx = (x - lowerX) / SURFACE_GRID;
double dz = (z - lowerZ) / SURFACE_GRID; double dz = (z - lowerZ) / SURFACE_GRID;
IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes(); IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes;
double northWest = lattice(scratch, stripes, lowerX, lowerZ); double northWest = lattice(scratch, stripes, lowerX, lowerZ);
if (dx == 0D && dz == 0D) { if (dx == 0D && dz == 0D) {
return northWest; return northWest;
@@ -124,7 +130,7 @@ public final class GeneratorProgram {
double height = IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, cliffs.sample(scratch, sampleX, sampleZ)); double height = IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, cliffs.sample(scratch, sampleX, sampleZ));
value = (Math.round((value * 255D) / height) * height) / 255D; value = (Math.round((value * 255D) / height) * height) / 255D;
} }
return cellCracks ? generator.cell(x, z, value, 0D) : value; return cellCracks ? generator.cell(runtime, x, z, value, 0D) : value;
} }
private void surfaceHeights(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) { private void surfaceHeights(TerrainBatchScratch scratch, double[] xs, double[] zs, int count, double[] out) {
@@ -226,7 +232,7 @@ public final class GeneratorProgram {
} }
private void resolveLattice(TerrainBatchScratch scratch, int nodes, double[] lattice) { private void resolveLattice(TerrainBatchScratch scratch, int nodes, double[] lattice) {
IrisGenerator.SurfaceCacheStripe[] stripes = generator.surfaceStripes(); IrisGenerator.SurfaceCacheStripe[] stripes = surfaceStripes;
int indexMark = scratch.indexMark(); int indexMark = scratch.indexMark();
int mark = scratch.mark(); int mark = scratch.mark();
try { try {
@@ -308,7 +314,7 @@ public final class GeneratorProgram {
} }
if (cellCracks) { if (cellCracks) {
for (int index = 0; index < count; index++) { for (int index = 0; index < count; index++) {
out[index] = generator.cell(xs[index], zs[index], out[index], 0D); out[index] = generator.cell(runtime, xs[index], zs[index], out[index], 0D);
} }
} }
} }
@@ -0,0 +1,45 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.SeedTable;
import art.arcane.volmlib.util.noise.CellGenerator;
/**
* What one engine derives from an {@link IrisGenerator}: the lattice of smoothed surface heights it has sampled and
* the cell generators of its crack seeds.
*/
public final class GeneratorRuntime {
private static final int CELL_SEED_CAPACITY = 8;
private final IrisGenerator.SurfaceCacheStripe[] surfaceStripes = IrisGenerator.createSurfaceStripes();
private final SeedTable<CellGenerator> cellGenerators;
public GeneratorRuntime(IrisGenerator generator) {
this.cellGenerators = new SeedTable<>(CELL_SEED_CAPACITY, generator::buildCellGenerator);
}
IrisGenerator.SurfaceCacheStripe[] surfaceStripes() {
return surfaceStripes;
}
public CellGenerator cellGenerator(long seed) {
return cellGenerators.get(seed);
}
}
@@ -20,28 +20,22 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import com.dfsek.paralithic.Expression; import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.eval.parser.Parser; import com.dfsek.paralithic.eval.parser.Parser;
import com.dfsek.paralithic.eval.parser.Scope; import com.dfsek.paralithic.eval.parser.Scope;
import art.arcane.iris.pack.loading.IrisRegistrant; import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import art.arcane.iris.generation.noise.IrisExpressionFunction.FunctionContext;
import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.util.function.Function;
@Accessors(chain = true) @Accessors(chain = true)
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@@ -49,9 +43,6 @@ import lombok.experimental.Accessors;
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class IrisExpression extends IrisRegistrant { public class IrisExpression extends IrisRegistrant {
private static final int MAX_RETAINED_EVALUATION_DEPTH = 8;
private static final int MAX_RETAINED_ARGUMENTS = 256;
@ArrayType(type = IrisExpressionLoad.class, min = 1) @ArrayType(type = IrisExpressionLoad.class, min = 1)
@Description("Variables to use in this expression") @Description("Variables to use in this expression")
private KList<IrisExpressionLoad> variables = new KList<>(); private KList<IrisExpressionLoad> variables = new KList<>();
@@ -64,88 +55,38 @@ public class IrisExpression extends IrisRegistrant {
@Description("The expression. Inherited variables are x, y and z. Avoid using those variable names.") @Description("The expression. Inherited variables are x, y and z. Avoid using those variable names.")
private String expression; private String expression;
private transient AtomicCache<Expression> expressionCache = new AtomicCache<>(); /**
@Getter(AccessLevel.NONE) * Parses this expression with each valid function bound to the runtime object the caller built for it.
@Setter(AccessLevel.NONE) * Returns null when the expression does not parse; the failure is reported.
private final transient LazyBoundedCache<Long, ProceduralStream<Double>> streams = new LazyBoundedCache<>(8); */
public Expression parse(Function<IrisExpressionFunction, DynamicFunction> functionRuntime) {
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
Parser parser = new Parser();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient ThreadLocal<EvaluationScratch> evaluationScratch = ThreadLocal.withInitial(EvaluationScratch::new);
private Expression expression() {
return expressionCache.aquire(() -> {
Scope scope = new Scope(); // Create variable scope. This scope can hold both constants and invocation variables.
Parser parser = new Parser();
try {
for (IrisExpressionLoad i : variables) {
scope.addInvocationVariable(i.getName());
}
scope.addInvocationVariable("x");
scope.addInvocationVariable("y");
scope.addInvocationVariable("z");
} catch (Throwable e) {
IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
}
for (IrisExpressionFunction f : functions) {
if (!f.isValid()) continue;
f.setData(getLoader());
parser.registerFunction(f.getName(), f);
}
try {
return parser.parse(getExpression(), scope);
} catch (Throwable e) {
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
}
return null;
});
}
public ProceduralStream<Double> stream(RNG rng) {
return streams.computeIfAbsent(rng.getSeed(), seed -> {
RNG streamRng = new RNG(seed);
return ProceduralStream.of((x, z) -> evaluate(streamRng, x, z),
(x, y, z) -> evaluate(streamRng, x, y, z), Interpolated.DOUBLE);
});
}
public double evaluate(RNG rng, double x, double z) {
EvaluationScratch scratch = evaluationScratch.get();
double[] arguments = scratch.acquire(3 + getVariables().size());
try { try {
int index = 0; for (IrisExpressionLoad i : variables) {
for (IrisExpressionLoad variable : getVariables()) { scope.addInvocationVariable(i.getName());
arguments[index++] = variable.getValue(rng, getLoader(), x, z);
} }
arguments[index++] = x;
arguments[index++] = z;
arguments[index] = -1;
return expression().evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
}
}
public double evaluate(RNG rng, double x, double y, double z) { scope.addInvocationVariable("x");
EvaluationScratch scratch = evaluationScratch.get(); scope.addInvocationVariable("y");
double[] arguments = scratch.acquire(3 + getVariables().size()); scope.addInvocationVariable("z");
try { } catch (Throwable e) {
int index = 0; IrisLogging.reportError("Script variable load failed in " + getLoadFile().getPath() + ".", e);
for (IrisExpressionLoad variable : getVariables()) {
arguments[index++] = variable.getValue(rng, getLoader(), x, y, z);
}
arguments[index++] = x;
arguments[index++] = y;
arguments[index] = z;
return expression().evaluate(new FunctionContext(rng), arguments);
} finally {
scratch.release();
} }
for (IrisExpressionFunction f : functions) {
if (!f.isValid()) continue;
parser.registerFunction(f.getName(), functionRuntime.apply(f));
}
try {
return parser.parse(getExpression(), scope);
} catch (Throwable e) {
IrisLogging.reportError("Script load failed in " + getLoadFile().getPath() + ".", e);
}
return null;
} }
@Override @Override
@@ -157,28 +98,4 @@ public class IrisExpression extends IrisRegistrant {
public String getTypeName() { public String getTypeName() {
return "Expression"; return "Expression";
} }
private static final class EvaluationScratch {
private final double[][] retained = new double[MAX_RETAINED_EVALUATION_DEPTH][];
private int depth;
private double[] acquire(int length) {
double[] arguments;
if (depth >= retained.length || length > MAX_RETAINED_ARGUMENTS) {
arguments = new double[length];
} else {
arguments = retained[depth];
if (arguments == null || arguments.length != length) {
arguments = new double[length];
retained[depth] = arguments;
}
}
depth++;
return arguments;
}
private void release() {
depth--;
}
}
} }
@@ -2,31 +2,15 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MinNumber; import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.stream.ProceduralStream;
import java.util.Objects;
import art.arcane.volmlib.util.math.RNG;
import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Snippet("expression-function") @Snippet("expression-function")
@Accessors(chain = true) @Accessors(chain = true)
@@ -35,7 +19,7 @@ import org.jetbrains.annotations.Nullable;
@Description("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.") @Description("Represents a function to use in your expression. Do not set the name to x, y, or z, also don't duplicate names.")
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class IrisExpressionFunction implements DynamicFunction { public class IrisExpressionFunction {
@Required @Required
@Description("The function to assign this value to. Do not set the name to x, y, or z") @Description("The function to assign this value to. Do not set the name to x, y, or z")
private String name; private String name;
@@ -50,102 +34,12 @@ public class IrisExpressionFunction implements DynamicFunction {
@Description("Number of arguments for the function") @Description("Number of arguments for the function")
private int args = 2; private int args = 2;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final LazyBoundedCache<FunctionKey, Provider> providers = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedProvider recentProvider;
private transient IrisData data;
public boolean isValid() { public boolean isValid() {
return styleValue != null || engineStreamValue != null; return styleValue != null || engineStreamValue != null;
} }
@Override public int argumentCount() {
public int getArgNumber() {
if (engineStreamValue != null) return 2; if (engineStreamValue != null) return 2;
return Math.max(args, 2); return Math.max(args, 2);
} }
@NotNull
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... doubles) {
return 0;
}
@Override
public double eval(@Nullable Context raw, double... args) {
FunctionContext context = Objects.requireNonNull((FunctionContext) raw, "Expression context");
IrisData currentData = data;
Engine engine = currentData == null ? null : currentData.getEngine();
long seed = context.rng.getSeed();
CachedProvider recent = recentProvider;
if (recent != null && recent.key.matches(seed, currentData, engine)) {
return recent.provider.eval(args);
}
FunctionKey key = new FunctionKey(seed, currentData, engine);
Provider provider = providers.computeIfAbsent(key, ignored -> createProvider(key));
recentProvider = new CachedProvider(key, provider);
return provider.eval(args);
}
private Provider createProvider(FunctionKey key) {
if (engineStreamValue != null) {
if (key.engine == null) {
throw new IllegalStateException("Expression function '" + name + "' requires an active Iris engine.");
}
ProceduralStream<Double> stream = engineStreamValue.get(key.engine);
return coordinates -> stream.get(coordinates[0], coordinates[1]);
}
if (styleValue != null) {
return styleValue.create(new RNG(key.seed), key.data, key.engine)::noise;
}
return coordinates -> Double.NaN;
}
private record FunctionKey(long seed, IrisData data, Engine engine) {
private boolean matches(long seed, IrisData data, Engine engine) {
return this.seed == seed && this.data == data && this.engine == engine;
}
@Override
public boolean equals(Object object) {
return object instanceof FunctionKey other && matches(other.seed, other.data, other.engine);
}
@Override
public int hashCode() {
int hash = Long.hashCode(seed);
hash = 31 * hash + System.identityHashCode(data);
return 31 * hash + System.identityHashCode(engine);
}
}
private record CachedProvider(FunctionKey key, Provider provider) {
}
public record FunctionContext(@NonNull RNG rng) implements Context {
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
FunctionContext that = (FunctionContext) o;
return rng.getSeed() == that.rng.getSeed();
}
@Override
public int hashCode() {
return Long.hashCode(rng.getSeed());
}
}
@FunctionalInterface
private interface Provider {
double eval(double... args);
}
} }
@@ -21,30 +21,15 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import art.arcane.iris.generation.runtime.IrisEngineValueType; import art.arcane.iris.generation.runtime.IrisEngineValueType;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Required; import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
@Snippet("expression-load") @Snippet("expression-load")
@Accessors(chain = true) @Accessors(chain = true)
@NoArgsConstructor @NoArgsConstructor
@@ -53,7 +38,6 @@ import java.util.Map;
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
public class IrisExpressionLoad { public class IrisExpressionLoad {
private static final int STYLE_CACHE_SIZE = 8;
@Required @Required
@Description("The variable to assign this value to. Do not set the name to x, y, or z") @Description("The variable to assign this value to. Do not set the name to x, y, or z")
private String name = ""; private String name = "";
@@ -69,119 +53,4 @@ public class IrisExpressionLoad {
@Description("If defined, iris will use an internal value from the engine as it's value") @Description("If defined, iris will use an internal value from the engine as it's value")
private IrisEngineValueType engineValue = null; private IrisEngineValueType engineValue = null;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final Map<Engine, EngineCache> engineCaches =
Collections.synchronizedMap(new IdentityHashMap<>());
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient final LazyBoundedCache<StandaloneStyleKey, CNG> standaloneStyleCache =
new LazyBoundedCache<>(STYLE_CACHE_SIZE);
public double getValue(RNG rng, IrisData data, double x, double z) {
if (engineValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
}
if (engineStreamValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
}
if (styleValue != null) {
return style(data, rng).noise(x, z);
}
return staticValue;
}
public double getValue(RNG rng, IrisData data, double x, double y, double z) {
if (engineValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).value.aquire(() -> engineValue.get(engine));
}
if (engineStreamValue != null) {
Engine engine = requireEngine(data);
return cacheFor(engine).stream.aquire(() -> engineStreamValue.get(engine)).get(x, z);
}
if (styleValue != null) {
return style(data, rng).noise(x, y, z);
}
return staticValue;
}
private Engine requireEngine(IrisData data) {
Engine engine = data.getEngine();
if (engine == null) {
throw new IllegalStateException("Expression variable '" + name + "' requires an active Iris engine.");
}
return engine;
}
private EngineCache cacheFor(Engine engine) {
synchronized (engineCaches) {
Iterator<Map.Entry<Engine, EngineCache>> iterator = engineCaches.entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getKey().isClosed()) {
iterator.remove();
}
}
EngineCache cache = engineCaches.get(engine);
if (cache != null) {
return cache;
}
EngineCache created = new EngineCache();
engineCaches.put(engine, created);
return created;
}
}
private CNG style(IrisData data, RNG rng) {
Engine engine = data.getEngine();
long seed = rng.getSeed();
if (engine != null) {
return cacheFor(engine).styles.computeIfAbsent(seed,
ignored -> styleValue.createNoCache(new RNG(seed), data));
}
StandaloneStyleKey key = new StandaloneStyleKey(data, seed);
return standaloneStyleCache.computeIfAbsent(key,
ignored -> styleValue.createNoCache(new RNG(seed), data));
}
private static final class EngineCache {
private final AtomicCache<ProceduralStream<Double>> stream = new AtomicCache<>();
private final AtomicCache<Double> value = new AtomicCache<>();
private final LazyBoundedCache<Long, CNG> styles = new LazyBoundedCache<>(STYLE_CACHE_SIZE);
}
private static final class StandaloneStyleKey {
private final IrisData data;
private final long seed;
private StandaloneStyleKey(IrisData data, long seed) {
this.data = data;
this.seed = seed;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof StandaloneStyleKey key)) {
return false;
}
return data == key.data && seed == key.seed;
}
@Override
public int hashCode() {
return 31 * System.identityHashCode(data) + Long.hashCode(seed);
}
}
} }
@@ -19,9 +19,7 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisRegistrant; import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.generation.cache.LazyBoundedCache; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber; import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -32,13 +30,10 @@ import art.arcane.volmlib.util.interpolation.IrisInterpolation;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CellGenerator; import art.arcane.volmlib.util.noise.CellGenerator;
import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.atomic.AtomicReferenceArray;
import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.util.List; import java.util.List;
@@ -54,15 +49,6 @@ public class IrisGenerator extends IrisRegistrant {
private static final int SURFACE_CACHE_STRIPES = 16; private static final int SURFACE_CACHE_STRIPES = 16;
private static final int SURFACE_CACHE_STRIPE_SIZE = 1024; private static final int SURFACE_CACHE_STRIPE_SIZE = 1024;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<Long, CellGenerator> cellGenerators = new LazyBoundedCache<>(8);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedCellGenerator recentCellGenerator;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile SurfaceCache surfaceSamples;
@MinNumber(0.001) @MinNumber(0.001)
@Description("The zoom or frequency.") @Description("The zoom or frequency.")
private double zoom = 1; private double zoom = 1;
@@ -119,21 +105,13 @@ public class IrisGenerator extends IrisRegistrant {
return cliffHeightMax > 0; return cliffHeightMax > 0;
} }
public CellGenerator getCellGenerator(long seed) { CellGenerator buildCellGenerator(long seed) {
CachedCellGenerator recent = recentCellGenerator; CellGenerator created = new CellGenerator(new RNG(seed + 239466));
if (recent != null && recent.seed == seed) { created.setShuffle(getCellFractureShuffle());
return recent.generator; return created;
}
CellGenerator generator = cellGenerators.computeIfAbsent(seed, ignored -> {
CellGenerator created = new CellGenerator(new RNG(seed + 239466));
created.setShuffle(getCellFractureShuffle());
return created;
});
recentCellGenerator = new CachedCellGenerator(seed, generator);
return generator;
} }
public <T> T fit(T[] v, long superSeed, double rx, double rz) { public <T> T fit(PackRuntime runtime, T[] v, long superSeed, double rx, double rz) {
if (v.length == 0) { if (v.length == 0) {
return null; return null;
} }
@@ -142,10 +120,10 @@ public class IrisGenerator extends IrisRegistrant {
return v[0]; return v[0];
} }
return v[fit(0, v.length - 1, superSeed, rx, rz)]; return v[fit(runtime, 0, v.length - 1, superSeed, rx, rz)];
} }
public <T> T fit(List<T> v, long superSeed, double rx, double rz) { public <T> T fit(PackRuntime runtime, List<T> v, long superSeed, double rx, double rz) {
if (v.size() == 0) { if (v.size() == 0) {
return null; return null;
} }
@@ -154,61 +132,59 @@ public class IrisGenerator extends IrisRegistrant {
return v.get(0); return v.get(0);
} }
return v.get(fit(0, v.size() - 1, superSeed, rx, rz)); return v.get(fit(runtime, 0, v.size() - 1, superSeed, rx, rz));
} }
public int fit(int min, int max, long superSeed, double rx, double rz) { public int fit(PackRuntime runtime, int min, int max, long superSeed, double rx, double rz) {
if (min == max) { if (min == max) {
return min; return min;
} }
double noise = getHeight(rx, rz, superSeed); double noise = getHeight(runtime, rx, rz, superSeed);
return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
} }
public int fit(double min, double max, long superSeed, double rx, double rz) { public int fit(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) {
if (min == max) { if (min == max) {
return (int) Math.round(min); return (int) Math.round(min);
} }
double noise = getHeight(rx, rz, superSeed); double noise = getHeight(runtime, rx, rz, superSeed);
return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); return (int) Math.round(IrisInterpolation.lerp(min, max, noise));
} }
public double fitDouble(double min, double max, long superSeed, double rx, double rz) { public double fitDouble(PackRuntime runtime, double min, double max, long superSeed, double rx, double rz) {
if (min == max) { if (min == max) {
return min; return min;
} }
double noise = getHeight(rx, rz, superSeed); double noise = getHeight(runtime, rx, rz, superSeed);
return IrisInterpolation.lerp(min, max, noise); return IrisInterpolation.lerp(min, max, noise);
} }
public double getHeight(double rx, double rz, long superSeed) { public double getHeight(PackRuntime runtime, double rx, double rz, long superSeed) {
return getHeight(rx, 0, rz, superSeed, true); return getHeight(runtime, rx, 0, rz, superSeed, true);
} }
public double getHeight(double rx, double ry, double rz, long superSeed) { public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed) {
return getHeight(rx, ry, rz, superSeed, false); return getHeight(runtime, rx, ry, rz, superSeed, false);
} }
public double getHeight(double rx, double ry, double rz, long superSeed, boolean no3d) { public double getHeight(PackRuntime runtime, double rx, double ry, double rz, long superSeed, boolean no3d) {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) { if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1"); throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
} }
if (composite.isEmpty()) { if (composite.isEmpty()) {
return 0D; return 0D;
} }
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
if (surfaceDetail == 1D) { if (surfaceDetail == 1D) {
return sampleHeight(rx, rz, superSeed, data, engine); return sampleHeight(rx, rz, superSeed, runtime);
} }
return surfaceHeight(rx, rz, superSeed, data, engine); return surfaceHeight(rx, rz, superSeed, runtime);
} }
public boolean supportsBatch() { public boolean supportsBatch() {
@@ -224,35 +200,28 @@ public class IrisGenerator extends IrisRegistrant {
return !hasCliffs() || cliffHeightGenerator.supportsBatch(); return !hasCliffs() || cliffHeightGenerator.supportsBatch();
} }
public GeneratorProgram compileProgram(long superSeed) { public GeneratorProgram compileProgram(PackRuntime runtime, long superSeed) {
if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) { if (!Double.isFinite(surfaceDetail) || surfaceDetail < 0D || surfaceDetail > 1D) {
throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1"); throw new IllegalArgumentException("Generator surfaceDetail must be finite and between 0 and 1");
} }
if (!supportsBatch()) { if (!supportsBatch()) {
throw new IllegalStateException("Generator " + getLoadKey() + " cannot be compiled into a batch program"); throw new IllegalStateException("Generator " + getLoadKey() + " cannot be compiled into a batch program");
} }
IrisData data = getLoader();
Engine engine = data == null ? null : data.getEngine();
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
NoiseLayerProgram[] layers = new NoiseLayerProgram[composite.size()]; NoiseLayerProgram[] layers = new NoiseLayerProgram[composite.size()];
double totalOpacity = 0D; double totalOpacity = 0D;
for (int index = 0; index < layers.length; index++) { for (int index = 0; index < layers.length; index++) {
IrisNoiseGenerator layer = composite.get(index); IrisNoiseGenerator layer = composite.get(index);
layers[index] = layer.compileProgram(getSeed() + superSeed + hc, data, engine); layers[index] = layer.compileProgram(getSeed() + superSeed + hc, runtime);
if (!multiplicitive) { if (!multiplicitive) {
totalOpacity += layer.getOpacity(); totalOpacity += layer.getOpacity();
} }
} }
double cliffSeed = (double) (superSeed + 294596 + hc) - 34857; double cliffSeed = (double) (superSeed + 294596 + hc) - 34857;
NoiseLayerProgram cliffs = hasCliffs() NoiseLayerProgram cliffs = hasCliffs()
? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), data, engine) ? cliffHeightGenerator.compileProgram((long) (getSeed() + cliffSeed + hc), runtime)
: null; : null;
return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs); return new GeneratorProgram(this, superSeed, layers, totalOpacity, cliffs, runtime);
}
SurfaceCacheStripe[] surfaceStripes() {
IrisData data = getLoader();
return surfaceCache(data, data == null ? null : data.getEngine()).stripes();
} }
static boolean cachedSurface(SurfaceCacheStripe[] stripes, double x, double z, long superSeed, double[] target, int index) { static boolean cachedSurface(SurfaceCacheStripe[] stripes, double x, double z, long superSeed, double[] target, int index) {
@@ -281,30 +250,30 @@ public class IrisGenerator extends IrisRegistrant {
return mixed; return mixed;
} }
private double surfaceHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) { private double surfaceHeight(double rx, double rz, long superSeed, PackRuntime runtime) {
SurfaceCacheStripe[] stripes = surfaceCache(data, engine).stripes(); SurfaceCacheStripe[] stripes = runtime.generator(this).surfaceStripes();
double lowerX = Math.floor(rx / SURFACE_GRID) * SURFACE_GRID; double lowerX = Math.floor(rx / SURFACE_GRID) * SURFACE_GRID;
double lowerZ = Math.floor(rz / SURFACE_GRID) * SURFACE_GRID; double lowerZ = Math.floor(rz / SURFACE_GRID) * SURFACE_GRID;
double dx = (rx - lowerX) / SURFACE_GRID; double dx = (rx - lowerX) / SURFACE_GRID;
double dz = (rz - lowerZ) / SURFACE_GRID; double dz = (rz - lowerZ) / SURFACE_GRID;
double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, data, engine); double northWest = cachedSurfaceHeight(lowerX, lowerZ, superSeed, stripes, runtime);
if (dx == 0D && dz == 0D) { if (dx == 0D && dz == 0D) {
return northWest; return northWest;
} }
double north = dx == 0D ? northWest : IrisInterpolation.lerp(northWest, double north = dx == 0D ? northWest : IrisInterpolation.lerp(northWest,
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, data, engine), dx); cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ, superSeed, stripes, runtime), dx);
double smooth = north; double smooth = north;
if (dz != 0D) { if (dz != 0D) {
double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine); double southWest = cachedSurfaceHeight(lowerX, lowerZ + SURFACE_GRID, superSeed, stripes, runtime);
double south = dx == 0D ? southWest : IrisInterpolation.lerp(southWest, double south = dx == 0D ? southWest : IrisInterpolation.lerp(southWest,
cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, data, engine), dx); cachedSurfaceHeight(lowerX + SURFACE_GRID, lowerZ + SURFACE_GRID, superSeed, stripes, runtime), dx);
smooth = IrisInterpolation.lerp(north, south, dz); smooth = IrisInterpolation.lerp(north, south, dz);
} }
return surfaceDetail == 0D ? smooth return surfaceDetail == 0D ? smooth
: smooth + (sampleHeight(rx, rz, superSeed, data, engine) - smooth) * surfaceDetail; : smooth + (sampleHeight(rx, rz, superSeed, runtime) - smooth) * surfaceDetail;
} }
private double sampleHeight(double rx, double rz, long superSeed, IrisData data, Engine engine) { private double sampleHeight(double rx, double rz, long superSeed, PackRuntime runtime) {
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
double h = multiplicitive ? 1 : 0; double h = multiplicitive ? 1 : 0;
double tp = 0; double tp = 0;
@@ -313,18 +282,18 @@ public class IrisGenerator extends IrisRegistrant {
if (composite.size() == 1) { if (composite.size() == 1) {
if (multiplicitive) { if (multiplicitive) {
h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); h *= composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
} else { } else {
tp += composite.get(0).getOpacity(); tp += composite.get(0).getOpacity();
h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); h += composite.get(0).getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
} }
} else { } else {
for (IrisNoiseGenerator i : composite) { for (IrisNoiseGenerator i : composite) {
if (multiplicitive) { if (multiplicitive) {
h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); h *= i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
} else { } else {
tp += i.getOpacity(); tp += i.getOpacity();
h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, data, engine); h += i.getNoise(getSeed() + superSeed + hc, sampleX, sampleZ, runtime);
} }
} }
} }
@@ -335,15 +304,15 @@ public class IrisGenerator extends IrisRegistrant {
v = 0; v = 0;
} }
v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc, data, engine) : v; v = hasCliffs() ? cliff(runtime, rx, rz, v, superSeed + 294596 + hc) : v;
v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v; v = hasCellCracks() ? cell(runtime, rx, rz, v, superSeed + 48622 + hc) : v;
return v; return v;
} }
private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, IrisData data, Engine engine) { private double cachedSurfaceHeight(double x, double z, long superSeed, SurfaceCacheStripe[] stripes, PackRuntime runtime) {
if (x != (int) x || z != (int) z) { if (x != (int) x || z != (int) z) {
return sampleHeight(x, z, superSeed, data, engine); return sampleHeight(x, z, superSeed, runtime);
} }
long key = ((long) (int) x << 32) | ((int) z & 0xffffffffL); long key = ((long) (int) x << 32) | ((int) z & 0xffffffffL);
long mixed = surfaceMix(key); long mixed = surfaceMix(key);
@@ -353,27 +322,12 @@ public class IrisGenerator extends IrisRegistrant {
if (cached != null) { if (cached != null) {
return cached.height(); return cached.height();
} }
double height = sampleHeight(x, z, superSeed, data, engine); double height = sampleHeight(x, z, superSeed, runtime);
stripe.put(slot, new SurfaceSample(key, superSeed, height)); stripe.put(slot, new SurfaceSample(key, superSeed, height));
return height; return height;
} }
private SurfaceCache surfaceCache(IrisData data, Engine engine) { static SurfaceCacheStripe[] createSurfaceStripes() {
SurfaceCache cached = surfaceSamples;
if (cached != null && cached.data() == data && cached.engine() == engine) {
return cached;
}
synchronized (this) {
cached = surfaceSamples;
if (cached == null || cached.data() != data || cached.engine() != engine) {
cached = new SurfaceCache(data, engine, createSurfaceCache());
surfaceSamples = cached;
}
return cached;
}
}
private static SurfaceCacheStripe[] createSurfaceCache() {
SurfaceCacheStripe[] stripes = new SurfaceCacheStripe[SURFACE_CACHE_STRIPES]; SurfaceCacheStripe[] stripes = new SurfaceCacheStripe[SURFACE_CACHE_STRIPES];
for (int i = 0; i < stripes.length; i++) { for (int i = 0; i < stripes.length; i++) {
stripes[i] = new SurfaceCacheStripe(); stripes[i] = new SurfaceCacheStripe();
@@ -381,45 +335,29 @@ public class IrisGenerator extends IrisRegistrant {
return stripes; return stripes;
} }
public double cell(double rx, double rz, double v, double superSeed) { public double cell(PackRuntime runtime, double rx, double rz, double v, double superSeed) {
double fractureX = rx / getCellFractureZoom(); double fractureX = rx / getCellFractureZoom();
double fractureZ = rz / getCellFractureZoom(); double fractureZ = rz / getCellFractureZoom();
return getCellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; return runtime.generator(this).cellGenerator(getSeed() + 46222).getDistance(fractureX, fractureZ) > getCellPercentSize() ? (v * getCellFractureHeight()) : v;
} }
private boolean hasCellCracks() { private boolean hasCellCracks() {
return getCellFractureHeight() != 0; return getCellFractureHeight() != 0;
} }
public double getCliffHeight(double rx, double rz, double superSeed) { public double getCliffHeight(PackRuntime runtime, double rx, double rz, double superSeed) {
IrisData data = getLoader();
return getCliffHeight(rx, rz, superSeed, data, data == null ? null : data.getEngine());
}
private double getCliffHeight(double rx, double rz, double superSeed, IrisData data, Engine engine) {
int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ); int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * getSeed() + offsetX + offsetZ);
double sampleX = (rx + offsetX) / zoom; double sampleX = (rx + offsetX) / zoom;
double sampleZ = (rz + offsetZ) / zoom; double sampleZ = (rz + offsetZ) / zoom;
double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, data, engine); double h = cliffHeightGenerator.getNoise((long) (getSeed() + superSeed + hc), sampleX, sampleZ, runtime);
return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h); return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h);
} }
public double cliff(double rx, double rz, double v, double superSeed) { public double cliff(PackRuntime runtime, double rx, double rz, double v, double superSeed) {
IrisData data = getLoader(); double cliffHeight = getCliffHeight(runtime, rx, rz, superSeed - 34857);
return cliff(rx, rz, v, superSeed, data, data == null ? null : data.getEngine());
}
private double cliff(double rx, double rz, double v, double superSeed, IrisData data, Engine engine) {
double cliffHeight = getCliffHeight(rx, rz, superSeed - 34857, data, engine);
return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D; return (Math.round((v * 255D) / cliffHeight) * cliffHeight) / 255D;
} }
public IrisGenerator rescale(double scale) {
zoom /= scale;
surfaceSamples = null;
return this;
}
public KList<IrisNoiseGenerator> getAllComposites() { public KList<IrisNoiseGenerator> getAllComposites() {
KList<IrisNoiseGenerator> g = new KList<>(); KList<IrisNoiseGenerator> g = new KList<>();
@@ -440,9 +378,6 @@ public class IrisGenerator extends IrisRegistrant {
return "Generator"; return "Generator";
} }
private record SurfaceCache(IrisData data, Engine engine, SurfaceCacheStripe[] stripes) {
}
private record SurfaceSample(long key, long seed, double height) { private record SurfaceSample(long key, long seed, double height) {
} }
@@ -458,7 +393,4 @@ public class IrisGenerator extends IrisRegistrant {
entries.set(slot, sample); entries.set(slot, sample);
} }
} }
private record CachedCellGenerator(long seed, CellGenerator generator) {
}
} }
@@ -21,8 +21,8 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.image.IrisImageMap; import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.world.history.GenerationKernelRegistry; import art.arcane.iris.world.history.GenerationKernelRegistry;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber; import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -52,15 +52,7 @@ import java.util.concurrent.ConcurrentHashMap;
@Description("A gen style") @Description("A gen style")
@Data @Data
public class IrisGeneratorStyle { public class IrisGeneratorStyle {
private static final int GENERATOR_CACHE_SIZE = 8;
private static final ConcurrentHashMap<String, String> ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, String> ACTIVE_CACHE_KEYS = new ConcurrentHashMap<>();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<GeneratorCacheKey, CNG> generatorCache =
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private transient volatile CachedGenerator recentGenerator;
@Description("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style, except one that names an unknown engine stream, which fails the pack load.") @Description("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style, except one that names an unknown engine stream, which fails the pack load.")
private NoiseStyle style = NoiseStyle.FLAT; private NoiseStyle style = NoiseStyle.FLAT;
@@ -101,24 +93,20 @@ public class IrisGeneratorStyle {
return this; return this;
} }
public CNG createNoCache(RNG rng, IrisData data) { public CNG createNoCache(RNG rng, PackRuntime runtime) {
return createNoCache(rng, data, 1, 0, false, resolveEngine(data)); return createNoCache(rng, runtime, 1, 0, false);
} }
public CNG createScaledGenerator(RNG rng, IrisData data, double scaleFactor) { public CNG createScaledGenerator(RNG rng, PackRuntime runtime, double scaleFactor) {
return createNoCache(rng, data).bake().scale(scaleFactor).bake(); return createNoCache(rng, runtime).bake().scale(scaleFactor).bake();
} }
public CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier) { public CNG createForLayer(RNG rng, PackRuntime runtime, int octaveMultiplier) {
return createForLayer(rng, data, octaveMultiplier, resolveEngine(data)); return createNoCache(rng, runtime, Math.clamp(octaveMultiplier, 1, 16), 0, false);
} }
CNG createForLayer(RNG rng, IrisData data, int octaveMultiplier, Engine engine) { public CNG createForPrebake(RNG rng, PackRuntime runtime, int fallbackCacheSize) {
return createNoCache(rng, data, Math.clamp(octaveMultiplier, 1, 16), 0, false, engine); return createNoCache(rng, runtime, 1, Math.max(0, fallbackCacheSize), true);
}
public CNG createForPrebake(RNG rng, IrisData data, int fallbackCacheSize) {
return createNoCache(rng, data, 1, Math.max(0, fallbackCacheSize), true, resolveEngine(data));
} }
@@ -175,8 +163,10 @@ public class IrisGeneratorStyle {
} }
} }
private CNG createNoCache(RNG rng, IrisData data, int octaveMultiplier, int fallbackCacheSize, private CNG createNoCache(RNG rng, PackRuntime runtime, int octaveMultiplier, int fallbackCacheSize,
boolean quietCacheLog, Engine engine) { boolean quietCacheLog) {
IrisData data = runtime.data();
Engine engine = runtime.engine();
requirePositiveFinite("zoom", zoom); requirePositiveFinite("zoom", zoom);
requirePositiveFinite("exponent", exponent); requirePositiveFinite("exponent", exponent);
if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) { if (!Double.isFinite(cellularFrequency) || cellularFrequency < 0D) {
@@ -193,7 +183,7 @@ public class IrisGeneratorStyle {
if (getExpression() != null) { if (getExpression() != null) {
IrisExpression e = data.getExpressionLoader().load(getExpression()); IrisExpression e = data.getExpressionLoader().load(getExpression());
if (e != null) { if (e != null) {
cng = new CNG(rng, new ExpressionNoise(rng, e), 1D, 1).bake(); cng = new CNG(rng, new ExpressionNoise(rng, runtime.expression(e)), 1D, 1).bake();
sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(), sourceStamp = Integer.toUnsignedLong(Objects.hash(getExpression(),
e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified())); e.getLoadFile() == null ? 0L : e.getLoadFile().lastModified()));
} }
@@ -211,8 +201,8 @@ public class IrisGeneratorStyle {
.pow(cng.getPower() * exponent); .pow(cng.getPower() * exponent);
if (fracture != null) { if (fracture != null) {
cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), data, 1, cng.fractureWith(fracture.createNoCache(rng.nextParallelRNG(2934), runtime, 1,
fallbackCacheSize, quietCacheLog, engine), fracture.getMultiplier()); fallbackCacheSize, quietCacheLog), fracture.getMultiplier());
} }
if (cellularFrequency > 0) { if (cellularFrequency > 0) {
@@ -232,32 +222,17 @@ public class IrisGeneratorStyle {
return cng; return cng;
} }
public double warp(RNG rng, IrisData data, double value, double... coords) { public double warp(RNG rng, PackRuntime runtime, double value, double... coords) {
return create(rng, data).noise(coords) + value; return create(rng, runtime).noise(coords) + value;
} }
public CNG create(RNG rng, IrisData data) { /** The generator this runtime shares for this style and seed. */
return create(rng, data, resolveEngine(data)); public CNG create(RNG rng, PackRuntime runtime) {
return create(rng.getSeed(), runtime);
} }
public CNG create(long seed, IrisData data) { public CNG create(long seed, PackRuntime runtime) {
return cachedGenerator(seed, data, resolveEngine(data)); return runtime.styleGenerator(this, seed);
}
public CNG create(RNG rng, IrisData data, Engine engine) {
return cachedGenerator(rng.getSeed(), data, engine);
}
private CNG cachedGenerator(long seed, IrisData data, Engine engine) {
CachedGenerator recent = recentGenerator;
if (recent != null && recent.key.matches(data, engine, seed)) {
return recent.generator;
}
GeneratorCacheKey key = new GeneratorCacheKey(data, engine, seed);
CNG generator = generatorCache.computeIfAbsent(key,
ignored -> createNoCache(new RNG(seed), data, 1, 0, false, engine));
recentGenerator = new CachedGenerator(key, generator);
return generator;
} }
@SuppressWarnings("BooleanMethodIsAlwaysInverted") @SuppressWarnings("BooleanMethodIsAlwaysInverted")
@@ -282,10 +257,6 @@ public class IrisGeneratorStyle {
)); ));
} }
private Engine resolveEngine(IrisData data) {
return data == null ? null : data.getEngine();
}
private static void requirePositiveFinite(String field, double value) { private static void requirePositiveFinite(String field, double value) {
if (!Double.isFinite(value) || value <= 0D || !Double.isFinite(1D / value)) { if (!Double.isFinite(value) || value <= 0D || !Double.isFinite(1D / value)) {
throw new IllegalArgumentException(field + " must be finite and positive"); throw new IllegalArgumentException(field + " must be finite and positive");
@@ -304,41 +275,4 @@ public class IrisGeneratorStyle {
} }
} }
} }
private static final class GeneratorCacheKey {
private final IrisData data;
private final Engine engine;
private final long seed;
private GeneratorCacheKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = engine;
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine == engine && this.seed == seed;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof GeneratorCacheKey key)) {
return false;
}
return data == key.data && engine == key.engine && seed == key.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + System.identityHashCode(engine);
return 31 * result + Long.hashCode(seed);
}
}
private record CachedGenerator(GeneratorCacheKey key, CNG generator) {
}
} }
@@ -18,9 +18,7 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cache.LazyBoundedCache;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.schema.annotation.ArrayType; import art.arcane.iris.pack.schema.annotation.ArrayType;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber; import art.arcane.iris.pack.schema.annotation.MaxNumber;
@@ -40,16 +38,12 @@ import art.arcane.volmlib.util.noise.OffsetNoiseGenerator;
import art.arcane.volmlib.util.noise.PerlinNoise; import art.arcane.volmlib.util.noise.PerlinNoise;
import art.arcane.volmlib.util.noise.SimplexNoise; import art.arcane.volmlib.util.noise.SimplexNoise;
import art.arcane.volmlib.util.noise.program.NoiseProgram; import art.arcane.volmlib.util.noise.program.NoiseProgram;
import lombok.AccessLevel;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
@Snippet("generator") @Snippet("generator")
@Accessors(chain = true) @Accessors(chain = true)
@@ -58,7 +52,6 @@ import java.util.concurrent.atomic.AtomicReference;
@Description("A noise generator") @Description("A noise generator")
@Data @Data
public class IrisNoiseGenerator { public class IrisNoiseGenerator {
private static final int GENERATOR_CACHE_SIZE = 32;
private static final long GENERATOR_SEED_SALT = 33_955_677L; private static final long GENERATOR_SEED_SALT = 33_955_677L;
private static final int MINIMUM_FRACTURE_DEPTH = 4; private static final int MINIMUM_FRACTURE_DEPTH = 4;
private static final int MAXIMUM_FRACTURE_NODES = 32; private static final int MAXIMUM_FRACTURE_NODES = 32;
@@ -67,13 +60,6 @@ public class IrisNoiseGenerator {
static final int Z_AXIS = 1; static final int Z_AXIS = 1;
private static final ThreadLocal<FractureSamples> FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new); private static final ThreadLocal<FractureSamples> FRACTURE_SAMPLES = ThreadLocal.withInitial(FractureSamples::new);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient LazyBoundedCache<GeneratorKey, CNG> generators =
new LazyBoundedCache<>(GENERATOR_CACHE_SIZE);
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private final transient AtomicReference<CachedGenerator> recentGenerator = new AtomicReference<>();
@MinNumber(0.0001) @MinNumber(0.0001)
@Description("The coordinate input zoom") @Description("The coordinate input zoom")
private double zoom = 1; private double zoom = 1;
@@ -118,43 +104,28 @@ public class IrisNoiseGenerator {
this.enabled = enabled; this.enabled = enabled;
} }
CNG getGenerator(long superSeed, IrisData data, Engine engine) { CNG getGenerator(long superSeed, PackRuntime runtime) {
long generatorSeed = superSeed + GENERATOR_SEED_SALT - seed; return runtime.noiseLayerGenerator(this, superSeed + GENERATOR_SEED_SALT - seed);
CachedGenerator recent = recentGenerator.get(); }
if (recent != null && recent.key.matches(data, engine, generatorSeed)) {
return recent.generator;
}
GeneratorKey key = new GeneratorKey(data, engine, generatorSeed); /** Builds this layer's generator for one derived seed; {@link PackRuntime} shares the result. */
CNG generator = generators.computeIfAbsent(key, public CNG buildGenerator(long generatorSeed, PackRuntime runtime) {
ignored -> style.createForLayer(new RNG(generatorSeed), data, octaves, engine)); return style.createForLayer(new RNG(generatorSeed), runtime, octaves);
if (generator != null) {
recentGenerator.set(new CachedGenerator(key, generator));
}
return generator;
} }
public double getMax() { public double getMax() {
return getOffsetY() + opacity; return getOffsetY() + opacity;
} }
public double getNoise(long superSeed, double xv, double zv, IrisData data) { public double getNoise(long superSeed, double xv, double zv, PackRuntime runtime) {
if (!enabled) { return getNoiseForAxis(superSeed, xv, zv, runtime, X_AXIS);
return offsetY;
}
return getNoise(superSeed, xv, zv, data, data == null ? null : data.getEngine());
}
double getNoise(long superSeed, double xv, double zv, IrisData data, Engine engine) {
return getNoiseForAxis(superSeed, xv, zv, data, engine, X_AXIS);
} }
/** /**
* This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at * This layer read as the fracture of one axis. Each axis samples this layer's generator reseeded for that axis at
* the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other. * the same coordinates, so the x and z warps are uncorrelated instead of mirror images of each other.
*/ */
private double getNoiseForAxis(long superSeed, double xv, double zv, IrisData data, Engine engine, int axis) { private double getNoiseForAxis(long superSeed, double xv, double zv, PackRuntime runtime, int axis) {
if (!enabled) { if (!enabled) {
return offsetY; return offsetY;
} }
@@ -164,7 +135,7 @@ public class IrisNoiseGenerator {
if (!samples.active) { if (!samples.active) {
samples.active = true; samples.active = true;
try { try {
if (samples.prepare(this, superSeed, data, engine)) { if (samples.prepare(this, superSeed, runtime)) {
return samples.sample(xv, zv, axis); return samples.sample(xv, zv, axis);
} }
} finally { } finally {
@@ -180,13 +151,13 @@ public class IrisNoiseGenerator {
for (IrisNoiseGenerator i : fracture) { for (IrisNoiseGenerator i : fracture) {
if (i.isEnabled()) { if (i.isEnabled()) {
double fractureOffset = i.getOpacity() / 2D; double fractureOffset = i.getOpacity() / 2D;
x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, X_AXIS) - fractureOffset; x += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, X_AXIS) - fractureOffset;
z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, data, engine, Z_AXIS) - fractureOffset; z += i.getNoiseForAxis(superSeed + seed + g, xv, zv, runtime, Z_AXIS) - fractureOffset;
} }
g += 819; g += 819;
} }
return sample(getGenerator(superSeed, data, engine).reseededForAxis(axis), x, z); return sample(getGenerator(superSeed, runtime).reseededForAxis(axis), x, z);
} }
boolean supportsBatch() { boolean supportsBatch() {
@@ -210,11 +181,11 @@ public class IrisNoiseGenerator {
return true; return true;
} }
NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine) { NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime) {
return compileProgram(superSeed, data, engine, false); return compileProgram(superSeed, runtime, false);
} }
private NoiseLayerProgram compileProgram(long superSeed, IrisData data, Engine engine, boolean readAsFracture) { private NoiseLayerProgram compileProgram(long superSeed, PackRuntime runtime, boolean readAsFracture) {
if (!enabled) { if (!enabled) {
return NoiseLayerProgram.disabled(this); return NoiseLayerProgram.disabled(this);
} }
@@ -230,12 +201,12 @@ public class IrisNoiseGenerator {
int compiled = 0; int compiled = 0;
for (IrisNoiseGenerator child : fracture) { for (IrisNoiseGenerator child : fracture) {
if (child.isEnabled()) { if (child.isEnabled()) {
children[compiled] = child.compileProgram(superSeed + seed + salt, data, engine, true); children[compiled] = child.compileProgram(superSeed + seed + salt, runtime, true);
offsets[compiled++] = child.getOpacity() / 2D; offsets[compiled++] = child.getOpacity() / 2D;
} }
salt += 819; salt += 819;
} }
CNG generator = Objects.requireNonNull(getGenerator(superSeed, data, engine), "Noise layer generator"); CNG generator = Objects.requireNonNull(getGenerator(superSeed, runtime), "Noise layer generator");
NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null; NoiseProgram zAxisProgram = readAsFracture ? NoiseProgram.compile2D(generator.reseededForAxis(Z_AXIS)) : null;
return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets); return NoiseLayerProgram.of(this, NoiseProgram.compile2D(generator), zAxisProgram, children, offsets);
} }
@@ -311,54 +282,19 @@ public class IrisNoiseGenerator {
return false; return false;
} }
private static final class GeneratorKey {
private final IrisData data;
private final Engine engine;
private final long seed;
private GeneratorKey(IrisData data, Engine engine, long seed) {
this.data = data;
this.engine = engine;
this.seed = seed;
}
private boolean matches(IrisData data, Engine engine, long seed) {
return this.data == data && this.engine == engine && this.seed == seed;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof GeneratorKey other)) {
return false;
}
return data == other.data && engine == other.engine && seed == other.seed;
}
@Override
public int hashCode() {
int result = System.identityHashCode(data);
result = 31 * result + System.identityHashCode(engine);
result = 31 * result + Long.hashCode(seed);
return result;
}
}
private static final class FractureSamples { private static final class FractureSamples {
private final IrisNoiseGenerator[] nodes = new IrisNoiseGenerator[MAXIMUM_FRACTURE_NODES]; private final IrisNoiseGenerator[] nodes = new IrisNoiseGenerator[MAXIMUM_FRACTURE_NODES];
private final CNG[] generators = new CNG[MAXIMUM_FRACTURE_NODES]; private final CNG[] generators = new CNG[MAXIMUM_FRACTURE_NODES];
private int size; private int size;
private boolean active; private boolean active;
private boolean prepare(IrisNoiseGenerator node, long superSeed, IrisData data, Engine engine) { private boolean prepare(IrisNoiseGenerator node, long superSeed, PackRuntime runtime) {
while (size < MAXIMUM_FRACTURE_NODES) { while (size < MAXIMUM_FRACTURE_NODES) {
if (node.getClass() != IrisNoiseGenerator.class || !node.enabled || !node.hasPureStyle() if (node.getClass() != IrisNoiseGenerator.class || !node.enabled || !node.hasPureStyle()
|| node.fracture.size() > 1) { || node.fracture.size() > 1) {
return false; return false;
} }
CNG generator = node.getGenerator(superSeed, data, engine); CNG generator = node.getGenerator(superSeed, runtime);
if (!isPureGenerator(generator)) { if (!isPureGenerator(generator)) {
return false; return false;
} }
@@ -404,14 +340,4 @@ public class IrisNoiseGenerator {
active = false; active = false;
} }
} }
private static final class CachedGenerator {
private final GeneratorKey key;
private final CNG generator;
private CachedGenerator(GeneratorKey key, CNG generator) {
this.key = key;
this.generator = generator;
}
}
} }
@@ -18,7 +18,7 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.MaxNumber; import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber; import art.arcane.iris.pack.schema.annotation.MinNumber;
@@ -63,16 +63,16 @@ public class IrisShapedGeneratorStyle {
this.generator = new IrisGeneratorStyle(style); this.generator = new IrisGeneratorStyle(style);
} }
public double get(RNG rng, IrisData data, double... dim) { public double get(RNG rng, PackRuntime runtime, double... dim) {
return generator.create(rng, data).fitDouble(min, max, dim); return generator.create(rng, runtime).fitDouble(min, max, dim);
} }
public double get(RNG rng, IrisData data, double x, double z) { public double get(RNG rng, PackRuntime runtime, double x, double z) {
return generator.create(rng, data).fitDouble(min, max, x, z); return generator.create(rng, runtime).fitDouble(min, max, x, z);
} }
public double get(RNG rng, IrisData data, double x, double y, double z) { public double get(RNG rng, PackRuntime runtime, double x, double y, double z) {
return generator.create(rng, data).fitDouble(min, max, x, y, z); return generator.create(rng, runtime).fitDouble(min, max, x, y, z);
} }
public boolean isFlat() { public boolean isFlat() {
@@ -18,7 +18,7 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.documentation.Description; import art.arcane.volmlib.util.documentation.Description;
import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.M;
@@ -46,7 +46,7 @@ public class IrisStyledRange {
@Description("The style to pick the range") @Description("The style to pick the range")
private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC); private IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.STATIC);
public double get(RNG rng, double x, double z, IrisData data) { public double get(RNG rng, double x, double z, PackRuntime runtime) {
if (min == max) { if (min == max) {
return min; return min;
} }
@@ -55,11 +55,11 @@ public class IrisStyledRange {
return M.lerp(min, max, 0.5); return M.lerp(min, max, 0.5);
} }
return style.create(rng, data).fitDouble(min, max, x, z); return style.create(rng, runtime).fitDouble(min, max, x, z);
} }
public ProceduralStream<Double> stream(RNG rng, IrisData data) { public ProceduralStream<Double> stream(RNG rng, PackRuntime runtime) {
return ProceduralStream.of((x, z) -> get(rng, x, z, data), Interpolated.DOUBLE); return ProceduralStream.of((x, z) -> get(rng, x, z, runtime), Interpolated.DOUBLE);
} }
public boolean isFlat() { public boolean isFlat() {
@@ -133,7 +133,7 @@ public final class DimensionStackContext {
upper.getDimension().getLoadKey() upper.getDimension().getLoadKey()
); );
RNG seamRng = new RNG(engine.getSeedManager().getTerrain() ^ salt); RNG seamRng = new RNG(engine.getSeedManager().getTerrain() ^ salt);
CNG seamNoise = style.create(seamRng, engine.getData(), engine); CNG seamNoise = style.create(seamRng, PackRuntime.of(engine, engine.getData()));
int amplitude = blend.getAmplitude(); int amplitude = blend.getAmplitude();
samplers.add((x, z) -> clampSeamOffset( samplers.add((x, z) -> clampSeamOffset(
seamNoise.fitDouble(-amplitude, amplitude, x, z), amplitude)); seamNoise.fitDouble(-amplitude, amplitude, x, z), amplitude));
@@ -154,6 +154,7 @@ public final class DimensionTerrainContext implements DataProvider {
resolvedData = engine.getData(); resolvedData = engine.getData();
} }
IrisData dimensionData = resolvedData; IrisData dimensionData = resolvedData;
PackRuntime dimensionRuntime = PackRuntime.of(engine, dimensionData);
IrisImageMapRuntime imageMapRuntime = IrisImageMapRuntime.compile( IrisImageMapRuntime imageMapRuntime = IrisImageMapRuntime.compile(
dimensionData, dimensionData,
dimension, dimension,
@@ -219,7 +220,7 @@ public final class DimensionTerrainContext implements DataProvider {
} }
ProceduralStream<Double> regionStyleStream = dimension.getRegionStyle() ProceduralStream<Double> regionStyleStream = dimension.getRegionStyle()
.create(rng.nextParallelRNG(883), dimensionData).stream() .create(rng.nextParallelRNG(883), dimensionRuntime).stream()
.zoom(dimension.getRegionZoom()); .zoom(dimension.getRegionZoom());
KList<IrisRegion> regionPool = new KList<>(); KList<IrisRegion> regionPool = new KList<>();
for (IrisRegion region : dimensionData.getRegionLoader().loadAll(dimension.getRegions())) { for (IrisRegion region : dimensionData.getRegionLoader().loadAll(dimension.getRegions())) {
@@ -238,7 +239,7 @@ public final class DimensionTerrainContext implements DataProvider {
.convertAware2D((region, x, z) -> mappedRegion(imageMapRuntime, region, x, z)), cachePrefix + "ImageMappedRegionStream", engine, cacheSize) .convertAware2D((region, x, z) -> mappedRegion(imageMapRuntime, region, x, z)), cachePrefix + "ImageMappedRegionStream", engine, cacheSize)
: proceduralRegionStream; : proceduralRegionStream;
Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> preparedBiomeStreams = Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> preparedBiomeStreams =
compileInferredBiomeStreams(dimension, dimensionData, rng, preparedRegions); compileInferredBiomeStreams(dimension, dimensionRuntime, rng, preparedRegions);
ProceduralStream<IrisBiome> landBiomeStream = regionStream ProceduralStream<IrisBiome> landBiomeStream = regionStream
.convert(region -> IrisComplex.preparedInferredBiomeStream( .convert(region -> IrisComplex.preparedInferredBiomeStream(
@@ -259,7 +260,7 @@ public final class DimensionTerrainContext implements DataProvider {
inferredStreams.put(InferredType.SHORE, shoreBiomeStream); inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
ProceduralStream<InferredType> bridgeStream = focusBiome == null ProceduralStream<InferredType> bridgeStream = focusBiome == null
? ContinentGenerator.create(dimension, rng, dimensionData).stream() ? ContinentGenerator.create(dimension, rng, dimensionRuntime).stream()
.convert(value -> value >= dimension.getLandChance() .convert(value -> value >= dimension.getLandChance()
? InferredType.SEA ? InferredType.SEA
: InferredType.LAND) : InferredType.LAND)
@@ -293,7 +294,7 @@ public final class DimensionTerrainContext implements DataProvider {
: ProceduralStream.ofDouble((x, z) -> { : ProceduralStream.ofDouble((x, z) -> {
double value = 0D; double value = 0D;
for (IrisShapedGeneratorStyle style : overlayNoise) { for (IrisShapedGeneratorStyle style : overlayNoise) {
value += style.get(rng, dimensionData, x, z); value += style.get(rng, dimensionRuntime, x, z);
} }
return value; return value;
}); });
@@ -340,6 +341,7 @@ public final class DimensionTerrainContext implements DataProvider {
} }
}); });
interpolatedHeight += IrisComplex.averageGeneratorHeights( interpolatedHeight += IrisComplex.averageGeneratorHeights(
dimensionRuntime,
groupGenerators, groupGenerators,
sampledBounds.min(), sampledBounds.min(),
sampledBounds.max(), sampledBounds.max(),
@@ -394,7 +396,7 @@ public final class DimensionTerrainContext implements DataProvider {
Terrain3DRuntime terrain3D = !terrain3DEnabled ? null : new Terrain3DRuntime( Terrain3DRuntime terrain3D = !terrain3DEnabled ? null : new Terrain3DRuntime(
new Terrain3DRuntime.Sources(heightStream::getDouble, finalBiomeStream::get), new Terrain3DRuntime.Sources(heightStream::getDouble, finalBiomeStream::get),
new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain() ^ seedOffset, new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain() ^ seedOffset,
localHeight, fluidHeight, dimensionData, true, Math.max(4096, cacheSize)) localHeight, fluidHeight, dimensionRuntime, true, Math.max(4096, cacheSize))
); );
ProceduralStream<Double> shapedHeightStream = terrain3D == null ? heightStream ProceduralStream<Double> shapedHeightStream = terrain3D == null ? heightStream
: GenerationStreams.cache2DDouble(ProceduralStream.ofDouble((x, z) -> shapedHeight(terrain3D, x, z)), cachePrefix + "Terrain3DHeightStream", engine, cacheSize); : GenerationStreams.cache2DDouble(ProceduralStream.ofDouble((x, z) -> shapedHeight(terrain3D, x, z)), cachePrefix + "Terrain3DHeightStream", engine, cacheSize);
@@ -505,7 +507,7 @@ public final class DimensionTerrainContext implements DataProvider {
private static Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> compileInferredBiomeStreams( private static Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> compileInferredBiomeStreams(
IrisDimension dimension, IrisDimension dimension,
IrisData data, PackRuntime runtime,
RNG rng, RNG rng,
Iterable<IrisRegion> regions Iterable<IrisRegion> regions
) { ) {
@@ -517,11 +519,11 @@ public final class DimensionTerrainContext implements DataProvider {
} }
EnumMap<InferredType, ProceduralStream<IrisBiome>> streams = new EnumMap<>(InferredType.class); EnumMap<InferredType, ProceduralStream<IrisBiome>> streams = new EnumMap<>(InferredType.class);
streams.put(InferredType.LAND, createInferredBiomeStream( streams.put(InferredType.LAND, createInferredBiomeStream(
dimension, data, rng, region, InferredType.LAND)); dimension, runtime, rng, region, InferredType.LAND));
streams.put(InferredType.SEA, createInferredBiomeStream( streams.put(InferredType.SEA, createInferredBiomeStream(
dimension, data, rng, region, InferredType.SEA)); dimension, runtime, rng, region, InferredType.SEA));
streams.put(InferredType.SHORE, createInferredBiomeStream( streams.put(InferredType.SHORE, createInferredBiomeStream(
dimension, data, rng, region, InferredType.SHORE)); dimension, runtime, rng, region, InferredType.SHORE));
compiled.put(region, Collections.unmodifiableMap(streams)); compiled.put(region, Collections.unmodifiableMap(streams));
} }
return Collections.unmodifiableMap(compiled); return Collections.unmodifiableMap(compiled);
@@ -529,29 +531,29 @@ public final class DimensionTerrainContext implements DataProvider {
private static ProceduralStream<IrisBiome> createInferredBiomeStream( private static ProceduralStream<IrisBiome> createInferredBiomeStream(
IrisDimension dimension, IrisDimension dimension,
IrisData data, PackRuntime runtime,
RNG rng, RNG rng,
IrisRegion region, IrisRegion region,
InferredType type InferredType type
) { ) {
return switch (type) { return switch (type) {
case LAND -> dimension.getLandBiomeStyle() case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream() .create(rng.nextParallelRNG(InferredType.LAND.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom()) .zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom()) .zoom(region.getLandBiomeZoom())
.selectRarity(loadInferredBiomes(data, region.getLandBiomes(), InferredType.LAND)); .selectRarity(loadInferredBiomes(runtime.data(), region.getLandBiomes(), InferredType.LAND));
case SEA -> dimension.getSeaBiomeStyle() case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream() .create(rng.nextParallelRNG(InferredType.SEA.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(dimension.getSeaZoom()) .zoom(dimension.getSeaZoom())
.zoom(region.getSeaBiomeZoom()) .zoom(region.getSeaBiomeZoom())
.selectRarity(loadInferredBiomes(data, region.getSeaBiomes(), InferredType.SEA)); .selectRarity(loadInferredBiomes(runtime.data(), region.getSeaBiomes(), InferredType.SEA));
case SHORE -> dimension.getShoreBiomeStyle() case SHORE -> dimension.getShoreBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream() .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), runtime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(region.getShoreBiomeZoom()) .zoom(region.getShoreBiomeZoom())
.selectRarity(loadInferredBiomes(data, region.getShoreBiomes(), InferredType.SHORE)); .selectRarity(loadInferredBiomes(runtime.data(), region.getShoreBiomes(), InferredType.SHORE));
default -> throw new IllegalArgumentException("Unsupported stacked terrain biome type: " + type); default -> throw new IllegalArgumentException("Unsupported stacked terrain biome type: " + type);
}; };
} }
@@ -200,6 +200,7 @@ public class IrisComplex implements DataProvider {
private RNG rng; private RNG rng;
private double fluidHeight; private double fluidHeight;
private IrisData data; private IrisData data;
private final transient PackRuntime packRuntime;
private Map<IrisInterpolator, Set<IrisGenerator>> generators; private Map<IrisInterpolator, Set<IrisGenerator>> generators;
private ProceduralStream<IrisRegion> regionStream; private ProceduralStream<IrisRegion> regionStream;
private ProceduralStream<Double> regionStyleStream; private ProceduralStream<Double> regionStyleStream;
@@ -325,6 +326,7 @@ public class IrisComplex implements DataProvider {
this.rng = new RNG(engine.getSeedManager().getComplex()); this.rng = new RNG(engine.getSeedManager().getComplex());
childStyleSeed = IrisBiome.childStyleSeed(rng, 123); childStyleSeed = IrisBiome.childStyleSeed(rng, 123);
this.data = engine.getData(); this.data = engine.getData();
this.packRuntime = PackRuntime.of(engine, data);
imageMapRuntime = IrisImageMapRuntime.compile(engine); imageMapRuntime = IrisImageMapRuntime.compile(engine);
double height = engine.getMaxHeight(); double height = engine.getMaxHeight();
fluidHeight = engine.getDimension().getFluidHeight(); fluidHeight = engine.getDimension().getFluidHeight();
@@ -412,7 +414,7 @@ public class IrisComplex implements DataProvider {
double value = 0D; double value = 0D;
for (IrisShapedGeneratorStyle style : overlayNoise) { for (IrisShapedGeneratorStyle style : overlayNoise) {
value += style.get(rng, getData(), x, z); value += style.get(rng, packRuntime, x, z);
} }
return value; return value;
@@ -425,7 +427,7 @@ public class IrisComplex implements DataProvider {
fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream() fluidSource = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream()
.select(engine.getDimension().getFluidPalette().getBlockData(data)); .select(engine.getDimension().getFluidPalette().getBlockData(data));
fluidStream = new BakedStream<>(bakeCache, BakePlane.FLUID, fluidSource); fluidStream = new BakedStream<>(bakeCache, BakePlane.FLUID, fluidSource);
regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), getData()).stream() regionStyleStream = engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883), packRuntime).stream()
.zoom(engine.getDimension().getRegionZoom()); .zoom(engine.getDimension().getRegionZoom());
regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE); regionIdentityStream = regionStyleStream.fit(Integer.MIN_VALUE, Integer.MAX_VALUE);
regionSource = focusedRegions != null ? focusedRegions regionSource = focusedRegions != null ? focusedRegions
@@ -451,7 +453,7 @@ public class IrisComplex implements DataProvider {
.convertAware2D(ProceduralStream::get); .convertAware2D(ProceduralStream::get);
inferredStreams.put(InferredType.SHORE, shoreBiomeStream); inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) : bridgeStream = focusedBiomes != null ? focusedBiomes.convert(IrisBiome::getInferredType) :
ContinentGenerator.create(engine.getDimension(), rng, getData()).stream() ContinentGenerator.create(engine.getDimension(), rng, packRuntime).stream()
.convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND); .convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND);
ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes ProceduralStream<IrisBiome> proceduralBaseBiomeStream = focusedBiomes != null ? focusedBiomes
: ProceduralStream.of(this::proceduralBaseBiome, : ProceduralStream.of(this::proceduralBaseBiome,
@@ -483,7 +485,7 @@ public class IrisComplex implements DataProvider {
(x, z) -> baseTerrainHeightStream.getDouble(x, z), (x, z) -> baseTerrainHeightStream.getDouble(x, z),
this::sampleTerrain3DBiome), this::sampleTerrain3DBiome),
new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain(), engine.getHeight(), new Terrain3DRuntime.Options(engine.getSeedManager().getTerrain(), engine.getHeight(),
fluidHeight, data, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE)); fluidHeight, packRuntime, terrain3DEnabled, TERRAIN_COLUMN_CACHE_SIZE));
unblendedNaturalHeightStream = terrain3DEnabled unblendedNaturalHeightStream = terrain3DEnabled
? ProceduralStream.ofDouble(this::sampleTerrain3DHeight) ? ProceduralStream.ofDouble(this::sampleTerrain3DHeight)
: baseTerrainHeightStream; : baseTerrainHeightStream;
@@ -1056,7 +1058,7 @@ public class IrisComplex implements DataProvider {
synchronized (this) { synchronized (this) {
program = terrainProgram; program = terrainProgram;
if (program == null) { if (program == null) {
program = TerrainProgram.compile(frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945); program = TerrainProgram.compile(packRuntime, frozenGenerators, terrainEngine.getSeedManager().getHeight() + 239945);
terrainProgram = program; terrainProgram = program;
} }
} }
@@ -1174,21 +1176,21 @@ public class IrisComplex implements DataProvider {
private ProceduralStream<Double> biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) { private ProceduralStream<Double> biomePickNoiseStream(IrisDimension dimension, IrisRegion region, InferredType inferredType) {
return switch (inferredType) { return switch (inferredType) {
case CAVE -> dimension.getCaveBiomeStyle() case CAVE -> dimension.getCaveBiomeStyle()
.create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), getData()).stream() .create(rng.nextParallelRNG(InferredType.CAVE.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(region.getCaveBiomeZoom()); .zoom(region.getCaveBiomeZoom());
case LAND -> dimension.getLandBiomeStyle() case LAND -> dimension.getLandBiomeStyle()
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), getData()).stream() .create(rng.nextParallelRNG(InferredType.LAND.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(dimension.getLandZoom()) .zoom(dimension.getLandZoom())
.zoom(region.getLandBiomeZoom()); .zoom(region.getLandBiomeZoom());
case SEA -> dimension.getSeaBiomeStyle() case SEA -> dimension.getSeaBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), getData()).stream() .create(rng.nextParallelRNG(InferredType.SEA.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(dimension.getSeaZoom()) .zoom(dimension.getSeaZoom())
.zoom(region.getSeaBiomeZoom()); .zoom(region.getSeaBiomeZoom());
case SHORE -> dimension.getShoreBiomeStyle() case SHORE -> dimension.getShoreBiomeStyle()
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), getData()).stream() .create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), packRuntime).stream()
.zoom(dimension.getBiomeZoom()) .zoom(dimension.getBiomeZoom())
.zoom(region.getShoreBiomeZoom()); .zoom(region.getShoreBiomeZoom());
}; };
@@ -1961,7 +1963,7 @@ public class IrisComplex implements DataProvider {
} }
if (program == null || program.heightSeed() != heightSeed || group >= program.groups() if (program == null || program.heightSeed() != heightSeed || group >= program.groups()
|| program.groupSize(group) != generators.length || generators != frozenGenerators[group]) { || program.groupSize(group) != generators.length || generators != frozenGenerators[group]) {
return averageGeneratorHeights(generators, low, high, x, z, heightSeed); return averageGeneratorHeights(packRuntime, generators, low, high, x, z, heightSeed);
} }
return program.average(group, BATCH_SCRATCH.get(), low, high, x, z); return program.average(group, BATCH_SCRATCH.get(), low, high, x, z);
} }
@@ -2128,7 +2130,7 @@ public class IrisComplex implements DataProvider {
IrisBiome biome = focusedBiomeAt(x, z); IrisBiome biome = focusedBiomeAt(x, z);
for (GeneratorGroup group : biomeBuffetGenerators.get(biome)) { for (GeneratorGroup group : biomeBuffetGenerators.get(biome)) {
NoiseBounds bounds = generatorBounds.get(group.interpolator()).get(biome).noiseBounds; NoiseBounds bounds = generatorBounds.get(group.interpolator()).get(biome).noiseBounds;
h += averageGeneratorHeights(group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945); h += averageGeneratorHeights(packRuntime, group.generators(), bounds.min(), bounds.max(), x, z, seed + 239945);
} }
return h; return h;
} }
@@ -2407,6 +2409,7 @@ public class IrisComplex implements DataProvider {
} }
static double averageGeneratorHeights( static double averageGeneratorHeights(
PackRuntime runtime,
IrisGenerator[] generators, IrisGenerator[] generators,
double low, double low,
double high, double high,
@@ -2433,7 +2436,7 @@ public class IrisComplex implements DataProvider {
GenerationCounter.GENERATOR_EVALUATIONS.add(generators.length); GenerationCounter.GENERATOR_EVALUATIONS.add(generators.length);
} }
for (IrisGenerator generator : generators) { for (IrisGenerator generator : generators) {
double noise = generator.getHeight(x, z, seed); double noise = generator.getHeight(runtime, x, z, seed);
if (!Double.isFinite(noise)) { if (!Double.isFinite(noise)) {
throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z throw new IllegalStateException("Terrain generator noise was not finite at " + x + "," + z
+ " (generator=" + generator.getLoadKey() + ", noise=" + noise + " (generator=" + generator.getLoadKey() + ", noise=" + noise
@@ -18,7 +18,15 @@
package art.arcane.iris.generation.runtime; package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.noise.ExpressionRuntime;
import art.arcane.iris.generation.noise.GeneratorRuntime;
import art.arcane.iris.generation.noise.IrisExpression;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import java.util.Objects; import java.util.Objects;
@@ -28,18 +36,32 @@ import java.util.Objects;
* An engine owns one per generation runtime; engine-less tools use the scope their {@link IrisData} owns. * An engine owns one per generation runtime; engine-less tools use the scope their {@link IrisData} owns.
*/ */
public final class PackRuntime { public final class PackRuntime {
private static final int STYLE_SEED_CAPACITY = 8;
private static final int NOISE_LAYER_SEED_CAPACITY = 32;
private final Engine engine; private final Engine engine;
private final IrisData data; private final IrisData data;
private final RuntimeTable<IrisData, PackRuntime> foreignDataScopes;
private final RuntimeTable<IrisGeneratorStyle, SeedTable<CNG>> styleGenerators = new RuntimeTable<>(
style -> new SeedTable<>(STYLE_SEED_CAPACITY, seed -> style.createNoCache(new RNG(seed), this)));
private final RuntimeTable<IrisNoiseGenerator, SeedTable<CNG>> noiseLayerGenerators = new RuntimeTable<>(
layer -> new SeedTable<>(NOISE_LAYER_SEED_CAPACITY, seed -> layer.buildGenerator(seed, this)));
private final RuntimeTable<IrisGenerator, GeneratorRuntime> generators = new RuntimeTable<>(GeneratorRuntime::new);
private final RuntimeTable<IrisExpression, ExpressionRuntime> expressions =
new RuntimeTable<>(expression -> new ExpressionRuntime(expression, this));
private PackRuntime(Engine engine, IrisData data) { private PackRuntime(Engine engine, IrisData data) {
this.engine = engine; this.engine = engine;
this.data = Objects.requireNonNull(data, "pack data"); this.data = data;
this.foreignDataScopes = engine == null ? null : new RuntimeTable<>(foreign -> new PackRuntime(engine, foreign));
} }
static PackRuntime forEngine(Engine engine, IrisData data) { /** The scope an engine owns for its pack; the engine creates it with each generation runtime. */
public static PackRuntime forEngine(Engine engine, IrisData data) {
return new PackRuntime(Objects.requireNonNull(engine, "engine"), data); return new PackRuntime(Objects.requireNonNull(engine, "engine"), data);
} }
/** A scope for tools without an engine. A null pack is allowed for content that never loads other files. */
public static PackRuntime standalone(IrisData data) { public static PackRuntime standalone(IrisData data) {
return new PackRuntime(null, data); return new PackRuntime(null, data);
} }
@@ -50,10 +72,18 @@ public final class PackRuntime {
*/ */
public static PackRuntime of(Engine engine, IrisData data) { public static PackRuntime of(Engine engine, IrisData data) {
PackRuntime engineRuntime = engine == null ? null : engine.getPackRuntime(); PackRuntime engineRuntime = engine == null ? null : engine.getPackRuntime();
if (engineRuntime != null) { if (engineRuntime == null) {
return engineRuntime; return data == null ? standalone(null) : data.standalonePackRuntime();
} }
return Objects.requireNonNull(data, "pack data").standalonePackRuntime(); return engineRuntime.scopeFor(data);
}
/**
* The scope for a pack object whose class still finds its engine through the pack data's context. Each use is a
* caller that has not been handed its runtime scope yet.
*/
public static PackRuntime forContext(IrisData data) {
return of(data == null ? null : data.getEngine(), data);
} }
/** The owning engine, or null for an engine-less scope. */ /** The owning engine, or null for an engine-less scope. */
@@ -64,4 +94,33 @@ public final class PackRuntime {
public IrisData data() { public IrisData data() {
return data; return data;
} }
/**
* The scope this owner keeps for another pack, such as a stacked dimension's. Pack objects resolve expressions
* and images through their own data, so runtime objects of a foreign pack must be built against it.
*/
public PackRuntime scopeFor(IrisData packData) {
if (packData == null || packData == data || foreignDataScopes == null) {
return this;
}
return foreignDataScopes.get(packData);
}
/** Styles are shared configuration that each caller seeds itself, so a style keeps one generator per seed. */
public CNG styleGenerator(IrisGeneratorStyle style, long seed) {
return styleGenerators.get(style).get(seed);
}
/** Noise layers are seeded from the generator that reads them, so a layer keeps one generator per seed. */
public CNG noiseLayerGenerator(IrisNoiseGenerator layer, long seed) {
return noiseLayerGenerators.get(layer).get(seed);
}
public GeneratorRuntime generator(IrisGenerator generator) {
return generators.get(generator);
}
public ExpressionRuntime expression(IrisExpression expression) {
return expressions.get(expression);
}
} }
@@ -0,0 +1,83 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.generation.runtime;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.function.LongFunction;
/**
* The values one runtime object builds per seed, for pack objects that callers sample with seeds they derive
* themselves. Bounded by least-recent use; an evicted value is rebuilt from the same seed, so eviction never changes
* output. The most recent value is kept aside because callers usually ask for the same seed many times in a row.
*/
public final class SeedTable<T> {
private final int capacity;
private final LongFunction<T> builder;
private final LinkedHashMap<Long, T> entries;
private volatile Recent<T> recent;
public SeedTable(int capacity, LongFunction<T> builder) {
if (capacity < 1) {
throw new IllegalArgumentException("Seed table capacity must be positive.");
}
this.capacity = capacity;
this.builder = Objects.requireNonNull(builder, "seed builder");
this.entries = new LinkedHashMap<>(capacity * 2, 0.75F, true);
}
public T get(long seed) {
Recent<T> last = recent;
if (last != null && last.seed == seed) {
return last.value;
}
T value = stored(seed);
if (value == null) {
value = publish(seed, Objects.requireNonNull(builder.apply(seed), "seeded runtime value"));
}
recent = new Recent<>(seed, value);
return value;
}
private T stored(long seed) {
synchronized (entries) {
return entries.get(seed);
}
}
private T publish(long seed, T built) {
synchronized (entries) {
T raced = entries.putIfAbsent(seed, built);
if (raced != null) {
return raced;
}
evictBeyondCapacity();
return built;
}
}
private void evictBeyondCapacity() {
while (entries.size() > capacity) {
entries.sequencedKeySet().removeFirst();
}
}
private record Recent<T>(long seed, T value) {
}
}
@@ -1,6 +1,6 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
@@ -10,12 +10,12 @@ public final class ContinentGenerator {
private ContinentGenerator() { private ContinentGenerator() {
} }
public static CNG create(IrisDimension dimension, RNG parentSeedSource, IrisData packData) { public static CNG create(IrisDimension dimension, RNG parentSeedSource, PackRuntime runtime) {
return createScaledContinentalStyleGenerator(dimension, deriveContinentSeed(parentSeedSource), packData); return createScaledContinentalStyleGenerator(dimension, deriveContinentSeed(parentSeedSource), runtime);
} }
private static CNG createScaledContinentalStyleGenerator(IrisDimension dimension, RNG continentSeed, IrisData packData) { private static CNG createScaledContinentalStyleGenerator(IrisDimension dimension, RNG continentSeed, PackRuntime runtime) {
return dimension.getContinentalStyle().createScaledGenerator(continentSeed, packData, inverseContinentZoom(dimension)); return dimension.getContinentalStyle().createScaledGenerator(continentSeed, runtime, inverseContinentZoom(dimension));
} }
static RNG deriveContinentSeed(RNG parentSeedSource) { static RNG deriveContinentSeed(RNG parentSeedSource) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
@@ -87,7 +88,7 @@ public class IrisDimensionCarvingEntry {
} }
private CNG createChildrenGenerator(long childrenGeneratorSeed, IrisData data) { private CNG createChildrenGenerator(long childrenGeneratorSeed, IrisData data) {
return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), data, childShrinkFactor()); return getChildStyle().createScaledGenerator(deriveChildStyleSeed(childrenGeneratorSeed), PackRuntime.forContext(data), childShrinkFactor());
} }
long deriveChildrenGeneratorSeed(long worldSeed) { long deriveChildrenGeneratorSeed(long worldSeed) {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette; import art.arcane.volmlib.nativelib.terrain.structure.StructurePalette;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
@@ -120,7 +121,7 @@ public class IrisMaterialPalette implements StructurePalette {
LayerGeneratorKey key = new LayerGeneratorKey(rdata, engine, generatorSeed); LayerGeneratorKey key = new LayerGeneratorKey(rdata, engine, generatorSeed);
CNG generator = layerGenerators.computeIfAbsent(key, CNG generator = layerGenerators.computeIfAbsent(key,
ignored -> style.create(new RNG(generatorSeed), rdata, engine)); ignored -> style.create(new RNG(generatorSeed), PackRuntime.of(engine, rdata)));
if (generator != null) { if (generator != null) {
recentLayerGenerator.set(new CachedLayerGenerator(key, generator)); recentLayerGenerator.set(new CachedLayerGenerator(key, generator));
} }
@@ -53,7 +53,7 @@ public final class RegionSelection {
} }
} }
return select(new Options(dimension, data, return select(new Options(dimension, data,
dimension.getRegionStyle().create(new RNG(snapshot.complexSeed()).nextParallelRNG(883), data) dimension.getRegionStyle().create(new RNG(snapshot.complexSeed()).nextParallelRNG(883), data.standalonePackRuntime())
.stream().zoom(dimension.getRegionZoom()), .stream().zoom(dimension.getRegionZoom()),
IrisImageMapRuntime.compile(data, dimension, dimension.getMinHeight()), focused)); IrisImageMapRuntime.compile(data, dimension, dimension.getMinHeight()), focused));
} }
@@ -1,7 +1,7 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.cache.ConcurrentClockCache; import art.arcane.iris.generation.cache.ConcurrentClockCache;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
@@ -38,7 +38,7 @@ public final class Terrain3DRuntime {
public Terrain3DRuntime(Sources sources, Options options) { public Terrain3DRuntime(Sources sources, Options options) {
this(sources, options, (style, seed) -> { this(sources, options, (style, seed) -> {
CNG noise = style.createNoCache(new RNG(seed), options.data()); CNG noise = style.createNoCache(new RNG(seed), options.runtime());
return noise::noiseFastSigned3D; return noise::noiseFastSigned3D;
}); });
} }
@@ -317,7 +317,7 @@ public final class Terrain3DRuntime {
} }
} }
public record Options(long seed, int height, double fluidHeight, IrisData data, public record Options(long seed, int height, double fluidHeight, PackRuntime runtime,
boolean enabled, int maximumColumns) { boolean enabled, int maximumColumns) {
public Options { public Options {
if (height < 2 || height > 4096 || !Double.isFinite(fluidHeight) if (height < 2 || height > 4096 || !Double.isFinite(fluidHeight)
@@ -58,11 +58,11 @@ public final class SelectorCompiler {
IrisGeneratorStyle exported = exportable(key.style()); IrisGeneratorStyle exported = exportable(key.style());
RNG seed = new RNG(CALIBRATION_SEED).nextParallelRNG(key.salt()); RNG seed = new RNG(CALIBRATION_SEED).nextParallelRNG(key.salt());
if (key.scaled()) { if (key.scaled()) {
CNG iris = exported.createScaledGenerator(seed, data, key.factor()); CNG iris = exported.createScaledGenerator(seed, data.standalonePackRuntime(), key.factor());
IrisGeneratorStyle compiled = scaledCopy(exported, key.factor()); IrisGeneratorStyle compiled = scaledCopy(exported, key.factor());
return compile(compiled, key.salt(), iris::noiseFast2D, COHERENT_BLOCKS * compiled.getZoom()); return compile(compiled, key.salt(), iris::noiseFast2D, COHERENT_BLOCKS * compiled.getZoom());
} }
CNG iris = exported.create(seed, data); CNG iris = exported.create(seed, data.standalonePackRuntime());
double zoom = key.factor(); double zoom = key.factor();
IrisGeneratorStyle compiled = copy(exported); IrisGeneratorStyle compiled = copy(exported);
compiled.setZoom(exported.getZoom() * zoom); compiled.setZoom(exported.getZoom() * zoom);
@@ -30,7 +30,7 @@ final class DecoratorCoverage {
} }
static Coverage measure(IrisGeneratorStyle style, double chance, IrisData data) { static Coverage measure(IrisGeneratorStyle style, double chance, IrisData data) {
CNG generator = style.createNoCache(new RNG(STYLE_SEED), data); CNG generator = style.createNoCache(new RNG(STYLE_SEED), data.standalonePackRuntime());
double zoom = style.getZoom(); double zoom = style.getZoom();
return measure((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance); return measure((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance);
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.noise; package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator; import art.arcane.iris.generation.noise.IrisNoiseGenerator;
@@ -38,6 +39,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
private final StyleCompiler selectors; private final StyleCompiler selectors;
private final Map<LeafKey, LeafNoiseFit.FittedLeaf> leaves = new ConcurrentHashMap<>(); private final Map<LeafKey, LeafNoiseFit.FittedLeaf> leaves = new ConcurrentHashMap<>();
private final Map<LevelKey, WarpFit.LevelFit> levels = new ConcurrentHashMap<>(); private final Map<LevelKey, WarpFit.LevelFit> levels = new ConcurrentHashMap<>();
private final PackRuntime runtime = PackRuntime.standalone(null);
public NoiseStyleCompiler(CellularStyleLowering cellular) { public NoiseStyleCompiler(CellularStyleLowering cellular) {
this.cellular = Objects.requireNonNull(cellular, "cellular"); this.cellular = Objects.requireNonNull(cellular, "cellular");
@@ -56,7 +58,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
} }
public static CNG generator(IrisGeneratorStyle style) { public static CNG generator(IrisGeneratorStyle style) {
return build(prepared(Objects.requireNonNull(style, "style"), 1.0), 1); return build(prepared(Objects.requireNonNull(style, "style"), 1.0), 1, PackRuntime.standalone(null));
} }
@Override @Override
@@ -182,7 +184,7 @@ public final class NoiseStyleCompiler implements StyleCompiler {
private Field style(IrisGeneratorStyle style, int octaveMultiplier, Domain domain, Emit emit, String path) { private Field style(IrisGeneratorStyle style, int octaveMultiplier, Domain domain, Emit emit, String path) {
IrisGeneratorStyle prepared = prepared(Objects.requireNonNull(style, "noise style"), domain.zoom()); IrisGeneratorStyle prepared = prepared(Objects.requireNonNull(style, "noise style"), domain.zoom());
String stylePath = path + "/" + styleName(style); String stylePath = path + "/" + styleName(style);
CNG root = build(prepared, octaveMultiplier); CNG root = build(prepared, octaveMultiplier, runtime);
if (cellular(prepared, root)) { if (cellular(prepared, root)) {
if (domain.warpX() != null || domain.warpZ() != null) { if (domain.warpX() != null || domain.warpZ() != null) {
throw new IllegalArgumentException("Cellular noise style " + styleName(style) + " cannot be exported under a layer fracture warp"); throw new IllegalArgumentException("Cellular noise style " + styleName(style) + " cannot be exported under a layer fracture warp");
@@ -393,8 +395,8 @@ public final class NoiseStyleCompiler implements StyleCompiler {
} }
} }
private static CNG build(IrisGeneratorStyle style, int octaveMultiplier) { private static CNG build(IrisGeneratorStyle style, int octaveMultiplier, PackRuntime runtime) {
return style.createForLayer(new RNG(BUILD_SEED), null, octaveMultiplier); return style.createForLayer(new RNG(BUILD_SEED), runtime, octaveMultiplier);
} }
private static IrisGeneratorStyle prepared(IrisGeneratorStyle style, double zoom) { private static IrisGeneratorStyle prepared(IrisGeneratorStyle style, double zoom) {
@@ -184,7 +184,7 @@ final class VariantPlanner {
return warps; return warps;
} }
String key = ContentIds.hash(GSON.toJson(style)); String key = ContentIds.hash(GSON.toJson(style));
CNG generator = style.create(new RNG(ContentIds.seed(key)), data); CNG generator = style.create(new RNG(ContentIds.seed(key)), data.standalonePackRuntime());
double half = style.getMultiplier() / 2; double half = style.getMultiplier() / 2;
WarpField field = (x, y, z) -> generator.fitDouble(-half, half, x, y, z); WarpField field = (x, y, z) -> generator.fitDouble(-half, half, x, y, z);
for (int index = 0; index < WARP_VARIANTS; index++) { for (int index = 0; index < WARP_VARIANTS; index++) {
@@ -101,7 +101,7 @@ public final class VolumetricCompiler {
} }
private static List<Field.Knot> fit(Marginal marginal, Field unit, Sampling sampling) { private static List<Field.Knot> fit(Marginal marginal, Field unit, Sampling sampling) {
CNG iris = marginal.style().createNoCache(new RNG(MARGINAL_SEED), sampling.data()); CNG iris = marginal.style().createNoCache(new RNG(MARGINAL_SEED), sampling.data().standalonePackRuntime());
Map<String, NoiseDef> noises = sampling.registry().byReference(); Map<String, NoiseDef> noises = sampling.registry().byReference();
double frequency = STYLE_SCALE / marginal.horizontalScale(); double frequency = STYLE_SCALE / marginal.horizontalScale();
SplittableRandom random = new SplittableRandom(MARGINAL_SEED); SplittableRandom random = new SplittableRandom(MARGINAL_SEED);
@@ -18,6 +18,7 @@
package art.arcane.iris.structure.object; package art.arcane.iris.structure.object;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.block.TileData; import art.arcane.iris.generation.block.TileData;
@@ -37,11 +38,11 @@ public class HeightmapObjectPlacer implements IObjectPlacer {
} }
public int getHighest(int param1Int1, int param1Int2, IrisData data) { public int getHighest(int param1Int1, int param1Int2, IrisData data) {
return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, data)); return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, PackRuntime.forContext(data)));
} }
public int getHighest(int param1Int1, int param1Int2, IrisData data, boolean param1Boolean) { public int getHighest(int param1Int1, int param1Int2, IrisData data, boolean param1Boolean) {
return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, data)); return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2, PackRuntime.forContext(data)));
} }
public void set(int param1Int1, int param1Int2, int param1Int3, NativeBlockState param1BlockData) { public void set(int param1Int1, int param1Int2, int param1Int3, NativeBlockState param1BlockData) {
@@ -18,6 +18,7 @@
package art.arcane.iris.structure.object; package art.arcane.iris.structure.object;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.CarvingMode; import art.arcane.iris.generation.cave.CarvingMode;
import art.arcane.iris.generation.cave.IrisCaveAnchorMode; import art.arcane.iris.generation.cave.IrisCaveAnchorMode;
import art.arcane.iris.generation.decoration.IrisStiltSettings; import art.arcane.iris.generation.decoration.IrisStiltSettings;
@@ -367,7 +368,7 @@ public class IrisObjectPlacement {
long seed = engine == null ? rng.getSeed() : engine.getSeedManager().getComponent() + 1024L; long seed = engine == null ? rng.getSeed() : engine.getSeedManager().getComponent() + 1024L;
SurfaceWarpCacheKey key = new SurfaceWarpCacheKey(data, engine, seed); SurfaceWarpCacheKey key = new SurfaceWarpCacheKey(data, engine, seed);
return surfaceWarpCache.computeIfAbsent(key, return surfaceWarpCache.computeIfAbsent(key,
ignored -> getWarp().create(new RNG(seed), data, engine)); ignored -> getWarp().create(new RNG(seed), PackRuntime.of(engine, data)));
} }
public double warp(RNG rng, double x, double y, double z, IrisData data) { public double warp(RNG rng, double x, double y, double z, IrisData data) {
@@ -419,7 +420,7 @@ public class IrisObjectPlacement {
return density; return density;
} }
return (int) Math.round(densityStyle.get(rng, x, z, data)); return (int) Math.round(densityStyle.get(rng, x, z, PackRuntime.forContext(data)));
} }
private TableCache getCache(IrisData manager) { private TableCache getCache(IrisData manager) {
@@ -18,6 +18,7 @@
package art.arcane.iris.studio.map; package art.arcane.iris.studio.map;
import art.arcane.iris.generation.runtime.PackRuntime;
import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.FlatClientProperties;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.configuration.IrisSettings;
@@ -570,7 +571,8 @@ public final class NoiseExplorerGUI extends JPanel {
} }
long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax(); long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax();
IrisGenerator selectedGenerator = generator; IrisGenerator selectedGenerator = generator;
return (x, z) -> selectedGenerator.getHeight(x, z, mixedSeed); PackRuntime runtime = PackRuntime.of(engine, selectedGenerator.getLoader());
return (x, z) -> selectedGenerator.getHeight(runtime, x, z, mixedSeed);
} }
private List<SourceItem> loadPackSources(Engine engine) { private List<SourceItem> loadPackSources(Engine engine) {
@@ -608,7 +610,8 @@ public final class NoiseExplorerGUI extends JPanel {
throw new IllegalStateException("Pack generator not found: " + key); throw new IllegalStateException("Pack generator not found: " + key);
} }
long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax(); long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax();
return LoadedSource.of((x, z) -> generator.getHeight(x, z, mixedSeed)); PackRuntime runtime = data.standalonePackRuntime();
return LoadedSource.of((x, z) -> generator.getHeight(runtime, x, z, mixedSeed));
} }
)); ));
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.biome; package art.arcane.iris.generation.biome;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
@@ -20,7 +21,7 @@ import static org.mockito.Mockito.mock;
public class IrisBiomeFieldSeedCohesionTest { public class IrisBiomeFieldSeedCohesionTest {
@Test @Test
public void childrenGeneratorsSeparateSeedsSignaturesAndScales() { public void childrenGeneratorsSeparateSeedsSignaturesAndScales() {
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
IrisBiome shared = biome(data); IrisBiome shared = biome(data);
for (long seed : new long[]{29L, 11L, 29L}) { for (long seed : new long[]{29L, 11L, 29L}) {
for (int signature : new int[]{2137, 91}) { for (int signature : new int[]{2137, 91}) {
@@ -36,7 +37,7 @@ public class IrisBiomeFieldSeedCohesionTest {
@Test(timeout = 15000) @Test(timeout = 15000)
public void concurrentFloatingFieldsAndEvictionRetainSeedAssignments() throws Exception { public void concurrentFloatingFieldsAndEvictionRetainSeedAssignments() throws Exception {
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
IrisFloatingChildBiomes shared = new IrisFloatingChildBiomes(); IrisFloatingChildBiomes shared = new IrisFloatingChildBiomes();
ExecutorService workers = Executors.newFixedThreadPool(4); ExecutorService workers = Executors.newFixedThreadPool(4);
try { try {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.biome; package art.arcane.iris.generation.biome;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.SeedManager; import art.arcane.iris.generation.runtime.SeedManager;
@@ -115,7 +116,7 @@ public class IrisBiomeGeneratorSeedIsolationTest {
} }
private IrisData dataWithActiveEngine(AtomicReference<Engine> activeEngine) { private IrisData dataWithActiveEngine(AtomicReference<Engine> activeEngine) {
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
when(data.getEngine()).thenAnswer(ignored -> activeEngine.get()); when(data.getEngine()).thenAnswer(ignored -> activeEngine.get());
return data; return data;
} }
@@ -85,7 +85,7 @@ public final class IrisBiomePaletteLayerGeneratorCacheTest {
11L + SIGNATURE + LAYER_SIGNATURE, carveGenerator, 11L + SIGNATURE + LAYER_SIGNATURE, carveGenerator,
29L + SIGNATURE + LAYER_SIGNATURE, postGenerator 29L + SIGNATURE + LAYER_SIGNATURE, postGenerator
); );
when(style.create(any(RNG.class), same(data), same(engine))).thenAnswer(invocation -> { when(style.create(any(RNG.class), any())).thenAnswer(invocation -> {
RNG rng = invocation.getArgument(0); RNG rng = invocation.getArgument(0);
return generators.get(rng.getSeed()); return generators.get(rng.getSeed());
}); });
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.cave; package art.arcane.iris.generation.cave;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.noise.IrisStyledRange; import art.arcane.iris.generation.noise.IrisStyledRange;
@@ -26,7 +27,7 @@ public class IrisCaveProfileSamplerTest {
public void resolvesThresholdNoiseOnceWhilePreservingCoordinateDecisions() { public void resolvesThresholdNoiseOnceWhilePreservingCoordinateDecisions() {
IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class);
CNG thresholdNoise = mock(CNG.class); CNG thresholdNoise = mock(CNG.class);
when(style.create(any(), isNull())).thenReturn(thresholdNoise); when(style.create(any(), any(PackRuntime.class))).thenReturn(thresholdNoise);
when(thresholdNoise.fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble())) when(thresholdNoise.fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble()))
.thenAnswer(invocation -> (double) invocation.getArgument(2) * 0.003D .thenAnswer(invocation -> (double) invocation.getArgument(2) * 0.003D
+ (double) invocation.getArgument(3) * 0.005D); + (double) invocation.getArgument(3) * 0.005D);
@@ -41,7 +42,7 @@ public class IrisCaveProfileSamplerTest {
assertEquals(density <= threshold, sampler.shouldCarve(x, y, z, 0.75D)); assertEquals(density <= threshold, sampler.shouldCarve(x, y, z, 0.75D));
} }
} }
verify(style, times(1)).create(any(), isNull()); verify(style, times(1)).create(any(), any(PackRuntime.class));
verify(thresholdNoise, times(585)).fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble()); verify(thresholdNoise, times(585)).fitDouble(anyDouble(), anyDouble(), anyDouble(), anyDouble());
} }
@@ -58,7 +59,7 @@ public class IrisCaveProfileSamplerTest {
for (int z : coordinates) { for (int z : coordinates) {
for (int y = -60; y <= 60; y += 3) { for (int y = -60; y <= 60; y += 3) {
for (double floatingThreshold : floatingThresholds) { for (double floatingThreshold : floatingThresholds) {
double threshold = range.get(thresholdRng, x, z, null) - profile.getThresholdBias(); double threshold = range.get(thresholdRng, x, z, PackRuntime.standalone(null)) - profile.getThresholdBias();
threshold += (1D - Math.max(0D, Math.min(1D, floatingThreshold))) * 0.2D; threshold += (1D - Math.max(0D, Math.min(1D, floatingThreshold))) * 0.2D;
assertEquals("x=" + x + " y=" + y + " z=" + z + " floating=" + floatingThreshold, assertEquals("x=" + x + " y=" + y + " z=" + z + " floating=" + floatingThreshold,
density(x, y, z) <= threshold, sampler.shouldCarve(x, y, z, floatingThreshold)); density(x, y, z) <= threshold, sampler.shouldCarve(x, y, z, floatingThreshold));
@@ -98,7 +99,7 @@ public class IrisCaveProfileSamplerTest {
when(densityNoise.noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble())).thenAnswer(invocation -> when(densityNoise.noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble())).thenAnswer(invocation ->
density(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2))); density(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2)));
IrisGeneratorStyle densityStyle = mock(IrisGeneratorStyle.class); IrisGeneratorStyle densityStyle = mock(IrisGeneratorStyle.class);
when(densityStyle.create(any(), isNull())).thenReturn(densityNoise); when(densityStyle.create(any(), any(PackRuntime.class))).thenReturn(densityNoise);
IrisCaveProfile profile = mock(IrisCaveProfile.class); IrisCaveProfile profile = mock(IrisCaveProfile.class);
when(profile.getBaseDensityStyle()).thenReturn(densityStyle); when(profile.getBaseDensityStyle()).thenReturn(densityStyle);
when(profile.getDetailDensityStyle()).thenReturn(densityStyle); when(profile.getDetailDensityStyle()).thenReturn(densityStyle);
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.decoration; package art.arcane.iris.generation.decoration;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
@@ -41,7 +42,7 @@ public class HydrologyVegetationTest {
private static final Set<String> WATER_PLANTS = Set.of("minecraft:seagrass", "minecraft:tall_seagrass", "minecraft:kelp", "minecraft:kelp_plant"); private static final Set<String> WATER_PLANTS = Set.of("minecraft:seagrass", "minecraft:tall_seagrass", "minecraft:kelp", "minecraft:kelp_plant");
private static final int[][] SIDES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private static final int[][] SIDES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private final IrisData data = mock(IrisData.class); private final IrisData data = MockPackData.create();
private PlantPlatform platform; private PlantPlatform platform;
@Before @Before
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.decoration; package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.KeyedBlockState; import art.arcane.iris.testsupport.KeyedBlockState;
@@ -71,7 +72,7 @@ public class IrisOreBandsTest {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.FLAT).setZoom(2.5D).setExponent(1.3D) IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.FLAT).setZoom(2.5D).setExponent(1.3D)
.setFracture(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setMultiplier(9D)); .setFracture(new IrisGeneratorStyle(NoiseStyle.SIMPLEX).setMultiplier(9D));
flat.setPalette(palette).setChanceStyle(style).setRange(new IrisRange(0, 100)); flat.setPalette(palette).setChanceStyle(style).setRange(new IrisRange(0, 100));
CNG reference = style.create(RNG_SOURCE, null); CNG reference = style.create(RNG_SOURCE, PackRuntime.standalone(null));
for (double threshold : new double[]{0.1D, 0.5D, 0.99D, 1D}) { for (double threshold : new double[]{0.1D, 0.5D, 0.99D, 1D}) {
flat.setThreshold(threshold); flat.setThreshold(threshold);
for (int index = 0; index < 100; index++) { for (int index = 0; index < 100; index++) {
@@ -137,7 +138,7 @@ public class IrisOreBandsTest {
} }
@Override @Override
public CNG create(RNG rng, IrisData data) { public CNG create(RNG rng, PackRuntime runtime) {
return chance; return chance;
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.decoration; package art.arcane.iris.generation.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisMaterialPalette;
@@ -62,7 +63,7 @@ public class IrisOreGeneratorTest {
when(palette.getPalette()).thenReturn(new KList<>(mock(IrisBlockData.class))); when(palette.getPalette()).thenReturn(new KList<>(mock(IrisBlockData.class)));
when(palette.get(any(), anyDouble(), anyDouble(), anyDouble(), isNull())).thenReturn(ore); when(palette.get(any(), anyDouble(), anyDouble(), anyDouble(), isNull())).thenReturn(ore);
when(noise.noise(anyDouble(), anyDouble(), anyDouble())).thenReturn(sample); when(noise.noise(anyDouble(), anyDouble(), anyDouble())).thenReturn(sample);
when(style.create(any(), isNull())).thenReturn(noise); when(style.create(any(), any(PackRuntime.class))).thenReturn(noise);
generator.setPalette(palette); generator.setPalette(palette);
generator.setChanceStyle(style); generator.setChanceStyle(style);
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle; package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveFieldModule; import art.arcane.iris.generation.cave.IrisCaveFieldModule;
import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
@@ -154,6 +155,7 @@ public class IrisCaveCarver3DCellKernelTest {
IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly());
SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly());
doReturn(data).when(engine).getData(); doReturn(data).when(engine).getData();
doReturn(PackRuntime.forEngine(engine, data)).when(engine).getPackRuntime();
doReturn(dimension).when(engine).getDimension(); doReturn(dimension).when(engine).getDimension();
doReturn(seedManager).when(engine).getSeedManager(); doReturn(seedManager).when(engine).getSeedManager();
doReturn(CARVE_SEED).when(seedManager).getCarve(); doReturn(CARVE_SEED).when(seedManager).getCarve();
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle; package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.cave.IrisCaveFieldModule; import art.arcane.iris.generation.cave.IrisCaveFieldModule;
import art.arcane.iris.generation.cave.IrisCaveProfile; import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
@@ -162,6 +163,7 @@ public class IrisCaveCarver3DLatticeTest {
IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly());
SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly()); SeedManager seedManager = mock(SeedManager.class, withSettings().stubOnly());
doReturn(data).when(engine).getData(); doReturn(data).when(engine).getData();
doReturn(PackRuntime.forEngine(engine, data)).when(engine).getPackRuntime();
doReturn(dimension).when(engine).getDimension(); doReturn(dimension).when(engine).getDimension();
doReturn(seedManager).when(engine).getSeedManager(); doReturn(seedManager).when(engine).getSeedManager();
doReturn(CARVE_SEED).when(seedManager).getCarve(); doReturn(CARVE_SEED).when(seedManager).getCarve();
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle; package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineMetrics; import art.arcane.iris.generation.runtime.EngineMetrics;
@@ -209,7 +210,7 @@ public class IrisCaveCarver3DNearParityTest {
}).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); }).when(density).noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble());
IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly()); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly());
doReturn("density_expression").when(style).getExpression(); doReturn("density_expression").when(style).getExpression();
doReturn(density).when(style).create(any(RNG.class), any(IrisData.class)); doReturn(density).when(style).create(any(RNG.class), any());
IrisCaveProfile profile = createProfile(false, false).setBaseDensityStyle(style) IrisCaveProfile profile = createProfile(false, false).setBaseDensityStyle(style)
.setDetailWeight(0D).setAllowFluid(false) .setDetailWeight(0D).setAllowFluid(false)
.setDensityThreshold(new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT))); .setDensityThreshold(new IrisStyledRange(0.15D, 0.15D, new IrisGeneratorStyle(NoiseStyle.FLAT)));
@@ -1304,7 +1305,7 @@ public class IrisCaveCarver3DNearParityTest {
.noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble()); .noiseFastSigned3D(anyDouble(), anyDouble(), anyDouble());
IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly()); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class, withSettings().stubOnly());
doReturn("density_expression").when(style).getExpression(); doReturn("density_expression").when(style).getExpression();
doReturn(density).when(style).create(any(RNG.class), any(IrisData.class)); doReturn(density).when(style).create(any(RNG.class), any());
AtomicInteger lookups = new AtomicInteger(); AtomicInteger lookups = new AtomicInteger();
CaveDensityGrid grid = countingGrid(4, lookups); CaveDensityGrid grid = countingGrid(4, lookups);
IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, IrisCaveCarver3D carver = new IrisCaveCarver3D(engine,
@@ -1470,7 +1471,7 @@ public class IrisCaveCarver3DNearParityTest {
continue; continue;
} }
passThreshold[columnIndex] = profile.getDensityThreshold().get(thresholdRng, x, z, data) - profile.getThresholdBias(); passThreshold[columnIndex] = profile.getDensityThreshold().get(thresholdRng, x, z, PackRuntime.standalone(data)) - profile.getThresholdBias();
} }
} }
@@ -1642,6 +1643,7 @@ public class IrisCaveCarver3DNearParityTest {
IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(worldHeight).build(); IrisWorld world = IrisWorld.builder().minHeight(0).maxHeight(worldHeight).build();
doReturn(data).when(engine).getData(); doReturn(data).when(engine).getData();
doReturn(PackRuntime.forEngine(engine, data)).when(engine).getPackRuntime();
doReturn(dimension).when(engine).getDimension(); doReturn(dimension).when(engine).getDimension();
doReturn(seedManager).when(engine).getSeedManager(); doReturn(seedManager).when(engine).getSeedManager();
doReturn(CARVE_SEED).when(seedManager).getCarve(); doReturn(CARVE_SEED).when(seedManager).getCarve();
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle; package art.arcane.iris.generation.mantle;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.block.TileData; import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.generation.decoration.IrisStiltSettings; import art.arcane.iris.generation.decoration.IrisStiltSettings;
import art.arcane.iris.generation.decoration.IrisVacuumSettings; import art.arcane.iris.generation.decoration.IrisVacuumSettings;
@@ -78,9 +79,9 @@ public class PlacementReachTest {
when(engine.getHeight()).thenReturn(256); when(engine.getHeight()).thenReturn(256);
when(engine.getMinHeight()).thenReturn(0); when(engine.getMinHeight()).thenReturn(0);
when(engine.getComplex()).thenReturn(complex); when(engine.getComplex()).thenReturn(complex);
data = mock(IrisData.class, withSettings().stubOnly()); data = MockPackData.stubOnly();
when(data.getEngine()).thenReturn(engine); when(data.getEngine()).thenReturn(engine);
objectData = mock(IrisData.class, withSettings().stubOnly()); objectData = MockPackData.stubOnly();
} }
@After @After
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import org.junit.Test; import org.junit.Test;
@@ -8,6 +9,8 @@ import java.util.SplittableRandom;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class GeneratorProgramParityTest { public class GeneratorProgramParityTest {
private final PackRuntime runtime = PackRuntime.standalone(null);
private static final NoiseStyle[] STYLES = { private static final NoiseStyle[] STYLES = {
NoiseStyle.SIMPLEX, NoiseStyle.PERLIN, NoiseStyle.IRIS, NoiseStyle.IRIS_HALF, NoiseStyle.FRACTAL_SMOKE, NoiseStyle.SIMPLEX, NoiseStyle.PERLIN, NoiseStyle.IRIS, NoiseStyle.IRIS_HALF, NoiseStyle.FRACTAL_SMOKE,
NoiseStyle.FRACTAL_WATER, NoiseStyle.CLOVER, NoiseStyle.CELLULAR, NoiseStyle.NOWHERE, NoiseStyle.FRACTAL_WATER, NoiseStyle.CLOVER, NoiseStyle.CELLULAR, NoiseStyle.NOWHERE,
@@ -24,7 +27,7 @@ public class GeneratorProgramParityTest {
IrisGenerator scalar = generator(new SplittableRandom(shapeSeed)); IrisGenerator scalar = generator(new SplittableRandom(shapeSeed));
IrisGenerator batch = generator(new SplittableRandom(shapeSeed)); IrisGenerator batch = generator(new SplittableRandom(shapeSeed));
long superSeed = random.nextLong(); long superSeed = random.nextLong();
GeneratorProgram program = batch.compileProgram(superSeed); GeneratorProgram program = batch.compileProgram(runtime, superSeed);
int count = 1 + random.nextInt(600); int count = 1 + random.nextInt(600);
double[] xs = new double[count]; double[] xs = new double[count];
double[] zs = new double[count]; double[] zs = new double[count];
@@ -33,7 +36,7 @@ public class GeneratorProgramParityTest {
program.heights(scratch, xs, zs, count, out); program.heights(scratch, xs, zs, count, out);
for (int index = 0; index < count; index++) { for (int index = 0; index < count; index++) {
assertEquals("generator " + generatorIndex + " point " + xs[index] + "," + zs[index], assertEquals("generator " + generatorIndex + " point " + xs[index] + "," + zs[index],
Double.doubleToRawLongBits(scalar.getHeight(xs[index], zs[index], superSeed)), Double.doubleToRawLongBits(scalar.getHeight(runtime, xs[index], zs[index], superSeed)),
Double.doubleToRawLongBits(out[index])); Double.doubleToRawLongBits(out[index]));
} }
} }
@@ -48,12 +51,12 @@ public class GeneratorProgramParityTest {
IrisGenerator scalar = generator(new SplittableRandom(shapeSeed)); IrisGenerator scalar = generator(new SplittableRandom(shapeSeed));
IrisGenerator compiled = generator(new SplittableRandom(shapeSeed)); IrisGenerator compiled = generator(new SplittableRandom(shapeSeed));
long superSeed = random.nextLong(); long superSeed = random.nextLong();
GeneratorProgram program = compiled.compileProgram(superSeed); GeneratorProgram program = compiled.compileProgram(runtime, superSeed);
for (int sample = 0; sample < 400; sample++) { for (int sample = 0; sample < 400; sample++) {
double x = coordinate(random); double x = coordinate(random);
double z = random.nextInt(5) == 0 ? x : coordinate(random); double z = random.nextInt(5) == 0 ? x : coordinate(random);
assertEquals("generator " + generatorIndex + " point " + x + "," + z, assertEquals("generator " + generatorIndex + " point " + x + "," + z,
Double.doubleToRawLongBits(scalar.getHeight(x, z, superSeed)), Double.doubleToRawLongBits(scalar.getHeight(runtime, x, z, superSeed)),
Double.doubleToRawLongBits(program.height(scratch, x, z))); Double.doubleToRawLongBits(program.height(scratch, x, z)));
} }
} }
@@ -71,7 +74,7 @@ public class GeneratorProgramParityTest {
IrisGenerator scalar = generator(new SplittableRandom(shapeSeed)); IrisGenerator scalar = generator(new SplittableRandom(shapeSeed));
IrisGenerator batch = generator(new SplittableRandom(shapeSeed)); IrisGenerator batch = generator(new SplittableRandom(shapeSeed));
long superSeed = random.nextLong(); long superSeed = random.nextLong();
GeneratorProgram program = batch.compileProgram(superSeed); GeneratorProgram program = batch.compileProgram(runtime, superSeed);
for (int chunk = 0; chunk < 4; chunk++) { for (int chunk = 0; chunk < 4; chunk++) {
int originX = random.nextInt(-200_000, 200_000) << 4; int originX = random.nextInt(-200_000, 200_000) << 4;
int originZ = random.nextInt(-200_000, 200_000) << 4; int originZ = random.nextInt(-200_000, 200_000) << 4;
@@ -81,7 +84,7 @@ public class GeneratorProgramParityTest {
} }
program.heights(scratch, xs, zs, 256, out); program.heights(scratch, xs, zs, 256, out);
for (int index = 0; index < 256; index++) { for (int index = 0; index < 256; index++) {
assertEquals(Double.doubleToRawLongBits(scalar.getHeight(xs[index], zs[index], superSeed)), assertEquals(Double.doubleToRawLongBits(scalar.getHeight(runtime, xs[index], zs[index], superSeed)),
Double.doubleToRawLongBits(out[index])); Double.doubleToRawLongBits(out[index]));
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import org.junit.Test; import org.junit.Test;
@@ -10,17 +11,17 @@ public class IrisExpressionCoordinateTest {
@Test @Test
public void planarEvaluationBindsHorizontalAxesAndAbsentHeight() { public void planarEvaluationBindsHorizontalAxesAndAbsentHeight() {
RNG rng = new RNG(17L); RNG rng = new RNG(17L);
assertEquals(23.5D, expression("x").evaluate(rng, 23.5D, -94.75D), 0D); assertEquals(23.5D, runtimeOf(expression("x")).evaluate(rng, 23.5D, -94.75D), 0D);
assertEquals(-94.75D, expression("y").evaluate(rng, 23.5D, -94.75D), 0D); assertEquals(-94.75D, runtimeOf(expression("y")).evaluate(rng, 23.5D, -94.75D), 0D);
assertEquals(-1D, expression("z").evaluate(rng, 23.5D, -94.75D), 0D); assertEquals(-1D, runtimeOf(expression("z")).evaluate(rng, 23.5D, -94.75D), 0D);
} }
@Test @Test
public void volumetricEvaluationBindsEachAxis() { public void volumetricEvaluationBindsEachAxis() {
RNG rng = new RNG(17L); RNG rng = new RNG(17L);
assertEquals(23.5D, expression("x").evaluate(rng, 23.5D, 61D, -94.75D), 0D); assertEquals(23.5D, runtimeOf(expression("x")).evaluate(rng, 23.5D, 61D, -94.75D), 0D);
assertEquals(61D, expression("y").evaluate(rng, 23.5D, 61D, -94.75D), 0D); assertEquals(61D, runtimeOf(expression("y")).evaluate(rng, 23.5D, 61D, -94.75D), 0D);
assertEquals(-94.75D, expression("z").evaluate(rng, 23.5D, 61D, -94.75D), 0D); assertEquals(-94.75D, runtimeOf(expression("z")).evaluate(rng, 23.5D, 61D, -94.75D), 0D);
} }
@Test @Test
@@ -28,16 +29,20 @@ public class IrisExpressionCoordinateTest {
IrisExpression expression = expression("value + x + 10 * y + 100 * z") IrisExpression expression = expression("value + x + 10 * y + 100 * z")
.setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStaticValue(7D))); .setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStaticValue(7D)));
RNG rng = new RNG(17L); RNG rng = new RNG(17L);
assertEquals(-1017D, expression.evaluate(rng, 23.5D, -94.75D), 0D); assertEquals(-1017D, runtimeOf(expression).evaluate(rng, 23.5D, -94.75D), 0D);
assertEquals(-8834.5D, expression.evaluate(rng, 23.5D, 61D, -94.75D), 0D); assertEquals(-8834.5D, runtimeOf(expression).evaluate(rng, 23.5D, 61D, -94.75D), 0D);
} }
@Test @Test
public void expressionStreamsAndNoiseUsePlanarCoordinates() { public void expressionStreamsAndNoiseUsePlanarCoordinates() {
IrisExpression expression = expression("x + 100 * y"); IrisExpression expression = expression("x + 100 * y");
RNG rng = new RNG(17L); RNG rng = new RNG(17L);
assertEquals(-9451.5D, expression.stream(rng).getDouble(23.5D, -94.75D), 0D); assertEquals(-9451.5D, runtimeOf(expression).stream(rng).getDouble(23.5D, -94.75D), 0D);
assertEquals(-9451.5D, new ExpressionNoise(rng, expression).noise(23.5D, -94.75D), 0D); assertEquals(-9451.5D, new ExpressionNoise(rng, runtimeOf(expression)).noise(23.5D, -94.75D), 0D);
}
private static ExpressionRuntime runtimeOf(IrisExpression expression) {
return PackRuntime.standalone(null).expression(expression);
} }
private static IrisExpression expression(String source) { private static IrisExpression expression(String source) {
@@ -1,68 +1,60 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import art.arcane.iris.generation.runtime.IrisEngineValueType; import art.arcane.iris.generation.runtime.IrisEngineValueType;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.volmlib.util.collection.KList;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class IrisExpressionLoadEngineCacheTest { public class IrisExpressionLoadEngineCacheTest {
@Test @Test
public void engineValuesAreCachedPerEngineIdentity() { public void engineValuesBelongToTheEngineRuntime() {
Engine first = mock(Engine.class); Engine first = mock(Engine.class);
Engine second = mock(Engine.class); Engine second = mock(Engine.class);
when(first.getHeight()).thenReturn(128); when(first.getHeight()).thenReturn(128);
when(second.getHeight()).thenReturn(320); when(second.getHeight()).thenReturn(320);
AtomicReference<Engine> active = new AtomicReference<>(first); IrisExpression expression = expression(new IrisExpressionLoad()
IrisData data = data(active);
IrisExpressionLoad load = new IrisExpressionLoad()
.setName("height") .setName("height")
.setEngineValue(IrisEngineValueType.ENGINE_HEIGHT); .setEngineValue(IrisEngineValueType.ENGINE_HEIGHT));
IrisData data = mock(IrisData.class);
assertEquals(128D, load.getValue(new RNG(1L), data, 0D, 0D), 0D); assertEquals(128D, PackRuntime.forEngine(first, data).expression(expression).evaluate(new RNG(1L), 0D, 0D), 0D);
active.set(second); assertEquals(320D, PackRuntime.forEngine(second, data).expression(expression).evaluate(new RNG(1L), 0D, 0D), 0D);
assertEquals(320D, load.getValue(new RNG(1L), data, 0D, 0D), 0D);
} }
@Test @Test
public void engineStreamsAreCachedPerEngineIdentity() { public void engineStreamsBelongToTheEngineRuntime() {
Engine first = streamEngine(12D); IrisExpression expression = expression(new IrisExpressionLoad()
Engine second = streamEngine(27D);
AtomicReference<Engine> active = new AtomicReference<>(first);
IrisData data = data(active);
IrisExpressionLoad load = new IrisExpressionLoad()
.setName("height") .setName("height")
.setEngineStreamValue(IrisEngineStreamType.HEIGHT); .setEngineStreamValue(IrisEngineStreamType.HEIGHT));
IrisData data = mock(IrisData.class);
assertEquals(12D, load.getValue(new RNG(1L), data, 4D, 8D), 0D); assertEquals(12D, PackRuntime.forEngine(streamEngine(12D), data).expression(expression)
active.set(second); .evaluate(new RNG(1L), 4D, 8D), 0D);
assertEquals(27D, load.getValue(new RNG(1L), data, 4D, 8D), 0D); assertEquals(27D, PackRuntime.forEngine(streamEngine(27D), data).expression(expression)
.evaluate(new RNG(1L), 4D, 8D), 0D);
} }
@Test(expected = IllegalStateException.class) @Test(expected = IllegalStateException.class)
public void engineBackedValueFailsWithoutUnambiguousEngine() { public void engineBackedValueFailsWithoutAnEngine() {
IrisData data = mock(IrisData.class); IrisExpression expression = expression(new IrisExpressionLoad()
IrisExpressionLoad load = new IrisExpressionLoad()
.setName("height") .setName("height")
.setEngineValue(IrisEngineValueType.ENGINE_HEIGHT); .setEngineValue(IrisEngineValueType.ENGINE_HEIGHT));
load.getValue(new RNG(1L), data, 0D, 0D); PackRuntime.standalone(mock(IrisData.class)).expression(expression).evaluate(new RNG(1L), 0D, 0D);
} }
private IrisData data(AtomicReference<Engine> active) { private static IrisExpression expression(IrisExpressionLoad variable) {
IrisData data = mock(IrisData.class); return new IrisExpression().setExpression("height").setVariables(new KList<>(variable));
when(data.getEngine()).thenAnswer(ignored -> active.get());
return data;
} }
private Engine streamEngine(double value) { private Engine streamEngine(double value) {
@@ -1,10 +1,12 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import com.dfsek.paralithic.Expression; import com.dfsek.paralithic.Expression;
import com.dfsek.paralithic.functions.dynamic.Context; import com.dfsek.paralithic.functions.dynamic.Context;
import com.dfsek.paralithic.functions.dynamic.DynamicFunction;
import com.dfsek.paralithic.node.Statefulness;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
@@ -15,6 +17,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNotSame;
@@ -27,9 +30,8 @@ import static org.mockito.Mockito.mock;
public class IrisExpressionScratchTest { public class IrisExpressionScratchTest {
@Test @Test
public void sequentialPlanarAndVolumetricSamplesReuseTheArgumentArrayAndKeepRngState() { public void sequentialPlanarAndVolumetricSamplesReuseTheArgumentArrayAndKeepRngState() {
IrisExpression expression = new IrisExpression();
Expression compiled = mock(Expression.class); Expression compiled = mock(Expression.class);
expression.getExpressionCache().aquire(() -> compiled); ExpressionRuntime expression = runtimeOf(parsedAs(new IrisExpression(), compiled));
AtomicReference<double[]> first = new AtomicReference<>(); AtomicReference<double[]> first = new AtomicReference<>();
doAnswer(invocation -> { doAnswer(invocation -> {
double[] arguments = (double[]) invocation.getRawArguments()[1]; double[] arguments = (double[]) invocation.getRawArguments()[1];
@@ -51,21 +53,16 @@ public class IrisExpressionScratchTest {
} }
@Test @Test
public void recursiveVariableEvaluationKeepsOuterArgumentsBeyondTheRetainedDepth() { public void recursiveEvaluationWithVariablesKeepsOuterArgumentsBeyondTheRetainedDepth() {
AtomicReference<IrisExpression> expression = new AtomicReference<>(); AtomicReference<ExpressionRuntime> expression = new AtomicReference<>();
IrisExpressionLoad recursive = new IrisExpressionLoad() { IrisExpression config = recursive(new IrisExpression().setExpression("prior(x, y) + value + 17 * x + 31 * y + z")
@Override .setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStaticValue(-1D))), expression);
public double getValue(RNG rng, IrisData data, double x, double z) { expression.set(runtimeOf(config));
return x <= 0D ? 7D : expression.get().evaluate(rng, x - 1D, z);
}
}.setName("prior");
expression.set(new IrisExpression().setExpression("prior + 17 * x + 31 * y + z")
.setVariables(new KList<>(recursive)));
RNG rng = new RNG(78264193L); RNG rng = new RNG(78264193L);
RNG control = new RNG(78264193L); RNG control = new RNG(78264193L);
double expected = 7D; double expected = 7D;
for (int x = 0; x <= 31; x++) { for (int x = 0; x <= 31; x++) {
expected = expected + 17D * x + 31D * 3.75D - 1D; expected = expected + 17D * x + 31D * 3.75D - 2D;
} }
assertEquals(expected, expression.get().evaluate(rng, 31D, 3.75D), 0D); assertEquals(expected, expression.get().evaluate(rng, 31D, 3.75D), 0D);
@@ -75,22 +72,9 @@ public class IrisExpressionScratchTest {
@Test @Test
public void recursiveFunctionEvaluationDoesNotOverwriteTheOuterCoordinates() { public void recursiveFunctionEvaluationDoesNotOverwriteTheOuterCoordinates() {
AtomicReference<IrisExpression> expression = new AtomicReference<>(); AtomicReference<ExpressionRuntime> expression = new AtomicReference<>();
IrisExpressionFunction recursive = new IrisExpressionFunction() { expression.set(runtimeOf(recursive(new IrisExpression().setExpression("prior(x, y) + 17 * x + 31 * y + z"),
@Override expression)));
public boolean isValid() {
return true;
}
@Override
public double eval(Context context, double... coordinates) {
RNG rng = ((FunctionContext) context).rng();
return coordinates[0] <= 0D ? 7D
: expression.get().evaluate(rng, coordinates[0] - 1D, coordinates[1]);
}
}.setName("prior");
expression.set(new IrisExpression().setExpression("prior(x, y) + 17 * x + 31 * y + z")
.setFunctions(new KList<>(recursive)));
double expected = 7D; double expected = 7D;
for (int x = 0; x <= 31; x++) { for (int x = 0; x <= 31; x++) {
expected = expected + 17D * x + 31D * 3.75D - 1D; expected = expected + 17D * x + 31D * 3.75D - 1D;
@@ -102,9 +86,8 @@ public class IrisExpressionScratchTest {
@Test @Test
public void failedEvaluationUnwindsTheRetainedFrame() { public void failedEvaluationUnwindsTheRetainedFrame() {
IrisExpression expression = new IrisExpression();
Expression compiled = mock(Expression.class); Expression compiled = mock(Expression.class);
expression.getExpressionCache().aquire(() -> compiled); ExpressionRuntime expression = runtimeOf(parsedAs(new IrisExpression(), compiled));
AtomicBoolean fail = new AtomicBoolean(true); AtomicBoolean fail = new AtomicBoolean(true);
AtomicReference<double[]> failedArguments = new AtomicReference<>(); AtomicReference<double[]> failedArguments = new AtomicReference<>();
doAnswer(invocation -> { doAnswer(invocation -> {
@@ -124,14 +107,12 @@ public class IrisExpressionScratchTest {
@Test @Test
public void largeArgumentListsRemainSupportedWithoutRetainingTheirArrays() { public void largeArgumentListsRemainSupportedWithoutRetainingTheirArrays() {
IrisExpression expression = new IrisExpression();
KList<IrisExpressionLoad> variables = new KList<>(); KList<IrisExpressionLoad> variables = new KList<>();
for (int i = 0; i < 300; i++) { for (int i = 0; i < 300; i++) {
variables.add(new IrisExpressionLoad().setName("value" + i).setStaticValue(i)); variables.add(new IrisExpressionLoad().setName("value" + i).setStaticValue(i));
} }
expression.setVariables(variables);
Expression compiled = mock(Expression.class); Expression compiled = mock(Expression.class);
expression.getExpressionCache().aquire(() -> compiled); ExpressionRuntime expression = runtimeOf(parsedAs(new IrisExpression().setVariables(variables), compiled));
AtomicReference<double[]> first = new AtomicReference<>(); AtomicReference<double[]> first = new AtomicReference<>();
doAnswer(invocation -> { doAnswer(invocation -> {
double[] arguments = (double[]) invocation.getRawArguments()[1]; double[] arguments = (double[]) invocation.getRawArguments()[1];
@@ -152,7 +133,7 @@ public class IrisExpressionScratchTest {
@Test(timeout = 15000) @Test(timeout = 15000)
public void sharedExpressionKeepsExactSamplesAcrossThreadsAndDimensions() throws Exception { public void sharedExpressionKeepsExactSamplesAcrossThreadsAndDimensions() throws Exception {
IrisExpression expression = new IrisExpression().setExpression("sin(x) + cos(y) + z / 7"); ExpressionRuntime expression = runtimeOf(new IrisExpression().setExpression("sin(x) + cos(y) + z / 7"));
RNG control = new RNG(17L); RNG control = new RNG(17L);
long[] expected = new long[128]; long[] expected = new long[128];
for (int i = 0; i < expected.length; i++) { for (int i = 0; i < expected.length; i++) {
@@ -182,4 +163,54 @@ public class IrisExpressionScratchTest {
executor.awaitTermination(5, TimeUnit.SECONDS); executor.awaitTermination(5, TimeUnit.SECONDS);
} }
} }
private static ExpressionRuntime runtimeOf(IrisExpression expression) {
return PackRuntime.standalone(null).expression(expression);
}
private static IrisExpression parsedAs(IrisExpression template, Expression compiled) {
return new IrisExpression() {
@Override
public Expression parse(Function<IrisExpressionFunction, DynamicFunction> functionRuntime) {
return compiled;
}
}.setVariables(template.getVariables());
}
private static IrisExpression recursive(IrisExpression template, AtomicReference<ExpressionRuntime> expression) {
IrisExpression config = new IrisExpression() {
@Override
public Expression parse(Function<IrisExpressionFunction, DynamicFunction> functionRuntime) {
return super.parse(function -> new PriorFunction(expression));
}
};
config.setExpression(template.getExpression());
config.setVariables(template.getVariables());
config.setFunctions(new KList<>(new IrisExpressionFunction().setName("prior")
.setStyleValue(new IrisGeneratorStyle())));
return config;
}
private record PriorFunction(AtomicReference<ExpressionRuntime> expression) implements DynamicFunction {
@Override
public int getArgNumber() {
return 2;
}
@Override
public Statefulness statefulness() {
return Statefulness.STATEFUL;
}
@Override
public double eval(double... coordinates) {
return 0D;
}
@Override
public double eval(Context context, double... coordinates) {
RNG rng = ((ExpressionRuntime.FunctionContext) context).rng();
return coordinates[0] <= 0D ? 7D : expression.get().evaluate(rng, coordinates[0] - 1D, coordinates[1]);
}
}
} }
@@ -3,6 +3,7 @@ package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex; import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.IrisEngineStreamType; import art.arcane.iris.generation.runtime.IrisEngineStreamType;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
@@ -15,7 +16,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
@@ -26,9 +26,9 @@ public class IrisExpressionSeedCohesionTest {
@Test @Test
public void expressionStreamsSeparateSeedsAndInitializationOrder() { public void expressionStreamsSeparateSeedsAndInitializationOrder() {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
IrisExpression expression = expression(data); ExpressionRuntime expression = PackRuntime.standalone(data).expression(expression(data));
double first = expression(data).evaluate(new RNG(17L), 23.5D, -94.75D); double first = PackRuntime.standalone(data).expression(expression(data)).evaluate(new RNG(17L), 23.5D, -94.75D);
double second = expression(data).evaluate(new RNG(53L), 23.5D, -94.75D); double second = PackRuntime.standalone(data).expression(expression(data)).evaluate(new RNG(53L), 23.5D, -94.75D);
ProceduralStream<Double> secondStream = expression.stream(new RNG(53L)); ProceduralStream<Double> secondStream = expression.stream(new RNG(53L));
ProceduralStream<Double> firstStream = expression.stream(new RNG(17L)); ProceduralStream<Double> firstStream = expression.stream(new RNG(17L));
assertEquals(second, secondStream.get(23.5D, -94.75D), 0D); assertEquals(second, secondStream.get(23.5D, -94.75D), 0D);
@@ -37,41 +37,39 @@ public class IrisExpressionSeedCohesionTest {
} }
@Test @Test
public void expressionFunctionTracksEngineIdentity() { public void expressionFunctionReadsItsOwnEngine() {
Engine firstEngine = engine(17D);
Engine secondEngine = engine(53D);
AtomicReference<Engine> active = new AtomicReference<>(firstEngine);
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
when(data.getEngine()).thenAnswer(ignored -> active.get()); IrisExpression expression = new IrisExpression()
IrisExpressionFunction function = new IrisExpressionFunction() .setExpression("height(x, z)")
.setName("height") .setFunctions(new KList<>(new IrisExpressionFunction()
.setData(data) .setName("height")
.setEngineStreamValue(IrisEngineStreamType.HEIGHT); .setEngineStreamValue(IrisEngineStreamType.HEIGHT)));
IrisExpressionFunction.FunctionContext context = new IrisExpressionFunction.FunctionContext(new RNG(91L)); ExpressionRuntime first = PackRuntime.forEngine(engine(17D), data).expression(expression);
assertEquals(17D, function.eval(context, 4D, -8D), 0D); ExpressionRuntime second = PackRuntime.forEngine(engine(53D), data).expression(expression);
active.set(secondEngine); RNG rng = new RNG(91L);
assertEquals(53D, function.eval(context, 4D, -8D), 0D);
active.set(firstEngine); assertEquals(17D, first.evaluate(rng, 4D, -8D), 0D);
assertEquals(17D, function.eval(context, 4D, -8D), 0D); assertEquals(53D, second.evaluate(rng, 4D, -8D), 0D);
assertEquals(17D, first.evaluate(rng, 4D, -8D), 0D);
} }
@Test(timeout = 15000) @Test(timeout = 15000)
public void concurrentFunctionInitializationAndEvictionRetainSeedSamples() throws Exception { public void concurrentFunctionInitializationAndEvictionRetainSeedSamples() throws Exception {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
IrisExpressionFunction shared = function(data); IrisExpression config = new IrisExpression().setExpression("field(x, z)").setFunctions(new KList<>(function()));
ExpressionRuntime shared = PackRuntime.standalone(data).expression(config);
ExecutorService workers = Executors.newFixedThreadPool(4); ExecutorService workers = Executors.newFixedThreadPool(4);
try { try {
List<Future<Double>> results = new ArrayList<>(32); List<Future<Double>> results = new ArrayList<>(32);
double[] expected = new double[32]; double[] expected = new double[32];
for (int index = 0; index < 32; index++) { for (int index = 0; index < 32; index++) {
long seed = index; long seed = index;
expected[index] = function(data).eval(new IrisExpressionFunction.FunctionContext(new RNG(seed)), 23.5D, -94.75D); expected[index] = PackRuntime.standalone(data).expression(config).evaluate(new RNG(seed), 23.5D, -94.75D);
results.add(workers.submit(() -> shared.eval( results.add(workers.submit(() -> shared.evaluate(new RNG(seed), 23.5D, -94.75D)));
new IrisExpressionFunction.FunctionContext(new RNG(seed)), 23.5D, -94.75D)));
} }
for (int index = 0; index < results.size(); index++) { for (int index = 0; index < results.size(); index++) {
assertEquals(expected[index], results.get(index).get(5L, TimeUnit.SECONDS), 0D); assertEquals(expected[index], results.get(index).get(5L, TimeUnit.SECONDS), 0D);
assertEquals(expected[index], shared.eval(new IrisExpressionFunction.FunctionContext(new RNG(index)), 23.5D, -94.75D), 0D); assertEquals(expected[index], shared.evaluate(new RNG(index), 23.5D, -94.75D), 0D);
} }
} finally { } finally {
workers.shutdownNow(); workers.shutdownNow();
@@ -81,14 +79,14 @@ public class IrisExpressionSeedCohesionTest {
private static IrisExpression expression(IrisData data) { private static IrisExpression expression(IrisData data) {
IrisExpression expression = new IrisExpression() IrisExpression expression = new IrisExpression()
.setExpression("field(x, z) + value") .setExpression("field(x, z) + value")
.setFunctions(new KList<>(function(data))) .setFunctions(new KList<>(function()))
.setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStyleValue(NoiseStyle.PERLIN.style()))); .setVariables(new KList<>(new IrisExpressionLoad().setName("value").setStyleValue(NoiseStyle.PERLIN.style())));
expression.setLoader(data); expression.setLoader(data);
return expression; return expression;
} }
private static IrisExpressionFunction function(IrisData data) { private static IrisExpressionFunction function() {
return new IrisExpressionFunction().setName("field").setStyleValue(NoiseStyle.SIMPLEX.style()).setData(data); return new IrisExpressionFunction().setName("field").setStyleValue(NoiseStyle.SIMPLEX.style());
} }
private static Engine engine(double height) { private static Engine engine(double height) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import org.junit.Test; import org.junit.Test;
@@ -8,13 +9,15 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
public class IrisGeneratorBatchTest { public class IrisGeneratorBatchTest {
private final PackRuntime runtime = PackRuntime.standalone(null);
private static final double[] XS = {-0D, 0D, -12D, -5.75D, 18D, 18D, 8191.25D, -29999999.5D, 2147483647D}; private static final double[] XS = {-0D, 0D, -12D, -5.75D, 18D, 18D, 8191.25D, -29999999.5D, 2147483647D};
private static final double[] ZS = {0D, -0D, 6D, 2.5D, -6D, -6D, -4096.75D, 29999998D, -2147483648D}; private static final double[] ZS = {0D, -0D, 6D, 2.5D, -6D, -6D, -4096.75D, 29999998D, -2147483648D};
@@ -31,10 +34,10 @@ public class IrisGeneratorBatchTest {
assertTrue(batch.supportsBatch()); assertTrue(batch.supportsBatch());
double[] sampled = new double[XS.length]; double[] sampled = new double[XS.length];
for (long seed : seeds) { for (long seed : seeds) {
batch.compileProgram(seed).heights(new TerrainBatchScratch(), XS, ZS, sampled.length, sampled); batch.compileProgram(runtime, seed).heights(new TerrainBatchScratch(), XS, ZS, sampled.length, sampled);
for (int index = 0; index < sampled.length; index++) { for (int index = 0; index < sampled.length; index++) {
assertEquals(style + " detail=" + detail + " seed=" + seed + " index=" + index, assertEquals(style + " detail=" + detail + " seed=" + seed + " index=" + index,
Double.doubleToRawLongBits(scalar.getHeight(XS[index], ZS[index], seed)), Double.doubleToRawLongBits(scalar.getHeight(runtime, XS[index], ZS[index], seed)),
Double.doubleToRawLongBits(sampled[index])); Double.doubleToRawLongBits(sampled[index]));
} }
} }
@@ -51,9 +54,9 @@ public class IrisGeneratorBatchTest {
IrisGenerator batch = generator(style, detail, false).setCliffHeightMax(0D).setCellFractureHeight(0D); IrisGenerator batch = generator(style, detail, false).setCliffHeightMax(0D).setCellFractureHeight(0D);
double[] values = new double[XS.length]; double[] values = new double[XS.length];
for (long seed : new long[]{-1337L, Long.MAX_VALUE - 37L}) { for (long seed : new long[]{-1337L, Long.MAX_VALUE - 37L}) {
batch.compileProgram(seed).heights(new TerrainBatchScratch(), XS, ZS, XS.length, values); batch.compileProgram(runtime, seed).heights(new TerrainBatchScratch(), XS, ZS, XS.length, values);
for (int index = 0; index < XS.length; index++) { for (int index = 0; index < XS.length; index++) {
assertEquals(Double.doubleToRawLongBits(scalar.getHeight(XS[index], ZS[index], seed)), assertEquals(Double.doubleToRawLongBits(scalar.getHeight(runtime, XS[index], ZS[index], seed)),
Double.doubleToRawLongBits(values[index])); Double.doubleToRawLongBits(values[index]));
} }
} }
@@ -66,27 +69,27 @@ public class IrisGeneratorBatchTest {
IrisNoiseGenerator layer = spy(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style())); IrisNoiseGenerator layer = spy(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()));
IrisGenerator generator = new IrisGenerator().setComposite(new KList<>(layer)); IrisGenerator generator = new IrisGenerator().setComposite(new KList<>(layer));
double[] sampled = new double[XS.length]; double[] sampled = new double[XS.length];
GeneratorProgram program = generator.compileProgram(99L); GeneratorProgram program = generator.compileProgram(runtime, 99L);
verify(layer, times(1)).getGenerator(anyLong(), isNull(), isNull()); verify(layer, times(1)).getGenerator(anyLong(), same(runtime));
clearInvocations(layer); clearInvocations(layer);
program.heights(new TerrainBatchScratch(), XS, ZS, XS.length, sampled); program.heights(new TerrainBatchScratch(), XS, ZS, XS.length, sampled);
verify(layer, times(0)).getGenerator(anyLong(), isNull(), isNull()); verify(layer, times(0)).getGenerator(anyLong(), same(runtime));
for (int index = 0; index < XS.length; index++) { for (int index = 0; index < XS.length; index++) {
generator.getHeight(XS[index], ZS[index], 99L); generator.getHeight(runtime, XS[index], ZS[index], 99L);
} }
verify(layer, times(XS.length)).getGenerator(anyLong(), isNull(), isNull()); verify(layer, times(XS.length)).getGenerator(anyLong(), same(runtime));
} }
@Test @Test
public void customGeneratorsCannotCompile() { public void customGeneratorsCannotCompile() {
IrisGenerator generator = new IrisGenerator() { IrisGenerator generator = new IrisGenerator() {
@Override @Override
public double getHeight(double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
return x; return x;
} }
}; };
assertFalse(generator.supportsBatch()); assertFalse(generator.supportsBatch());
assertThrows(IllegalStateException.class, () -> generator.compileProgram(0L)); assertThrows(IllegalStateException.class, () -> generator.compileProgram(runtime, 0L));
} }
@Test @Test
@@ -1,14 +1,13 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
@@ -32,39 +31,34 @@ public class IrisGeneratorStyleCacheIsolationTest {
} }
@Test @Test
public void cacheSeparatesSeedsAndEngineIdentity() throws Exception { public void runtimeSeparatesSeedsAndOwners() throws Exception {
Engine firstEngine = mock(Engine.class);
Engine secondEngine = mock(Engine.class);
AtomicReference<Engine> activeEngine = new AtomicReference<>(firstEngine);
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
when(data.getEngine()).thenAnswer(ignored -> activeEngine.get());
when(data.getDataFolder()).thenReturn(temporaryFolder.newFolder("pack")); when(data.getDataFolder()).thenReturn(temporaryFolder.newFolder("pack"));
PackRuntime owner = PackRuntime.standalone(data);
PackRuntime otherOwner = PackRuntime.standalone(data);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
CNG first = style.create(new RNG(41L), data); CNG first = style.create(new RNG(41L), owner);
CNG firstAgain = style.create(new RNG(41L), data); CNG firstAgain = style.create(new RNG(41L), owner);
CNG differentSeed = style.create(new RNG(42L), data); CNG differentSeed = style.create(new RNG(42L), owner);
activeEngine.set(secondEngine); CNG differentOwner = style.create(new RNG(41L), otherOwner);
CNG differentEngine = style.create(new RNG(41L), data);
assertSame(first, firstAgain); assertSame(first, firstAgain);
assertNotSame(first, differentSeed); assertNotSame(first, differentSeed);
assertNotSame(first, differentEngine); assertNotSame(first, differentOwner);
assertNotEquals(first.noise(12D, -7D), differentSeed.noise(12D, -7D), 0D); assertNotEquals(first.noise(12D, -7D), differentSeed.noise(12D, -7D), 0D);
} }
@Test @Test
public void cacheEvictsOldEngineSeedEntries() { public void runtimeEvictsOldSeedEntries() {
IrisData data = mock(IrisData.class); PackRuntime owner = PackRuntime.standalone(mock(IrisData.class));
Engine engine = mock(Engine.class);
when(data.getEngine()).thenReturn(engine);
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
CNG first = style.create(new RNG(0L), data); CNG first = style.create(new RNG(0L), owner);
for (long seed = 1L; seed <= 8L; seed++) { for (long seed = 1L; seed <= 8L; seed++) {
style.create(new RNG(seed), data); style.create(new RNG(seed), owner);
} }
assertNotSame(first, style.create(new RNG(0L), data)); assertNotSame(first, style.create(new RNG(0L), owner));
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.image.IrisImage; import art.arcane.iris.generation.image.IrisImage;
import art.arcane.iris.generation.image.IrisImageMap; import art.arcane.iris.generation.image.IrisImageMap;
import art.arcane.iris.generation.image.IrisImageMapOutOfBounds; import art.arcane.iris.generation.image.IrisImageMapOutOfBounds;
@@ -41,13 +42,14 @@ public class IrisGeneratorStyleOverrideTest {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.FLAT).setExpression("height"); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.FLAT).setExpression("height");
IrisStyledRange range = new IrisStyledRange().setMin(2D).setMax(14D).setStyle(style); IrisStyledRange range = new IrisStyledRange().setMin(2D).setMax(14D).setStyle(style);
RNG rng = new RNG(78264193L); RNG rng = new RNG(78264193L);
double first = style.create(rng, data).fitDouble(2D, 14D, 0D, 0D); PackRuntime runtime = PackRuntime.standalone(data);
double second = style.create(rng, data).fitDouble(2D, 14D, 1D, 0D); double first = style.create(rng, runtime).fitDouble(2D, 14D, 0D, 0D);
double second = style.create(rng, runtime).fitDouble(2D, 14D, 1D, 0D);
assertNotEquals(8D, first, 0D); assertNotEquals(8D, first, 0D);
assertNotEquals(first, second, 0D); assertNotEquals(first, second, 0D);
assertEquals(first, range.get(rng, 0D, 0D, data), 0D); assertEquals(first, range.get(rng, 0D, 0D, runtime), 0D);
assertEquals(second, range.get(rng, 1D, 0D, data), 0D); assertEquals(second, range.get(rng, 1D, 0D, runtime), 0D);
} }
@Test @Test
@@ -66,7 +68,8 @@ public class IrisGeneratorStyleOverrideTest {
IrisStyledRange range = new IrisStyledRange().setMin(2D).setMax(14D).setStyle(style); IrisStyledRange range = new IrisStyledRange().setMin(2D).setMax(14D).setStyle(style);
RNG rng = new RNG(78264193L); RNG rng = new RNG(78264193L);
assertEquals(2D, range.get(rng, 0D, 0D, data), 0D); PackRuntime runtime = PackRuntime.standalone(data);
assertEquals(14D, range.get(rng, 1D, 0D, data), 0D); assertEquals(2D, range.get(rng, 0D, 0D, runtime), 0D);
assertEquals(14D, range.get(rng, 1D, 0D, runtime), 0D);
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
@@ -20,6 +21,8 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class IrisGeneratorSurfaceDetailTest { public class IrisGeneratorSurfaceDetailTest {
private final PackRuntime runtime = PackRuntime.standalone(null);
@Test @Test
public void defaultUsesTheOriginalSampleOnce() { public void defaultUsesTheOriginalSampleOnce() {
AtomicInteger samples = new AtomicInteger(); AtomicInteger samples = new AtomicInteger();
@@ -28,7 +31,7 @@ public class IrisGeneratorSurfaceDetailTest {
return x * 0.01D + z * 0.02D; return x * 0.01D + z * 0.02D;
}); });
assertEquals(0.07D, generator.getHeight(1, 3, 27L), 1e-12D); assertEquals(0.07D, generator.getHeight(runtime, 1, 3, 27L), 1e-12D);
assertEquals(1, samples.get()); assertEquals(1, samples.get());
} }
@@ -41,7 +44,7 @@ public class IrisGeneratorSurfaceDetailTest {
for (int z = -12; z <= 12; z++) { for (int z = -12; z <= 12; z++) {
for (int x = -12; x <= 12; x++) { for (int x = -12; x <= 12; x++) {
double expected = x % 6 == 0 && z % 6 == 0 ? 0.2D : 0.5D; double expected = x % 6 == 0 && z % 6 == 0 ? 0.2D : 0.5D;
assertEquals(expected, generator.getHeight(x, z, 27L), 1e-12D); assertEquals(expected, generator.getHeight(runtime, x, z, 27L), 1e-12D);
} }
} }
} }
@@ -54,7 +57,7 @@ public class IrisGeneratorSurfaceDetailTest {
for (double z = -4.25D; z < 4D; z += 0.5D) { for (double z = -4.25D; z < 4D; z += 0.5D) {
for (double x = -4.75D; x < 4D; x += 0.5D) { for (double x = -4.75D; x < 4D; x += 0.5D) {
assertEquals(0.5D + x * 0.01D + z * 0.02D, assertEquals(0.5D + x * 0.01D + z * 0.02D,
generator.getHeight(x, z, 27L), 1e-12D); generator.getHeight(runtime, x, z, 27L), 1e-12D);
} }
} }
} }
@@ -70,7 +73,7 @@ public class IrisGeneratorSurfaceDetailTest {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
assertEquals(0.5D, generator.getHeight(x, z, 27L), 0D); assertEquals(0.5D, generator.getHeight(runtime, x, z, 27L), 0D);
} }
} }
@@ -89,7 +92,7 @@ public class IrisGeneratorSurfaceDetailTest {
for (int z = -16; z < 16; z += 4) { for (int z = -16; z < 16; z += 4) {
for (int x = -16; x < 16; x += 4) { for (int x = -16; x < 16; x += 4) {
generator.getHeight(x, z, 27L); generator.getHeight(runtime, x, z, 27L);
} }
} }
@@ -108,10 +111,9 @@ public class IrisGeneratorSurfaceDetailTest {
}; };
for (double[] point : points) { for (double[] point : points) {
cold.rescale(1D); long expected = Double.doubleToRawLongBits(cold.getHeight(PackRuntime.standalone(null), point[0], point[1], 27L));
long expected = Double.doubleToRawLongBits(cold.getHeight(point[0], point[1], 27L));
for (int repeat = 0; repeat < 4; repeat++) { for (int repeat = 0; repeat < 4; repeat++) {
assertEquals(expected, Double.doubleToRawLongBits(warm.getHeight(point[0], point[1], 27L))); assertEquals(expected, Double.doubleToRawLongBits(warm.getHeight(runtime, point[0], point[1], 27L)));
} }
} }
} }
@@ -124,16 +126,16 @@ public class IrisGeneratorSurfaceDetailTest {
return seed * 0.000001D; return seed * 0.000001D;
}).setSurfaceDetail(0.5D); }).setSurfaceDetail(0.5D);
double first = generator.getHeight(0, 0, 27L); double first = generator.getHeight(runtime, 0, 0, 27L);
assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L)));
assertEquals(1, samples.get()); assertEquals(1, samples.get());
double second = generator.getHeight(0, 0, 28L); double second = generator.getHeight(runtime, 0, 0, 28L);
assertEquals(0.000001D, second - first, 1e-12D); assertEquals(0.000001D, second - first, 1e-12D);
assertEquals(Double.doubleToRawLongBits(second), Double.doubleToRawLongBits(generator.getHeight(0, 0, 28L))); assertEquals(Double.doubleToRawLongBits(second), Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 28L)));
assertEquals(2, samples.get()); assertEquals(2, samples.get());
assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); assertEquals(Double.doubleToRawLongBits(first), Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L)));
assertEquals(3, samples.get()); assertEquals(3, samples.get());
} }
@@ -147,14 +149,14 @@ public class IrisGeneratorSurfaceDetailTest {
return x * 0.00001D; return x * 0.00001D;
}).setSurfaceDetail(0.5D); }).setSurfaceDetail(0.5D);
assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L)));
assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L)));
assertEquals(1, originSamples.get()); assertEquals(1, originSamples.get());
assertEquals(Double.doubleToRawLongBits(71754D * 0.00001D), assertEquals(Double.doubleToRawLongBits(71754D * 0.00001D),
Double.doubleToRawLongBits(generator.getHeight(71754, 0, 27L))); Double.doubleToRawLongBits(generator.getHeight(runtime, 71754, 0, 27L)));
assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L)));
assertEquals(2, originSamples.get()); assertEquals(2, originSamples.get());
assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(0, 0, 27L))); assertEquals(0L, Double.doubleToRawLongBits(generator.getHeight(runtime, 0, 0, 27L)));
assertEquals(2, originSamples.get()); assertEquals(2, originSamples.get());
} }
@@ -168,7 +170,7 @@ public class IrisGeneratorSurfaceDetailTest {
long[][] expected = new long[xs.length][seeds.length]; long[][] expected = new long[xs.length][seeds.length];
for (int coordinate = 0; coordinate < xs.length; coordinate++) { for (int coordinate = 0; coordinate < xs.length; coordinate++) {
for (int seed = 0; seed < seeds.length; seed++) { for (int seed = 0; seed < seeds.length; seed++) {
expected[coordinate][seed] = Double.doubleToRawLongBits(reference.getHeight(xs[coordinate], 0D, seeds[seed])); expected[coordinate][seed] = Double.doubleToRawLongBits(reference.getHeight(runtime, xs[coordinate], 0D, seeds[seed]));
} }
} }
ForkJoinPool pool = new ForkJoinPool(4); ForkJoinPool pool = new ForkJoinPool(4);
@@ -181,7 +183,7 @@ public class IrisGeneratorSurfaceDetailTest {
int coordinate = (sample + offset) & 1; int coordinate = (sample + offset) & 1;
int seed = (sample / 2 + offset) & 1; int seed = (sample / 2 + offset) & 1;
assertEquals(expected[coordinate][seed], assertEquals(expected[coordinate][seed],
Double.doubleToRawLongBits(generator.getHeight(xs[coordinate], 0D, seeds[seed]))); Double.doubleToRawLongBits(generator.getHeight(runtime, xs[coordinate], 0D, seeds[seed])));
} }
})); }));
} }
@@ -198,67 +200,32 @@ public class IrisGeneratorSurfaceDetailTest {
public void cachedLatticeHeightsRemainIsolatedBySeed() { public void cachedLatticeHeightsRemainIsolatedBySeed() {
IrisGenerator generator = generator((seed, x, z) -> seed * 0.000001D); IrisGenerator generator = generator((seed, x, z) -> seed * 0.000001D);
generator.setSurfaceDetail(0.5D); generator.setSurfaceDetail(0.5D);
double first = generator.getHeight(1, 1, 27L); double first = generator.getHeight(runtime, 1, 1, 27L);
double second = generator.getHeight(1, 1, 28L); double second = generator.getHeight(runtime, 1, 1, 28L);
assertEquals(0.000001D, second - first, 1e-12D); assertEquals(0.000001D, second - first, 1e-12D);
assertEquals(first, generator.getHeight(1, 1, 27L), 0D); assertEquals(first, generator.getHeight(runtime, 1, 1, 27L), 0D);
} }
@Test @Test
public void cachedLatticeHeightsRemainIsolatedByEngine() { public void cachedLatticeHeightsBelongToTheirRuntime() {
Engine firstEngine = mock(Engine.class);
Engine secondEngine = mock(Engine.class);
AtomicReference<Engine> activeEngine = new AtomicReference<>(firstEngine);
IrisData data = mock(IrisData.class);
when(data.getEngine()).thenAnswer(ignored -> activeEngine.get());
IrisGenerator generator = new IrisGenerator().setSurfaceDetail(0.5D).setComposite(new KList<>(
new ContextNoise(loader -> loader.getEngine() == firstEngine ? 0.2D : 0.8D)));
generator.setLoader(data);
assertEquals(0.2D, generator.getHeight(0, 0, 27L), 1e-12D);
assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D);
activeEngine.set(secondEngine);
assertEquals(0.8D, generator.getHeight(0, 0, 27L), 1e-12D);
assertEquals(0.8D, generator.getHeight(1, 1, 27L), 1e-12D);
activeEngine.set(firstEngine);
assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D);
}
@Test
public void cachedLatticeHeightsRemainIsolatedByLoader() {
Engine engine = mock(Engine.class);
IrisData firstData = mock(IrisData.class); IrisData firstData = mock(IrisData.class);
IrisData secondData = mock(IrisData.class); IrisData secondData = mock(IrisData.class);
when(firstData.getEngine()).thenReturn(engine); PackRuntime first = PackRuntime.standalone(firstData);
when(secondData.getEngine()).thenReturn(engine); PackRuntime second = PackRuntime.standalone(secondData);
IrisGenerator generator = new IrisGenerator().setSurfaceDetail(0.5D).setComposite(new KList<>( IrisGenerator generator = new IrisGenerator().setSurfaceDetail(0.5D).setComposite(new KList<>(
new ContextNoise(loader -> loader == firstData ? 0.2D : 0.8D))); new ContextNoise(scope -> scope.data() == firstData ? 0.2D : 0.8D)));
generator.setLoader(firstData);
assertEquals(0.2D, generator.getHeight(0, 0, 27L), 1e-12D); assertEquals(0.2D, generator.getHeight(first, 0, 0, 27L), 1e-12D);
assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D); assertEquals(0.2D, generator.getHeight(first, 1, 1, 27L), 1e-12D);
generator.setLoader(secondData); assertEquals(0.8D, generator.getHeight(second, 0, 0, 27L), 1e-12D);
assertEquals(0.8D, generator.getHeight(0, 0, 27L), 1e-12D); assertEquals(0.8D, generator.getHeight(second, 1, 1, 27L), 1e-12D);
assertEquals(0.8D, generator.getHeight(1, 1, 27L), 1e-12D); assertEquals(0.2D, generator.getHeight(first, 1, 1, 27L), 1e-12D);
generator.setLoader(firstData);
assertEquals(0.2D, generator.getHeight(1, 1, 27L), 1e-12D);
}
@Test
public void rescalingClearsCachedLatticeHeights() {
IrisGenerator generator = generator((seed, x, z) -> x * 0.01D + z * 0.02D);
generator.setSurfaceDetail(0.5D);
assertEquals(0.06D, generator.getHeight(2, 2, 27L), 1e-12D);
generator.rescale(2D);
assertEquals(0.12D, generator.getHeight(2, 2, 27L), 1e-12D);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void rejectsNonfiniteDetail() { public void rejectsNonfiniteDetail() {
generator((seed, x, z) -> 0D).setSurfaceDetail(Double.NaN).getHeight(1, 1, 27L); generator((seed, x, z) -> 0D).setSurfaceDetail(Double.NaN).getHeight(runtime, 1, 1, 27L);
} }
private static IrisGenerator generator(Sampler sampler) { private static IrisGenerator generator(Sampler sampler) {
@@ -277,21 +244,21 @@ public class IrisGeneratorSurfaceDetailTest {
} }
@Override @Override
public double getNoise(long superSeed, double x, double z, IrisData data, Engine engine) { public double getNoise(long superSeed, double x, double z, PackRuntime runtime) {
return sampler.sample(superSeed, x, z); return sampler.sample(superSeed, x, z);
} }
} }
private static final class ContextNoise extends IrisNoiseGenerator { private static final class ContextNoise extends IrisNoiseGenerator {
private final ToDoubleFunction<IrisData> sampler; private final ToDoubleFunction<PackRuntime> sampler;
private ContextNoise(ToDoubleFunction<IrisData> sampler) { private ContextNoise(ToDoubleFunction<PackRuntime> sampler) {
this.sampler = sampler; this.sampler = sampler;
} }
@Override @Override
public double getNoise(long superSeed, double x, double z, IrisData data, Engine engine) { public double getNoise(long superSeed, double x, double z, PackRuntime runtime) {
return sampler.applyAsDouble(data); return sampler.applyAsDouble(runtime);
} }
} }
} }
@@ -1,9 +1,9 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import org.junit.Test; import org.junit.Test;
@@ -24,7 +24,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.never;
public final class IrisNoiseGeneratorCacheTest { public final class IrisNoiseGeneratorCacheTest {
private static final long GENERATOR_SALT = 33_955_677L; private static final long GENERATOR_SALT = 33_955_677L;
@@ -35,17 +34,17 @@ public final class IrisNoiseGeneratorCacheTest {
public void callerSeedsDoNotShareAFirstWinnerGenerator() { public void callerSeedsDoNotShareAFirstWinnerGenerator() {
GeneratorFixture fixture = new GeneratorFixture(); GeneratorFixture fixture = new GeneratorFixture();
assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.data, fixture.engine)); assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.runtime));
assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.data, fixture.engine)); assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.runtime));
assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.data, fixture.engine)); assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.runtime));
} }
@Test @Test
public void reverseInitializationOrderKeepsSeedAssignments() { public void reverseInitializationOrderKeepsSeedAssignments() {
GeneratorFixture fixture = new GeneratorFixture(); GeneratorFixture fixture = new GeneratorFixture();
assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.data, fixture.engine)); assertSame(fixture.secondGenerator, fixture.generator.getGenerator(29L, fixture.runtime));
assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.data, fixture.engine)); assertSame(fixture.firstGenerator, fixture.generator.getGenerator(11L, fixture.runtime));
} }
@Test @Test
@@ -56,11 +55,11 @@ public final class IrisNoiseGeneratorCacheTest {
try { try {
Future<CNG> first = executor.submit(() -> { Future<CNG> first = executor.submit(() -> {
assertTrue(start.await(5L, TimeUnit.SECONDS)); assertTrue(start.await(5L, TimeUnit.SECONDS));
return fixture.generator.getGenerator(11L, fixture.data, fixture.engine); return fixture.generator.getGenerator(11L, fixture.runtime);
}); });
Future<CNG> second = executor.submit(() -> { Future<CNG> second = executor.submit(() -> {
assertTrue(start.await(5L, TimeUnit.SECONDS)); assertTrue(start.await(5L, TimeUnit.SECONDS));
return fixture.generator.getGenerator(29L, fixture.data, fixture.engine); return fixture.generator.getGenerator(29L, fixture.runtime);
}); });
start.countDown(); start.countDown();
@@ -72,55 +71,34 @@ public final class IrisNoiseGeneratorCacheTest {
} }
@Test @Test
public void heightResolvesEngineOnceAcrossFracturesAndSurfaceCorners() { public void eachRuntimeBuildsItsOwnGeneratorAndKeepsIt() {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
Engine engine = mock(Engine.class); PackRuntime firstRuntime = PackRuntime.forEngine(mock(Engine.class), data);
when(data.getEngine()).thenReturn(engine); PackRuntime secondRuntime = PackRuntime.forEngine(mock(Engine.class), data);
IrisNoiseGenerator child = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style());
IrisNoiseGenerator layer = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style())
.setFracture(new KList<>(child));
IrisGenerator generator = new IrisGenerator().setComposite(new KList<>(layer, child))
.setSurfaceDetail(0.5D);
generator.setLoader(data);
double first = generator.getHeight(13D, -21D, 71L);
verify(data, times(1)).getEngine();
assertEquals(Double.doubleToRawLongBits(first),
Double.doubleToRawLongBits(generator.getHeight(13D, -21D, 71L)));
verify(data, times(2)).getEngine();
}
@Test
public void changedEngineUsesDistinctConstructionAndRestoresPreviousGenerator() {
IrisData data = mock(IrisData.class);
Engine firstEngine = mock(Engine.class);
Engine secondEngine = mock(Engine.class);
IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); IrisGeneratorStyle style = mock(IrisGeneratorStyle.class);
CNG first = mock(CNG.class); CNG first = mock(CNG.class);
CNG second = mock(CNG.class); CNG second = mock(CNG.class);
IrisNoiseGenerator layer = new IrisNoiseGenerator().setStyle(style); IrisNoiseGenerator layer = new IrisNoiseGenerator().setStyle(style);
when(data.getEngine()).thenReturn(firstEngine, secondEngine, firstEngine); when(style.createForLayer(any(RNG.class), same(firstRuntime), eq(1))).thenReturn(first);
when(style.createForLayer(any(RNG.class), same(data), eq(1), same(firstEngine))).thenReturn(first); when(style.createForLayer(any(RNG.class), same(secondRuntime), eq(1))).thenReturn(second);
when(style.createForLayer(any(RNG.class), same(data), eq(1), same(secondEngine))).thenReturn(second);
assertSame(first, layer.getGenerator(11L, data, data.getEngine())); assertSame(first, layer.getGenerator(11L, firstRuntime));
assertSame(second, layer.getGenerator(11L, data, data.getEngine())); assertSame(second, layer.getGenerator(11L, secondRuntime));
assertSame(first, layer.getGenerator(11L, data, data.getEngine())); assertSame(first, layer.getGenerator(11L, firstRuntime));
verify(style, times(1)).createForLayer(any(RNG.class), same(data), eq(1), same(firstEngine)); verify(style, times(1)).createForLayer(any(RNG.class), same(firstRuntime), eq(1));
verify(style, times(1)).createForLayer(any(RNG.class), same(data), eq(1), same(secondEngine)); verify(style, times(1)).createForLayer(any(RNG.class), same(secondRuntime), eq(1));
} }
@Test @Test
public void disabledNoiseDoesNotResolveEngine() { public void disabledNoiseReturnsItsOffset() {
IrisData data = mock(IrisData.class);
IrisNoiseGenerator layer = new IrisNoiseGenerator(false).setOffsetY(0.37D); IrisNoiseGenerator layer = new IrisNoiseGenerator(false).setOffsetY(0.37D);
assertEquals(0.37D, layer.getNoise(11L, 13D, -21D, data), 0D); assertEquals(0.37D, layer.getNoise(11L, 13D, -21D, PackRuntime.standalone(null)), 0D);
verify(data, never()).getEngine();
} }
private static final class GeneratorFixture { private static final class GeneratorFixture {
private final IrisData data = mock(IrisData.class); private final IrisData data = mock(IrisData.class);
private final Engine engine = mock(Engine.class); private final Engine engine = mock(Engine.class);
private final PackRuntime runtime = PackRuntime.forEngine(engine, data);
private final IrisGeneratorStyle style = mock(IrisGeneratorStyle.class); private final IrisGeneratorStyle style = mock(IrisGeneratorStyle.class);
private final CNG firstGenerator = mock(CNG.class); private final CNG firstGenerator = mock(CNG.class);
private final CNG secondGenerator = mock(CNG.class); private final CNG secondGenerator = mock(CNG.class);
@@ -130,12 +108,11 @@ public final class IrisNoiseGeneratorCacheTest {
.setOctaves(OCTAVES); .setOctaves(OCTAVES);
private GeneratorFixture() { private GeneratorFixture() {
when(data.getEngine()).thenReturn(engine);
Map<Long, CNG> generators = Map.of( Map<Long, CNG> generators = Map.of(
11L + GENERATOR_SALT - CONFIGURED_SEED, firstGenerator, 11L + GENERATOR_SALT - CONFIGURED_SEED, firstGenerator,
29L + GENERATOR_SALT - CONFIGURED_SEED, secondGenerator 29L + GENERATOR_SALT - CONFIGURED_SEED, secondGenerator
); );
when(style.createForLayer(any(RNG.class), same(data), eq(OCTAVES), same(engine))).thenAnswer(invocation -> { when(style.createForLayer(any(RNG.class), same(runtime), eq(OCTAVES))).thenAnswer(invocation -> {
RNG rng = invocation.getArgument(0); RNG rng = invocation.getArgument(0);
return generators.get(rng.getSeed()); return generators.get(rng.getSeed());
}); });
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.noise.NoiseGenerator; import art.arcane.volmlib.util.noise.NoiseGenerator;
import org.junit.Test; import org.junit.Test;
@@ -7,6 +8,8 @@ import org.junit.Test;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public final class IrisNoiseGeneratorFractureMirrorTest { public final class IrisNoiseGeneratorFractureMirrorTest {
private static final PackRuntime RUNTIME = PackRuntime.standalone(null);
private static final long SEED = 71L; private static final long SEED = 71L;
private static final int GRID_SIZE = 40; private static final int GRID_SIZE = 40;
private static final double GRID_STEP = 7.3D; private static final double GRID_STEP = 7.3D;
@@ -31,7 +34,7 @@ public final class IrisNoiseGeneratorFractureMirrorTest {
for (int j = i + 1; j < GRID_SIZE; j++) { for (int j = i + 1; j < GRID_SIZE; j++) {
double a = i * GRID_STEP; double a = i * GRID_STEP;
double b = j * GRID_STEP + 0.5D; double b = j * GRID_STEP + 0.5D;
if (Math.abs(noise.getNoise(SEED, a, b, null) - noise.getNoise(SEED, b, a, null)) < MIRRORED) { if (Math.abs(noise.getNoise(SEED, a, b, RUNTIME) - noise.getNoise(SEED, b, a, RUNTIME)) < MIRRORED) {
mirroredSamples++; mirroredSamples++;
} }
} }
@@ -41,7 +44,7 @@ public final class IrisNoiseGeneratorFractureMirrorTest {
private static IrisNoiseGenerator diagonalSymmetricRoot() { private static IrisNoiseGenerator diagonalSymmetricRoot() {
IrisNoiseGenerator root = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(5L); IrisNoiseGenerator root = new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()).setSeed(5L);
root.getGenerator(SEED, null, null).setGenerator(new DiagonalSymmetricGenerator()); root.getGenerator(SEED, RUNTIME).setGenerator(new DiagonalSymmetricGenerator());
return root; return root;
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KList;
@@ -29,6 +30,8 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
public final class IrisNoiseGeneratorFractureTest { public final class IrisNoiseGeneratorFractureTest {
private static final PackRuntime RUNTIME = PackRuntime.standalone(null);
@Test @Test
public void deepChainsMatchRecursiveSamplingBits() { public void deepChainsMatchRecursiveSamplingBits() {
Random coordinates = new Random(718311L); Random coordinates = new Random(718311L);
@@ -37,13 +40,13 @@ public final class IrisNoiseGeneratorFractureTest {
for (int depth : new int[]{0, 1, 3, 4, 5, 8}) { for (int depth : new int[]{0, 1, 3, 4, 5, 8}) {
IrisNoiseGenerator root = chain(depth, style).getFirst(); IrisNoiseGenerator root = chain(depth, style).getFirst();
for (long seed : new long[]{0L, -4193L, Long.MIN_VALUE, Long.MAX_VALUE}) { for (long seed : new long[]{0L, -4193L, Long.MIN_VALUE, Long.MAX_VALUE}) {
assertParity(root, seed, 0D, -0D, null, null); assertParity(root, seed, 0D, -0D, RUNTIME);
assertParity(root, seed, -0D, 0D, null, null); assertParity(root, seed, -0D, 0D, RUNTIME);
assertParity(root, seed, -30_000_000D, 29_999_999.75D, null, null); assertParity(root, seed, -30_000_000D, 29_999_999.75D, RUNTIME);
assertParity(root, seed, Math.nextDown(-64D), Math.nextUp(64D), null, null); assertParity(root, seed, Math.nextDown(-64D), Math.nextUp(64D), RUNTIME);
for (int index = 0; index < 8; index++) { for (int index = 0; index < 8; index++) {
assertParity(root, seed, coordinates.nextDouble() * 4096D - 2048D, assertParity(root, seed, coordinates.nextDouble() * 4096D - 2048D,
coordinates.nextDouble() * 4096D - 2048D, null, null); coordinates.nextDouble() * 4096D - 2048D, RUNTIME);
} }
} }
} }
@@ -54,13 +57,13 @@ public final class IrisNoiseGeneratorFractureTest {
public void fourFracturesReducePrimitiveSamplesFromThirtyOneToNine() { public void fourFracturesReducePrimitiveSamplesFromThirtyOneToNine() {
List<IrisNoiseGenerator> chain = chain(4, NoiseStyle.SIMPLEX); List<IrisNoiseGenerator> chain = chain(4, NoiseStyle.SIMPLEX);
List<NoiseGenerator> bases = spyBases(chain, 71L); List<NoiseGenerator> bases = spyBases(chain, 71L);
reference(chain.getFirst(), 71L, 13.25D, -21.75D, null, null); reference(chain.getFirst(), 71L, 13.25D, -21.75D, RUNTIME);
for (int index = 0; index < bases.size(); index++) { for (int index = 0; index < bases.size(); index++) {
verify(bases.get(index), times(1 << index)).noise(anyDouble(), anyDouble()); verify(bases.get(index), times(1 << index)).noise(anyDouble(), anyDouble());
clearInvocations(bases.get(index)); clearInvocations(bases.get(index));
} }
chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME);
for (int index = 0; index < bases.size(); index++) { for (int index = 0; index < bases.size(); index++) {
verify(bases.get(index), times(index == 0 ? 1 : 2)).noise(anyDouble(), anyDouble()); verify(bases.get(index), times(index == 0 ? 1 : 2)).noise(anyDouble(), anyDouble());
} }
@@ -70,7 +73,7 @@ public final class IrisNoiseGeneratorFractureTest {
public void shallowChainsKeepTheirSamplingCounts() { public void shallowChainsKeepTheirSamplingCounts() {
List<IrisNoiseGenerator> chain = chain(3, NoiseStyle.SIMPLEX); List<IrisNoiseGenerator> chain = chain(3, NoiseStyle.SIMPLEX);
List<NoiseGenerator> bases = spyBases(chain, 71L); List<NoiseGenerator> bases = spyBases(chain, 71L);
chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME);
for (int index = 0; index < bases.size(); index++) { for (int index = 0; index < bases.size(); index++) {
verify(bases.get(index), times(1 << index)).noise(anyDouble(), anyDouble()); verify(bases.get(index), times(1 << index)).noise(anyDouble(), anyDouble());
} }
@@ -80,18 +83,18 @@ public final class IrisNoiseGeneratorFractureTest {
public void changedParametersAndFracturesRemainVisible() { public void changedParametersAndFracturesRemainVisible() {
List<IrisNoiseGenerator> chain = chain(5, NoiseStyle.IRIS); List<IrisNoiseGenerator> chain = chain(5, NoiseStyle.IRIS);
IrisNoiseGenerator root = chain.getFirst(); IrisNoiseGenerator root = chain.getFirst();
assertParity(root, 19L, 31D, -79D, null, null); assertParity(root, 19L, 31D, -79D, RUNTIME);
chain.get(3).setOffsetX(-319D).setOffsetZ(17D).setOffsetY(-0.7D) chain.get(3).setOffsetX(-319D).setOffsetZ(17D).setOffsetY(-0.7D)
.setSeed(Long.MAX_VALUE).setOpacity(0.35D).setZoom(17D); .setSeed(Long.MAX_VALUE).setOpacity(0.35D).setZoom(17D);
assertParity(root, 19L, 31D, -79D, null, null); assertParity(root, 19L, 31D, -79D, RUNTIME);
chain.get(4).setEnabled(false); chain.get(4).setEnabled(false);
assertParity(root, 19L, 31D, -79D, null, null); assertParity(root, 19L, 31D, -79D, RUNTIME);
chain.get(4).setEnabled(true); chain.get(4).setEnabled(true);
chain.get(2).getFracture().add(new IrisNoiseGenerator().setStyle(NoiseStyle.PERLIN.style())); chain.get(2).getFracture().add(new IrisNoiseGenerator().setStyle(NoiseStyle.PERLIN.style()));
assertParity(root, 19L, 31D, -79D, null, null); assertParity(root, 19L, 31D, -79D, RUNTIME);
chain.get(2).getFracture().removeLast(); chain.get(2).getFracture().removeLast();
chain.getLast().getFracture().add(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style())); chain.getLast().getFracture().add(new IrisNoiseGenerator().setStyle(NoiseStyle.SIMPLEX.style()));
assertParity(root, 19L, 31D, -79D, null, null); assertParity(root, 19L, 31D, -79D, RUNTIME);
} }
@Test @Test
@@ -99,11 +102,11 @@ public final class IrisNoiseGeneratorFractureTest {
List<IrisNoiseGenerator> chain = chain(4, NoiseStyle.SIMPLEX); List<IrisNoiseGenerator> chain = chain(4, NoiseStyle.SIMPLEX);
long leafSeed = childSeed(chain, 23L, chain.size() - 1); long leafSeed = childSeed(chain, 23L, chain.size() - 1);
StatefulNoise stateful = new StatefulNoise(); StatefulNoise stateful = new StatefulNoise();
chain.getLast().getGenerator(leafSeed, null, null).setGenerator(stateful); chain.getLast().getGenerator(leafSeed, RUNTIME).setGenerator(stateful);
double expected = reference(chain.getFirst(), 23L, 17D, -31D, null, null); double expected = reference(chain.getFirst(), 23L, 17D, -31D, RUNTIME);
assertEquals(16, stateful.samples); assertEquals(16, stateful.samples);
stateful.samples = 0; stateful.samples = 0;
double actual = chain.getFirst().getNoise(23L, 17D, -31D, null); double actual = chain.getFirst().getNoise(23L, 17D, -31D, RUNTIME);
assertBits(expected, actual); assertBits(expected, actual);
assertEquals(16, stateful.samples); assertEquals(16, stateful.samples);
} }
@@ -113,11 +116,11 @@ public final class IrisNoiseGeneratorFractureTest {
List<IrisNoiseGenerator> chain = chain(4, NoiseStyle.SIMPLEX); List<IrisNoiseGenerator> chain = chain(4, NoiseStyle.SIMPLEX);
List<NoiseGenerator> bases = spyBases(chain, 71L); List<NoiseGenerator> bases = spyBases(chain, 71L);
chain.getLast().getStyle().setExpression("custom"); chain.getLast().getStyle().setExpression("custom");
chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME);
verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble()); verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble());
chain.getLast().getStyle().setExpression(null).setImageMap("map"); chain.getLast().getStyle().setExpression(null).setImageMap("map");
clearInvocations(bases.getLast()); clearInvocations(bases.getLast());
chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME);
verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble()); verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble());
} }
@@ -127,7 +130,7 @@ public final class IrisNoiseGeneratorFractureTest {
List<NoiseGenerator> bases = spyBases(chain, 71L); List<NoiseGenerator> bases = spyBases(chain, 71L);
chain.getLast().setStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX) { chain.getLast().setStyle(new IrisGeneratorStyle(NoiseStyle.SIMPLEX) {
}); });
chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME);
verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble()); verify(bases.getLast(), times(16)).noise(anyDouble(), anyDouble());
} }
@@ -138,9 +141,9 @@ public final class IrisNoiseGeneratorFractureTest {
doThrow(new IllegalStateException("sample failed")).doCallRealMethod() doThrow(new IllegalStateException("sample failed")).doCallRealMethod()
.when(bases.getLast()).noise(anyDouble(), anyDouble()); .when(bases.getLast()).noise(anyDouble(), anyDouble());
assertThrows(IllegalStateException.class, assertThrows(IllegalStateException.class,
() -> chain.getFirst().getNoise(71L, 13.25D, -21.75D, null)); () -> chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME));
clearInvocations(bases.getLast()); clearInvocations(bases.getLast());
chain.getFirst().getNoise(71L, 13.25D, -21.75D, null); chain.getFirst().getNoise(71L, 13.25D, -21.75D, RUNTIME);
verify(bases.getLast(), times(2)).noise(anyDouble(), anyDouble()); verify(bases.getLast(), times(2)).noise(anyDouble(), anyDouble());
} }
@@ -148,24 +151,24 @@ public final class IrisNoiseGeneratorFractureTest {
public void threadsAndEngineIdentitiesRemainIndependent() throws Exception { public void threadsAndEngineIdentitiesRemainIndependent() throws Exception {
IrisNoiseGenerator root = chain(5, NoiseStyle.IRIS).getFirst(); IrisNoiseGenerator root = chain(5, NoiseStyle.IRIS).getFirst();
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
Engine firstEngine = mock(Engine.class); PackRuntime firstEngine = PackRuntime.forEngine(mock(Engine.class), data);
Engine secondEngine = mock(Engine.class); PackRuntime secondEngine = PackRuntime.forEngine(mock(Engine.class), data);
CountDownLatch start = new CountDownLatch(1); CountDownLatch start = new CountDownLatch(1);
ExecutorService executor = Executors.newFixedThreadPool(2); ExecutorService executor = Executors.newFixedThreadPool(2);
try { try {
Future<?> first = executor.submit(() -> sampleConcurrently(root, data, firstEngine, 47L, start)); Future<?> first = executor.submit(() -> sampleConcurrently(root, firstEngine, 47L, start));
Future<?> second = executor.submit(() -> sampleConcurrently(root, data, secondEngine, -131L, start)); Future<?> second = executor.submit(() -> sampleConcurrently(root, secondEngine, -131L, start));
start.countDown(); start.countDown();
first.get(15L, TimeUnit.SECONDS); first.get(15L, TimeUnit.SECONDS);
second.get(15L, TimeUnit.SECONDS); second.get(15L, TimeUnit.SECONDS);
} finally { } finally {
executor.shutdownNow(); executor.shutdownNow();
} }
assertParity(root, 47L, 17D, 19D, data, secondEngine); assertParity(root, 47L, 17D, 19D, secondEngine);
assertParity(root, 47L, 17D, 19D, data, firstEngine); assertParity(root, 47L, 17D, 19D, firstEngine);
} }
private static void sampleConcurrently(IrisNoiseGenerator root, IrisData data, Engine engine, private static void sampleConcurrently(IrisNoiseGenerator root, PackRuntime RUNTIME,
long seed, CountDownLatch start) { long seed, CountDownLatch start) {
try { try {
assertTrue(start.await(5L, TimeUnit.SECONDS)); assertTrue(start.await(5L, TimeUnit.SECONDS));
@@ -174,7 +177,7 @@ public final class IrisNoiseGeneratorFractureTest {
throw new AssertionError(failure); throw new AssertionError(failure);
} }
for (int index = 0; index < 64; index++) { for (int index = 0; index < 64; index++) {
assertParity(root, seed, index * 13.75D, -index * 2.25D, data, engine); assertParity(root, seed, index * 13.75D, -index * 2.25D, RUNTIME);
} }
} }
@@ -198,7 +201,7 @@ public final class IrisNoiseGeneratorFractureTest {
private static List<NoiseGenerator> spyBases(List<IrisNoiseGenerator> nodes, long superSeed) { private static List<NoiseGenerator> spyBases(List<IrisNoiseGenerator> nodes, long superSeed) {
List<NoiseGenerator> bases = new ArrayList<>(nodes.size()); List<NoiseGenerator> bases = new ArrayList<>(nodes.size());
for (IrisNoiseGenerator node : nodes) { for (IrisNoiseGenerator node : nodes) {
CNG generator = node.getGenerator(superSeed, null, null); CNG generator = node.getGenerator(superSeed, RUNTIME);
NoiseGenerator base = spy(generator.getGenerator()); NoiseGenerator base = spy(generator.getGenerator());
generator.setGenerator(base); generator.setGenerator(base);
bases.add(base); bases.add(base);
@@ -215,8 +218,8 @@ public final class IrisNoiseGeneratorFractureTest {
} }
private static void assertParity(IrisNoiseGenerator node, long seed, double x, double z, private static void assertParity(IrisNoiseGenerator node, long seed, double x, double z,
IrisData data, Engine engine) { PackRuntime RUNTIME) {
assertBits(reference(node, seed, x, z, data, engine), node.getNoise(seed, x, z, data, engine)); assertBits(reference(node, seed, x, z, RUNTIME), node.getNoise(seed, x, z, RUNTIME));
} }
private static void assertBits(double expected, double actual) { private static void assertBits(double expected, double actual) {
@@ -224,12 +227,12 @@ public final class IrisNoiseGeneratorFractureTest {
} }
private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv, private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv,
IrisData data, Engine engine) { PackRuntime RUNTIME) {
return reference(node, superSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS); return reference(node, superSeed, xv, zv, RUNTIME, IrisNoiseGenerator.X_AXIS);
} }
private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv, private static double reference(IrisNoiseGenerator node, long superSeed, double xv, double zv,
IrisData data, Engine engine, int axis) { PackRuntime RUNTIME, int axis) {
if (!node.isEnabled()) { if (!node.isEnabled()) {
return node.getOffsetY(); return node.getOffsetY();
} }
@@ -240,14 +243,14 @@ public final class IrisNoiseGeneratorFractureTest {
if (child.isEnabled()) { if (child.isEnabled()) {
double offset = child.getOpacity() / 2D; double offset = child.getOpacity() / 2D;
long childSeed = superSeed + node.getSeed() + salt; long childSeed = superSeed + node.getSeed() + salt;
x += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.X_AXIS) - offset; x += reference(child, childSeed, xv, zv, RUNTIME, IrisNoiseGenerator.X_AXIS) - offset;
z += reference(child, childSeed, xv, zv, data, engine, IrisNoiseGenerator.Z_AXIS) - offset; z += reference(child, childSeed, xv, zv, RUNTIME, IrisNoiseGenerator.Z_AXIS) - offset;
} }
salt += 819; salt += 819;
} }
double sampleX = (x / node.getZoom()) + node.getOffsetX(); double sampleX = (x / node.getZoom()) + node.getOffsetX();
double sampleZ = (z / node.getZoom()) + node.getOffsetZ(); double sampleZ = (z / node.getZoom()) + node.getOffsetZ();
CNG generator = node.getGenerator(superSeed, data, engine).reseededForAxis(axis); CNG generator = node.getGenerator(superSeed, RUNTIME).reseededForAxis(axis);
double result = generator.noiseFast2D(sampleX, sampleZ) * node.getOpacity(); double result = generator.noiseFast2D(sampleX, sampleZ) * node.getOpacity();
result = node.isNegative() ? -result + node.getOpacity() : result; result = node.isNegative() ? -result + node.getOpacity() : result;
result = (node.getExponent() != 1D ? result < 0D ? -Math.pow(-result, node.getExponent()) result = (node.getExponent() != 1D ? result < 0D ? -Math.pow(-result, node.getExponent())
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -13,7 +14,7 @@ public class IrisNoiseGeneratorRemapTest {
.setStyle(NoiseStyle.FLAT.style()) .setStyle(NoiseStyle.FLAT.style())
.setOpacity(sample[0]) .setOpacity(sample[0])
.setParametric(true); .setParametric(true);
assertEquals(sample[1], layer.getNoise(75L, 13D, -21D, null), 0.000000000001D); assertEquals(sample[1], layer.getNoise(75L, 13D, -21D, PackRuntime.standalone(null)), 0.000000000001D);
} }
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
import org.junit.Test; import org.junit.Test;
@@ -60,12 +61,12 @@ public class NoiseSeedCohesionTest {
public void generatorCacheEvictionRetainsSamples() { public void generatorCacheEvictionRetainsSamples() {
for (NoiseStyle style : NoiseStyle.values()) { for (NoiseStyle style : NoiseStyle.values()) {
IrisGeneratorStyle configured = style.style(); IrisGeneratorStyle configured = style.style();
double[] expected = samples(configured.create(new RNG(SEEDS[0]), null), false); double[] expected = samples(configured.create(new RNG(SEEDS[0]), PackRuntime.standalone(null)), false);
for (long seed = 0; seed < 9; seed++) { for (long seed = 0; seed < 9; seed++) {
configured.create(new RNG(seed), null); configured.create(new RNG(seed), PackRuntime.standalone(null));
} }
assertArrayEquals(style.name(), expected, assertArrayEquals(style.name(), expected,
samples(configured.create(new RNG(SEEDS[0]), null), true), 0D); samples(configured.create(new RNG(SEEDS[0]), PackRuntime.standalone(null)), true), 0D);
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.noise.NoiseGenerator; import art.arcane.volmlib.util.noise.NoiseGenerator;
@@ -71,8 +72,8 @@ public final class NoiseStyleContractTest {
if (style == NoiseStyle.STATIC) { if (style == NoiseStyle.STATIC) {
continue; continue;
} }
CNG normal = style.style().createNoCache(new RNG(45231L), null); CNG normal = style.style().createNoCache(new RNG(45231L), PackRuntime.standalone(null));
CNG enlarged = style.style().zoomed(2D).createNoCache(new RNG(45231L), null); CNG enlarged = style.style().zoomed(2D).createNoCache(new RNG(45231L), PackRuntime.standalone(null));
assertEquals(style.name(), normal.noise(13.25D, -17.75D), assertEquals(style.name(), normal.noise(13.25D, -17.75D),
enlarged.noise(26.5D, -35.5D), 0.000000001D); enlarged.noise(26.5D, -35.5D), 0.000000001D);
assertEquals(style.name(), normal.noise(13.25D), enlarged.noise(26.5D), 0.000000001D); assertEquals(style.name(), normal.noise(13.25D), enlarged.noise(26.5D), 0.000000001D);
@@ -85,7 +86,7 @@ public final class NoiseStyleContractTest {
public void defaultSettingsPreserveEveryPreset() { public void defaultSettingsPreserveEveryPreset() {
for (NoiseStyle style : NoiseStyle.values()) { for (NoiseStyle style : NoiseStyle.values()) {
CNG direct = style.create(new RNG(7253L)); CNG direct = style.create(new RNG(7253L));
CNG configured = style.style().createNoCache(new RNG(7253L), null); CNG configured = style.style().createNoCache(new RNG(7253L), PackRuntime.standalone(null));
for (int index = 0; index < 32; index++) { for (int index = 0; index < 32; index++) {
double x = index * 19.713D - 400D; double x = index * 19.713D - 400D;
double z = index * -31.579D + 100D; double z = index * -31.579D + 100D;
@@ -119,16 +120,16 @@ public final class NoiseStyleContractTest {
NoiseStyle.IRIS.style().setCellularFrequency(0.7D).setCellularZoom(1.25D) NoiseStyle.IRIS.style().setCellularFrequency(0.7D).setCellularZoom(1.25D)
}; };
for (IrisGeneratorStyle style : styles) { for (IrisGeneratorStyle style : styles) {
CNG normal = style.createNoCache(new RNG(217L), null); CNG normal = style.createNoCache(new RNG(217L), PackRuntime.standalone(null));
CNG enlarged = style.setZoom(2D).createNoCache(new RNG(217L), null); CNG enlarged = style.setZoom(2D).createNoCache(new RNG(217L), PackRuntime.standalone(null));
assertEquals(normal.noise(19.25D, -71.75D), enlarged.noise(38.5D, -143.5D), 0.000000001D); assertEquals(normal.noise(19.25D, -71.75D), enlarged.noise(38.5D, -143.5D), 0.000000001D);
} }
} }
@Test @Test
public void configuredExponentCompoundsThePresetCurve() { public void configuredExponentCompoundsThePresetCurve() {
CNG base = NoiseStyle.VASCULAR_THIN.style().createNoCache(new RNG(8831L), null); CNG base = NoiseStyle.VASCULAR_THIN.style().createNoCache(new RNG(8831L), PackRuntime.standalone(null));
CNG squared = NoiseStyle.VASCULAR_THIN.style().setExponent(2D).createNoCache(new RNG(8831L), null); CNG squared = NoiseStyle.VASCULAR_THIN.style().setExponent(2D).createNoCache(new RNG(8831L), PackRuntime.standalone(null));
double value = base.noise(29.5D, -33.25D); double value = base.noise(29.5D, -33.25D);
assertEquals(value * value, squared.noise(29.5D, -33.25D), 0.000000000001D); assertEquals(value * value, squared.noise(29.5D, -33.25D), 0.000000000001D);
} }
@@ -158,11 +159,11 @@ public final class NoiseStyleContractTest {
@Test @Test
public void layerOctavesPreserveAndMultiplyPresetDetail() { public void layerOctavesPreserveAndMultiplyPresetDetail() {
IrisGeneratorStyle style = NoiseStyle.QUADOCTAVE_SIMPLEX.style(); IrisGeneratorStyle style = NoiseStyle.QUADOCTAVE_SIMPLEX.style();
CNG unchanged = style.createForLayer(new RNG(71L), null, 1); CNG unchanged = style.createForLayer(new RNG(71L), PackRuntime.standalone(null), 1);
CNG detailed = style.createForLayer(new RNG(71L), null, 2); CNG detailed = style.createForLayer(new RNG(71L), PackRuntime.standalone(null), 2);
assertEquals(4, unchanged.getOct()); assertEquals(4, unchanged.getOct());
assertEquals(8, detailed.getOct()); assertEquals(8, detailed.getOct());
assertEquals(16, style.createForLayer(new RNG(71L), null, Integer.MAX_VALUE).getOct()); assertEquals(16, style.createForLayer(new RNG(71L), PackRuntime.standalone(null), Integer.MAX_VALUE).getOct());
assertNotEquals(unchanged.noise(21D, -31D), detailed.noise(21D, -31D), 0D); assertNotEquals(unchanged.noise(21D, -31D), detailed.noise(21D, -31D), 0D);
} }
@@ -172,10 +173,10 @@ public final class NoiseStyleContractTest {
IrisData data = mock(IrisData.class); IrisData data = mock(IrisData.class);
when(data.getDataFolder()).thenReturn(dataFolder); when(data.getDataFolder()).thenReturn(dataFolder);
IrisGeneratorStyle cached = NoiseStyle.BIOCTAVE_SIMPLEX.style().setCacheSize(32); IrisGeneratorStyle cached = NoiseStyle.BIOCTAVE_SIMPLEX.style().setCacheSize(32);
CNG first = cached.createForLayer(new RNG(921L), data, 3); CNG first = cached.createForLayer(new RNG(921L), PackRuntime.standalone(data), 3);
CNG reloaded = cached.createForLayer(new RNG(921L), data, 3); CNG reloaded = cached.createForLayer(new RNG(921L), PackRuntime.standalone(data), 3);
CNG uncached = NoiseStyle.BIOCTAVE_SIMPLEX.style().createForLayer(new RNG(921L), data, 3); CNG uncached = NoiseStyle.BIOCTAVE_SIMPLEX.style().createForLayer(new RNG(921L), PackRuntime.standalone(data), 3);
CNG different = cached.createForLayer(new RNG(921L), data, 1); CNG different = cached.createForLayer(new RNG(921L), PackRuntime.standalone(data), 1);
assertEquals(6, first.getOct()); assertEquals(6, first.getOct());
assertEquals(6, reloaded.getOct()); assertEquals(6, reloaded.getOct());
assertEquals(uncached.noise(4D, 7D), first.noise(4D, 7D), 0.000001D); assertEquals(uncached.noise(4D, 7D), first.noise(4D, 7D), 0.000001D);
@@ -190,12 +191,12 @@ public final class NoiseStyleContractTest {
double[] invalid = {0D, -1D, Double.NaN, Double.POSITIVE_INFINITY, Double.MIN_VALUE}; double[] invalid = {0D, -1D, Double.NaN, Double.POSITIVE_INFINITY, Double.MIN_VALUE};
for (double value : invalid) { for (double value : invalid) {
assertThrows(IllegalArgumentException.class, assertThrows(IllegalArgumentException.class,
() -> NoiseStyle.SIMPLEX.style().setZoom(value).createNoCache(new RNG(1L), null)); () -> NoiseStyle.SIMPLEX.style().setZoom(value).createNoCache(new RNG(1L), PackRuntime.standalone(null)));
assertThrows(IllegalArgumentException.class, assertThrows(IllegalArgumentException.class,
() -> NoiseStyle.SIMPLEX.style().setExponent(value).createNoCache(new RNG(1L), null)); () -> NoiseStyle.SIMPLEX.style().setExponent(value).createNoCache(new RNG(1L), PackRuntime.standalone(null)));
assertThrows(IllegalArgumentException.class, assertThrows(IllegalArgumentException.class,
() -> NoiseStyle.SIMPLEX.style().setCellularFrequency(1D).setCellularZoom(value) () -> NoiseStyle.SIMPLEX.style().setCellularFrequency(1D).setCellularZoom(value)
.createNoCache(new RNG(1L), null)); .createNoCache(new RNG(1L), PackRuntime.standalone(null)));
} }
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.noise; package art.arcane.iris.generation.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
import org.junit.Test; import org.junit.Test;
@@ -18,7 +19,7 @@ public class PatternNoiseStyleTest {
public void styleIntegrationUsesTheSameScaleInEveryDimension() { public void styleIntegrationUsesTheSameScaleInEveryDimension() {
for (NoiseStyle style : STYLES) { for (NoiseStyle style : STYLES) {
CNG direct = style.create(new RNG(7331L)); CNG direct = style.create(new RNG(7331L));
CNG zoomed = style.style().zoomed(2D).createNoCache(new RNG(7331L), null); CNG zoomed = style.style().zoomed(2D).createNoCache(new RNG(7331L), PackRuntime.standalone(null));
for (int index = 0; index < 128; index++) { for (int index = 0; index < 128; index++) {
double x = index * 13.713D - 400D; double x = index * 13.713D - 400D;
double y = index * 1.119D - 70D; double y = index * 1.119D - 70D;
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.runtime; package art.arcane.iris.generation.runtime;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.HydrologyVegetation; import art.arcane.iris.generation.decoration.HydrologyVegetation;
@@ -42,7 +43,7 @@ public class HydrologyVegetationSourceTest {
private static final Set<String> KNOWN = Set.of("minecraft:air", "minecraft:dirt", "minecraft:fern", "minecraft:sugar_cane", private static final Set<String> KNOWN = Set.of("minecraft:air", "minecraft:dirt", "minecraft:fern", "minecraft:sugar_cane",
"minecraft:short_grass", "minecraft:dead_bush", "minecraft:poppy", "minecraft:dandelion"); "minecraft:short_grass", "minecraft:dead_bush", "minecraft:poppy", "minecraft:dandelion");
private final IrisData data = mock(IrisData.class); private final IrisData data = MockPackData.create();
private PlantPlatform platform; private PlantPlatform platform;
@Before @Before
@@ -257,7 +257,7 @@ public class IrisComplexChunkCornersTest {
private boolean nested; private boolean nested;
@Override @Override
public double getHeight(double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
if (nested) { if (nested) {
return Math.cos(x * 0.13D) * 0.5D; return Math.cos(x * 0.13D) * 0.5D;
} }
@@ -281,7 +281,7 @@ public class IrisComplexChunkCornersTest {
} }
@Override @Override
public double getHeight(double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
invocations++; invocations++;
return Math.sin(x * 0.37D + seed) * Math.cos(z * 0.21D) * amplitude; return Math.sin(x * 0.37D + seed) * Math.cos(z * 0.21D) * amplitude;
} }
@@ -32,7 +32,7 @@ public class IrisComplexConstantGeneratorBoundsTest {
expected += M.lerp(low, high, noise); expected += M.lerp(low, high, noise);
} }
expected /= size; expected /= size;
assertBits(expected, IrisComplex.averageGeneratorHeights(generators, low, high, 12D, -9D, 7331L)); assertBits(expected, IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), generators, low, high, 12D, -9D, 7331L));
assertEquals(0, generator.calls); assertEquals(0, generator.calls);
} }
} }
@@ -44,8 +44,8 @@ public class IrisComplexConstantGeneratorBoundsTest {
public void inactiveInvalidNoiseMatchesExistingConstantFitContract() { public void inactiveInvalidNoiseMatchesExistingConstantFitContract() {
for (double noise : new double[]{Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) { for (double noise : new double[]{Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) {
CountingGenerator generator = new CountingGenerator(noise); CountingGenerator generator = new CountingGenerator(noise);
assertBits(generator.fitDouble(0D, 0D, 7331L, 12D, -9D), assertBits(generator.fitDouble(PackRuntime.standalone(null), 0D, 0D, 7331L, 12D, -9D),
IrisComplex.averageGeneratorHeights(new IrisGenerator[]{generator}, 0D, 0D, 12D, -9D, 7331L)); IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{generator}, 0D, 0D, 12D, -9D, 7331L));
assertEquals(0, generator.calls); assertEquals(0, generator.calls);
assertTrue(Double.isNaN(M.lerp(0D, 0D, noise))); assertTrue(Double.isNaN(M.lerp(0D, 0D, noise)));
} }
@@ -58,7 +58,7 @@ public class IrisComplexConstantGeneratorBoundsTest {
for (double noise : new double[]{0.3D, -2D, 3D}) { for (double noise : new double[]{0.3D, -2D, 3D}) {
CountingGenerator generator = new CountingGenerator(noise); CountingGenerator generator = new CountingGenerator(noise);
double expected = (0D + M.lerp(pair[0], pair[1], noise)) / 1; double expected = (0D + M.lerp(pair[0], pair[1], noise)) / 1;
assertBits(expected, IrisComplex.averageGeneratorHeights(new IrisGenerator[]{generator}, assertBits(expected, IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{generator},
pair[0], pair[1], 12D, -9D, 7331L)); pair[0], pair[1], 12D, -9D, 7331L));
assertEquals(1, generator.calls); assertEquals(1, generator.calls);
} }
@@ -72,7 +72,7 @@ public class IrisComplexConstantGeneratorBoundsTest {
CountingGenerator generator = new CountingGenerator(0.3D); CountingGenerator generator = new CountingGenerator(0.3D);
generator.setLoadKey("diagnostic/terrain"); generator.setLoadKey("diagnostic/terrain");
IllegalStateException failure = assertThrows(IllegalStateException.class, IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> IrisComplex.averageGeneratorHeights(new IrisGenerator[]{generator}, () -> IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{generator},
bounds[0], bounds[1], 671D, 2437D, 7331L)); bounds[0], bounds[1], 671D, 2437D, 7331L));
assertTrue(failure.getMessage().contains("671.0,2437.0")); assertTrue(failure.getMessage().contains("671.0,2437.0"));
assertTrue(failure.getMessage().contains("generator=diagnostic/terrain")); assertTrue(failure.getMessage().contains("generator=diagnostic/terrain"));
@@ -90,7 +90,7 @@ public class IrisComplexConstantGeneratorBoundsTest {
invalidGenerator.setLoadKey("diagnostic/cliffs"); invalidGenerator.setLoadKey("diagnostic/cliffs");
CountingGenerator unsampled = new CountingGenerator(0.5D); CountingGenerator unsampled = new CountingGenerator(0.5D);
IllegalStateException failure = assertThrows(IllegalStateException.class, IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> IrisComplex.averageGeneratorHeights(new IrisGenerator[]{valid, invalidGenerator, unsampled}, () -> IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null), new IrisGenerator[]{valid, invalidGenerator, unsampled},
0D, 44D, 671D, 2437D, 7331L)); 0D, 44D, 671D, 2437D, 7331L));
assertTrue(failure.getMessage().contains("671.0,2437.0")); assertTrue(failure.getMessage().contains("671.0,2437.0"));
assertTrue(failure.getMessage().contains("generator=diagnostic/cliffs")); assertTrue(failure.getMessage().contains("generator=diagnostic/cliffs"));
@@ -115,7 +115,7 @@ public class IrisComplexConstantGeneratorBoundsTest {
} }
@Override @Override
public double getHeight(double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
calls++; calls++;
return value; return value;
} }
@@ -60,7 +60,7 @@ public class IrisComplexGeneratorOrderingTest {
); );
double output = 0D; double output = 0D;
for (IrisComplex.GeneratorGroup group : groups) { for (IrisComplex.GeneratorGroup group : groups) {
output += IrisComplex.averageGeneratorHeights( output += IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null),
group.generators(), group.generators(),
0D, 0D,
1D, 1D,
@@ -78,7 +78,7 @@ public class IrisComplexGeneratorOrderingTest {
Map<IrisInterpolator, Set<IrisGenerator>> generators = Map.of(); Map<IrisInterpolator, Set<IrisGenerator>> generators = Map.of();
assertEquals(0, IrisComplex.freezeGeneratorGroups(generators).length); assertEquals(0, IrisComplex.freezeGeneratorGroups(generators).length);
assertEquals(0D, IrisComplex.averageGeneratorHeights( assertEquals(0D, IrisComplex.averageGeneratorHeights(PackRuntime.standalone(null),
new IrisGenerator[0], new IrisGenerator[0],
-1D, -1D,
1D, 1D,
@@ -141,7 +141,7 @@ public class IrisComplexGeneratorOrderingTest {
} }
@Override @Override
public double getHeight(double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
return height; return height;
} }
} }
@@ -392,7 +392,7 @@ public class IrisComplexGridBoundsCacheTest {
} }
@Override @Override
public double getHeight(double x, double z, long seed) { public double getHeight(PackRuntime runtime, double x, double z, long seed) {
invocations++; invocations++;
return value; return value;
} }
@@ -92,7 +92,7 @@ public class IrisEngineStreamTypeTest {
assertUnknownStream("NOT_A_STREAM", () -> data.getExpressionLoader().load("inline")); assertUnknownStream("NOT_A_STREAM", () -> data.getExpressionLoader().load("inline"));
assertUnknownStream("NOT_A_STREAM", () -> data.getExpressionLoader().load("snippet")); assertUnknownStream("NOT_A_STREAM", () -> data.getExpressionLoader().load("snippet"));
assertUnknownStream("water_head", () -> data.getExpressionLoader().load("lowercase")); assertUnknownStream("water_head", () -> data.getExpressionLoader().load("lowercase"));
assertUnknownStream("NOT_A_STREAM", () -> new IrisGeneratorStyle().setExpression("inline").create(new RNG(7L), data)); assertUnknownStream("NOT_A_STREAM", () -> new IrisGeneratorStyle().setExpression("inline").create(new RNG(7L), PackRuntime.standalone(data)));
IrisExpression known = data.getExpressionLoader().load("known"); IrisExpression known = data.getExpressionLoader().load("known");
assertSame(IrisEngineStreamType.WATER_HEAD, known.getVariables().get(0).getEngineStreamValue()); assertSame(IrisEngineStreamType.WATER_HEAD, known.getVariables().get(0).getEngineStreamValue());
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.subterrain; package art.arcane.iris.generation.subterrain;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomePaletteLayer; import art.arcane.iris.generation.biome.IrisBiomePaletteLayer;
import art.arcane.iris.generation.decoration.IrisDecorationPart; import art.arcane.iris.generation.decoration.IrisDecorationPart;
@@ -235,7 +236,7 @@ public class SubterrainSurfaceMaterialsTest {
private final NativeBlockState wall = solid("minecraft:andesite"); private final NativeBlockState wall = solid("minecraft:andesite");
private final IrisDimension dimension = new IrisDimension(); private final IrisDimension dimension = new IrisDimension();
private final IrisComplex complex = mock(IrisComplex.class); private final IrisComplex complex = mock(IrisComplex.class);
private final IrisData data = mock(IrisData.class); private final IrisData data = MockPackData.create();
private final IrisBiome biome = mock(IrisBiome.class); private final IrisBiome biome = mock(IrisBiome.class);
private final RNG random = new RNG(44339L); private final RNG random = new RNG(44339L);
private final SubterrainPlanner planner; private final SubterrainPlanner planner;
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
@@ -95,7 +96,7 @@ public class ContinentGeneratorTest {
} }
private double[] sampleContinentMap(IrisDimension dimension, double[][] blocks) { private double[] sampleContinentMap(IrisDimension dimension, double[][] blocks) {
return sampleAtBlocks(ContinentGenerator.create(dimension, new RNG(WORLD_SEED), packData), blocks); return sampleAtBlocks(ContinentGenerator.create(dimension, new RNG(WORLD_SEED), PackRuntime.forContext(packData)), blocks);
} }
private static double[][] shrinkByContinentZoom(double[][] blocks) { private static double[][] shrinkByContinentZoom(double[][] blocks) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.value.IrisRange; import art.arcane.iris.pack.value.IrisRange;
@@ -395,7 +396,7 @@ public class IrisDimensionCarvingResolverParityTest {
Fixture fixture = createFixture(); Fixture fixture = createFixture();
Engine engine = fixture.engine; Engine engine = fixture.engine;
IrisData firstData = engine.getData(); IrisData firstData = engine.getData();
IrisData replacementData = mock(IrisData.class); IrisData replacementData = MockPackData.create();
IrisDimensionCarvingEntry entry = mock(IrisDimensionCarvingEntry.class); IrisDimensionCarvingEntry entry = mock(IrisDimensionCarvingEntry.class);
IrisBiome firstBiome = new IrisBiome(); IrisBiome firstBiome = new IrisBiome();
IrisBiome replacementBiome = new IrisBiome(); IrisBiome replacementBiome = new IrisBiome();
@@ -430,7 +431,7 @@ public class IrisDimensionCarvingResolverParityTest {
Fixture fixture = createFixture(); Fixture fixture = createFixture();
IrisData firstData = fixture.engine.getData(); IrisData firstData = fixture.engine.getData();
IrisDimension dimension = fixture.engine.getDimension(); IrisDimension dimension = fixture.engine.getDimension();
IrisData replacementData = mock(IrisData.class); IrisData replacementData = MockPackData.create();
IrisDimensionCarvingEntry entry = mock(IrisDimensionCarvingEntry.class); IrisDimensionCarvingEntry entry = mock(IrisDimensionCarvingEntry.class);
IrisBiome firstBiome = new IrisBiome(); IrisBiome firstBiome = new IrisBiome();
IrisBiome replacementBiome = new IrisBiome(); IrisBiome replacementBiome = new IrisBiome();
@@ -547,7 +548,7 @@ public class IrisDimensionCarvingResolverParityTest {
} }
private RetainedFixture createRetainedFixture() { private RetainedFixture createRetainedFixture() {
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
IrisBiome biome = new IrisBiome(); IrisBiome biome = new IrisBiome();
biome.setLoader(data); biome.setLoader(data);
@@ -602,7 +603,7 @@ public class IrisDimensionCarvingResolverParityTest {
doReturn(childBBiome).when(biomeLoader).load("child-b"); doReturn(childBBiome).when(biomeLoader).load("child-b");
doReturn(childCBiome).when(biomeLoader).load("child-c"); doReturn(childCBiome).when(biomeLoader).load("child-c");
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
doReturn(biomeLoader).when(data).getBiomeLoader(); doReturn(biomeLoader).when(data).getBiomeLoader();
IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 4, List.of("child-a", "child-b")); IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 4, List.of("child-a", "child-b"));
@@ -678,7 +679,7 @@ public class IrisDimensionCarvingResolverParityTest {
doReturn(childFBiome).when(biomeLoader).load("child-f"); doReturn(childFBiome).when(biomeLoader).load("child-f");
doReturn(childGBiome).when(biomeLoader).load("child-g"); doReturn(childGBiome).when(biomeLoader).load("child-g");
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
doReturn(biomeLoader).when(data).getBiomeLoader(); doReturn(biomeLoader).when(data).getBiomeLoader();
IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 7, List.of("child-a", "child-d", "child-e")); IrisDimensionCarvingEntry rootLow = buildEntry("root-low", "root-low", new IrisRange(-64, 120), 7, List.of("child-a", "child-d", "child-e"));
@@ -79,7 +79,7 @@ public final class IrisMaterialPaletteGeneratorCacheTest {
11L + GENERATOR_SALT, firstGenerator, 11L + GENERATOR_SALT, firstGenerator,
29L + GENERATOR_SALT, secondGenerator 29L + GENERATOR_SALT, secondGenerator
); );
when(style.create(any(RNG.class), same(data), same(engine))).thenAnswer(invocation -> { when(style.create(any(RNG.class), any())).thenAnswer(invocation -> {
RNG rng = invocation.getArgument(0); RNG rng = invocation.getArgument(0);
return generators.get(rng.getSeed()); return generators.get(rng.getSeed());
}); });
@@ -1,5 +1,7 @@
package art.arcane.iris.generation.terrain; package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.noise.GeneratorRuntime;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG; import art.arcane.volmlib.util.noise.CNG;
@@ -28,12 +30,12 @@ public class TerrainFieldSeedCohesionTest {
@Test @Test
public void cellGeneratorsRetainSeedAssignments() { public void cellGeneratorsRetainSeedAssignments() {
IrisGenerator generator = new IrisGenerator(); GeneratorRuntime generator = PackRuntime.standalone(null).generator(new IrisGenerator());
CellGenerator first = generator.getCellGenerator(17L); CellGenerator first = generator.cellGenerator(17L);
CellGenerator second = generator.getCellGenerator(91L); CellGenerator second = generator.cellGenerator(91L);
assertNotSame(first, second); assertNotSame(first, second);
assertSame(first, generator.getCellGenerator(17L)); assertSame(first, generator.cellGenerator(17L));
CellGenerator expected = new IrisGenerator().getCellGenerator(91L); CellGenerator expected = PackRuntime.standalone(null).generator(new IrisGenerator()).cellGenerator(91L);
assertEquals(expected.getDistance(17D, -81D), second.getDistance(17D, -81D), 0D); assertEquals(expected.getDistance(17D, -81D), second.getDistance(17D, -81D), 0D);
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.biome; package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome; import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.stream.RarityStream; import art.arcane.iris.generation.stream.RarityStream;
import art.arcane.iris.generation.terrain.ContinentGenerator; import art.arcane.iris.generation.terrain.ContinentGenerator;
@@ -40,15 +41,15 @@ final class IrisSelectionReference {
loaded.add(region); loaded.add(region);
} }
} }
regions = new RarityStream<>(dimension.getRegionStyle().create(rng.nextParallelRNG(883), data).stream().zoom(dimension.getRegionZoom()), loaded); regions = new RarityStream<>(dimension.getRegionStyle().create(rng.nextParallelRNG(883), PackRuntime.standalone(data)).stream().zoom(dimension.getRegionZoom()), loaded);
continent = ContinentGenerator.create(dimension, rng, data); continent = ContinentGenerator.create(dimension, rng, PackRuntime.standalone(data));
for (IrisRegion region : loaded) { for (IrisRegion region : loaded) {
Map<InferredType, RarityStream<IrisBiome>> streams = new EnumMap<>(InferredType.class); Map<InferredType, RarityStream<IrisBiome>> streams = new EnumMap<>(InferredType.class);
streams.put(InferredType.LAND, new RarityStream<>(dimension.getLandBiomeStyle().create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream() streams.put(InferredType.LAND, new RarityStream<>(dimension.getLandBiomeStyle().create(rng.nextParallelRNG(InferredType.LAND.ordinal()), PackRuntime.standalone(data)).stream()
.zoom(dimension.getBiomeZoom()).zoom(dimension.getLandZoom()).zoom(region.getLandBiomeZoom()), pool(region.getLandBiomes()))); .zoom(dimension.getBiomeZoom()).zoom(dimension.getLandZoom()).zoom(region.getLandBiomeZoom()), pool(region.getLandBiomes())));
streams.put(InferredType.SEA, new RarityStream<>(dimension.getSeaBiomeStyle().create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream() streams.put(InferredType.SEA, new RarityStream<>(dimension.getSeaBiomeStyle().create(rng.nextParallelRNG(InferredType.SEA.ordinal()), PackRuntime.standalone(data)).stream()
.zoom(dimension.getBiomeZoom()).zoom(dimension.getSeaZoom()).zoom(region.getSeaBiomeZoom()), pool(region.getSeaBiomes()))); .zoom(dimension.getBiomeZoom()).zoom(dimension.getSeaZoom()).zoom(region.getSeaBiomeZoom()), pool(region.getSeaBiomes())));
streams.put(InferredType.SHORE, new RarityStream<>(dimension.getShoreBiomeStyle().create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream() streams.put(InferredType.SHORE, new RarityStream<>(dimension.getShoreBiomeStyle().create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), PackRuntime.standalone(data)).stream()
.zoom(dimension.getBiomeZoom()).zoom(region.getShoreBiomeZoom()), pool(region.getShoreBiomes()))); .zoom(dimension.getBiomeZoom()).zoom(region.getShoreBiomeZoom()), pool(region.getShoreBiomes())));
picks.put(region, streams); picks.put(region, streams);
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.decoration; package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.datapack.DataVersion; import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ExportTestPacks; import art.arcane.iris.pack.datapack.export.ExportTestPacks;
@@ -461,7 +462,7 @@ public class DecorationStageTest {
private static GatePattern irisPattern(String styleJson, double chance) { private static GatePattern irisPattern(String styleJson, double chance) {
IrisGeneratorStyle style = new Gson().fromJson(styleJson, IrisGeneratorStyle.class); IrisGeneratorStyle style = new Gson().fromJson(styleJson, IrisGeneratorStyle.class);
CNG generator = style.create(new RNG(4242L), null); CNG generator = style.create(new RNG(4242L), PackRuntime.standalone(null));
double zoom = style.getZoom(); double zoom = style.getZoom();
return pattern((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance); return pattern((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance);
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.noise; package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator; import art.arcane.iris.generation.noise.IrisNoiseGenerator;
@@ -245,7 +246,7 @@ public final class NoiseStyleCompilerTest {
NoiseRegistry registry = new NoiseRegistry("iris_export"); NoiseRegistry registry = new NoiseRegistry("iris_export");
Field field = SMOOTH.compileLayer(layer, SEED, registry, CAPABILITIES); Field field = SMOOTH.compileLayer(layer, SEED, registry, CAPABILITIES);
for (int x = -20; x <= 20; x += 10) { for (int x = -20; x <= 20; x += 10) {
assertEquals(layer.getNoise(SUPER_SEED, x, -x, null), sample(field, registry, x, -x), tolerance); assertEquals(layer.getNoise(SUPER_SEED, x, -x, PackRuntime.standalone(null)), sample(field, registry, x, -x), tolerance);
} }
} }
@@ -253,7 +254,7 @@ public final class NoiseStyleCompilerTest {
NoiseRegistry registry = new NoiseRegistry("iris_export"); NoiseRegistry registry = new NoiseRegistry("iris_export");
Field field = SMOOTH.compileComposite(generator, SEED, registry, CAPABILITIES); Field field = SMOOTH.compileComposite(generator, SEED, registry, CAPABILITIES);
for (int x = -30; x <= 30; x += 15) { for (int x = -30; x <= 30; x += 15) {
assertEquals(generator.getHeight(x, 2 * x, SUPER_SEED), sample(field, registry, x, 2 * x), FLOAT_TOLERANCE); assertEquals(generator.getHeight(PackRuntime.standalone(null), x, 2 * x, SUPER_SEED), sample(field, registry, x, 2 * x), FLOAT_TOLERANCE);
} }
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.noise; package art.arcane.iris.pack.datapack.export.compile.noise;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator; import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
@@ -60,7 +61,7 @@ public final class SmoothNoiseFidelityTest {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.SIMPLEX);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE); NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES); Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
CNG iris = style.createNoCache(new RNG(IRIS_SEED), null); CNG iris = style.createNoCache(new RNG(IRIS_SEED), PackRuntime.standalone(null));
double[] irisValues = grid((x, z) -> iris.noise(x, z), 0, 0, SIZE, STRIDE); double[] irisValues = grid((x, z) -> iris.noise(x, z), 0, 0, SIZE, STRIDE);
double[] lowered = new double[0]; double[] lowered = new double[0];
for (int window = 0; window < 4; window++) { for (int window = 0; window < 4; window++) {
@@ -76,7 +77,7 @@ public final class SmoothNoiseFidelityTest {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.QUADOCTAVE_FRACTAL_FBM_SIMPLEX).zoomed(0.5); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.QUADOCTAVE_FRACTAL_FBM_SIMPLEX).zoomed(0.5);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE); NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES); Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
CNG iris = style.createNoCache(new RNG(IRIS_SEED), null); CNG iris = style.createNoCache(new RNG(IRIS_SEED), PackRuntime.standalone(null));
double[] irisSpectrum = new double[SIZE / 2]; double[] irisSpectrum = new double[SIZE / 2];
double[] loweredSpectrum = new double[SIZE / 2]; double[] loweredSpectrum = new double[SIZE / 2];
for (int window = 0; window < WINDOWS.length; window++) { for (int window = 0; window < WINDOWS.length; window++) {
@@ -115,7 +116,7 @@ public final class SmoothNoiseFidelityTest {
IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.NOWHERE).zoomed(0.5); IrisGeneratorStyle style = new IrisGeneratorStyle(NoiseStyle.NOWHERE).zoomed(0.5);
NoiseRegistry registry = new NoiseRegistry(NAMESPACE); NoiseRegistry registry = new NoiseRegistry(NAMESPACE);
Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES); Field field = COMPILER.compile(style, SALT, registry, CAPABILITIES);
CNG iris = style.createNoCache(new RNG(IRIS_SEED), null); CNG iris = style.createNoCache(new RNG(IRIS_SEED), PackRuntime.standalone(null));
long irisFragments = 0L; long irisFragments = 0L;
long loweredFragments = 0L; long loweredFragments = 0L;
for (int window = 0; window < WINDOWS.length; window++) { for (int window = 0; window < WINDOWS.length; window++) {
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.datapack.export.compile.terrain; package art.arcane.iris.pack.datapack.export.compile.terrain;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisDimension;
@@ -101,7 +102,7 @@ public class VolumetricCompilerTest {
try { try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE); NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0)); Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), data); CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), PackRuntime.standalone(data));
SplittableRandom random = new SplittableRandom(MARGINAL_SEED); SplittableRandom random = new SplittableRandom(MARGINAL_SEED);
double[] exported = new double[MARGINAL_SAMPLES]; double[] exported = new double[MARGINAL_SAMPLES];
double[] expected = new double[MARGINAL_SAMPLES]; double[] expected = new double[MARGINAL_SAMPLES];
@@ -129,7 +130,7 @@ public class VolumetricCompilerTest {
try { try {
NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE); NoiseRegistry registry = new NoiseRegistry(TerrainTestSupport.NAMESPACE);
Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0)); Compiled compiled = compile(data, registry, NoiseStyleCompiler.create(new ArrayList<>()), TerrainTestSupport.twoBiomeCodes(registry, 0.0));
CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), data); CNG iris = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).createNoCache(new RNG(MARGINAL_SEED), PackRuntime.standalone(data));
SplittableRandom random = new SplittableRandom(MARGINAL_SEED); SplittableRandom random = new SplittableRandom(MARGINAL_SEED);
int exported = 0; int exported = 0;
int expected = 0; int expected = 0;
@@ -1,5 +1,6 @@
package art.arcane.iris.pack.value; package art.arcane.iris.pack.value;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGenerator; import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator; import art.arcane.iris.generation.noise.IrisNoiseGenerator;
@@ -38,17 +39,17 @@ public class IrisMathNoiseHotPathParityTest {
.setStyle(NoiseStyle.PERLIN_IRIS.style()) .setStyle(NoiseStyle.PERLIN_IRIS.style())
.setExponent(1.15D); .setExponent(1.15D);
assertEquals(0.4646529061250786D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, null), 0D); assertEquals(0.4646529061250786D, noiseGenerator.getNoise(9988L, 31.25D, -17.5D, PackRuntime.standalone(null)), 0D);
IrisGeneratorStyle style = NoiseStyle.IRIS_DOUBLE.style(); IrisGeneratorStyle style = NoiseStyle.IRIS_DOUBLE.style();
assertEquals(0.6855680984398492D, style.createNoCache(new RNG(112233L), null).noiseFast2D(42.5D, -19.75D), 0D); assertEquals(0.6855680984398492D, style.createNoCache(new RNG(112233L), PackRuntime.standalone(null)).noiseFast2D(42.5D, -19.75D), 0D);
IrisGenerator generator = new IrisGenerator() IrisGenerator generator = new IrisGenerator()
.setZoom(9.5D) .setZoom(9.5D)
.setOpacity(0.91D) .setOpacity(0.91D)
.setComposite(new KList<IrisNoiseGenerator>().qadd(noiseGenerator)); .setComposite(new KList<IrisNoiseGenerator>().qadd(noiseGenerator));
assertEquals(0.5023367573389593D, generator.getHeight(63.0D, -27.0D, 445566L), 0D); assertEquals(0.5023367573389593D, generator.getHeight(PackRuntime.standalone(null), 63.0D, -27.0D, 445566L), 0D);
} }
@Test @Test
@@ -217,21 +217,6 @@ public class PackRuntimeStateGateTest {
pending("art.arcane.iris.generation.decoration.IrisDepositGenerator", "scaledObjects", Kind.RUNTIME), pending("art.arcane.iris.generation.decoration.IrisDepositGenerator", "scaledObjects", Kind.RUNTIME),
pending("art.arcane.iris.generation.decoration.IrisOreGenerator", "chanceCache", Kind.RUNTIME), pending("art.arcane.iris.generation.decoration.IrisOreGenerator", "chanceCache", Kind.RUNTIME),
pending("art.arcane.iris.generation.decoration.IrisOreGenerator", "recentChance", Kind.RUNTIME), pending("art.arcane.iris.generation.decoration.IrisOreGenerator", "recentChance", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpression", "evaluationScratch", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpression", "expressionCache", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpression", "streams", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionFunction", "data", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionFunction", "providers", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionFunction", "recentProvider", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionLoad", "engineCaches", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionLoad", "standaloneStyleCache", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGenerator", "cellGenerators", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGenerator", "recentCellGenerator", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGenerator", "surfaceSamples", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGeneratorStyle", "generatorCache", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGeneratorStyle", "recentGenerator", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisNoiseGenerator", "generators", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisNoiseGenerator", "recentGenerator", Kind.RUNTIME),
pending("art.arcane.iris.generation.terrain.IrisDimension", "coordinateFractures", Kind.RUNTIME), pending("art.arcane.iris.generation.terrain.IrisDimension", "coordinateFractures", Kind.RUNTIME),
pending("art.arcane.iris.generation.terrain.IrisDimension", "featuresUsed", Kind.RUNTIME), pending("art.arcane.iris.generation.terrain.IrisDimension", "featuresUsed", Kind.RUNTIME),
pending("art.arcane.iris.generation.terrain.IrisDimension", "fluidLayerGenerator", Kind.RUNTIME), pending("art.arcane.iris.generation.terrain.IrisDimension", "fluidLayerGenerator", Kind.RUNTIME),
@@ -275,13 +260,8 @@ public class PackRuntimeStateGateTest {
pending("art.arcane.iris.generation.biome.IrisFloatingChildBiomes$RuntimeKey", "engine", Kind.RUNTIME), pending("art.arcane.iris.generation.biome.IrisFloatingChildBiomes$RuntimeKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.decoration.IrisDecorator$GeneratorKey", "engine", Kind.RUNTIME), pending("art.arcane.iris.generation.decoration.IrisDecorator$GeneratorKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.decoration.IrisOreGenerator$ChanceKey", "engine", Kind.RUNTIME), pending("art.arcane.iris.generation.decoration.IrisOreGenerator$ChanceKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionFunction$FunctionKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGenerator$SurfaceCache", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisGeneratorStyle$GeneratorCacheKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisNoiseGenerator$GeneratorKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.terrain.IrisMaterialPalette$LayerGeneratorKey", "engine", Kind.RUNTIME), pending("art.arcane.iris.generation.terrain.IrisMaterialPalette$LayerGeneratorKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.structure.object.IrisObjectPlacement$SurfaceWarpCacheKey", "engine", Kind.RUNTIME), pending("art.arcane.iris.structure.object.IrisObjectPlacement$SurfaceWarpCacheKey", "engine", Kind.RUNTIME),
pending("art.arcane.iris.generation.noise.IrisExpressionLoad$EngineCache", "styles", Kind.RUNTIME),
pending("art.arcane.iris.generation.bake.ChunkBakeCache", "SPARSE", Kind.SCRATCH), pending("art.arcane.iris.generation.bake.ChunkBakeCache", "SPARSE", Kind.SCRATCH),
pending("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_DENSITY", Kind.SCRATCH), pending("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_DENSITY", Kind.SCRATCH),
pending("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_REJECT", Kind.SCRATCH), pending("art.arcane.iris.generation.biome.FloatingIslandSample", "LAST_REJECT", Kind.SCRATCH),
@@ -464,6 +444,7 @@ public class PackRuntimeStateGateTest {
); );
private static final List<Entry> SETTLED_HOLDERS = List.of( private static final List<Entry> SETTLED_HOLDERS = List.of(
holder("art.arcane.iris.generation.noise.ExpressionRuntime", "EVALUATION_SCRATCH", Kind.SCRATCH, "per-depth double argument arrays, no engine or pack reference"),
holder("art.arcane.iris.generation.runtime.EnginePanic$Diagnostics", "current", Kind.UNRELATED, "panic diagnostics strings for crash reports"), holder("art.arcane.iris.generation.runtime.EnginePanic$Diagnostics", "current", Kind.UNRELATED, "panic diagnostics strings for crash reports"),
holder("art.arcane.iris.pack.IrisPackBenchmarking", "instance", Kind.UNRELATED, "benchmark command session") holder("art.arcane.iris.pack.IrisPackBenchmarking", "instance", Kind.UNRELATED, "benchmark command session")
); );
@@ -1,5 +1,6 @@
package art.arcane.iris.structure.object; package art.arcane.iris.structure.object;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
@@ -23,7 +24,7 @@ public class IrisObjectPlacementSurfaceWarpCacheTest {
Engine first = engine(100L); Engine first = engine(100L);
Engine second = engine(200L); Engine second = engine(200L);
AtomicReference<Engine> active = new AtomicReference<>(first); AtomicReference<Engine> active = new AtomicReference<>(first);
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
when(data.getEngine()).thenAnswer(ignored -> active.get()); when(data.getEngine()).thenAnswer(ignored -> active.get());
IrisObjectPlacement placement = placement(); IrisObjectPlacement placement = placement();
@@ -36,7 +37,7 @@ public class IrisObjectPlacementSurfaceWarpCacheTest {
@Test @Test
public void standaloneSurfaceWarpUsesSuppliedSeed() { public void standaloneSurfaceWarpUsesSuppliedSeed() {
IrisData data = mock(IrisData.class); IrisData data = MockPackData.create();
IrisObjectPlacement placement = placement(); IrisObjectPlacement placement = placement();
CNG first = placement.getSurfaceWarp(new RNG(1L), data); CNG first = placement.getSurfaceWarp(new RNG(1L), data);
@@ -1,5 +1,6 @@
package art.arcane.iris.structure.object; package art.arcane.iris.structure.object;
import art.arcane.iris.testsupport.MockPackData;
import art.arcane.iris.generation.hydrology.raster.WaterRole; import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.block.BlockDataMergeSupport; import art.arcane.iris.generation.block.BlockDataMergeSupport;
import art.arcane.iris.generation.block.IrisBlockData; import art.arcane.iris.generation.block.IrisBlockData;
@@ -125,10 +126,10 @@ public class ObjectPlacementGoldenTest {
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
ContentGate gate = mock(ContentGate.class, withSettings().stubOnly()); ContentGate gate = mock(ContentGate.class, withSettings().stubOnly());
when(gate.ready()).thenReturn(false); when(gate.ready()).thenReturn(false);
data = mock(IrisData.class, withSettings().stubOnly()); data = MockPackData.stubOnly();
when(data.getEngine()).thenReturn(engine); when(data.getEngine()).thenReturn(engine);
when(data.getContentGate()).thenReturn(gate); when(data.getContentGate()).thenReturn(gate);
objectData = mock(IrisData.class, withSettings().stubOnly()); objectData = MockPackData.stubOnly();
when(objectData.getContentGate()).thenReturn(gate); when(objectData.getContentGate()).thenReturn(gate);
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.testsupport; package art.arcane.iris.testsupport;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.RNG;
@@ -14,7 +15,7 @@ public final class GeneratorSampling {
} }
public static double[] sampleSharedGenerator(IrisGeneratorStyle style, RNG seed, IrisData packData) { public static double[] sampleSharedGenerator(IrisGeneratorStyle style, RNG seed, IrisData packData) {
return sampleAtBlocks(style.create(seed, packData), SAMPLE_BLOCKS); return sampleAtBlocks(style.create(seed, PackRuntime.forContext(packData)), SAMPLE_BLOCKS);
} }
public static double[] sampleAtBlocks(CNG generator, double[][] blocks) { public static double[] sampleAtBlocks(CNG generator, double[][] blocks) {
@@ -0,0 +1,29 @@
package art.arcane.iris.testsupport;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
/**
* Mocked pack data that still owns a standalone runtime scope, the way loaded pack data does.
*/
public final class MockPackData {
private MockPackData() {
}
public static IrisData create() {
return withStandaloneRuntime(mock(IrisData.class));
}
public static IrisData stubOnly() {
return withStandaloneRuntime(mock(IrisData.class, withSettings().stubOnly()));
}
private static IrisData withStandaloneRuntime(IrisData data) {
doReturn(PackRuntime.standalone(data)).when(data).standalonePackRuntime();
return data;
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.testsupport; package art.arcane.iris.testsupport;
import art.arcane.iris.generation.runtime.Engine; import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -12,7 +13,9 @@ public final class RunningEnginePackData {
public static IrisData create() { public static IrisData create() {
IrisData packData = mock(IrisData.class); IrisData packData = mock(IrisData.class);
when(packData.getEngine()).thenReturn(mock(Engine.class)); Engine engine = mock(Engine.class);
when(engine.getPackRuntime()).thenReturn(PackRuntime.forEngine(engine, packData));
when(packData.getEngine()).thenReturn(engine);
return packData; return packData;
} }
} }