Merge remote-tracking branch 'origin/master'

This commit is contained in:
SwiftSwamp committed 2026-10-31 17:42:51 -06:00
commit 55bc7365f1
498 files changed
+54571 -1345

No files matched your search

@@ -20,7 +20,7 @@ package art.arcane.iris.generation.chunk;
import art.arcane.volmlib.util.hunk.Hunk;
public final class ColumnExtentListeningHunk<T> implements Hunk<T>, ColumnExtent, ColumnRunHunk<T> {
public final class ColumnExtentListeningHunk<T> implements Hunk<T>, ColumnExtent, ColumnRunHunk<T>, ColumnReadHunk<T> {
private final Hunk<T> source;
private final Listener<T> listener;
@@ -46,6 +46,11 @@ public final class ColumnExtentListeningHunk<T> implements Hunk<T>, ColumnExtent
return source.getRaw(x, y, z);
}
@Override
public void readColumn(int x, int z, int yFromInclusive, int yToInclusive, T[] target, int targetOffset) {
ColumnReadHunk.readColumn(source, x, z, yFromInclusive, yToInclusive, target, targetOffset);
}
@Override
public int getWidth() {
return source.getWidth();
@@ -0,0 +1,37 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2026 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.chunk;
import art.arcane.volmlib.util.hunk.Hunk;
public interface ColumnReadHunk<T> {
void readColumn(int x, int z, int yFromInclusive, int yToInclusive, T[] target, int targetOffset);
@SuppressWarnings("unchecked")
static <T> void readColumn(Hunk<T> hunk, int x, int z, int yFromInclusive, int yToInclusive, T[] target,
int targetOffset) {
if (hunk instanceof ColumnReadHunk<?> reads) {
((ColumnReadHunk<T>) reads).readColumn(x, z, yFromInclusive, yToInclusive, target, targetOffset);
return;
}
for (int y = yFromInclusive; y <= yToInclusive; y++) {
target[targetOffset + y - yFromInclusive] = hunk.getRaw(x, y, z);
}
}
}
@@ -27,7 +27,8 @@ import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Arrays;
public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectionVolume, ColumnExtent, ColumnRunHunk<NativeBlockState> {
public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectionVolume, ColumnExtent, ColumnRunHunk<NativeBlockState>,
ColumnReadHunk<NativeBlockState> {
private static final BoundBlockState AIR = BoundBlockState.of("AIR");
private static final VarHandle SECTIONS = MethodHandles.arrayElementVarHandle(short[][].class);
private static final VarHandle COLUMN_TOPS = MethodHandles.arrayElementVarHandle(int[].class);
@@ -43,6 +44,8 @@ public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectio
private PaletteEntry[] slots;
private NativeBlockState[] states;
private int paletteSize;
private NativeBlockState air;
private PaletteEntry lastEntry;
public SectionBuffer(int height) {
if (height <= 0) {
@@ -76,12 +79,17 @@ public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectio
if (state == null) {
return 0;
}
PaletteEntry last = lastEntry;
if (last != null && last.state == state) {
return last.id;
}
PaletteEntry[] table = slots;
int mask = table.length - 1;
int slot = System.identityHashCode(state) & mask;
PaletteEntry entry;
while ((entry = table[slot]) != null) {
if (entry.state == state) {
lastEntry = entry;
return entry.id;
}
slot = (slot + 1) & mask;
@@ -101,7 +109,7 @@ public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectio
@Override
public NativeBlockState getRaw(int x, int y, int z) {
if (y < 0 || y >= height) {
return AIR.get();
return air();
}
short[] section = sections[y >> 4];
if (section != null) {
@@ -110,7 +118,7 @@ public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectio
return state(id);
}
}
return AIR.get();
return air();
}
@Override
@@ -126,6 +134,32 @@ public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectio
return id == 0 ? null : state(id);
}
@Override
public void readColumn(int x, int z, int yFromInclusive, int yToInclusive, NativeBlockState[] target, int targetOffset) {
int column = (z << 4) | x;
int shift = targetOffset - yFromInclusive;
int y = yFromInclusive;
while (y <= yToInclusive) {
if (y < 0 || y >= height) {
target[shift + y] = air();
y++;
continue;
}
int sectionIndex = y >> 4;
int last = Math.min(Math.min(yToInclusive, height - 1), (sectionIndex << 4) | 15);
short[] section = sections[sectionIndex];
if (section == null) {
Arrays.fill(target, shift + y, shift + last + 1, air());
} else {
for (int row = y; row <= last; row++) {
int id = section[((row & 15) << 8) | column] & 0xFFFF;
target[shift + row] = id == 0 ? air() : state(id);
}
}
y = last + 1;
}
}
@Override
public void fillColumnRun(int x, int z, int yFromInclusive, int yToInclusive, NativeBlockState value) {
if (value == null || yToInclusive < yFromInclusive) {
@@ -176,6 +210,15 @@ public final class SectionBuffer implements Hunk<NativeBlockState>, NativeSectio
}
}
private NativeBlockState air() {
NativeBlockState resolved = air;
if (resolved == null) {
resolved = AIR.get();
air = resolved;
}
return resolved;
}
private short[] writableSection(int sectionIndex) {
short[] section = sections[sectionIndex];
if (section != null) {
@@ -28,9 +28,14 @@ import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.volmlib.util.collection.KMap;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
public final class IrisContext {
private static final ThreadLocal<IrisContext> CONTEXT = new ThreadLocal<>();
private static final int SLOTS = 512;
private static final AtomicReferenceArray<Binding> BINDINGS = new AtomicReferenceArray<>(SLOTS);
private static final ThreadLocal<Binding> OVERFLOW = new ThreadLocal<>();
private static final AtomicInteger OVERFLOW_BINDINGS = new AtomicInteger();
private final Engine engine;
private final ChunkContext chunkContext;
private final long generationSessionId;
@@ -42,7 +47,8 @@ public final class IrisContext {
}
public static IrisContext get() {
return CONTEXT.get();
Binding binding = binding(Thread.currentThread());
return binding == null ? null : binding.context;
}
public static IrisContext require() {
@@ -55,9 +61,10 @@ public final class IrisContext {
public static Scope open(Engine engine, long generationSessionId, ChunkContext chunkContext) {
Thread thread = Thread.currentThread();
IrisContext previous = CONTEXT.get();
Binding binding = bind(thread);
IrisContext previous = binding.context;
IrisContext installed = new IrisContext(engine, generationSessionId, chunkContext);
CONTEXT.set(installed);
binding.context = installed;
return new Scope(thread, previous, installed);
}
@@ -99,6 +106,42 @@ public final class IrisContext {
.qput("queued", mantle.getUnloadRegionCount()));
}
private static Binding binding(Thread thread) {
Binding binding = BINDINGS.getPlain(slot(thread));
if (binding != null && binding.owner == thread) {
return binding;
}
return OVERFLOW_BINDINGS.get() == 0 ? null : OVERFLOW.get();
}
private static Binding bind(Thread thread) {
Binding binding = binding(thread);
if (binding != null) {
return binding;
}
binding = new Binding(thread);
if (!BINDINGS.compareAndSet(slot(thread), null, binding)) {
binding.overflow = true;
OVERFLOW.set(binding);
OVERFLOW_BINDINGS.incrementAndGet();
}
return binding;
}
private static void release(Binding binding) {
binding.context = null;
if (binding.overflow) {
OVERFLOW.remove();
OVERFLOW_BINDINGS.decrementAndGet();
return;
}
BINDINGS.compareAndSet(slot(binding.owner), binding, null);
}
private static int slot(Thread thread) {
return (int) thread.threadId() & (SLOTS - 1);
}
public static final class Scope implements NativeGenerationScope {
private final Thread owner;
private final IrisContext previous;
@@ -119,16 +162,26 @@ public final class IrisContext {
if (Thread.currentThread() != owner) {
throw new IllegalStateException("Iris execution context scope closed from a different thread.");
}
IrisContext current = CONTEXT.get();
if (current != installed) {
Binding binding = binding(owner);
if (binding == null || binding.context != installed) {
throw new IllegalStateException("Iris execution context scopes must close in LIFO order.");
}
if (previous == null) {
CONTEXT.remove();
release(binding);
} else {
CONTEXT.set(previous);
binding.context = previous;
}
closed = true;
}
}
private static final class Binding {
private final Thread owner;
private boolean overflow;
private IrisContext context;
private Binding(Thread owner) {
this.owner = owner;
}
}
}
@@ -22,6 +22,9 @@ public class IrisHydrology {
@Description("Fraction of eligible water features to keep after local placement probabilities. 0.5 keeps half the candidate river sources, ponds, lakes and underground water features without changing their configured sizes.")
private double density = 1D;
@Description("Wet and dry zones that decide where streams and ponds gather. Within a wet zone the configured density applies unchanged.")
private IrisHydrologyClimate climate = new IrisHydrologyClimate();
@Description("How water drains across the terrain before rivers and ponds are placed.")
private IrisHydrologyDrainage drainage = new IrisHydrologyDrainage();
@@ -0,0 +1,37 @@
package art.arcane.iris.generation.hydrology.config;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.volmlib.util.documentation.Description;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Wet and dry zones across the dimension. A noise field splits the land into zones: wet zones keep the rainfall and pond density of their biome, dry zones lose them. Streams and ponds then cluster in the wet zones instead of reaching every hill, and a river that rises in a wet zone still flows on through dry land.")
@Data
public class IrisHydrologyClimate {
@Description("Turns wet and dry zones on. When off, rainfall and pond density follow the hydrology policies alone.")
private boolean enabled = false;
@Description("Noise that lays out the zones. Land where its value is below dryness is dry. A larger zoom makes larger zones.")
private IrisGeneratorStyle style = NoiseStyle.SIMPLEX.style().zoomed(24D);
@MinNumber(0)
@MaxNumber(1)
@Description("Noise value below which land is dry. 0 keeps all land wet, and higher values dry out more of it.")
private double dryness = 0.5D;
@MinNumber(0)
@MaxNumber(1)
@Description("Width of the noise band over which rainfall fades from dry to wet. 0 gives sharp zone edges.")
private double transition = 0.1D;
@MinNumber(0)
@MaxNumber(1)
@Description("Share of the area's rainfall and pond density kept in dry zones. 0 lets dry zones start no streams or ponds of their own.")
private double dryRainfall = 0D;
}
@@ -24,12 +24,12 @@ public class IrisHydrologyDeformation {
@MinNumber(0)
@MaxNumber(16)
@Description("How much steeper banks become on steep terrain.")
@Description("How much steeper a bank stays where the natural ground between it and the water is steep.")
private double bankSteepFactor = 3.5D;
@MinNumber(0)
@MaxNumber(2)
@Description("Strength of the noise that roughens bank edges.")
@Description("Strength of the smooth noise that roughens bank edges.")
private double bankNoise = 0.2D;
@Description("Keeps caves from opening under water, so rivers and ponds never drain into them.")
@@ -31,13 +31,16 @@ public class IrisHydrologyPolicy {
@Description("Multiplier on how many ponds form in this area. With no value set anywhere it is 1.")
private Double pondDensity = null;
@Description("Whether the dimension's wet and dry zones apply in this area. false keeps this area's full rainfall and pond density even inside a dry zone. With no value set anywhere they apply.")
private Boolean climateZones = null;
@Description("Whether streams and rivers may form in this area. With no value set anywhere they are allowed.")
private IrisHydrologyPermission streams = null;
@Description("Whether ponds may form in this area. With no value set anywhere they are allowed.")
private IrisHydrologyPermission ponds = null;
@Description("Name of a fluid profile that fills ponds and lakes whose floor lies in this area, instead of the ponds' own fluid. Channels always use the fluid of their tier.")
@Description("Name of a fluid profile that fills the water in this area instead of its usual fluid: ponds and lakes whose floor lies here, and every stretch of stream or river that flows through here.")
private String fluid = null;
@RegistryListResource(IrisBiome.class)
@@ -1,53 +0,0 @@
package art.arcane.iris.generation.hydrology.engine;
import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.HydrologyTerrainSource;
import java.util.Objects;
final class FineLatticeSource implements HydrologyTerrainSource {
private final HeightLattice fine;
private final HydrologyTerrainSource terrain;
FineLatticeSource(HeightLattice fine, HydrologyTerrainSource terrain) {
this.fine = Objects.requireNonNull(fine, "fine");
this.terrain = Objects.requireNonNull(terrain, "terrain");
}
@Override
public void sample(int[] xs, int[] zs, HydrologySampleBuffer out, boolean baseOnly) {
if (baseOnly) {
throw new IllegalArgumentException("The fine lattice holds natural heights only");
}
if (xs.length != zs.length) {
throw new IllegalArgumentException("Fine lattice read has " + xs.length + " x and " + zs.length + " z coordinates");
}
int cell = fine.cell();
int[] cellXs = new int[xs.length];
int[] cellZs = new int[zs.length];
for (int index = 0; index < xs.length; index++) {
if (Math.floorMod(xs[index], cell) != 0 || Math.floorMod(zs[index], cell) != 0) {
throw new IllegalArgumentException("Column " + xs[index] + "," + zs[index] + " is not a node of the " + cell + "-block fine lattice");
}
cellXs[index] = Math.floorDiv(xs[index], cell);
cellZs[index] = Math.floorDiv(zs[index], cell);
}
fine.fill(cellXs, cellZs, out);
}
@Override
public int seaLevel() {
return terrain.seaLevel();
}
@Override
public int minY() {
return terrain.minY();
}
@Override
public int maxY() {
return terrain.maxY();
}
}
@@ -11,23 +11,21 @@ import art.arcane.iris.generation.hydrology.water.ReachShaper;
import java.util.Objects;
public record HydrologyPlanners(RegionPlanner regions, WindowPlanner windows, HeightLattice windowLattice) {
public record HydrologyPlanners(RegionPlanner regions, WindowPlanner windows, HeightLattice fineLattice) {
public HydrologyPlanners {
Objects.requireNonNull(regions, "regions");
Objects.requireNonNull(windows, "windows");
Objects.requireNonNull(windowLattice, "windowLattice");
Objects.requireNonNull(fineLattice, "fineLattice");
}
public static HydrologyPlanners create(HydrologySettings settings, HydrologyTerrainSource source) {
Objects.requireNonNull(settings, "settings");
Objects.requireNonNull(source, "source");
HeightLattice fine = new HeightLattice(source, WindowPlanner.FINE_CELL, false, HydrologyPlanCache.FINE_LATTICE_CELLS);
HeightLattice window = new HeightLattice(new FineLatticeSource(fine, source), WindowPlanner.CELL, false,
HydrologyPlanCache.WINDOW_LATTICE_CELLS);
PondPlanner ponds = new PondPlanner(settings);
ReachShaper shaper = new ReachShaper(settings);
RegionPlanner regions = new RegionPlanner(settings,
new HeightLattice(source, RegionPlanner.CELL, true, HydrologyPlanCache.REGION_LATTICE_CELLS), fine, ponds, shaper);
return new HydrologyPlanners(regions, new WindowPlanner(settings, window, fine, ponds, shaper), window);
return new HydrologyPlanners(regions, new WindowPlanner(settings, fine, ponds, shaper), fine);
}
}
@@ -18,6 +18,12 @@ public final class HydrologyPregeneration implements AutoCloseable {
}
}
public synchronized void bound(int minRegionX, int minRegionZ, int maxRegionX, int maxRegionZ) {
if (!closed) {
runtime.boundPregeneration(epoch, minRegionX, minRegionZ, maxRegionX, maxRegionZ);
}
}
@Override
public synchronized void close() {
if (!closed) {
@@ -14,8 +14,10 @@ import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.ChannelFluids;
import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.NaturalHeights;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
@@ -36,6 +38,7 @@ import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -50,13 +53,12 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.LongSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;
public final class HydrologyRuntime {
private static final int RASTER_CAPACITY = 1024;
private static final int RASTER_CAPACITY = 8192;
private static final int KEEP_SCOPES = 2;
private static final int CHUNKS_PER_WINDOW = WindowKey.SIZE >> 4;
public static final int MAX_PREGENERATION_REGIONS = 4096;
@@ -67,16 +69,18 @@ public final class HydrologyRuntime {
private final HydrologySettings settings;
private final HydrologyPlanCache cache;
private final ChunkRasterizer rasterizer;
private final IntBinaryOperator naturalHeight;
private final NaturalHeights naturalHeight;
private final BooleanSupplier mainThread;
private final RasterLru rasters;
private final ThreadLocal<LastRaster> last;
private final Set<Long> queued;
private final ConcurrentHashMap<Long, CompletableFuture<ChunkWaterRaster>> building;
private final RasterFailures failures;
private final RasterFailures windowPreviewFailures;
private final RasterFailures regionPreviewFailures;
private final Set<Object> previews;
private final LinkedHashMap<WindowKey, WindowPrefetch> prefetches;
private final Map<Object, PregenArea> pregenAreas;
private final HydrologyBinding binding;
private final Function<PreparedHydrologyCacheIdentity, HydrologyPlanStore> stores;
private final boolean caveFluidPolicies;
@@ -94,37 +98,41 @@ public final class HydrologyRuntime {
this.rasters = null;
this.last = null;
this.queued = null;
this.building = null;
this.failures = null;
this.windowPreviewFailures = null;
this.regionPreviewFailures = null;
this.previews = null;
this.prefetches = null;
this.pregenAreas = null;
this.binding = HydrologyBinding.UNBOUND;
this.stores = identity -> null;
this.caveFluidPolicies = false;
}
public HydrologyRuntime(HydrologySettings settings, HydrologyPlanCache cache, IntBinaryOperator naturalHeight,
public HydrologyRuntime(HydrologySettings settings, HydrologyPlanCache cache, NaturalHeights naturalHeight,
BooleanSupplier mainThread, LongSupplier ticker) {
this(settings, cache, naturalHeight, mainThread, ticker, HydrologyBinding.UNBOUND, identity -> null, false);
this(settings, cache, naturalHeight, ChannelFluids.TIER, mainThread, ticker, HydrologyBinding.UNBOUND, identity -> null, false);
}
private HydrologyRuntime(HydrologySettings settings, HydrologyPlanCache cache, IntBinaryOperator naturalHeight,
BooleanSupplier mainThread, LongSupplier ticker, HydrologyBinding binding,
private HydrologyRuntime(HydrologySettings settings, HydrologyPlanCache cache, NaturalHeights naturalHeight,
ChannelFluids channelFluids, BooleanSupplier mainThread, LongSupplier ticker, HydrologyBinding binding,
Function<PreparedHydrologyCacheIdentity, HydrologyPlanStore> stores, boolean caveFluidPolicies) {
this.settings = Objects.requireNonNull(settings, "settings");
this.cache = Objects.requireNonNull(cache, "cache");
this.rasterizer = new ChunkRasterizer(settings);
this.rasterizer = new ChunkRasterizer(settings, channelFluids);
this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight");
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
this.rasters = new RasterLru();
this.last = ThreadLocal.withInitial(LastRaster::new);
this.queued = ConcurrentHashMap.newKeySet();
this.building = new ConcurrentHashMap<>();
this.failures = new RasterFailures(ticker);
this.windowPreviewFailures = new RasterFailures(ticker);
this.regionPreviewFailures = new RasterFailures(ticker);
this.previews = new HashSet<>();
this.prefetches = new LinkedHashMap<>(PREFETCH_CAPACITY * 2, 0.75f, true);
this.pregenAreas = new HashMap<>();
this.binding = Objects.requireNonNull(binding, "binding");
this.stores = Objects.requireNonNull(stores, "stores");
this.caveFluidPolicies = caveFluidPolicies;
@@ -153,7 +161,7 @@ public final class HydrologyRuntime {
HydrologyPlanCache cache = HydrologyPlanCache.create(settings, planners.regions(), planners.windows(), MultiBurst.hydrology, mainThread);
String dimensionKey = dimension.getLoadKey();
IrisWorld world = engine.getWorld();
return new HydrologyRuntime(settings, cache, source::naturalHeight, mainThread, System::nanoTime, binding,
return new HydrologyRuntime(settings, cache, source::naturalSurface, source, mainThread, System::nanoTime, binding,
identity -> store(world, dimensionKey, settings, identity), caveFluidPolicies);
}
@@ -234,7 +242,7 @@ public final class HydrologyRuntime {
requireOpen();
long key = key(chunkX, chunkZ);
ChunkWaterRaster known = remembered(key, slot);
return known != null ? known : remember(key, planned(chunkX, chunkZ, key));
return known != null ? known : build(chunkX, chunkZ, key, slot);
}
public ChunkWaterRaster rasterSnapshot(int chunkX, int chunkZ) {
@@ -354,8 +362,28 @@ public final class HydrologyRuntime {
}
}
void boundPregeneration(Object epoch, int minRegionX, int minRegionZ, int maxRegionX, int maxRegionZ) {
Objects.requireNonNull(epoch, "epoch");
if (maxRegionX < minRegionX || maxRegionZ < minRegionZ) {
throw new IllegalArgumentException("Invalid pregeneration bounds " + minRegionX + "," + minRegionZ + " to " + maxRegionX + ","
+ maxRegionZ);
}
if (cache == null) {
return;
}
synchronized (prefetches) {
pregenAreas.put(epoch, new PregenArea(minRegionX - 1, minRegionZ - 1, maxRegionX + 1, maxRegionZ + 1));
prefetches.clear();
}
}
void cancelPregeneration(Object epoch) {
if (cache != null) {
synchronized (prefetches) {
if (pregenAreas.remove(epoch) != null) {
prefetches.clear();
}
}
cache.cancel(epoch);
}
}
@@ -501,6 +529,41 @@ public final class HydrologyRuntime {
}
}
private ChunkWaterRaster build(int chunkX, int chunkZ, long key, LastRaster slot) {
CompletableFuture<ChunkWaterRaster> claim = new CompletableFuture<>();
CompletableFuture<ChunkWaterRaster> running = building.putIfAbsent(key, claim);
if (running != null) {
ChunkWaterRaster built = built(running);
slot.remember(key, built);
return built;
}
try {
ChunkWaterRaster known = remembered(key, slot);
ChunkWaterRaster raster = known != null ? known : remember(key, planned(chunkX, chunkZ, key));
claim.complete(raster);
return raster;
} catch (RuntimeException | Error failure) {
claim.completeExceptionally(failure);
throw failure;
} finally {
building.remove(key, claim);
}
}
private static ChunkWaterRaster built(CompletableFuture<ChunkWaterRaster> running) {
try {
return running.join();
} catch (CompletionException failure) {
if (failure.getCause() instanceof RuntimeException cause) {
throw cause;
}
if (failure.getCause() instanceof Error cause) {
throw cause;
}
throw failure;
}
}
private ChunkWaterRaster planned(int chunkX, int chunkZ, long chunk) {
try {
List<WindowKey> windowKeys = neighbourhood(chunkX, chunkZ);
@@ -667,7 +730,7 @@ public final class HydrologyRuntime {
&& (!known.prepared().isDone() || known.evictions() == evictions)) {
return;
}
CompletableFuture<Void> prepared = cache.prepareWindowsAround(chunkX, chunkZ, chunkX, chunkZ, 1 + settings.prefetchRings());
CompletableFuture<Void> prepared = prepareAround(chunkX, chunkZ, owner, 1 + settings.prefetchRings());
prefetches.put(owner, new WindowPrefetch(prepared, evictions));
if (prefetches.size() > PREFETCH_CAPACITY) {
prefetches.pollFirstEntry();
@@ -675,6 +738,24 @@ public final class HydrologyRuntime {
}
}
private CompletableFuture<Void> prepareAround(int chunkX, int chunkZ, WindowKey owner, int rings) {
PregenArea covering = null;
for (PregenArea area : pregenAreas.values()) {
if (area.contains(owner)) {
covering = covering == null ? area : covering.union(area);
}
}
if (covering == null) {
return cache.prepareWindowsAround(chunkX, chunkZ, chunkX, chunkZ, rings);
}
int minX = Math.max(owner.wx() - rings, covering.minX());
int minZ = Math.max(owner.wz() - rings, covering.minZ());
int maxX = Math.min(owner.wx() + rings, covering.maxX());
int maxZ = Math.min(owner.wz() + rings, covering.maxZ());
return cache.prepareWindowsAround(minX * CHUNKS_PER_WINDOW, minZ * CHUNKS_PER_WINDOW, (maxX + 1) * CHUNKS_PER_WINDOW - 1,
(maxZ + 1) * CHUNKS_PER_WINDOW - 1, 0);
}
private static List<WindowKey> neighbourhood(int chunkX, int chunkZ) {
WindowKey own = WindowKey.containing(chunkX << 4, chunkZ << 4);
List<WindowKey> keys = new ArrayList<>(9);
@@ -754,6 +835,16 @@ public final class HydrologyRuntime {
private record WindowPrefetch(CompletableFuture<Void> prepared, long evictions) {
}
private record PregenArea(int minX, int minZ, int maxX, int maxZ) {
private boolean contains(WindowKey key) {
return key.wx() > minX && key.wx() < maxX && key.wz() > minZ && key.wz() < maxZ;
}
private PregenArea union(PregenArea other) {
return new PregenArea(Math.min(minX, other.minX), Math.min(minZ, other.minZ), Math.max(maxX, other.maxX), Math.max(maxZ, other.maxZ));
}
}
private static final class LastRaster {
private long key;
private ChunkWaterRaster raster;
@@ -7,11 +7,13 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.HydrologyTerrainSource;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.raster.ChannelFluids;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.studio.generation.BiomeBuffetLayout;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import java.util.ArrayList;
@@ -25,9 +27,10 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource {
public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource, ChannelFluids {
private static final int MINIMUM_SLICE = 256;
private static final int POLICY_CAPACITY = 4096;
private static final long SALT_CLIMATE = 0x434c494d415445L;
private final IrisComplex complex;
private final IrisDimension dimension;
@@ -40,6 +43,8 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource
private final BiomeBuffetLayout buffet;
private final IrisBiome focus;
private final HydrologyBinding binding;
private final HydrologySettings.Climate climate;
private final CNG wetness;
private final ConcurrentHashMap<PolicyKey, Policy> policies = new ConcurrentHashMap<>();
public IrisHydrologyTerrainSource(IrisComplex complex, IrisDimension dimension, HydrologySettings settings, ExecutorService pool,
@@ -55,6 +60,8 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource
this.buffet = complex.getBiomeBuffet();
this.focus = complex.getFocusBiome();
this.binding = Objects.requireNonNull(binding, "binding");
this.climate = settings.climate();
this.wetness = climate.enabled() ? climate.style().create(settings.seed() ^ SALT_CLIMATE, complex.getData()) : null;
}
@Override
@@ -73,8 +80,13 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource
}
}
public int naturalHeight(int x, int z) {
return complex.naturalTrueHeight(x, z);
public double naturalSurface(int x, int z) {
return complex.naturalHeight(x, z);
}
@Override
public String channelFluid(int x, int z) {
return policy(biomes.get(x, z), regions.get(x, z)).fluid();
}
@Override
@@ -150,12 +162,17 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource
Policy policy = policy(biomes.get(x, z), regions.get(x, z));
out.height()[index] = (float) height;
out.ocean()[index] = StrictMath.round(height) < settings.seaLevel() && oceanIntent(x, z);
out.rainfall()[index] = policy.rainfall();
out.pondDensity()[index] = policy.pondDensity();
float wet = policy.climateZones() ? wetness(x, z) : 1f;
out.rainfall()[index] = policy.rainfall() * wet;
out.pondDensity()[index] = policy.pondDensity() * wet;
out.permission()[index] = policy.permission();
out.fluidProfile()[index] = policy.fluid();
}
private float wetness(int x, int z) {
return wetness == null ? 1f : (float) climate.wetness(wetness.noise(x, z));
}
private boolean oceanIntent(int x, int z) {
BiomeBuffetLayout.Cell cell = buffet == null ? null : buffet.terrain(x, z);
IrisBiome focused = cell == null ? focus : cell.biome();
@@ -183,13 +200,14 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource
IrisHydrologyPermission streams = inherited(biome, region, IrisHydrologyPolicy::getStreams, IrisHydrologyPermission.ALLOW);
IrisHydrologyPermission ponds = inherited(biome, region, IrisHydrologyPolicy::getPonds, IrisHydrologyPermission.ALLOW);
String fluid = inherited(biome, region, IrisHydrologyPolicy::getFluid, null);
boolean climateZones = inherited(biome, region, IrisHydrologyPolicy::getClimateZones, Boolean.TRUE);
requireMultiplier("rainfall", rainfall, biome, region);
requireMultiplier("pondDensity", pondDensity, biome, region);
if (fluid != null && !settings.fluids().containsKey(fluid)) {
throw new IllegalArgumentException("Hydrology policy for " + where(biome, region) + " names fluid '" + fluid
+ "', which is not one of the hydrology fluids " + settings.fluids().keySet());
}
return new Policy((float) rainfall, (float) pondDensity, permission(streams, ponds), fluid);
return new Policy((float) rainfall, (float) pondDensity, permission(streams, ponds), fluid, climateZones);
}
private <T> T inherited(IrisBiome biome, IrisRegion region, Function<IrisHydrologyPolicy, T> field, T fallback) {
@@ -214,7 +232,7 @@ public final class IrisHydrologyTerrainSource implements HydrologyTerrainSource
return "biome " + (biome == null ? "none" : biome.getLoadKey()) + " in region " + (region == null ? "none" : region.getLoadKey());
}
private record Policy(float rainfall, float pondDensity, byte permission, String fluid) {
private record Policy(float rainfall, float pondDensity, byte permission, String fluid, boolean climateZones) {
}
private record PolicyKey(IrisBiome biome, IrisRegion region) {
@@ -1,34 +1,59 @@
package art.arcane.iris.generation.hydrology.grid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReferenceArray;
public final class HeightLattice {
private static final int TILE_SHIFT = 5;
private static final int COLUMN_TILE_SHIFT = 3;
private static final int COLUMN_CELLS = 1 << 20;
private static final CompletableFuture<Void> READY = CompletableFuture.completedFuture(null);
private static final int[] NO_NODES = new int[0];
private static final Tile[] NO_TILES = new Tile[0];
private final HydrologyTerrainSource source;
private final int cell;
private final boolean baseOnly;
private final int capacityCells;
private final ConcurrentHashMap<Long, Slot> cells;
private final ConcurrentLinkedQueue<Long> insertionOrder;
private final int tileShift;
private final int tileMask;
private final int tileCells;
private final int capacityTiles;
private final ConcurrentHashMap<Long, Tile> tiles;
private final AtomicLong clock;
private final AtomicBoolean evicting;
private final HeightLattice columns;
public HeightLattice(HydrologyTerrainSource source, int cell, boolean baseOnly, int capacityCells) {
this(source, cell, baseOnly, capacityCells, TILE_SHIFT, new HeightLattice(source, 1, baseOnly, COLUMN_CELLS, COLUMN_TILE_SHIFT, null));
}
private HeightLattice(HydrologyTerrainSource source, int cell, boolean baseOnly, int capacityCells, int tileShift, HeightLattice columns) {
if (cell <= 0 || capacityCells <= 0) {
throw new IllegalArgumentException("Invalid lattice cell=" + cell + " capacityCells=" + capacityCells);
}
this.source = Objects.requireNonNull(source, "source");
this.cell = cell;
this.baseOnly = baseOnly;
this.capacityCells = capacityCells;
this.cells = new ConcurrentHashMap<>();
this.insertionOrder = new ConcurrentLinkedQueue<>();
this.tileShift = tileShift;
this.tileMask = (1 << tileShift) - 1;
this.tileCells = 1 << (2 * tileShift);
this.capacityTiles = Math.ceilDiv(capacityCells, tileCells);
this.tiles = new ConcurrentHashMap<>();
this.clock = new AtomicLong();
this.evicting = new AtomicBoolean();
this.columns = columns;
}
public int cell() {
@@ -67,19 +92,24 @@ public final class HeightLattice {
throw new IllegalArgumentException("Column sample has " + xs.length + " x and " + zs.length + " z coordinates");
}
requireCapacity(out, xs.length);
if (xs.length > 0) {
source.sample(xs, zs, out, baseOnly);
if (xs.length == 0) {
return;
}
if (columns == null) {
source.sample(xs, zs, out, baseOnly);
return;
}
columns.resolve(new Scatter(xs, zs), xs.length, out);
}
private void resolve(Nodes nodes, int count, HydrologySampleBuffer out) {
Slot[] slots = new Slot[count];
int unresolved = count;
while (unresolved > 0) {
CompletableFuture<HydrologySampleBuffer> batch = claimAndSample(nodes, slots);
unresolved = awaitForeign(batch, slots);
Pass pass = new Pass(nodes, out, clock.incrementAndGet());
int[] open = null;
int remaining = count;
while (remaining > 0) {
open = pass.run(open, remaining);
remaining = open == null ? 0 : open.length;
}
copy(slots, out);
evictOverflow();
}
@@ -94,130 +124,33 @@ public final class HeightLattice {
Math.multiplyExact(Math.addExact(cell0, Math.multiplyExact(extent - 1, stride)), cell);
}
private CompletableFuture<HydrologySampleBuffer> claimAndSample(Nodes nodes, Slot[] slots) {
CompletableFuture<HydrologySampleBuffer> batch = new CompletableFuture<>();
try {
int[] xs = new int[slots.length];
int[] zs = new int[slots.length];
int claimed = claim(batch, nodes, slots, xs, zs);
if (claimed > 0) {
HydrologySampleBuffer samples = new HydrologySampleBuffer(claimed);
source.sample(Arrays.copyOf(xs, claimed), Arrays.copyOf(zs, claimed), samples, baseOnly);
batch.complete(samples);
}
} catch (Throwable failure) {
try {
release(batch, nodes, slots);
} finally {
batch.completeExceptionally(failure);
}
throw failure;
}
return batch;
}
private int claim(CompletableFuture<HydrologySampleBuffer> batch, Nodes nodes, Slot[] slots, int[] xs, int[] zs) {
int claimed = 0;
for (int index = 0; index < slots.length; index++) {
if (slots[index] != null) {
continue;
}
int cellX = nodes.cellX(index);
int cellZ = nodes.cellZ(index);
Long key = key(cellX, cellZ);
Slot existing = cells.get(key);
if (existing == null) {
Slot fresh = new Slot(batch, claimed);
existing = cells.putIfAbsent(key, fresh);
if (existing == null) {
slots[index] = fresh;
insertionOrder.offer(key);
xs[claimed] = cellX * cell;
zs[claimed] = cellZ * cell;
claimed++;
continue;
}
}
slots[index] = existing;
}
return claimed;
}
private void release(CompletableFuture<HydrologySampleBuffer> batch, Nodes nodes, Slot[] slots) {
for (int index = 0; index < slots.length; index++) {
Slot slot = slots[index];
if (slot != null && slot.batch() == batch) {
cells.remove(key(nodes.cellX(index), nodes.cellZ(index)), slot);
}
}
}
private static int awaitForeign(CompletableFuture<HydrologySampleBuffer> own, Slot[] slots) {
int unresolved = 0;
for (int index = 0; index < slots.length; index++) {
CompletableFuture<HydrologySampleBuffer> batch = slots[index].batch();
if (batch != own && !await(batch)) {
slots[index] = null;
unresolved++;
}
}
return unresolved;
}
private static boolean await(CompletableFuture<HydrologySampleBuffer> batch) {
if (!batch.isDone()) {
try {
batch.get();
} catch (ExecutionException | CancellationException failure) {
return false;
} catch (InterruptedException interruption) {
Thread.currentThread().interrupt();
throw new CancellationException("Hydrology lattice wait interrupted.");
}
}
return !batch.isCompletedExceptionally();
}
private static void copy(Slot[] slots, HydrologySampleBuffer out) {
float[] height = out.height();
boolean[] ocean = out.ocean();
float[] rainfall = out.rainfall();
float[] pondDensity = out.pondDensity();
byte[] permission = out.permission();
String[] fluidProfile = out.fluidProfile();
for (int index = 0; index < slots.length; index++) {
Slot slot = slots[index];
HydrologySampleBuffer samples = slot.batch().join();
int sample = slot.index();
height[index] = samples.height()[sample];
ocean[index] = samples.ocean()[sample];
rainfall[index] = samples.rainfall()[sample];
pondDensity[index] = samples.pondDensity()[sample];
permission[index] = samples.permission()[sample];
fluidProfile[index] = samples.fluidProfile()[sample];
private Tile tile(int tileX, int tileZ) {
Long key = key(tileX, tileZ);
Tile known = tiles.get(key);
if (known != null) {
return known;
}
return tiles.computeIfAbsent(key, ignored -> new Tile(tileCells));
}
private void evictOverflow() {
if (cells.size() <= capacityCells || !evicting.compareAndSet(false, true)) {
if (tiles.size() <= capacityTiles || !evicting.compareAndSet(false, true)) {
return;
}
try {
int excess = cells.size() - capacityCells;
while (excess > 0) {
Long key = insertionOrder.poll();
if (key == null) {
return;
List<IdleTile> idle = new ArrayList<>(tiles.size());
for (Map.Entry<Long, Tile> entry : tiles.entrySet()) {
Tile tile = entry.getValue();
if (tile.pending.get() == 0) {
idle.add(new IdleTile(entry.getKey(), tile, tile.used));
}
Slot slot = cells.get(key);
if (slot == null) {
continue;
}
if (!slot.batch().isDone()) {
insertionOrder.offer(key);
excess--;
} else if (cells.remove(key, slot)) {
excess--;
}
idle.sort(Comparator.comparingLong(IdleTile::used));
int target = capacityTiles - (capacityTiles >> 3);
for (int index = 0; index < idle.size() && tiles.size() > target; index++) {
IdleTile candidate = idle.get(index);
if (candidate.tile().pending.get() == 0) {
tiles.remove(candidate.key(), candidate.tile());
}
}
} finally {
@@ -232,7 +165,219 @@ public final class HeightLattice {
return mixed ^ (mixed >>> 31);
}
private record Slot(CompletableFuture<HydrologySampleBuffer> batch, int index) {
private static boolean await(CompletableFuture<Void> batch) {
if (!batch.isDone()) {
try {
batch.get();
} catch (ExecutionException | CancellationException failure) {
return false;
} catch (InterruptedException interruption) {
Thread.currentThread().interrupt();
throw new CancellationException("Hydrology lattice wait interrupted.");
}
}
return !batch.isCompletedExceptionally();
}
private static void copy(HydrologySampleBuffer samples, int sample, HydrologySampleBuffer out, int index) {
out.height()[index] = samples.height()[sample];
out.ocean()[index] = samples.ocean()[sample];
out.rainfall()[index] = samples.rainfall()[sample];
out.pondDensity()[index] = samples.pondDensity()[sample];
out.permission()[index] = samples.permission()[sample];
out.fluidProfile()[index] = samples.fluidProfile()[sample];
}
private final class Pass {
private final Nodes nodes;
private final HydrologySampleBuffer out;
private final long stamp;
private int[] claimedIndex = NO_NODES;
private Tile[] claimedTile = NO_TILES;
private int[] claimedLocal = NO_NODES;
private int claimed;
private int[] waitingIndex = NO_NODES;
private Tile[] waitingTile = NO_TILES;
private int[] waitingLocal = NO_NODES;
private int waiting;
private Tile current;
private int currentX;
private int currentZ;
private Pass(Nodes nodes, HydrologySampleBuffer out, long stamp) {
this.nodes = nodes;
this.out = out;
this.stamp = stamp;
}
private int[] run(int[] open, int remaining) {
claimed = 0;
waiting = 0;
CompletableFuture<Void> batch = new CompletableFuture<>();
for (int position = 0; position < remaining; position++) {
visit(open == null ? position : open[position], batch);
}
if (claimed > 0) {
sample(batch);
}
return awaitWaiting();
}
private void visit(int index, CompletableFuture<Void> batch) {
int cellX = nodes.cellX(index);
int cellZ = nodes.cellZ(index);
Tile tile = tileOf(cellX >> tileShift, cellZ >> tileShift);
int local = ((cellZ & tileMask) << tileShift) | (cellX & tileMask);
while (true) {
CompletableFuture<Void> mark = tile.marks.get(local);
if (mark == READY) {
tile.copy(local, out, index);
return;
}
if (mark != null) {
addWaiting(index, tile, local);
return;
}
if (tile.marks.compareAndSet(local, null, batch)) {
tile.pending.incrementAndGet();
addClaimed(index, tile, local);
return;
}
}
}
private Tile tileOf(int tileX, int tileZ) {
if (current == null || currentX != tileX || currentZ != tileZ) {
current = tile(tileX, tileZ);
currentX = tileX;
currentZ = tileZ;
current.used = stamp;
}
return current;
}
private void sample(CompletableFuture<Void> batch) {
try {
int[] xs = new int[claimed];
int[] zs = new int[claimed];
for (int position = 0; position < claimed; position++) {
xs[position] = nodes.cellX(claimedIndex[position]) * cell;
zs[position] = nodes.cellZ(claimedIndex[position]) * cell;
}
HydrologySampleBuffer samples = new HydrologySampleBuffer(claimed);
source.sample(xs, zs, samples, baseOnly);
for (int position = 0; position < claimed; position++) {
Tile tile = claimedTile[position];
int local = claimedLocal[position];
tile.store(local, samples, position);
tile.marks.set(local, READY);
tile.pending.decrementAndGet();
copy(samples, position, out, claimedIndex[position]);
}
batch.complete(null);
} catch (Throwable failure) {
try {
release(batch);
} finally {
batch.completeExceptionally(failure);
}
throw failure;
}
}
private void release(CompletableFuture<Void> batch) {
for (int position = 0; position < claimed; position++) {
Tile tile = claimedTile[position];
if (tile.marks.compareAndSet(claimedLocal[position], batch, null)) {
tile.pending.decrementAndGet();
}
}
}
private int[] awaitWaiting() {
int[] open = null;
int unresolved = 0;
for (int position = 0; position < waiting; position++) {
Tile tile = waitingTile[position];
int local = waitingLocal[position];
CompletableFuture<Void> mark = tile.marks.get(local);
if (mark != READY && (mark == null || !await(mark) || tile.marks.get(local) != READY)) {
if (open == null) {
open = new int[waiting - position];
}
open[unresolved++] = waitingIndex[position];
continue;
}
tile.copy(local, out, waitingIndex[position]);
}
return open == null ? null : Arrays.copyOf(open, unresolved);
}
private void addClaimed(int index, Tile tile, int local) {
if (claimed == claimedIndex.length) {
int grown = Math.max(16, claimed * 2);
claimedIndex = Arrays.copyOf(claimedIndex, grown);
claimedTile = Arrays.copyOf(claimedTile, grown);
claimedLocal = Arrays.copyOf(claimedLocal, grown);
}
claimedIndex[claimed] = index;
claimedTile[claimed] = tile;
claimedLocal[claimed] = local;
claimed++;
}
private void addWaiting(int index, Tile tile, int local) {
if (waiting == waitingIndex.length) {
int grown = Math.max(16, waiting * 2);
waitingIndex = Arrays.copyOf(waitingIndex, grown);
waitingTile = Arrays.copyOf(waitingTile, grown);
waitingLocal = Arrays.copyOf(waitingLocal, grown);
}
waitingIndex[waiting] = index;
waitingTile[waiting] = tile;
waitingLocal[waiting] = local;
waiting++;
}
}
private static final class Tile {
private final float[] height;
private final boolean[] ocean;
private final float[] rainfall;
private final float[] pondDensity;
private final byte[] permission;
private final String[] fluidProfile;
private final AtomicReferenceArray<CompletableFuture<Void>> marks;
private final AtomicInteger pending = new AtomicInteger();
private volatile long used;
private Tile(int cells) {
this.height = new float[cells];
this.ocean = new boolean[cells];
this.rainfall = new float[cells];
this.pondDensity = new float[cells];
this.permission = new byte[cells];
this.fluidProfile = new String[cells];
this.marks = new AtomicReferenceArray<>(cells);
}
private void store(int local, HydrologySampleBuffer samples, int sample) {
height[local] = samples.height()[sample];
ocean[local] = samples.ocean()[sample];
rainfall[local] = samples.rainfall()[sample];
pondDensity[local] = samples.pondDensity()[sample];
permission[local] = samples.permission()[sample];
fluidProfile[local] = samples.fluidProfile()[sample];
}
private void copy(int local, HydrologySampleBuffer out, int index) {
out.height()[index] = height[local];
out.ocean()[index] = ocean[local];
out.rainfall()[index] = rainfall[local];
out.pondDensity()[index] = pondDensity[local];
out.permission()[index] = permission[local];
out.fluidProfile()[index] = fluidProfile[local];
}
}
private interface Nodes {
@@ -241,6 +386,9 @@ public final class HeightLattice {
int cellZ(int index);
}
private record IdleTile(Long key, Tile tile, long used) {
}
private record Span(int cellX0, int cellZ0, int width, int stride) implements Nodes {
@Override
public int cellX(int index) {
@@ -32,10 +32,10 @@ import java.util.function.Consumer;
import java.util.function.Function;
public final class HydrologyPlanCache {
private static final int FRONT = 3;
public static final int WINDOW_LATTICE_CELLS = frontCells(WindowKey.SIZE, WindowPlanner.CELL);
public static final int FINE_LATTICE_CELLS = frontCells(WindowKey.SIZE, WindowPlanner.FINE_CELL);
public static final int REGION_LATTICE_CELLS = frontCells(RegionKey.SIZE, RegionPlanner.CELL);
private static final int FINE_FRONT = 9;
private static final int REGION_FRONT = 5;
public static final int FINE_LATTICE_CELLS = frontCells(FINE_FRONT, WindowKey.SIZE, WindowPlanner.FINE_CELL);
public static final int REGION_LATTICE_CELLS = frontCells(REGION_FRONT, RegionKey.SIZE, RegionPlanner.CELL);
private static final int WINDOW_CAPACITY = 128;
private static final int REGION_CAPACITY = 64;
private static final long DEMAND = Long.MIN_VALUE;
@@ -312,8 +312,8 @@ public final class HydrologyPlanCache {
return Math.max(1, parallelism / 2);
}
private static int frontCells(int unit, int cell) {
int cells = (FRONT + 2) * unit / cell;
private static int frontCells(int front, int unit, int cell) {
int cells = (front + 2) * unit / cell;
return cells * cells;
}
@@ -5,6 +5,7 @@ import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.hydrology.config.IrisCavePools;
import art.arcane.iris.generation.hydrology.config.IrisFluidProfile;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyClimate;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyDeformation;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyDrainage;
@@ -20,6 +21,7 @@ import art.arcane.iris.generation.hydrology.config.IrisPondShore;
import art.arcane.iris.generation.hydrology.config.IrisSeaInlets;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import com.google.gson.Gson;
@@ -51,6 +53,7 @@ public final class HydrologySettings {
private final int maxY;
private final boolean enabled;
private final float density;
private final Climate climate;
private final Drainage drainage;
private final List<HydrologyTier> tiers;
private final Ponds ponds;
@@ -72,6 +75,7 @@ public final class HydrologySettings {
throw new IllegalArgumentException("Hydrology density must be within 0..1, got " + config.getDensity());
}
this.density = (float) config.getDensity();
this.climate = climate(config.getClimate());
this.drainage = drainage(config.getDrainage());
this.tiers = tiers(config.getTiers());
this.ponds = ponds(config.getPonds());
@@ -135,6 +139,10 @@ public final class HydrologySettings {
return density;
}
public Climate climate() {
return climate;
}
public Drainage drainage() {
return drainage;
}
@@ -167,6 +175,22 @@ public final class HydrologySettings {
return persist;
}
private static Climate climate(IrisHydrologyClimate config) {
Objects.requireNonNull(config, "Hydrology climate is missing");
IrisGeneratorStyle style = Objects.requireNonNull(config.getStyle(), "Hydrology climate.style is missing");
float dryness = unit(config.getDryness(), "climate.dryness");
float transition = unit(config.getTransition(), "climate.transition");
float dryRainfall = unit(config.getDryRainfall(), "climate.dryRainfall");
return new Climate(config.isEnabled(), style, dryness, transition, dryRainfall);
}
private static float unit(double value, String field) {
if (!Double.isFinite(value) || value < 0D || value > 1D) {
throw new IllegalArgumentException("Hydrology " + field + " must be within 0..1, got " + value);
}
return (float) value;
}
private static Drainage drainage(IrisHydrologyDrainage config) {
return new Drainage((float) config.getFillEpsilon(), config.getBreachDepth(), config.isWetnessThinning(),
(float) config.getMinimumHeadKeep(), (float) config.getHeadRelief(), (float) config.getSaturationCatchment());
@@ -468,6 +492,7 @@ public final class HydrologySettings {
private long computeFingerprint() {
Fingerprint hash = new Fingerprint().add(seed).add(seaLevel).add(minY).add(maxY).add(enabled)
.add(density).add(prefetchRings).add(persist);
addClimate(hash);
addDrainage(hash);
addTiers(hash);
addPonds(hash);
@@ -477,6 +502,12 @@ public final class HydrologySettings {
return hash.value();
}
private void addClimate(Fingerprint hash) {
if (climate.enabled()) {
hash.add(true).add(PALETTE_JSON.toJson(climate.style())).add(climate.dryness()).add(climate.transition()).add(climate.dryRainfall());
}
}
private void addDrainage(Fingerprint hash) {
hash.add(drainage.fillEpsilon()).add(drainage.breachDepth()).add(drainage.wetnessThinning())
.add(drainage.minimumHeadKeep()).add(drainage.headRelief()).add(drainage.saturationCatchment());
@@ -535,6 +566,23 @@ public final class HydrologySettings {
public record IntRange(int min, int max) {
}
public record Climate(boolean enabled, IrisGeneratorStyle style, float dryness, float transition, float dryRainfall) {
public double wetness(double noise) {
if (!enabled || dryness <= 0f) {
return 1D;
}
double half = 0.5D * transition;
double share;
if (half <= 0D) {
share = noise < dryness ? 0D : 1D;
} else {
double t = Math.clamp((noise - dryness + half) / transition, 0D, 1D);
share = t * t * (3D - 2D * t);
}
return dryRainfall + (1D - dryRainfall) * share;
}
}
public record Drainage(float fillEpsilon, int breachDepth, boolean wetnessThinning, float minimumHeadKeep, float headRelief,
float saturationCatchment) {
}
@@ -36,6 +36,7 @@ public final class WindowPlanner {
public static final int CELL = 8;
public static final int FINE_CELL = 4;
private static final int WINDOW_CELLS = WindowKey.SIZE / CELL;
private static final int FINE_STRIDE = CELL / FINE_CELL;
private static final int SPAN = 3 * WINDOW_CELLS;
private static final int REACH_OVERHANG = 256;
private static final float BASIN_DEPTH = 0.5f;
@@ -43,22 +44,17 @@ public final class WindowPlanner {
private static final long SALT_HEAD = 0x5354524541484dL;
private final HydrologySettings settings;
private final HeightLattice lattice;
private final HeightLattice fine;
private final PondPlanner ponds;
private final ReachShaper shaper;
private final SeaInletPlanner inlets;
public WindowPlanner(HydrologySettings settings, HeightLattice lattice, HeightLattice fine, PondPlanner ponds, ReachShaper shaper) {
public WindowPlanner(HydrologySettings settings, HeightLattice fine, PondPlanner ponds, ReachShaper shaper) {
this.settings = Objects.requireNonNull(settings, "settings");
this.lattice = Objects.requireNonNull(lattice, "lattice");
this.fine = Objects.requireNonNull(fine, "fine");
this.ponds = Objects.requireNonNull(ponds, "ponds");
this.shaper = Objects.requireNonNull(shaper, "shaper");
this.inlets = new SeaInletPlanner(settings);
if (lattice.cell() != CELL) {
throw new IllegalArgumentException("Window lattice cell " + lattice.cell() + " must be " + CELL);
}
if (fine.cell() != FINE_CELL) {
throw new IllegalArgumentException("Window fine lattice cell " + fine.cell() + " must be " + FINE_CELL);
}
@@ -87,7 +83,7 @@ public final class WindowPlanner {
int cellX = Math.multiplyExact(key.wx() - 1, WINDOW_CELLS);
int cellZ = Math.multiplyExact(key.wz() - 1, WINDOW_CELLS);
HydrologySampleBuffer samples = new HydrologySampleBuffer(SPAN * SPAN);
lattice.fill(cellX, cellZ, SPAN, SPAN, samples);
fine.fill(cellX * FINE_STRIDE, cellZ * FINE_STRIDE, SPAN, SPAN, FINE_STRIDE, samples);
DemGrid raw = new DemGrid(cellX * CELL, cellZ * CELL, CELL, SPAN, SPAN);
System.arraycopy(samples.height(), 0, raw.values(), 0, SPAN * SPAN);
List<Pond> lakes = regionLakes(plans.values());
@@ -6,6 +6,7 @@ final class BedProfile {
private static final long SALT_BROAD = 0x42454442524f4144L;
private static final long SALT_DETAIL = 0x4245444445544149L;
private static final long SALT_TEXTURE = 0x4245445445585455L;
private static final long SALT_ROUGHNESS = 0x42414e4b524f5547L;
private BedProfile() {
}
@@ -18,6 +19,10 @@ final class BedProfile {
return 0.35D * noise(seed, SALT_TEXTURE, x, z, 2);
}
static double roughness(long seed, int x, int z) {
return noise(seed, SALT_ROUGHNESS, x, z, 4) - 0.5D;
}
static double position(double u, double variation) {
double bounded = Math.clamp(u, 0D, 1D);
return bounded + 0.8D * variation * bounded * (1D - bounded);
@@ -0,0 +1,8 @@
package art.arcane.iris.generation.hydrology.raster;
@FunctionalInterface
public interface ChannelFluids {
ChannelFluids TIER = (x, z) -> null;
String channelFluid(int x, int z);
}
@@ -12,6 +12,7 @@ import art.arcane.iris.generation.hydrology.water.PondMask;
import art.arcane.iris.generation.hydrology.water.Reach;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -28,17 +29,20 @@ final class ChunkFeatures {
private final List<Pond> ponds;
private final List<Pond> lakes;
private final List<SeaInlet> inlets;
private final int[] inletBoxes;
private final int[] lakeBoxes;
private final ReachSegments segments = new ReachSegments(SEGMENT_CAPACITY);
private final MaskEdges pondShores = new MaskEdges(MaskEdges.Kind.WATER);
private final MaskEdges pondBanks = new MaskEdges(MaskEdges.Kind.BANK);
private final MaskEdges lakeReach = new MaskEdges(MaskEdges.Kind.GROWN_WATER);
private boolean inert;
private ChunkFeatures(List<Reach> reaches, List<Pond> ponds, List<Pond> lakes, List<SeaInlet> inlets) {
private ChunkFeatures(List<Reach> reaches, List<Pond> ponds, List<Pond> lakes, List<SeaInlet> inlets, int[] inletBoxes) {
this.reaches = reaches;
this.ponds = ponds;
this.lakes = lakes;
this.inlets = inlets;
this.inletBoxes = inletBoxes;
this.lakeBoxes = new int[4 * lakes.size()];
}
@@ -48,12 +52,15 @@ final class ChunkFeatures {
List<Reach> reaches = new ArrayList<>();
List<Pond> ponds = new ArrayList<>();
List<SeaInlet> inlets = new ArrayList<>();
int[] inletBoxes = new int[0];
for (IndexedWindow window : windows) {
for (SeaInlet inlet : window.plan().inlets()) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
int padding = RiffleProfile.RADIUS + 1;
if (bounds[0] <= chunkX * CHUNK + CHUNK - 1 + padding && bounds[2] >= chunkX * CHUNK - padding
&& bounds[1] <= chunkZ * CHUNK + CHUNK - 1 + padding && bounds[3] >= chunkZ * CHUNK - padding) {
inletBoxes = Arrays.copyOf(inletBoxes, inletBoxes.length + 4);
System.arraycopy(bounds, 0, inletBoxes, 4 * inlets.size(), 4);
inlets.add(inlet);
}
}
@@ -64,17 +71,22 @@ final class ChunkFeatures {
}
}
List<Pond> lakes = lakes(chunkX, chunkZ, halo, lakeRegionPlans, lakeRegions);
ChunkFeatures features = new ChunkFeatures(reaches, ponds, lakes, inlets);
ChunkFeatures features = new ChunkFeatures(reaches, ponds, lakes, inlets, inletBoxes);
features.index(settings, chunkX, chunkZ);
return features;
}
boolean empty() {
return reaches.isEmpty() && ponds.isEmpty() && lakes.isEmpty() && inlets.isEmpty();
boolean inert() {
return inert;
}
SeaInlet openInletAt(int x, int z, int[] column) {
for (SeaInlet inlet : inlets) {
for (int index = 0; index < inlets.size(); index++) {
int box = 4 * index;
if (x < inletBoxes[box] || z < inletBoxes[box + 1] || x > inletBoxes[box + 2] || z > inletBoxes[box + 3]) {
continue;
}
SeaInlet inlet = inlets.get(index);
if (SeaInletRasterizer.column(inlet, x, z, column) && column[1] == SeaInlet.OPEN) {
return inlet;
}
@@ -179,6 +191,8 @@ final class ChunkFeatures {
for (Reach reach : reaches) {
segments.addNear(reach, minX - 1f, minZ - 1f, maxX + 1f, maxZ + 1f, outward);
}
int riffle = RiffleProfile.RADIUS + 1;
segments.coverChannels(minX - riffle, minZ - riffle, maxX + riffle, maxZ + riffle);
HydrologySettings.PondShore shore = settings.ponds().shore();
int reach = Math.max(shore.taper(), ChunkWaterRaster.MAX_SHORE_DISTANCE) + 1;
int shelf = shore.shelf() + 1;
@@ -192,6 +206,39 @@ final class ChunkFeatures {
lakeReach.collect(mask, minX - shoreReach, minZ - shoreReach, maxX + shoreReach, maxZ + shoreReach);
System.arraycopy(grownBox(mask), 0, lakeBoxes, 4 * index, 4);
}
inert = segments.isEmpty() && !inletsTouch(minX - 1, minZ - 1, maxX + 1, maxZ + 1)
&& !pondsTouch(minX - 1 - reach, minZ - 1 - reach, maxX + 1 + reach, maxZ + 1 + reach)
&& !lakesTouch(minX - 2 - shoreReach, minZ - 2 - shoreReach, maxX + 2 + shoreReach, maxZ + 2 + shoreReach);
}
private boolean inletsTouch(int minX, int minZ, int maxX, int maxZ) {
for (int box = 0; box < inletBoxes.length; box += 4) {
if (inletBoxes[box] <= maxX && inletBoxes[box + 2] >= minX && inletBoxes[box + 1] <= maxZ && inletBoxes[box + 3] >= minZ) {
return true;
}
}
return false;
}
private boolean pondsTouch(int minX, int minZ, int maxX, int maxZ) {
for (Pond pond : ponds) {
PondMask mask = pond.mask();
int fromX = mask.originX() - (mask.step() >> 1);
int fromZ = mask.originZ() - (mask.step() >> 1);
if (fromX <= maxX && fromX + mask.width() * mask.step() > minX && fromZ <= maxZ && fromZ + mask.depth() * mask.step() > minZ) {
return true;
}
}
return false;
}
private boolean lakesTouch(int minX, int minZ, int maxX, int maxZ) {
for (int box = 0; box < lakeBoxes.length; box += 4) {
if (lakeBoxes[box] <= maxX && lakeBoxes[box + 2] > minX && lakeBoxes[box + 1] <= maxZ && lakeBoxes[box + 3] > minZ) {
return true;
}
}
return false;
}
private static Map<WindowKey, IndexedWindow> windowsByKey(int chunkX, int chunkZ, List<IndexedWindow> windows) {
@@ -8,17 +8,18 @@ import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import java.util.List;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
public final class ChunkRasterizer {
private static final int CHUNK = 16;
private static final int CANDIDATE_HALO = 48;
private final HydrologySettings settings;
private final ChannelFluids channelFluids;
private final int halo;
public ChunkRasterizer(HydrologySettings settings) {
public ChunkRasterizer(HydrologySettings settings, ChannelFluids channelFluids) {
this.settings = Objects.requireNonNull(settings, "settings");
this.channelFluids = Objects.requireNonNull(channelFluids, "channelFluids");
float widest = 0f;
for (HydrologyTier tier : settings.tiers()) {
widest = Math.max(widest, tier.maxHalfWidth());
@@ -33,13 +34,13 @@ public final class ChunkRasterizer {
chunkX * CHUNK + CHUNK - 1 + halo, chunkZ * CHUNK + CHUNK - 1 + halo);
}
public ChunkWaterRaster rasterize(int chunkX, int chunkZ, IntBinaryOperator naturalHeight, List<IndexedWindow> windows,
public ChunkWaterRaster rasterize(int chunkX, int chunkZ, NaturalHeights naturalHeight, List<IndexedWindow> windows,
List<RegionPlan> lakeRegionPlans) {
Objects.requireNonNull(naturalHeight, "naturalHeight");
ChunkFeatures features = ChunkFeatures.gather(settings, chunkX, chunkZ, halo, windows, lakeRegionPlans, lakeRegions(chunkX, chunkZ));
if (features.empty()) {
if (features.inert()) {
return ChunkWaterRaster.EMPTY;
}
return new RasterComposer(settings, features, chunkX, chunkZ).compose(naturalHeight);
return new RasterComposer(settings, features, channelFluids, chunkX, chunkZ).compose(naturalHeight);
}
}
@@ -2,6 +2,8 @@ package art.arcane.iris.generation.hydrology.raster;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import java.util.Arrays;
public final class ChunkWaterRaster {
public static final int MAX_SHORE_DISTANCE = 32;
public static final ChunkWaterRaster PROVISIONAL = new ChunkWaterRaster(true);
@@ -13,10 +15,13 @@ public final class ChunkWaterRaster {
private final int[] terrain;
private final int[] head;
private final byte[] role;
private final HydrologyTier[] tier;
private final long[] featureId;
private final String[] fluid;
private final int[] caveCeiling;
private final byte[] tier;
private final HydrologyTier[] tiers;
private final byte[] feature;
private final long[] features;
private final byte[] fluid;
private final String[] fluids;
private final boolean caveMask;
private final byte[] shoreDistance;
private ChunkWaterRaster(boolean provisional) {
@@ -25,26 +30,32 @@ public final class ChunkWaterRaster {
this.head = null;
this.role = null;
this.tier = null;
this.featureId = null;
this.tiers = null;
this.feature = null;
this.features = null;
this.fluid = null;
this.caveCeiling = null;
this.fluids = null;
this.caveMask = false;
this.shoreDistance = null;
}
ChunkWaterRaster(int[] terrain, int[] head, byte[] role, HydrologyTier[] tier, long[] featureId, String[] fluid, int[] caveCeiling,
byte[] shoreDistance) {
if (terrain.length != COLUMNS || head.length != COLUMNS || role.length != COLUMNS || tier.length != COLUMNS
|| featureId.length != COLUMNS || fluid.length != COLUMNS || caveCeiling.length != COLUMNS || shoreDistance.length != COLUMNS) {
ChunkWaterRaster(int[] terrain, int[] head, byte[] role, Palette<HydrologyTier> tiers, LongPalette features, Palette<String> fluids,
boolean caveMask, byte[] shoreDistance) {
if (terrain.length != COLUMNS || head.length != COLUMNS || role.length != COLUMNS || tiers.indices.length != COLUMNS
|| features.indices.length != COLUMNS || fluids.indices.length != COLUMNS || shoreDistance.length != COLUMNS) {
throw new IllegalArgumentException("A chunk water raster needs " + COLUMNS + " entries per array");
}
this.provisional = false;
this.terrain = terrain;
this.head = head;
this.role = role;
this.tier = tier;
this.featureId = featureId;
this.fluid = fluid;
this.caveCeiling = caveCeiling;
this.tier = tiers.indices;
this.tiers = tiers.values();
this.feature = features.indices;
this.features = features.values();
this.fluid = fluids.indices;
this.fluids = fluids.values();
this.caveMask = caveMask;
this.shoreDistance = shoreDistance;
}
@@ -68,22 +79,22 @@ public final class ChunkWaterRaster {
public HydrologyTier tier(int lx, int lz) {
int index = index(lx, lz);
return tier == null ? null : tier[index];
return tier == null ? null : tiers[tier[index] & 0xFF];
}
public long featureId(int lx, int lz) {
int index = index(lx, lz);
return featureId == null ? 0L : featureId[index];
return feature == null ? 0L : features[feature[index] & 0xFF];
}
public String fluid(int lx, int lz) {
int index = index(lx, lz);
return fluid == null ? null : fluid[index];
return fluid == null ? null : fluids[fluid[index] & 0xFF];
}
public int caveCeiling(int lx, int lz) {
int index = index(lx, lz);
return caveCeiling == null ? Integer.MAX_VALUE : caveCeiling[index];
return caveMask && head[index] != Integer.MIN_VALUE ? terrain[index] - 1 : Integer.MAX_VALUE;
}
public int shoreDistance(int lx, int lz) {
@@ -105,4 +116,53 @@ public final class ChunkWaterRaster {
}
return lz << 4 | lx;
}
static final class Palette<T> {
private final byte[] indices = new byte[COLUMNS];
private final T[] seen;
private int size;
Palette(T[] seen) {
if (seen.length != COLUMNS) {
throw new IllegalArgumentException("A raster palette needs room for " + COLUMNS + " values");
}
this.seen = seen;
}
void set(int column, T value) {
int found = 0;
while (found < size && seen[found] != value) {
found++;
}
if (found == size) {
seen[size++] = value;
}
indices[column] = (byte) found;
}
private T[] values() {
return Arrays.copyOf(seen, size);
}
}
static final class LongPalette {
private final byte[] indices = new byte[COLUMNS];
private final long[] seen = new long[COLUMNS];
private int size;
void set(int column, long value) {
int found = 0;
while (found < size && seen[found] != value) {
found++;
}
if (found == size) {
seen[size++] = value;
}
indices[column] = (byte) found;
}
private long[] values() {
return Arrays.copyOf(seen, size);
}
}
}
@@ -0,0 +1,6 @@
package art.arcane.iris.generation.hydrology.raster;
@FunctionalInterface
public interface NaturalHeights {
double height(int x, int z);
}
@@ -2,7 +2,6 @@ package art.arcane.iris.generation.hydrology.raster;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.grid.CellHash;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
@@ -11,7 +10,6 @@ import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import java.util.Arrays;
import java.util.function.IntBinaryOperator;
final class RasterComposer {
private static final int CHUNK = 16;
@@ -22,12 +20,15 @@ final class RasterComposer {
private static final double MAX_CONE_SLOPE = 2D;
private static final double CONE_EXPONENT = 0.8D;
private static final double ROUNDING = 1e-6D;
private static final long SALT_BANK = 0x42414e4b4e5aL;
private static final int SLOPE_REACH = 2;
private static final int RAY_STEP = 4;
private final HydrologySettings settings;
private final ChunkFeatures features;
private final ChannelFluids channelFluids;
private final int originX;
private final int originZ;
private final double[] exact = new double[CELLS];
private final int[] natural = new int[CELLS];
private final int[] terrain = new int[CELLS];
private final int[] head = new int[CELLS];
@@ -41,11 +42,12 @@ final class RasterComposer {
private final HydrologyTier[] nearTier = new HydrologyTier[CELLS];
private final ReachCursor cursor = new ReachCursor();
private final int[] inletColumn = new int[2];
private IntBinaryOperator naturalHeight;
private NaturalHeights naturalHeight;
RasterComposer(HydrologySettings settings, ChunkFeatures features, int chunkX, int chunkZ) {
RasterComposer(HydrologySettings settings, ChunkFeatures features, ChannelFluids channelFluids, int chunkX, int chunkZ) {
this.settings = settings;
this.features = features;
this.channelFluids = channelFluids;
this.originX = chunkX * CHUNK - 1;
this.originZ = chunkZ * CHUNK - 1;
Arrays.fill(head, Integer.MIN_VALUE);
@@ -54,11 +56,12 @@ final class RasterComposer {
Arrays.fill(distance, Double.POSITIVE_INFINITY);
}
ChunkWaterRaster compose(IntBinaryOperator naturalHeight) {
ChunkWaterRaster compose(NaturalHeights naturalHeight) {
this.naturalHeight = naturalHeight;
for (int cell = 0; cell < CELLS; cell++) {
if (!corner(cell)) {
natural[cell] = naturalHeight.applyAsInt(originX + cell % GRID, originZ + cell / GRID);
exact[cell] = naturalHeight.height(originX + cell % GRID, originZ + cell / GRID);
natural[cell] = (int) Math.round(exact[cell]);
terrain[cell] = natural[cell];
}
}
@@ -107,7 +110,7 @@ final class RasterComposer {
return;
}
if (cursor.channel.reach != null) {
channel(cell, ground, variation, BedProfile.detail(settings.seed(), x, z));
channel(cell, x, z, ground, variation);
} else if (interior(cell)) {
dry(cell, x, z, ground, variation);
}
@@ -129,16 +132,17 @@ final class RasterComposer {
return Math.min(floor, bed(hit, Math.min(level, level(hit.reach.grade()[hit.point()])), ground, variation, detail));
}
private void channel(int cell, int ground, double variation, double detail) {
private void channel(int cell, int x, int z, int ground, double variation) {
ReachCursor.Choice hit = cursor.channel;
Reach reach = hit.reach;
int point = hit.point();
String area = channelFluids.channelFluid(x, z);
head[cell] = level(reach.grade()[point]);
terrain[cell] = bed(hit, head[cell], ground, variation, detail);
terrain[cell] = bed(hit, head[cell], ground, variation, BedProfile.detail(settings.seed(), x, z));
role[cell] = role(reach.style()[point]);
feature[cell] = reach.id();
tier[cell] = reach.tier();
fluid[cell] = reach.tier().fluid();
fluid[cell] = area != null ? area : reach.tier().fluid();
}
private static int bed(ReachCursor.Choice hit, int surface, int ground, double variation, double detail) {
@@ -162,7 +166,8 @@ final class RasterComposer {
u = BedProfile.position(u, -variation);
}
if (ground >= surface) {
cut = BankProfile.cut(bankTier.bankStyle(), surface, ground, u, coneSlope(cell) * u * bankTier.bankBand(), noise(x, z));
double cone = coneSlope(steepestToWater(x, z, bank, bankEdge)) * u * bankTier.bankBand();
cut = BankProfile.cut(bankTier.bankStyle(), surface, ground, u, cone, noise(x, z));
} else {
raise = BankProfile.levee(bankTier.bankStyle(), surface, ground, u, noise(x, z), settings.deformation().maxFill());
}
@@ -205,15 +210,47 @@ final class RasterComposer {
distance[cell] = best;
}
private double coneSlope(int cell) {
double slope = Math.max(Math.abs(natural[cell + 1] - natural[cell - 1]), Math.abs(natural[cell + GRID] - natural[cell - GRID])) / 2D;
private double coneSlope(double slope) {
HydrologySettings.Deformation deformation = settings.deformation();
return Math.min(MAX_CONE_SLOPE, deformation.bankSlope() + deformation.bankSteepFactor() * Math.pow(slope, CONE_EXPONENT));
}
private double steepestToWater(int x, int z, ReachCursor.Choice bank, double bankEdge) {
Reach reach = bank.reach;
int next = Math.min(bank.segment + 1, reach.xs().length - 1);
double centreX = reach.xs()[bank.segment] + (reach.xs()[next] - reach.xs()[bank.segment]) * bank.t;
double centreZ = reach.zs()[bank.segment] + (reach.zs()[next] - reach.zs()[bank.segment]) * bank.t;
double steepest = slopeAt(x, z);
double length = Math.hypot(centreX - x, centreZ - z);
if (length <= 0D) {
return steepest;
}
double towardX = (centreX - x) / length;
double towardZ = (centreZ - z) / length;
for (double edge = 0D; edge < bankEdge; edge += RAY_STEP) {
double back = bankEdge - edge;
steepest = Math.max(steepest, slopeAt((int) Math.floor(x + towardX * back + 0.5D), (int) Math.floor(z + towardZ * back + 0.5D)));
}
return steepest;
}
private double slopeAt(int x, int z) {
return Math.max(Math.abs(exactAt(x + SLOPE_REACH, z) - exactAt(x - SLOPE_REACH, z)),
Math.abs(exactAt(x, z + SLOPE_REACH) - exactAt(x, z - SLOPE_REACH))) / (2D * SLOPE_REACH);
}
private double exactAt(int x, int z) {
int gx = x - originX;
int gz = z - originZ;
if (gx >= 0 && gz >= 0 && gx < GRID && gz < GRID && !corner(gz * GRID + gx)) {
return exact[gz * GRID + gx];
}
return naturalHeight.height(x, z);
}
private double noise(int x, int z) {
float strength = settings.deformation().bankNoise();
return strength == 0f ? 0D : (CellHash.unit(CellHash.mix(settings.seed(), SALT_BANK, x, z)) - 0.5D) * strength;
return strength == 0f ? 0D : BedProfile.roughness(settings.seed(), x, z) * strength;
}
private static int taperCut(int level, int ground, double u) {
@@ -349,7 +386,7 @@ final class RasterComposer {
if (gx >= 0 && gz >= 0 && gx < GRID && gz < GRID && !corner(gz * GRID + gx)) {
return natural[gz * GRID + gx];
}
return naturalHeight.applyAsInt(x, z);
return (int) Math.round(naturalHeight.height(x, z));
}
private void nameShores() {
@@ -385,34 +422,37 @@ final class RasterComposer {
private ChunkWaterRaster pack() {
int columns = ChunkWaterRaster.COLUMNS;
boolean affected = false;
for (int lz = 0; lz < CHUNK && !affected; lz++) {
for (int lx = 0; lx < CHUNK && !affected; lx++) {
int cell = (lz + 1) * GRID + lx + 1;
affected = role[cell] != WaterRole.NONE || terrain[cell] != natural[cell] || shore(cell) < ChunkWaterRaster.MAX_SHORE_DISTANCE;
}
}
if (!affected) {
return ChunkWaterRaster.EMPTY;
}
int[] terrainOut = new int[columns];
int[] headOut = new int[columns];
byte[] roleOut = new byte[columns];
HydrologyTier[] tierOut = new HydrologyTier[columns];
long[] featureOut = new long[columns];
String[] fluidOut = new String[columns];
int[] caveOut = new int[columns];
ChunkWaterRaster.Palette<HydrologyTier> tierOut = new ChunkWaterRaster.Palette<>(new HydrologyTier[columns]);
ChunkWaterRaster.LongPalette featureOut = new ChunkWaterRaster.LongPalette();
ChunkWaterRaster.Palette<String> fluidOut = new ChunkWaterRaster.Palette<>(new String[columns]);
byte[] shoreOut = new byte[columns];
boolean caveMask = settings.deformation().caveMask();
boolean affected = false;
for (int lz = 0; lz < CHUNK; lz++) {
for (int lx = 0; lx < CHUNK; lx++) {
int cell = (lz + 1) * GRID + lx + 1;
int index = lz << 4 | lx;
int shore = shore(cell);
terrainOut[index] = terrain[cell];
headOut[index] = head[cell];
roleOut[index] = (byte) role[cell].ordinal();
tierOut[index] = tier[cell];
featureOut[index] = feature[cell];
fluidOut[index] = fluid[cell];
caveOut[index] = caveMask && head[cell] != Integer.MIN_VALUE ? terrain[cell] - 1 : Integer.MAX_VALUE;
shoreOut[index] = (byte) shore;
affected |= role[cell] != WaterRole.NONE || terrain[cell] != natural[cell] || shore < ChunkWaterRaster.MAX_SHORE_DISTANCE;
tierOut.set(index, tier[cell]);
featureOut.set(index, feature[cell]);
fluidOut.set(index, fluid[cell]);
shoreOut[index] = (byte) shore(cell);
}
}
return affected ? new ChunkWaterRaster(terrainOut, headOut, roleOut, tierOut, featureOut, fluidOut, caveOut, shoreOut)
: ChunkWaterRaster.EMPTY;
return new ChunkWaterRaster(terrainOut, headOut, roleOut, tierOut, featureOut, fluidOut, settings.deformation().caveMask(), shoreOut);
}
private int shore(int cell) {
@@ -6,6 +6,8 @@ import java.util.Arrays;
final class ReachSegments {
private static final int RUN = 16;
private static final int COVER_SHIFT = 2;
private static final float COVER_MARGIN = 1f;
private Reach[] reaches;
private int[] segments;
@@ -24,6 +26,13 @@ final class ReachSegments {
private int[] runBands = new int[8];
private int runs;
private boolean sealed;
private boolean covered;
private int coverX;
private int coverZ;
private int coverWidth;
private int coverDepth;
private int[] coverStarts;
private int[] coverEntries;
ReachSegments(int capacity) {
int initial = Math.max(1, capacity);
@@ -71,6 +80,19 @@ final class ReachSegments {
}
}
boolean isEmpty() {
return size == 0;
}
void coverChannels(int minX, int minZ, int maxX, int maxZ) {
covered = true;
coverX = minX;
coverZ = minZ;
coverWidth = ((maxX - minX) >> COVER_SHIFT) + 1;
coverDepth = ((maxZ - minZ) >> COVER_SHIFT) + 1;
sealed = false;
}
void nearest(double x, double z, Scope scope, ReachCursor cursor) {
if (!sealed) {
seal();
@@ -89,6 +111,16 @@ final class ReachSegments {
hint(channelHint, x, z, unbounded, cursor);
hint(bankHint, x, z, unbounded, cursor);
hint(edgeHint, x, z, unbounded, cursor);
int cell = scope == Scope.CHANNEL ? coveredCell(x, z) : -1;
if (cell >= 0) {
for (int entry = coverStarts[cell]; entry < coverStarts[cell + 1]; entry++) {
int index = coverEntries[entry];
if (index != channelHint && index != bankHint && index != edgeHint && !beyondSegment(index, x, z, scope, cursor)) {
evaluate(index, x, z, false, cursor);
}
}
return;
}
int first = 0;
for (int run = 0; run < runs; run++) {
int end = runEnds[run];
@@ -99,9 +131,7 @@ final class ReachSegments {
continue;
}
for (int index = first; index < end; index++) {
if (!beyond(x, z, Math.min(startX[index], endX[index]), Math.min(startZ[index], endZ[index]), Math.max(startX[index], endX[index]),
Math.max(startZ[index], endZ[index]), limit(radius[index], bands[index], scope, cursor))
&& index != channelHint && index != bankHint && index != edgeHint) {
if (!beyondSegment(index, x, z, scope, cursor) && index != channelHint && index != bankHint && index != edgeHint) {
evaluate(index, x, z, unbounded, cursor);
}
}
@@ -109,6 +139,23 @@ final class ReachSegments {
}
}
private int coveredCell(double x, double z) {
if (coverStarts == null) {
return -1;
}
int cellX = ((int) Math.floor(x) - coverX) >> COVER_SHIFT;
int cellZ = ((int) Math.floor(z) - coverZ) >> COVER_SHIFT;
if (cellX < 0 || cellZ < 0 || cellX >= coverWidth || cellZ >= coverDepth) {
return -1;
}
return cellZ * coverWidth + cellX;
}
private boolean beyondSegment(int index, double x, double z, Scope scope, ReachCursor cursor) {
return beyond(x, z, Math.min(startX[index], endX[index]), Math.min(startZ[index], endZ[index]), Math.max(startX[index], endX[index]),
Math.max(startZ[index], endZ[index]), limit(radius[index], bands[index], scope, cursor));
}
private void hint(int index, double x, double z, boolean unbounded, ReachCursor cursor) {
if (index >= 0 && index < size) {
evaluate(index, x, z, unbounded, cursor);
@@ -171,9 +218,56 @@ final class ReachSegments {
addRun(start, end);
start = end;
}
if (covered) {
cover();
}
sealed = true;
}
private void cover() {
int cells = coverWidth * coverDepth;
int[] starts = new int[cells + 1];
int[] range = new int[4];
for (int index = 0; index < size; index++) {
if (coverRange(index, range)) {
for (int cellZ = range[1]; cellZ <= range[3]; cellZ++) {
for (int cellX = range[0]; cellX <= range[2]; cellX++) {
starts[cellZ * coverWidth + cellX + 1]++;
}
}
}
}
for (int cell = 0; cell < cells; cell++) {
starts[cell + 1] += starts[cell];
}
int[] entries = new int[starts[cells]];
int[] fill = Arrays.copyOf(starts, cells);
for (int index = 0; index < size; index++) {
if (coverRange(index, range)) {
for (int cellZ = range[1]; cellZ <= range[3]; cellZ++) {
for (int cellX = range[0]; cellX <= range[2]; cellX++) {
entries[fill[cellZ * coverWidth + cellX]++] = index;
}
}
}
}
coverStarts = starts;
coverEntries = entries;
}
private boolean coverRange(int index, int[] range) {
float reach = radius[index] + COVER_MARGIN;
range[0] = Math.max(0, coverCell(Math.min(startX[index], endX[index]) - reach, coverX));
range[1] = Math.max(0, coverCell(Math.min(startZ[index], endZ[index]) - reach, coverZ));
range[2] = Math.min(coverWidth - 1, coverCell(Math.max(startX[index], endX[index]) + reach, coverX));
range[3] = Math.min(coverDepth - 1, coverCell(Math.max(startZ[index], endZ[index]) + reach, coverZ));
return range[0] <= range[2] && range[1] <= range[3];
}
private static int coverCell(float block, int origin) {
return ((int) Math.floor(block) - origin) >> COVER_SHIFT;
}
private void addRun(int start, int end) {
if (runs == runEnds.length) {
runEnds = Arrays.copyOf(runEnds, 2 * runs);
@@ -15,6 +15,7 @@ final class RiffleProfile {
private static final int LIMIT = 10 * RADIUS;
private static final int DRY = Integer.MIN_VALUE;
private static final int[] SIDES = {1, -1, GRID, -GRID};
private static final int[] REMAINING = remaining();
private final List<Field> fields = new ArrayList<>();
@@ -85,6 +86,20 @@ final class RiffleProfile {
return (int) Math.max(original, Math.min(head - 1L, Math.round(raised)));
}
private static int[] remaining() {
int[] remaining = new int[GRID * GRID];
int low = PADDING - 1;
int high = PADDING + CHUNK;
for (int z = 0; z < GRID; z++) {
for (int x = 0; x < GRID; x++) {
int outsideX = Math.max(0, Math.max(low - x, x - high));
int outsideZ = Math.max(0, Math.max(low - z, z - high));
remaining[z * GRID + x] = 10 * Math.max(outsideX, outsideZ);
}
}
return remaining;
}
private record Field(int crest, int[] distances) {
}
@@ -107,6 +122,9 @@ final class RiffleProfile {
}
private void offer(int cell, int distance) {
if (distance + REMAINING[cell] >= LIMIT) {
return;
}
if (distances[cell] < LIMIT) {
remove(cell);
}
@@ -10,6 +10,7 @@ import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import java.util.Arrays;
import java.util.Set;
import java.util.function.Supplier;
public final class CavePoolFiller {
public static final int REACH = HydrologySettings.MAX_CAVE_POOL_RADIUS + 1;
@@ -40,15 +41,19 @@ public final class CavePoolFiller {
this.density = settings.density();
}
public void fill(int chunkX, int chunkZ, CarvedTerrain carved, MantleWriter writer, long seed) {
public void fill(int chunkX, int chunkZ, Supplier<? extends CarvedTerrain> terrain, MantleWriter writer, long seed) {
if (!pools.enabled() || density == 0f) {
return;
}
int attempts = attempts(seed, chunkX, chunkZ);
CarvedTerrain carved = null;
for (int attempt = 0; attempt < attempts; attempt++) {
if (density < 1f && CellHash.unit(CellHash.mix(seed, SALT_DENSITY + attempt, chunkX, chunkZ)) >= density) {
continue;
}
if (carved == null) {
carved = terrain.get();
}
long column = CellHash.mix(seed, SALT_COLUMN + attempt, chunkX, chunkZ);
int x = (chunkX << 4) + (int) (column & 15);
int z = (chunkZ << 4) + (int) ((column >>> 4) & 15);
@@ -33,6 +33,7 @@ public final class SeaInletPlanner {
private static final long SALT_HEADROOM = 0x53454148454144L;
private static final long SALT_DEPTH = 0x53454144455054L;
private static final long SALT_DENSITY = 0x53454144454e53L;
private static final double SQUARED_MARGIN = 1e-9D;
private final HydrologySettings settings;
@@ -403,22 +404,36 @@ public final class SeaInletPlanner {
double dx = bx - ax;
double dz = bz - az;
double span = dx * dx + dz * dz;
double outside = radius > 0f ? squaredAbove(radius) : Double.POSITIVE_INFINITY;
double inside = radius > 0f ? squaredBelow(radius) : Double.NEGATIVE_INFINITY;
double wetOutside = wetRadius > 0f ? squaredAbove(wetRadius) : Double.POSITIVE_INFINITY;
double wetInside = wetRadius > 0f ? squaredBelow(wetRadius) : Double.NEGATIVE_INFINITY;
for (int j = minJ; j <= maxJ; j++) {
double pz = grid.originZ() + (double) j * cell;
for (int i = minI; i <= maxI; i++) {
double px = grid.originX() + (double) i * cell;
double t = span <= 0D ? 0D : Math.clamp(((px - ax) * dx + (pz - az) * dz) / span, 0D, 1D);
double distance = Math.hypot(px - (ax + t * dx), pz - (az + t * dz));
if (distance > radius) {
double ex = px - (ax + t * dx);
double ez = pz - (az + t * dz);
double squared = ex * ex + ez * ez;
if (squared > outside || !(squared < inside) && Math.hypot(ex, ez) > radius) {
continue;
}
int index = j * grid.width() + i;
cover[index] = Math.min(cover[index], bed);
wet[index] |= distance <= wetRadius;
wet[index] |= squared < wetInside || !(squared > wetOutside) && Math.hypot(ex, ez) <= wetRadius;
}
}
}
private static double squaredAbove(float radius) {
return (double) radius * radius * (1D + SQUARED_MARGIN);
}
private static double squaredBelow(float radius) {
return (double) radius * radius * (1D - SQUARED_MARGIN);
}
private static float pathLength(DemGrid grid, List<Integer> path) {
float length = 0f;
for (int station = 1; station < path.size(); station++) {
@@ -85,8 +85,9 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
generateFalls(writer, complex, runtime, own, chunkX, chunkZ);
if (poolsActive()) {
HydrologySettings settings = runtime.settings();
new CavePoolFiller(settings).fill(chunkX, chunkZ,
new MantleCarvedTerrain(writer, complex, getEngineMantle().getEngine(), chunkX, chunkZ), writer, settings.seed());
Engine engine = getEngineMantle().getEngine();
new CavePoolFiller(settings).fill(chunkX, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, chunkX, chunkZ), writer,
settings.seed());
}
}
@@ -91,7 +91,6 @@ import art.arcane.volmlib.util.interpolation.NoiseBoundsProvider;
import art.arcane.volmlib.util.noise.CNG;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.util.stream.interpolation.Interpolated;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -120,10 +119,11 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
@Data
@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBoundsBiomes", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"})
@ToString(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBoundsBiomes", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"})
@EqualsAndHashCode(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"})
@ToString(exclude = {"data", "gridBoundsCache", "sharedCornerBounds", "sharedBaseHeights", "sharedBoundsBiomes", "regionBounds", "contextRegionStream", "terrainProgram", "bakeCache", "regionSource", "baseBiomeSource", "caveSource", "rockSource", "fluidSource", "childStyleSeed", "inferredByType", "naturalHeightSource", "naturalTrueBiomeSource", "trueBiomeSource", "frozenInterpolators", "frozenGenerators", "inferredBiomeStreams", "imageMapRuntime", "terrainEngine", "terrain3D", "hydrologyRuntime", "shoreBiomes", "waterVegetation", "effectiveChunks"})
public class IrisComplex implements DataProvider {
private static final NoiseBounds ZERO_NOISE_BOUNDS = new NoiseBounds(0D, 0D);
private static final long NEGATIVE_ZERO_BITS = Double.doubleToRawLongBits(-0D);
private static final AtomicLong lastBoundsFailureLog = new AtomicLong(0L);
private static final int GRID_BOUNDS_CACHE_SIZE = 8192;
private static final int STUDIO_NOISE_CACHE_SIZE = 32_768;
@@ -146,7 +146,6 @@ public class IrisComplex implements DataProvider {
Comparator.nullsFirst(Comparator.naturalOrder())
);
private static final ThreadLocal<TerrainBatchScratch> BATCH_SCRATCH = ThreadLocal.withInitial(TerrainBatchScratch::new);
private static final ThreadLocal<HydrologyBaseHeights> HYDROLOGY_BASE_HEIGHTS = new ThreadLocal<>();
private static final InferredType[] INFERRED_BIOME_PREPARATION_ORDER = {
InferredType.LAND,
InferredType.CAVE,
@@ -160,6 +159,7 @@ public class IrisComplex implements DataProvider {
@Getter(AccessLevel.NONE)
private final int biomeBoundsSamplingStep;
private transient volatile SharedCornerBounds sharedCornerBounds;
private transient volatile SharedBaseHeights sharedBaseHeights;
private transient volatile SharedBoundsBiomes sharedBoundsBiomes;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@@ -259,6 +259,10 @@ public class IrisComplex implements DataProvider {
private IrisBiome focusBiome;
private IrisRegion focusRegion;
private Map<IrisInterpolator, IdentityHashMap<IrisBiome, GeneratorBounds>> generatorBounds;
@Getter(AccessLevel.NONE)
private final transient RegionBounds regionBounds;
@Getter(AccessLevel.NONE)
private final transient ProceduralStream<IrisRegion> contextRegionStream;
private Set<IrisBiome> generatorBiomes;
@Setter(AccessLevel.NONE)
private final transient HydrologyRuntime hydrologyRuntime;
@@ -386,6 +390,9 @@ public class IrisComplex implements DataProvider {
frozenGenerators[frozenIndex] = generatorGroups[frozenIndex].generators();
}
generatorBounds = buildGeneratorBounds(engine);
regionBounds = focusedBiomes == null && !imageMapRuntime.has(IrisImageMapApplication.BIOME)
? RegionBounds.compile(preparedRegions, frozenInterpolators.length, new BoundsReach(), this::groupBounds)
: null;
biomeBuffetGenerators = compileBuffetGeneratorGroups();
chunkHeightBatch = engine.getDimension().getTerrainSamplingStep() == 1 && biomeBuffetGenerators.isEmpty()
&& (biomeBuffet == null || biomeBuffet.cells().isEmpty());
@@ -417,20 +424,21 @@ public class IrisComplex implements DataProvider {
: RegionSelection.select(new RegionSelection.Options(
engine.getDimension(), data, regionStyleStream, imageMapRuntime, null));
regionStream = focusedRegions != null ? focusedRegions : new BakedStream<>(bakeCache, BakePlane.REGION, regionSource);
caveSource = GenerationStreams.contextInjecting(regionStream, engine, (c, x, z) -> c.getRegion().get(x, z))
contextRegionStream = GenerationStreams.contextInjecting(regionStream, engine, (c, x, z) -> c.getRegion().get(x, z));
caveSource = contextRegionStream
.convert((r) -> createInferredBiomeStream(r, InferredType.CAVE))
.convertAware2D(ProceduralStream::get);
caveBiomeStream = new BakedStream<>(bakeCache, BakePlane.CAVE_BIOME, caveSource);
inferredStreams.put(InferredType.CAVE, caveBiomeStream);
landBiomeStream = GenerationStreams.contextInjecting(regionStream, engine, (c, x, z) -> c.getRegion().get(x, z))
landBiomeStream = contextRegionStream
.convert((r) -> createInferredBiomeStream(r, InferredType.LAND))
.convertAware2D(ProceduralStream::get);
inferredStreams.put(InferredType.LAND, landBiomeStream);
seaBiomeStream = GenerationStreams.contextInjecting(regionStream, engine, (c, x, z) -> c.getRegion().get(x, z))
seaBiomeStream = contextRegionStream
.convert((r) -> createInferredBiomeStream(r, InferredType.SEA))
.convertAware2D(ProceduralStream::get);
inferredStreams.put(InferredType.SEA, seaBiomeStream);
shoreBiomeStream = GenerationStreams.contextInjecting(regionStream, engine, (c, x, z) -> c.getRegion().get(x, z))
shoreBiomeStream = contextRegionStream
.convert((r) -> createInferredBiomeStream(r, InferredType.SHORE))
.convertAware2D(ProceduralStream::get);
inferredStreams.put(InferredType.SHORE, shoreBiomeStream);
@@ -812,17 +820,35 @@ public class IrisComplex implements DataProvider {
}
return;
}
SharedBaseHeights memo = sharedBaseHeights();
TerrainBatchScratch scratch = BATCH_SCRATCH.get();
int mark = scratch.mark();
int indexMark = scratch.indexMark();
try {
double[] batchXs = scratch.buffer(count);
double[] batchZs = scratch.buffer(count);
double[] computed = scratch.buffer(count);
int[] slots = scratch.indices(count);
int missing = 0;
for (int index = 0; index < count; index++) {
batchXs[index] = xs[from + index];
batchZs[index] = zs[from + index];
int x = xs[from + index];
int z = zs[from + index];
double known = memo.get(x, z);
if (Double.isNaN(known)) {
batchXs[missing] = x;
batchZs[missing] = z;
slots[missing++] = index;
} else {
heights[index] = known;
}
}
if (missing > 0) {
batchBaseHeights(scratch, batchXs, batchZs, missing, computed);
for (int index = 0; index < missing; index++) {
heights[slots[index]] = computed[index];
memo.put((int) batchXs[index], (int) batchZs[index], computed[index]);
}
}
batchBaseHeights(scratch, batchXs, batchZs, count, heights);
} finally {
scratch.reset(mark);
scratch.resetIndices(indexMark);
@@ -830,23 +856,9 @@ public class IrisComplex implements DataProvider {
if (baseOnly || terrain3D == null && transitionDisplacement == null) {
return;
}
Long2DoubleOpenHashMap known = new Long2DoubleOpenHashMap(count);
known.defaultReturnValue(Double.NaN);
for (int index = 0; index < count; index++) {
known.put(hydrologyColumnKey(xs[from + index], zs[from + index]), heights[index]);
heights[index] = naturalHeightStream.getDouble(xs[from + index], zs[from + index]);
}
HYDROLOGY_BASE_HEIGHTS.set(new HydrologyBaseHeights(this, known));
try {
for (int index = 0; index < count; index++) {
heights[index] = naturalHeightStream.getDouble(xs[from + index], zs[from + index]);
}
} finally {
HYDROLOGY_BASE_HEIGHTS.remove();
}
}
private static long hydrologyColumnKey(int x, int z) {
return ((long) x << 32) | (z & 0xFFFFFFFFL);
}
private void bakeBaseHeights(int chunkX, int chunkZ, long[] missing, double[] values) {
@@ -1082,15 +1094,21 @@ public class IrisComplex implements DataProvider {
}
private double sampleUnblendedNaturalTerrainHeight(double x, double z) {
HydrologyBaseHeights batched = HYDROLOGY_BASE_HEIGHTS.get();
if (batched != null && batched.owner() == this && (int) x == x && (int) z == z) {
double known = batched.heights().get(hydrologyColumnKey((int) x, (int) z));
if (!Double.isNaN(known)) {
return known;
}
if (!memoColumn(x) || !memoColumn(z)) {
return imageMapRuntime.sampleTerrainHeight(x, z, proceduralTerrainHeight.sample(x, z));
}
double proceduralHeight = proceduralTerrainHeight.sample(x, z);
return imageMapRuntime.sampleTerrainHeight(x, z, proceduralHeight);
SharedBaseHeights memo = sharedBaseHeights();
double known = memo.get((int) x, (int) z);
if (!Double.isNaN(known)) {
return known;
}
double height = imageMapRuntime.sampleTerrainHeight(x, z, proceduralTerrainHeight.sample(x, z));
memo.put((int) x, (int) z, height);
return height;
}
private static boolean memoColumn(double coordinate) {
return (int) coordinate == coordinate && Double.doubleToRawLongBits(coordinate) != NEGATIVE_ZERO_BITS;
}
static double calculateNaturalSlope(double naturalHeight, double easternHeight, double southernHeight) {
@@ -1662,7 +1680,11 @@ public class IrisComplex implements DataProvider {
/** The natural terrain height of a column, from the natural height stream only: never touches hydrology or its caches. */
public int naturalTrueHeight(int x, int z) {
return (int) Math.round(naturalHeightStream.getDouble(x, z));
return (int) Math.round(naturalHeight(x, z));
}
public double naturalHeight(int x, int z) {
return naturalHeightStream.getDouble(x, z);
}
/** The terrain slope of a column from the natural height stream only: never touches hydrology or its caches. */
@@ -1885,7 +1907,7 @@ public class IrisComplex implements DataProvider {
int grid = biomeBoundsSamplingStep;
GridBoundsCache cache = gridBoundsCache.get();
if (grid <= 1) {
return sampleBoundsRaw(cache, engine, interpolator, generators, x, z);
return sampleBoundsRaw(cache, engine, interpolator, interpolatorIndex, generators, x, z);
}
int xi = (int) Math.floor(x);
@@ -1941,7 +1963,7 @@ public class IrisComplex implements DataProvider {
if (GenerationCounter.ENABLED) {
GenerationCounter.CORNER_STARCASTS.increment();
}
packed = computePackedBounds(cache, engine, interpolator, generators, gx, gz);
packed = computePackedBounds(cache, engine, interpolator, interpolatorIndex, generators, gx, gz);
if (!Double.isFinite(boundsLow(packed)) || !Double.isFinite(boundsHigh(packed))) {
// A non-finite corner is a transient sampling fault, not a fact about the terrain:
// hand it back uncached so the next sample recomputes it instead of pinning it.
@@ -1972,6 +1994,20 @@ public class IrisComplex implements DataProvider {
return shared;
}
private SharedBaseHeights sharedBaseHeights() {
SharedBaseHeights shared = sharedBaseHeights;
if (shared == null) {
synchronized (this) {
shared = sharedBaseHeights;
if (shared == null) {
shared = new SharedBaseHeights(SharedBaseHeights.capacityFor(Runtime.getRuntime().maxMemory()));
sharedBaseHeights = shared;
}
}
}
return shared;
}
private SharedBoundsBiomes sharedBoundsBiomes(ProceduralStream<IrisBiome> source) {
SharedBoundsBiomes shared = sharedBoundsBiomes;
if (shared != null && shared.source() == source) {
@@ -1987,8 +2023,9 @@ public class IrisComplex implements DataProvider {
}
}
private long computePackedBounds(GridBoundsCache cache, Engine engine, IrisInterpolator interpolator, IrisGenerator[] generators, int gx, int gz) {
NoiseBounds bounds = sampleBoundsRaw(cache, engine, interpolator, generators, gx, gz);
private long computePackedBounds(GridBoundsCache cache, Engine engine, IrisInterpolator interpolator, int interpolatorIndex,
IrisGenerator[] generators, int gx, int gz) {
NoiseBounds bounds = sampleBoundsRaw(cache, engine, interpolator, interpolatorIndex, generators, gx, gz);
return (((long) Float.floatToRawIntBits((float) bounds.min())) << 32) | (Float.floatToRawIntBits((float) bounds.max()) & 0xFFFFFFFFL);
}
@@ -2006,10 +2043,11 @@ public class IrisComplex implements DataProvider {
return a + ((b - a) * fz);
}
private NoiseBounds sampleBoundsRaw(GridBoundsCache cache, Engine engine, IrisInterpolator interpolator, IrisGenerator[] generators, double x, double z) {
private NoiseBounds sampleBoundsRaw(GridBoundsCache cache, Engine engine, IrisInterpolator interpolator, int interpolatorIndex,
IrisGenerator[] generators, double x, double z) {
IdentityHashMap<IrisBiome, GeneratorBounds> cachedBounds = generatorBounds.get(interpolator);
BoundsSampler sampler = cache.sampler.isInUse() ? new BoundsSampler() : cache.sampler;
sampler.bind(this, engine, generators, cachedBounds);
sampler.bind(this, engine, interpolatorIndex, generators, cachedBounds);
try {
return interpolator.interpolateBounds(x, z, sampler);
@@ -2297,6 +2335,11 @@ public class IrisComplex implements DataProvider {
return reached;
}
private NoiseBounds groupBounds(int group, IrisBiome biome) {
GeneratorBounds cached = generatorBounds.get(frozenInterpolators[group]).get(biome);
return (cached == null ? computeGeneratorBounds(frozenGenerators[group], biome) : cached).noiseBounds;
}
static double averageGeneratorHeights(
IrisGenerator[] generators,
double low,
@@ -2604,6 +2647,32 @@ public class IrisComplex implements DataProvider {
}
}
private final class BoundsReach implements RegionBounds.Reach {
@Override
public List<IrisBiome> picks(IrisRegion region, InferredType type) {
return loadInferredBiomes(biomeKeys(region, type), type);
}
@Override
public Collection<IrisBiome> descendants(IrisBiome biome) {
Set<IrisBiome> reached = Collections.newSetFromMap(new IdentityHashMap<>());
ArrayDeque<IrisBiome> pending = new ArrayDeque<>();
pending.add(biome);
while (!pending.isEmpty()) {
IrisBiome next = pending.poll();
if (!reached.add(next)) {
continue;
}
for (IrisBiome child : next.getRealChildren(IrisComplex.this)) {
if (child != null) {
pending.add(child);
}
}
}
return reached;
}
}
/**
* Reusable per-thread bounds provider. Holds the biome memo and the lazily computed generator
* bounds for one sampleBoundsRaw pass so the pass allocates nothing; {@link #bind}
@@ -2619,9 +2688,12 @@ public class IrisComplex implements DataProvider {
private final IdentityHashMap<IrisBiome, GeneratorBounds> localBounds = new IdentityHashMap<>(8);
private IrisComplex complex;
private Engine engine;
private int group;
private IrisGenerator[] generators;
private IdentityHashMap<IrisBiome, GeneratorBounds> cachedBounds;
private SharedBoundsBiomes sharedBiomes;
private BakedStream<IrisBiome> bakedBiomes;
private RegionBounds regional;
private boolean integerCoordinates;
private boolean inUse;
@@ -2629,14 +2701,19 @@ public class IrisComplex implements DataProvider {
return inUse;
}
private void bind(IrisComplex complex, Engine engine, IrisGenerator[] generators, IdentityHashMap<IrisBiome, GeneratorBounds> cachedBounds) {
private void bind(IrisComplex complex, Engine engine, int group, IrisGenerator[] generators,
IdentityHashMap<IrisBiome, GeneratorBounds> cachedBounds) {
this.complex = complex;
this.engine = engine;
this.group = group;
this.generators = generators;
this.cachedBounds = cachedBounds;
this.integerCoordinates = complex.baseBiomeStream instanceof BakedStream<?>
|| complex.baseBiomeStream instanceof CachedStream2D<?>;
this.sharedBiomes = integerCoordinates ? complex.sharedBoundsBiomes(complex.baseBiomeStream) : null;
this.bakedBiomes = complex.regionBounds != null && complex.baseBiomeStream instanceof BakedStream<IrisBiome> baked
? baked : null;
this.regional = bakedBiomes == null ? null : complex.regionBounds;
this.inUse = true;
if (sampleSource.get() != complex.baseBiomeStream) {
sampleCache.clear();
@@ -2654,6 +2731,8 @@ public class IrisComplex implements DataProvider {
generators = null;
cachedBounds = null;
sharedBiomes = null;
bakedBiomes = null;
regional = null;
inUse = false;
}
@@ -2662,25 +2741,23 @@ public class IrisComplex implements DataProvider {
try {
double sampleX = integerCoordinates ? (int) xx : xx;
double sampleZ = integerCoordinates ? (int) zz : zz;
IrisBiome bx = sampleCache.get(sampleX, sampleZ);
if (bx == null) {
bx = sharedBiomes == null ? null : sharedBiomes.get((int) sampleX, (int) sampleZ);
if (bx == null) {
ChunkBakeCache.enterSparse();
try {
bx = complex.baseBiomeStream.get(xx, zz);
} finally {
ChunkBakeCache.exitSparse();
}
if (sharedBiomes != null) {
sharedBiomes.put((int) sampleX, (int) sampleZ, bx);
}
Object known = sampleCache.get(sampleX, sampleZ);
if (known == null && sharedBiomes != null) {
known = sharedBiomes.get((int) sampleX, (int) sampleZ);
if (known != null) {
sampleCache.put(sampleX, sampleZ, known);
}
sampleCache.put(sampleX, sampleZ, bx);
}
GeneratorBounds bounds = complex.resolveGeneratorBounds(engine, generators, bx, cachedBounds, localBounds);
return bounds.noiseBounds;
if (known instanceof IrisBiome biome) {
return bounds(biome);
}
ChunkBakeCache.enterSparse();
try {
return regional == null ? bounds(remember(sampleX, sampleZ, complex.baseBiomeStream.get(xx, zz)))
: regionalBounds(known, sampleX, sampleZ);
} finally {
ChunkBakeCache.exitSparse();
}
} catch (Throwable e) {
GenerationFailures.rethrowEngineFailure(e);
long now = System.currentTimeMillis();
@@ -2696,6 +2773,49 @@ public class IrisComplex implements DataProvider {
return ZERO_NOISE_BOUNDS;
}
private NoiseBounds regionalBounds(Object known, double x, double z) {
RegionBounds.Pick pick = known instanceof RegionBounds.Pick picked ? picked : null;
IrisRegion region = pick != null ? pick.region() : known instanceof IrisRegion cached ? cached : null;
if (region == null) {
IrisBiome baked = bakedBiomes.baked((int) x, (int) z);
if (baked != null) {
return bounds(remember(x, z, baked));
}
region = remember(x, z, complex.contextRegionStream.get(x, z));
}
RegionBounds.Constants constants = regional.of(region);
NoiseBounds constant = constants == null ? null : constants.any(group);
if (constant != null) {
return constant;
}
InferredType type = pick != null ? pick.type() : complex.bridgeStream.get(x, z);
constant = constants == null ? null : constants.typed(type, group);
if (constant != null) {
return constant;
}
IrisBiome picked = pick != null ? pick.biome() : complex.createInferredBiomeStream(region, type).get(x, z);
constant = regional.pick(picked, group);
if (constant != null) {
if (pick == null) {
remember(x, z, new RegionBounds.Pick(region, type, picked));
}
return constant;
}
return bounds(remember(x, z, complex.implode(picked, x, z)));
}
private NoiseBounds bounds(IrisBiome biome) {
return complex.resolveGeneratorBounds(engine, generators, biome, cachedBounds, localBounds).noiseBounds;
}
private <T> T remember(double x, double z, T sample) {
if (sharedBiomes != null) {
sharedBiomes.put((int) x, (int) z, sample);
}
sampleCache.put(x, z, sample);
return sample;
}
}
/**
@@ -2705,13 +2825,13 @@ public class IrisComplex implements DataProvider {
private static final class CoordinateBiomeCache {
private final long[] xBits;
private final long[] zBits;
private final IrisBiome[] values;
private final Object[] values;
private final int mask;
private CoordinateBiomeCache(int capacity) {
xBits = new long[capacity];
zBits = new long[capacity];
values = new IrisBiome[capacity];
values = new Object[capacity];
mask = capacity - 1;
}
@@ -2719,20 +2839,20 @@ public class IrisComplex implements DataProvider {
Arrays.fill(values, null);
}
private IrisBiome get(double x, double z) {
private Object get(double x, double z) {
long xb = Double.doubleToLongBits(x);
long zb = Double.doubleToLongBits(z);
int slot = mix(xb, zb) & mask;
return xBits[slot] == xb && zBits[slot] == zb ? values[slot] : null;
}
private void put(double x, double z, IrisBiome biome) {
private void put(double x, double z, Object sample) {
long xb = Double.doubleToLongBits(x);
long zb = Double.doubleToLongBits(z);
int slot = mix(xb, zb) & mask;
xBits[slot] = xb;
zBits[slot] = zb;
values[slot] = biome;
values[slot] = sample;
}
private int mix(long xb, long zb) {
@@ -2784,7 +2904,4 @@ public class IrisComplex implements DataProvider {
transitionDisplacement.clear();
}
}
private record HydrologyBaseHeights(IrisComplex owner, Long2DoubleOpenHashMap heights) {
}
}
@@ -0,0 +1,120 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.volmlib.util.interpolation.NoiseBounds;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class RegionBounds {
private final Map<IrisRegion, Constants> regions;
private final Map<IrisBiome, NoiseBounds[]> picks;
private RegionBounds(Map<IrisRegion, Constants> regions, Map<IrisBiome, NoiseBounds[]> picks) {
this.regions = regions;
this.picks = picks;
}
static RegionBounds compile(Collection<IrisRegion> regions, int groups, Reach reach, GroupBounds bounds) {
IdentityHashMap<IrisRegion, Constants> compiled = new IdentityHashMap<>(Math.max(16, regions.size() * 2));
IdentityHashMap<IrisBiome, NoiseBounds[]> picks = new IdentityHashMap<>();
for (IrisRegion region : regions) {
if (compiled.containsKey(region)) {
continue;
}
NoiseBounds[] land = typeConstants(reach.picks(region, InferredType.LAND), groups, reach, bounds, picks);
NoiseBounds[] sea = typeConstants(reach.picks(region, InferredType.SEA), groups, reach, bounds, picks);
NoiseBounds[] any = new NoiseBounds[groups];
for (int group = 0; group < groups; group++) {
any[group] = land[group] != null && sea[group] != null && sameBits(land[group], sea[group]) ? land[group] : null;
}
compiled.put(region, new Constants(any, land, sea));
}
return new RegionBounds(compiled, picks);
}
Constants of(IrisRegion region) {
return regions.get(region);
}
NoiseBounds pick(IrisBiome picked, int group) {
NoiseBounds[] constants = picks.get(picked);
return constants == null ? null : constants[group];
}
private static NoiseBounds[] typeConstants(List<IrisBiome> picked, int groups, Reach reach, GroupBounds bounds,
Map<IrisBiome, NoiseBounds[]> picks) {
if (picked.isEmpty()) {
return new NoiseBounds[groups];
}
Set<IrisBiome> reached = Collections.newSetFromMap(new IdentityHashMap<>());
for (IrisBiome biome : picked) {
Collection<IrisBiome> descendants = reach.descendants(biome);
reached.addAll(descendants);
if (!picks.containsKey(biome)) {
picks.put(biome, constants(descendants, groups, bounds));
}
}
return constants(reached, groups, bounds);
}
private static NoiseBounds[] constants(Collection<IrisBiome> biomes, int groups, GroupBounds bounds) {
NoiseBounds[] constants = new NoiseBounds[groups];
for (int group = 0; group < groups; group++) {
constants[group] = constant(biomes, group, bounds);
}
return constants;
}
private static NoiseBounds constant(Collection<IrisBiome> biomes, int group, GroupBounds bounds) {
NoiseBounds first = null;
for (IrisBiome biome : biomes) {
NoiseBounds next = bounds.of(group, biome);
if (first == null) {
first = next;
} else if (!sameBits(first, next)) {
return null;
}
}
return first;
}
private static boolean sameBits(NoiseBounds first, NoiseBounds second) {
return Double.doubleToRawLongBits(first.min()) == Double.doubleToRawLongBits(second.min())
&& Double.doubleToRawLongBits(first.max()) == Double.doubleToRawLongBits(second.max());
}
record Constants(NoiseBounds[] any, NoiseBounds[] land, NoiseBounds[] sea) {
NoiseBounds any(int group) {
return any[group];
}
NoiseBounds typed(InferredType type, int group) {
return switch (type) {
case LAND -> land[group];
case SEA -> sea[group];
case SHORE, CAVE -> null;
};
}
}
record Pick(IrisRegion region, InferredType type, IrisBiome biome) {
}
interface Reach {
List<IrisBiome> picks(IrisRegion region, InferredType type);
Collection<IrisBiome> descendants(IrisBiome biome);
}
@FunctionalInterface
interface GroupBounds {
NoiseBounds of(int group, IrisBiome biome);
}
}
@@ -0,0 +1,76 @@
package art.arcane.iris.generation.runtime;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
final class SharedBaseHeights {
static final int MINIMUM_CAPACITY = 1 << 16;
static final int MAXIMUM_CAPACITY = 1 << 21;
static final long BYTES_PER_ENTRY = 20L;
static final long HEAP_SHARE = 256L;
private static final VarHandle INTS = MethodHandles.arrayElementVarHandle(int[].class);
private static final VarHandle LONGS = MethodHandles.arrayElementVarHandle(long[].class);
private final long[] keys;
private final long[] values;
private final int[] stamps;
private final int mask;
SharedBaseHeights(int capacity) {
if (capacity < 2 || Integer.bitCount(capacity) != 1) {
throw new IllegalArgumentException("capacity must be a power of two of at least 2");
}
this.keys = new long[capacity];
this.values = new long[capacity];
this.stamps = new int[capacity];
this.mask = capacity - 1;
}
static int capacityFor(long maxMemory) {
long entries = Math.max(0L, maxMemory) / HEAP_SHARE / BYTES_PER_ENTRY;
long bounded = Math.max(MINIMUM_CAPACITY, Math.min(MAXIMUM_CAPACITY, entries));
return Integer.highestOneBit((int) bounded);
}
double get(int x, int z) {
long key = key(x, z);
int slot = slot(key);
int before = (int) INTS.getAcquire(stamps, slot);
if (before == 0 || (before & 1) != 0) {
return Double.NaN;
}
long storedKey = (long) LONGS.getAcquire(keys, slot);
long value = (long) LONGS.getAcquire(values, slot);
VarHandle.loadLoadFence();
int after = (int) INTS.getAcquire(stamps, slot);
if (before != after || storedKey != key) {
return Double.NaN;
}
return Double.longBitsToDouble(value);
}
void put(int x, int z, double height) {
if (!Double.isFinite(height)) {
return;
}
long key = key(x, z);
int slot = slot(key);
int stamp = (int) INTS.getAcquire(stamps, slot);
if ((stamp & 1) != 0 || !INTS.compareAndSet(stamps, slot, stamp, stamp + 1)) {
return;
}
LONGS.setRelease(keys, slot, key);
LONGS.setRelease(values, slot, Double.doubleToRawLongBits(height));
INTS.setRelease(stamps, slot, stamp + 2);
}
private int slot(long key) {
long mixed = (key ^ (key >>> 30)) * 0xBF58476D1CE4E5B9L;
mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL;
return (int) ((mixed ^ (mixed >>> 31)) & mask);
}
private static long key(int x, int z) {
return ((long) x << 32) | (z & 0xFFFFFFFFL);
}
}
@@ -1,7 +1,5 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.biome.IrisBiome;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Objects;
@@ -49,7 +47,7 @@ final class SharedBoundsBiomes {
return (int) ((mixed ^ (mixed >>> 31)) & mask);
}
IrisBiome get(int x, int z) {
Object get(int x, int z) {
long key = key(x, z);
int slot = slot(x, z);
int before = (int) INTS.getAcquire(stamps, slot);
@@ -63,11 +61,11 @@ final class SharedBoundsBiomes {
if (before != after || storedKey != key) {
return null;
}
return (IrisBiome) value;
return value;
}
void put(int x, int z, IrisBiome biome) {
if (biome == null) {
void put(int x, int z, Object sample) {
if (sample == null) {
return;
}
int slot = slot(x, z);
@@ -76,7 +74,7 @@ final class SharedBoundsBiomes {
return;
}
LONGS.setRelease(keys, slot, key(x, z));
OBJECTS.setRelease(values, slot, biome);
OBJECTS.setRelease(values, slot, sample);
INTS.setRelease(stamps, slot, stamp + 2);
}
@@ -49,6 +49,7 @@ import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveStorage;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.chunk.ColumnExtent;
import art.arcane.iris.generation.chunk.ColumnReadHunk;
import art.arcane.iris.generation.context.ChunkContext;
import art.arcane.iris.generation.context.IrisContext;
import art.arcane.iris.generation.block.B;
@@ -1086,19 +1087,21 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int height = output.getHeight();
ColumnExtent extent = output instanceof ColumnExtent columnExtent ? columnExtent : null;
SolidMemo solids = new SolidMemo();
ColumnWindow column = new ColumnWindow(output, height);
for (int localX = 0; localX < width; localX++) {
for (int localZ = 0; localZ < depth; localZ++) {
int worldX = blockX + localX;
int worldZ = blockZ + localZ;
int floor = -1;
int top = extent == null ? height - 1 : extent.highestStoredY(localX, localZ);
column.begin(localX, localZ, top);
boolean previousKnown = false;
boolean previousSolid = false;
for (int y = 1; y < height; y++) {
if (y > top) {
break;
}
boolean solid = solids.test(output.getRaw(localX, y, localZ));
boolean solid = solids.test(column.get(y));
boolean decorated = false;
if (solid) {
if (floor >= 0) {
@@ -1122,11 +1125,12 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
if (extent != null) {
top = extent.highestStoredY(localX, localZ);
}
column.begin(localX, localZ, top);
}
floor = -1;
}
} else if (floor < 0 && (previousKnown ? previousSolid
: solids.test(output.getRaw(localX, y - 1, localZ)))) {
: solids.test(column.get(y - 1)))) {
floor = y;
}
previousSolid = solid;
@@ -1472,6 +1476,43 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
private record CaveColumn(long key, IrisBiome surface, IrisBiome cave, int surfaceY, int minimumDepth) {
}
private static final class ColumnWindow {
private static final int ROWS = 16;
private final Hunk<NativeBlockState> output;
private final NativeBlockState[] states;
private int x;
private int z;
private int limit;
private int from;
private int to;
private ColumnWindow(Hunk<NativeBlockState> output, int height) {
this.output = output;
this.states = new NativeBlockState[height];
}
private void begin(int localX, int localZ, int top) {
x = localX;
z = localZ;
limit = Math.min(top, states.length - 1);
from = 0;
to = -1;
}
private NativeBlockState get(int y) {
if (y < from || y > to) {
if (y > limit) {
return output.getRaw(x, y, z);
}
from = y;
to = Math.min(limit, y + ROWS - 1);
ColumnReadHunk.readColumn(output, x, z, from, to, states, from);
}
return states[y];
}
}
private static final class SolidMemo {
private NativeBlockState state;
private boolean solid;
@@ -19,6 +19,7 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.chunk.ColumnExtent;
import art.arcane.iris.generation.chunk.ColumnReadHunk;
import art.arcane.iris.generation.decoration.IrisSpeleothems;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineAssignedModifier;
@@ -105,24 +106,29 @@ public class IrisPerfectionModifier extends EngineAssignedModifier<NativeBlockSt
StateFlags states = new StateFlags();
NativeBlockState air = AIR.get();
NativeBlockState water = WATER.get();
NativeBlockState[] column = new NativeBlockState[output.getHeight()];
for (int x = firstSlice; x < lastSlice; x++) {
for (int z = 0; z < 16; z++) {
perfectColumn(output, x, z, surfaces, states, air, water);
perfectColumn(output, x, z, surfaces, states, air, water, column);
}
}
}
private static void perfectColumn(Hunk<NativeBlockState> output, int x, int z, IntArrayList surfaces,
StateFlags states, NativeBlockState air, NativeBlockState water) {
StateFlags states, NativeBlockState air, NativeBlockState water,
NativeBlockState[] column) {
do {
surfaces.clear();
int top = getHeight(output, x, z, states);
int highest = Math.min(output.getHeight() - 1, ColumnExtent.highestStoredY(output, x, z));
ColumnReadHunk.readColumn(output, x, z, 0, Math.max(0, highest), column, 0);
int top = getHeight(column, highest, states);
boolean inside = true;
surfaces.add(top);
NativeBlockState classified = null;
int classifiedFlags = 0;
boolean columnRead = true;
for (int y = top; y >= 0; y--) {
NativeBlockState block = output.get(x, y, z);
NativeBlockState block = columnRead ? column[y] : output.get(x, y, z);
int flags = 0;
if (block != null) {
if (block != classified) {
@@ -133,6 +139,7 @@ public class IrisPerfectionModifier extends EngineAssignedModifier<NativeBlockSt
if ((flags & SPIKE) != 0) {
block = normalizeSpike(block, output, x, z, y, air, water);
flags = block == null ? 0 : states.of(block);
columnRead = false;
}
}
boolean now = (flags & SOLID) != 0;
@@ -233,11 +240,11 @@ public class IrisPerfectionModifier extends EngineAssignedModifier<NativeBlockSt
burst.complete();
}
private static int getHeight(Hunk<NativeBlockState> output, int x, int z, StateFlags states) {
private static int getHeight(NativeBlockState[] column, int highest, StateFlags states) {
NativeBlockState classified = null;
int classifiedFlags = 0;
for (int i = Math.min(output.getHeight() - 1, ColumnExtent.highestStoredY(output, x, z)); i >= 0; i--) {
NativeBlockState state = output.get(x, i, z);
for (int i = highest; i >= 0; i--) {
NativeBlockState state = column[i];
if (state == null) {
continue;
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.stage;
import art.arcane.iris.generation.chunk.ColumnReadHunk;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineAssignedComponent;
import art.arcane.iris.generation.runtime.EngineStage;
@@ -42,14 +43,14 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
if (plan == null || !plan.hasTransitionAtChunk(x >> 4, z >> 4)) {
return;
}
GeometrySource source = new GeometrySource(blocks, biomes, getEngine().getMinHeight(), context);
GeometrySource source = new GeometrySource(x, z, blocks, biomes, getEngine().getMinHeight(), context);
blendGeometry(x, z, blocks, context, source, plan);
}
public static SavedTerrainChunk capture(int x, int z, Hunk<NativeBlockState> blocks,
Hunk<NativeBiome> biomes, int minimumY,
ChunkContext context, boolean boundaryOnly) throws IOException {
GeometrySource source = new GeometrySource(blocks, biomes, minimumY, context);
GeometrySource source = new GeometrySource(x, z, blocks, biomes, minimumY, context);
return boundaryOnly
? SavedTerrainChunk.captureBoundary(x >> 4, z >> 4, minimumY, blocks.getHeight(), "minecraft:noise", source)
: SavedTerrainChunk.capture(x >> 4, z >> 4, minimumY, blocks.getHeight(), "minecraft:noise", source);
@@ -73,8 +74,10 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
if (blended == current) {
continue;
}
double expectedFloor = context.getRoundedHeight(localX, localZ);
int floor = blended.surfaceOffsetNear(expectedFloor);
int ground = context.getRoundedHeight(localX, localZ);
BoundaryColumnGeometry.WaterCap cap = paintedCap(current, blended, ground,
waterHead(complex, x + localX, z + localZ, current.height()));
int floor = blended.surfaceOffsetNear(ground, cap);
List<BoundaryColumnGeometry.Voxel> voxels = blended.voxels();
for (int offset = 0; offset < voxels.size(); offset++) {
BoundaryColumnGeometry.Voxel voxel = voxels.get(offset);
@@ -94,6 +97,9 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
&& voxels.get(fluidHeight + 1).phase() == BoundaryColumnGeometry.Phase.FLUID) {
fluidHeight++;
}
if (blended.capsWater(cap, floor)) {
fluidHeight = cap.top();
}
if (fluidHeight == floor) {
fluidHeight = -1;
}
@@ -104,17 +110,43 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
}
}
private static BoundaryColumnGeometry.WaterCap paintedCap(BoundaryColumnGeometry painted, BoundaryColumnGeometry blended,
int ground, int waterHead) {
BoundaryColumnGeometry.WaterCap cap = painted.waterCap(ground, waterHead);
if (!cap.present()) {
return cap;
}
int top = Math.min(cap.top() + 1, painted.height() - 1);
for (int offset = cap.bottom(); offset <= top; offset++) {
int y = painted.minimumY() + offset;
if (!painted.voxelAt(y).equals(blended.voxelAt(y))) {
return BoundaryColumnGeometry.WaterCap.none();
}
}
return cap;
}
private static int waterHead(IrisComplex complex, int blockX, int blockZ, int height) {
return Math.clamp(Math.round(complex.getWaterHeadStream().getDouble(blockX, blockZ)), -1, height - 1);
}
private static final class GeometrySource implements SavedTerrainChunk.VoxelSource {
private final int originX;
private final int originZ;
private final Hunk<NativeBlockState> blocks;
private final Hunk<NativeBiome> biomes;
private final int minimumY;
private final ChunkContext context;
private final Map<NativeBlockState, BoundaryColumnGeometry.Voxel> voxels = new IdentityHashMap<>();
private NativeBlockState air;
private NativeBlockState[] column = new NativeBlockState[0];
private NativeBlockState lastState;
private BoundaryColumnGeometry.Voxel lastVoxel;
private GeometrySource(Hunk<NativeBlockState> blocks, Hunk<NativeBiome> biomes, int minimumY, ChunkContext context) {
private GeometrySource(int originX, int originZ, Hunk<NativeBlockState> blocks, Hunk<NativeBiome> biomes,
int minimumY, ChunkContext context) {
this.originX = originX;
this.originZ = originZ;
this.blocks = blocks;
this.biomes = biomes;
this.minimumY = minimumY;
@@ -132,10 +164,14 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
return;
}
int base = minimumY - this.minimumY;
NativeBlockState runState = stateAt(localX, base, localZ);
if (column.length < height) {
column = new NativeBlockState[height];
}
ColumnReadHunk.readColumn(blocks, localX, localZ, base, base + height - 1, column, 0);
NativeBlockState runState = orAir(column[0]);
int start = 0;
for (int offset = 1; offset < height; offset++) {
NativeBlockState state = stateAt(localX, base + offset, localZ);
NativeBlockState state = orAir(column[offset]);
if (state != runState) {
runs.add(start, offset, voxelOf(runState));
start = offset;
@@ -146,7 +182,10 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
}
private NativeBlockState stateAt(int localX, int offset, int localZ) {
NativeBlockState state = blocks.getRaw(localX, offset, localZ);
return orAir(blocks.getRaw(localX, offset, localZ));
}
private NativeBlockState orAir(NativeBlockState state) {
if (state != null) {
return state;
}
@@ -169,6 +208,11 @@ public final class IrisTransitionGeometryActuator extends EngineAssignedComponen
return OptionalInt.of(Math.max(0, Math.min(blocks.getHeight() - 1, context.getRoundedHeight(localX, localZ))));
}
@Override
public OptionalInt waterSurface(int localX, int localZ) {
return OptionalInt.of(waterHead(context.getComplex(), originX + localX, originZ + localZ, blocks.getHeight()));
}
@Override
public String biome(int localX, int worldY, int localZ) throws IOException {
NativeBiome biome = biomes.getRaw(localX, worldY - minimumY, localZ);
@@ -39,6 +39,13 @@ public final class BakedStream<T> extends BasicStream<T> implements ChunkFillabl
return value;
}
@SuppressWarnings("unchecked")
public T baked(int blockX, int blockZ) {
int index = ((blockZ & 15) << 4) | (blockX & 15);
ChunkPlanes.Plane values = cache.planeIfPresent(plane, blockX >> 4, blockZ >> 4);
return values != null && values.ready(index) ? (T) values.objectAt(index) : null;
}
@Override
public T get(double x, double y, double z) {
return scalar.get(x, y, z);
@@ -0,0 +1,74 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2026 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.validation;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.spi.IrisLogging;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public final class ChunkSpiralScan {
private ChunkSpiralScan() {
}
public static int scan(List<int[]> targets, int threads, ChunkVisitor visitor, Listener listener) throws InterruptedException {
Semaphore inFlight = new Semaphore(Math.max(1, threads));
CountDownLatch done = new CountDownLatch(targets.size());
AtomicInteger failures = new AtomicInteger();
for (int[] target : targets) {
int chunkX = target[0];
int chunkZ = target[1];
inFlight.acquire();
MultiBurst.burst.lazy(() -> {
boolean ok = false;
try {
visitor.visit(chunkX, chunkZ);
ok = true;
} catch (Throwable e) {
failures.incrementAndGet();
IrisLogging.reportError(e);
listener.chunkFailed(chunkX, chunkZ, e);
} finally {
listener.chunkDone(chunkX, chunkZ, ok);
inFlight.release();
done.countDown();
}
});
}
done.await();
return failures.get();
}
@FunctionalInterface
public interface ChunkVisitor {
void visit(int chunkX, int chunkZ) throws Exception;
}
public interface Listener {
void chunkDone(int chunkX, int chunkZ, boolean ok);
void chunkFailed(int chunkX, int chunkZ, Throwable error);
}
}
@@ -26,7 +26,6 @@ import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.nativelib.terrain.NativeBiome;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.ChunkSpiral;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.volmlib.util.localization.MessageArgument;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
@@ -44,8 +43,6 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public final class GoldenHashEngine {
@@ -210,40 +207,18 @@ public final class GoldenHashEngine {
private Map<Long, String> scan(List<int[]> targets) throws InterruptedException {
Map<Long, String> lines = new ConcurrentHashMap<>();
Semaphore inFlight = new Semaphore(threads);
CountDownLatch done = new CountDownLatch(targets.size());
AtomicInteger completed = new AtomicInteger();
int total = targets.size();
for (int[] target : targets) {
int chunkX = target[0];
int chunkZ = target[1];
inFlight.acquire();
MultiBurst.burst.lazy(() -> {
boolean ok = false;
try {
ChunkSnapshot snapshot = source.generate(chunkX, chunkZ);
lines.put(chunkKey(chunkX, chunkZ), hashChunk(chunkX, chunkZ, snapshot));
if (request.deep()) {
writeDeepDump(chunkX, chunkZ, snapshot);
}
ok = true;
} catch (Throwable e) {
IrisLogging.reportError(e);
progress.chunkFailed(chunkX, chunkZ, e);
} finally {
progress.chunkDone(chunkX, chunkZ, ok, completed.incrementAndGet(), total);
inFlight.release();
done.countDown();
}
});
}
done.await();
ChunkSpiralScan.scan(targets, threads, (int chunkX, int chunkZ) -> hash(lines, chunkX, chunkZ), new ScanProgress(targets.size()));
return lines;
}
private void hash(Map<Long, String> lines, int chunkX, int chunkZ) throws Exception {
ChunkSnapshot snapshot = source.generate(chunkX, chunkZ);
lines.put(chunkKey(chunkX, chunkZ), hashChunk(chunkX, chunkZ, snapshot));
if (request.deep()) {
writeDeepDump(chunkX, chunkZ, snapshot);
}
}
private String hashChunk(int chunkX, int chunkZ, ChunkSnapshot snapshot) {
MessageDigest blockDigest = sha256();
MessageDigest biomeDigest = sha256();
@@ -562,4 +537,23 @@ public final class GoldenHashEngine {
throw new IllegalStateException(e);
}
}
private final class ScanProgress implements ChunkSpiralScan.Listener {
private final AtomicInteger completed = new AtomicInteger();
private final int total;
private ScanProgress(int total) {
this.total = total;
}
@Override
public void chunkDone(int chunkX, int chunkZ, boolean ok) {
progress.chunkDone(chunkX, chunkZ, ok, completed.incrementAndGet(), total);
}
@Override
public void chunkFailed(int chunkX, int chunkZ, Throwable error) {
progress.chunkFailed(chunkX, chunkZ, error);
}
}
}
@@ -33,6 +33,74 @@ public final class DirectorCommandMessages {
"iris.director.commanddatapack.param.datapack_id_folder_name_shown_by_iris_datapack_list",
"The datapack id (folder name) shown by /iris datapack list"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_DESCRIPTION = TextKey.of(
"iris.director.commanddatapack.director.export_dimension_vanilla_worldgen_datapack",
"Export a dimension as a vanilla worldgen datapack"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_DIMENSION = TextKey.of(
"iris.director.commanddatapack.param.export_dimension",
"The dimension to export"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_VERSION = TextKey.of(
"iris.director.commanddatapack.param.export_version",
"Target Minecraft version, 26.3 or later (blank uses the latest)"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_MODE = TextKey.of(
"iris.director.commanddatapack.param.export_mode",
"Output mode: preset, dimension, or overworld"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_NAMESPACE = TextKey.of(
"iris.director.commanddatapack.param.export_namespace",
"Namespace for the exported resources"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_OUTPUT = TextKey.of(
"iris.director.commanddatapack.param.export_output",
"Output name in the datapack exports folder (blank uses the dimension and version)"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_FORMAT = TextKey.of(
"iris.director.commanddatapack.param.export_format",
"zip or directory"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_OBJECTS = TextKey.of(
"iris.director.commanddatapack.param.export_objects",
"Include objects as structure templates"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_PARAM_REPLACE = TextKey.of(
"iris.director.commanddatapack.param.export_replace",
"Replace an existing export with the same name"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_STARTED = TextKey.of(
"iris.director.commanddatapack.export.started",
"Exporting {dimension} as a datapack for Minecraft {version}..."
);
public static final TextKey COMMAND_DATAPACK_EXPORT_STAGE = TextKey.of(
"iris.director.commanddatapack.export.stage",
"Datapack export: {stage}"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_RESOURCES = TextKey.of(
"iris.director.commanddatapack.export.resources",
"Datapack export: {done}/{total} resources"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_DIAGNOSTIC = TextKey.of(
"iris.director.commanddatapack.export.diagnostic",
"{key}: {message}"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_EXPORTED = TextKey.of(
"iris.director.commanddatapack.export.exported",
"Datapack exported: {path}"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_REJECTED = TextKey.of(
"iris.director.commanddatapack.export.rejected",
"Datapack export rejected: {reason}"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_FAILED = TextKey.of(
"iris.director.commanddatapack.export.failed",
"Datapack export failed: {reason}"
);
public static final TextKey COMMAND_DATAPACK_EXPORT_INVALID = TextKey.of(
"iris.director.commanddatapack.export.invalid",
"Invalid datapack export arguments: {reason}"
);
public static final TextKey COMMAND_DEVELOPER_DIRECTOR_IRIS_WORLD_MANAGER = TextKey.of(
"iris.director.commanddeveloper.director.iris_world_manager",
"Iris World Manager"
@@ -888,6 +956,23 @@ public final class DirectorCommandMessages {
COMMAND_DATAPACK_DIRECTOR_LIST_CONFIGURED_DATAPACK_IMPORTS_THEIR_INSTALLED_VERSIONS,
COMMAND_DATAPACK_DIRECTOR_REMOVE_INSTALLED_DATAPACK_BY_ID_ALSO_DELETE_ITS_URL_FROM_DATAPACKIMPORTS_KEEP,
COMMAND_DATAPACK_PARAM_DATAPACK_ID_FOLDER_NAME_SHOWN_BY_IRIS_DATAPACK_LIST,
COMMAND_DATAPACK_EXPORT_DESCRIPTION,
COMMAND_DATAPACK_EXPORT_PARAM_DIMENSION,
COMMAND_DATAPACK_EXPORT_PARAM_VERSION,
COMMAND_DATAPACK_EXPORT_PARAM_MODE,
COMMAND_DATAPACK_EXPORT_PARAM_NAMESPACE,
COMMAND_DATAPACK_EXPORT_PARAM_OUTPUT,
COMMAND_DATAPACK_EXPORT_PARAM_FORMAT,
COMMAND_DATAPACK_EXPORT_PARAM_OBJECTS,
COMMAND_DATAPACK_EXPORT_PARAM_REPLACE,
COMMAND_DATAPACK_EXPORT_STARTED,
COMMAND_DATAPACK_EXPORT_STAGE,
COMMAND_DATAPACK_EXPORT_RESOURCES,
COMMAND_DATAPACK_EXPORT_DIAGNOSTIC,
COMMAND_DATAPACK_EXPORT_EXPORTED,
COMMAND_DATAPACK_EXPORT_REJECTED,
COMMAND_DATAPACK_EXPORT_FAILED,
COMMAND_DATAPACK_EXPORT_INVALID,
COMMAND_DEVELOPER_DIRECTOR_IRIS_WORLD_MANAGER,
COMMAND_DEVELOPER_DIRECTOR_GET_LOADED_TECTONICPLATES_COUNT,
COMMAND_DEVELOPER_DIRECTOR_HASH_GENERATED_BLOCK_OUTPUT_FIXED_AREA_DETERMINISM_IDENTITY_TESTING,
@@ -13,20 +13,24 @@ import art.arcane.iris.pack.datapack.v263.DataFixerV263;
//https://minecraft.wiki/w/Pack_format
@Getter
public enum DataVersion {
UNSUPPORTED("0.0.0", 0, () -> null),
V1_21_1("1.21.1", 48, DataFixerV1206::new),
V26_1_2("26.1.2", 101, DataFixerV1217::new),
V26_2("26.2", 107, DataFixerV1217::new),
V26_3("26.3", 121, DataFixerV263::new);
UNSUPPORTED("0.0.0", 0, 0, 0, () -> null),
V1_21_1("1.21.1", 48, 0, 3955, DataFixerV1206::new),
V26_1_2("26.1.2", 101, 1, 4790, DataFixerV1217::new),
V26_2("26.2", 107, 1, 4903, DataFixerV1217::new),
V26_3("26.3", 121, 0, 5023, DataFixerV263::new);
private static final KMap<DataVersion, IDataFixer> cache = new KMap<>();
@Getter(AccessLevel.NONE)
private final Supplier<IDataFixer> constructor;
private final String version;
private final int packFormat;
private final int packFormatMinor;
private final int worldDataVersion;
DataVersion(String version, int packFormat, Supplier<IDataFixer> constructor) {
DataVersion(String version, int packFormat, int packFormatMinor, int worldDataVersion, Supplier<IDataFixer> constructor) {
this.constructor = constructor;
this.packFormat = packFormat;
this.packFormatMinor = packFormatMinor;
this.worldDataVersion = worldDataVersion;
this.version = version;
}
@@ -0,0 +1,99 @@
package art.arcane.iris.pack.datapack;
import art.arcane.iris.pack.datapack.DatapackIngestService.Entry;
import art.arcane.iris.pack.datapack.ModrinthResolver.ResolvedDatapack;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.io.IO;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.LinkOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
public final class DatapackExportArchives {
private static final String DIRECT_VERSION_PREFIX = "direct-";
private DatapackExportArchives() {
}
public static Path resolve(String source, DataVersion target) throws IOException {
String normalized = DatapackImportSources.normalizeConfiguredSource(Objects.requireNonNull(source, "datapack import source"));
URI uri = DatapackStartupValidation.parseSourceUri(normalized);
if (uri == null) {
throw new IOException("Empty datapack import source");
}
if ("file".equalsIgnoreCase(uri.getScheme())) {
return DatapackArchive.requireLocalDatapackPath(uri);
}
IrisPlatform platform = IrisPlatforms.get();
File root = platform.dataFolder("datapacks");
File cacheDir = new File(root, "cache");
boolean running = DataVersion.forMinecraftVersion(platform.minecraftVersion()) == target;
DatapackTransactions.TRANSACTION_LOCK.lock();
try {
Entry entry = manifestEntry(root, normalized);
Path cached = ingestCache(cacheDir, entry, running);
if (cached != null) {
return cached;
}
return download(cacheDir, normalized, entry, target);
} finally {
DatapackTransactions.TRANSACTION_LOCK.unlock();
}
}
private static Entry manifestEntry(File root, String source) {
try {
return DatapackManifestStore.readCommittedManifest(root).find(source);
} catch (IOException exception) {
IrisLogging.reportError("The datapack manifest under " + root.getPath() + " could not be read; '" + source
+ "' is resolved again for the export", exception);
return null;
}
}
private static Path ingestCache(File cacheDir, Entry entry, boolean running) throws IOException {
if (entry == null || entry.id == null || entry.sha1 == null) {
return null;
}
boolean direct = entry.versionId != null && entry.versionId.startsWith(DIRECT_VERSION_PREFIX);
if (!direct && !running) {
return null;
}
File archive = new File(cacheDir, entry.id + "-" + DatapackSupport.safeFile(entry.versionId) + ".zip");
return matches(archive, entry.sha1) ? archive.toPath() : null;
}
private static Path download(File cacheDir, String source, Entry entry, DataVersion target) throws IOException {
ResolvedDatapack resolved = ModrinthResolver.resolve(source, target.getVersion());
String id = entry == null || entry.id == null ? DatapackArchive.deriveId(resolved) : entry.id;
File archive = new File(cacheDir, id + "-" + DatapackSupport.safeFile(resolved.getVersionId()) + ".zip");
String expected = resolved.getSha1();
if (expected != null && !expected.isBlank() && matches(archive, expected)) {
return archive.toPath();
}
DatapackSupport.ensureScratchDirectory(cacheDir, "datapack download cache");
DatapackArchive.download(resolved.getDownloadUrl(), archive, null, null);
if (expected != null && !expected.isBlank()) {
String checksum = DatapackArchive.sha1(archive);
if (!expected.equalsIgnoreCase(checksum)) {
IO.delete(archive);
throw new IOException("Checksum mismatch for " + id + " (expected " + expected + ", got " + checksum + ")");
}
}
return archive.toPath();
}
private static boolean matches(File archive, String sha1) throws IOException {
Path path = archive.toPath();
if (Files.isSymbolicLink(path) || !Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
return false;
}
return sha1.equalsIgnoreCase(DatapackArchive.sha1(archive));
}
}
@@ -1,4 +1,4 @@
package art.arcane.iris.structure.export;
package art.arcane.iris.pack.datapack.export;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
@@ -14,25 +14,26 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.stream.Stream;
final class AtomicDatapackPublisher {
Publication publish(
Map<String, byte[]> resources,
Path output,
VanillaJigsawExportFormat format,
boolean replaceExisting
public final class AtomicDatapackPublisher {
public Publication publish(
Map<String, byte[]> files,
Path destination,
DatapackExportFormat format,
boolean replace,
String stagingPrefix
) throws IOException {
Path parent = output.getParent();
Path parent = destination.getParent();
if (parent == null) {
throw new IOException("Export output has no parent directory: " + output);
throw new IOException("Export output has no parent directory: " + destination);
}
Files.createDirectories(parent);
Path staging = Files.createTempDirectory(parent, ".iris-jigsaw-export-");
Path staging = Files.createTempDirectory(parent, stagingPrefix);
List<String> cleanupWarnings = new ArrayList<>();
try {
Path artifact = format == VanillaJigsawExportFormat.DIRECTORY
? createDirectoryArtifact(staging, resources)
: createZipArtifact(staging, resources);
replaceAtomically(artifact, output, replaceExisting, cleanupWarnings);
Path artifact = format == DatapackExportFormat.DIRECTORY
? createDirectoryArtifact(staging, files)
: createZipArtifact(staging, files);
replaceAtomically(artifact, destination, replace, cleanupWarnings);
} finally {
try {
deleteTree(staging);
@@ -152,8 +153,8 @@ final class AtomicDatapackPublisher {
}
}
record Publication(List<String> cleanupWarnings) {
Publication {
public record Publication(List<String> cleanupWarnings) {
public Publication {
cleanupWarnings = List.copyOf(cleanupWarnings);
}
}
@@ -0,0 +1,22 @@
package art.arcane.iris.pack.datapack.export;
public record ContentTrim(int filesBefore, long bytesBefore, int filesAfter, long bytesAfter) {
public static final ContentTrim NONE = new ContentTrim(0, 0L, 0, 0L);
public ContentTrim {
if (filesBefore < 0 || bytesBefore < 0L || filesAfter < 0 || bytesAfter < 0L) {
throw new IllegalArgumentException("Content trim counts cannot be negative");
}
if (filesAfter > filesBefore || bytesAfter > bytesBefore) {
throw new IllegalArgumentException("A content trim cannot add files or bytes");
}
}
public int filesRemoved() {
return filesBefore - filesAfter;
}
public long bytesRemoved() {
return bytesBefore - bytesAfter;
}
}
@@ -0,0 +1,53 @@
package art.arcane.iris.pack.datapack.export;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
public final class DatapackExportDestinations {
private static final Pattern OUTPUT_NAME = Pattern.compile("[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,127}");
private static final Set<Path> CLAIMED = ConcurrentHashMap.newKeySet();
private DatapackExportDestinations() {
}
public static DatapackExportFormat parseFormat(String raw) {
return switch (raw.trim().toLowerCase(Locale.ROOT)) {
case "zip" -> DatapackExportFormat.ZIP;
case "directory", "dir", "folder" -> DatapackExportFormat.DIRECTORY;
default -> throw new IllegalArgumentException("Export format must be directory or zip.");
};
}
public static Path resolve(Path exportRoot, String output, DatapackExportFormat format) {
Path root = Objects.requireNonNull(exportRoot, "Datapack export root").toAbsolutePath().normalize();
String requested = Objects.requireNonNull(output, "Datapack export output name");
String name = requested.trim();
if (!name.equals(requested) || !OUTPUT_NAME.matcher(name).matches()) {
throw new IllegalArgumentException(
"Export output must be one file name using letters, numbers, '.', '_', or '-'.");
}
String fileName = format == DatapackExportFormat.ZIP && !name.endsWith(".zip") ? name + ".zip" : name;
Path destination = root.resolve(fileName).normalize();
if (destination.equals(root) || !root.equals(destination.getParent())) {
throw new IllegalArgumentException("Export output must be one artifact inside the exports folder.");
}
return destination;
}
public static boolean claim(Path destination) {
return CLAIMED.add(normalized(destination));
}
public static void release(Path destination) {
CLAIMED.remove(normalized(destination));
}
private static Path normalized(Path destination) {
return Objects.requireNonNull(destination, "Datapack export destination").toAbsolutePath().normalize();
}
}
@@ -0,0 +1,6 @@
package art.arcane.iris.pack.datapack.export;
public enum DatapackExportFormat {
ZIP,
DIRECTORY
}
@@ -0,0 +1,83 @@
package art.arcane.iris.pack.datapack.export;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.Optional;
public record GenerationCost(Map<GenerationCost.Root, GenerationCost.RootCost> roots, long densityFunctionBytes) {
public static final GenerationCost NONE = new GenerationCost(Map.of(), 0L);
private static final String DATA_PREFIX = "data/";
private static final String DENSITY_FUNCTION_FOLDER = "/worldgen/density_function/";
private static final String JSON_SUFFIX = ".json";
public GenerationCost {
EnumMap<Root, RootCost> copy = new EnumMap<>(Root.class);
copy.putAll(roots);
roots = Collections.unmodifiableMap(copy);
if (densityFunctionBytes < 0L) {
throw new IllegalArgumentException("Density function JSON size cannot be negative, got " + densityFunctionBytes);
}
}
public static long densityFunctionBytes(Map<String, byte[]> files) {
long bytes = 0L;
for (Map.Entry<String, byte[]> file : files.entrySet()) {
String path = file.getKey();
if (path.startsWith(DATA_PREFIX) && path.contains(DENSITY_FUNCTION_FOLDER) && path.endsWith(JSON_SUFFIX)) {
bytes += file.getValue().length;
}
}
return bytes;
}
public Optional<RootCost> root(Root root) {
return Optional.ofNullable(roots.get(root));
}
public GenerationCost withDensityFunctionBytes(long bytes) {
return new GenerationCost(roots, bytes);
}
public enum Root {
TEMPERATURE("temperature", true),
VEGETATION("vegetation", true),
CONTINENTS("continents", true),
EROSION("erosion", true),
DEPTH("depth", true),
RIDGES("ridges", true),
CHUNK_SURFACE_LEVEL("chunk_surface_level", false),
FINAL_DENSITY("final_density", false),
AQUIFER_BARRIER("aquifer.barrier", false),
AQUIFER_FLOODEDNESS("aquifer.fluid_level_floodedness", false),
AQUIFER_SPREAD("aquifer.fluid_level_spread", false),
AQUIFER_LAVA("aquifer.lava", false),
AQUIFER_EXCLUSION("aquifer.exclusion", false),
AQUIFER_SURFACE_LEVEL("aquifer.surface_level", false);
private final String id;
private final boolean climate;
Root(String id, boolean climate) {
this.id = id;
this.climate = climate;
}
public String id() {
return id;
}
public boolean climate() {
return climate;
}
}
public record RootCost(double worstCaseNodes, double expandedNodes, long distinctNodes) {
public RootCost {
if (!(worstCaseNodes >= 0.0) || !(expandedNodes >= 0.0) || distinctNodes < 0L) {
throw new IllegalArgumentException("Generation cost counts cannot be negative, got " + worstCaseNodes + " worst case, "
+ expandedNodes + " expanded and " + distinctNodes + " distinct");
}
}
}
}
@@ -0,0 +1,195 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.generation.geometry.IrisBlockVector;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.Vector3i;
import art.arcane.volmlib.util.nbt.io.NBTUtil;
import art.arcane.volmlib.util.nbt.io.NamedTag;
import art.arcane.volmlib.util.nbt.mca.MCABlockStateCodecSupport;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import art.arcane.volmlib.util.nbt.tag.IntTag;
import art.arcane.volmlib.util.nbt.tag.ListTag;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.GZIPOutputStream;
public final class StructureTemplateEncoder {
private static final Comparator<TemplateBlock> BLOCK_ORDER = Comparator
.comparingInt(TemplateBlock::y)
.thenComparingInt(TemplateBlock::x)
.thenComparingInt(TemplateBlock::z);
public static TemplateVolume volume(IrisObject object, String resource, List<ExportDiagnostic> diagnostics) {
List<TemplateBlock> inside = new ArrayList<>();
int outside = 0;
String firstOutside = null;
for (TemplateBlock block : blocks(object, resource, diagnostics)) {
if (block.x() < 0 || block.y() < 0 || block.z() < 0
|| block.x() >= object.getW() || block.y() >= object.getH() || block.z() >= object.getD()) {
outside++;
if (firstOutside == null) {
firstOutside = block.x() + "," + block.y() + "," + block.z();
}
continue;
}
inside.add(block);
}
if (outside > 0) {
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.OBJECT_BOUNDS, resource,
outside + " blocks outside the " + object.getW() + "x" + object.getH() + "x" + object.getD()
+ " object size are left out of the template, first at " + firstOutside));
}
return new TemplateVolume(object.getW(), object.getH(), object.getD(), inside);
}
public static List<TemplateBlock> blocks(IrisObject object, String resource, List<ExportDiagnostic> diagnostics) {
List<TemplateBlock> blocks = new ArrayList<>();
Vector3i center = object.getCenter();
int droppedTiles = 0;
String firstDropped = null;
Set<String> customBlocks = new TreeSet<>();
for (Map.Entry<IrisBlockVector, NativeBlockState> entry : object.getBlocks()) {
IrisBlockVector signed = entry.getKey();
int x = signed.getBlockX() + center.getX();
int y = signed.getBlockY() + center.getY();
int z = signed.getBlockZ() + center.getZ();
VanillaBlockState state;
try {
state = VanillaBlockState.parse(entry.getValue().key());
} catch (IllegalArgumentException exception) {
customBlocks.add(entry.getValue().key());
continue;
}
TileData tile = object.getStates().get(signed);
CompoundTag nbt = null;
if (tile != null) {
Optional<CompoundTag> converted = TileEntityNbt.toNbt(tile.getMaterialKey(), tile.getProperties());
if (converted.isPresent()) {
nbt = converted.get();
} else {
droppedTiles++;
if (firstDropped == null) {
firstDropped = state.name() + " at " + x + "," + y + "," + z;
}
}
}
blocks.add(new TemplateBlock(x, y, z, state, nbt));
}
if (!customBlocks.isEmpty()) {
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.CUSTOM_BLOCK, resource,
"Blocks outside Minecraft are left out of the template: " + String.join(", ", customBlocks)));
}
if (droppedTiles > 0) {
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.TILE_ENTITY, resource,
droppedTiles + " tile entities have no vanilla block entity form and export as plain blocks, first "
+ firstDropped));
}
return blocks;
}
public byte[] encode(IrisObject object, List<TemplateBlock> extraBlocks, DataVersion target) throws IOException {
List<ExportDiagnostic> lossy = new ArrayList<>();
TemplateVolume volume = volume(object, object.getLoadKey(), lossy);
if (!lossy.isEmpty()) {
throw new IllegalArgumentException("Object '" + object.getLoadKey() + "' cannot be encoded: " + lossy.getFirst().message());
}
Map<BlockPosition, TemplateBlock> blocks = new LinkedHashMap<>();
for (TemplateBlock block : volume.blocks()) {
blocks.put(new BlockPosition(block.x(), block.y(), block.z()), block);
}
for (TemplateBlock extra : extraBlocks) {
blocks.put(new BlockPosition(extra.x(), extra.y(), extra.z()), extra);
}
return encode(new TemplateVolume(volume.sizeX(), volume.sizeY(), volume.sizeZ(), new ArrayList<>(blocks.values())), target);
}
public byte[] encode(TemplateVolume volume, DataVersion target) throws IOException {
MCABlockStateCodecSupport.Format format = paletteFormat(target);
List<TemplateBlock> orderedBlocks = new ArrayList<>(volume.blocks());
orderedBlocks.sort(BLOCK_ORDER);
for (int index = 1; index < orderedBlocks.size(); index++) {
if (BLOCK_ORDER.compare(orderedBlocks.get(index - 1), orderedBlocks.get(index)) == 0) {
TemplateBlock duplicate = orderedBlocks.get(index);
throw new IllegalArgumentException("Template has two blocks at " + duplicate.x() + "," + duplicate.y() + "," + duplicate.z());
}
}
Map<String, Integer> paletteIndexes = new LinkedHashMap<>();
List<VanillaBlockState> paletteStates = new ArrayList<>();
for (TemplateBlock block : orderedBlocks) {
String key = block.state().canonical();
if (!paletteIndexes.containsKey(key)) {
paletteIndexes.put(key, paletteStates.size());
paletteStates.add(block.state());
}
}
CompoundTag root = new CompoundTag();
root.put("size", intList(volume.sizeX(), volume.sizeY(), volume.sizeZ()));
root.put("palette", palette(paletteStates, format));
root.put("blocks", blocks(orderedBlocks, paletteIndexes));
root.put("entities", new ListTag<>(CompoundTag.class));
root.putInt("DataVersion", target.getWorldDataVersion());
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(output)) {
NBTUtil.write(new NamedTag("", root), gzip, false);
}
return output.toByteArray();
}
private static MCABlockStateCodecSupport.Format paletteFormat(DataVersion target) {
return switch (target) {
case V26_3 -> MCABlockStateCodecSupport.Format.LOWERCASE;
case V1_21_1, V26_1_2, V26_2 -> MCABlockStateCodecSupport.Format.CAPITALIZED;
case UNSUPPORTED -> throw new IllegalArgumentException("Structure templates need a supported target version");
};
}
private ListTag<CompoundTag> palette(List<VanillaBlockState> states, MCABlockStateCodecSupport.Format format) {
ListTag<CompoundTag> palette = new ListTag<>(CompoundTag.class);
for (VanillaBlockState state : states) {
palette.add(state.toNbt(format));
}
return palette;
}
private ListTag<CompoundTag> blocks(List<TemplateBlock> entries, Map<String, Integer> paletteIndexes) {
ListTag<CompoundTag> blocks = new ListTag<>(CompoundTag.class);
for (TemplateBlock entry : entries) {
CompoundTag block = new CompoundTag();
block.put("pos", intList(entry.x(), entry.y(), entry.z()));
block.putInt("state", paletteIndexes.get(entry.state().canonical()));
if (entry.nbt() != null) {
block.put("nbt", entry.nbt());
}
blocks.add(block);
}
return blocks;
}
private ListTag<IntTag> intList(int... values) {
ListTag<IntTag> list = new ListTag<>(IntTag.class);
for (int value : values) {
list.add(new IntTag(value));
}
return list;
}
private record BlockPosition(int x, int y, int z) {
}
}
@@ -0,0 +1,11 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import java.util.Objects;
public record TemplateBlock(int x, int y, int z, VanillaBlockState state, CompoundTag nbt) {
public TemplateBlock {
Objects.requireNonNull(state, "Template block state");
}
}
@@ -0,0 +1,22 @@
package art.arcane.iris.pack.datapack.export;
import java.util.List;
public record TemplateVolume(int sizeX, int sizeY, int sizeZ, List<TemplateBlock> blocks) {
public TemplateVolume {
if (sizeX < 0 || sizeY < 0 || sizeZ < 0) {
throw new IllegalArgumentException("Template size must not be negative, got " + sizeX + "x" + sizeY + "x" + sizeZ);
}
blocks = List.copyOf(blocks);
for (TemplateBlock block : blocks) {
if (block.x() < 0 || block.y() < 0 || block.z() < 0 || block.x() >= sizeX || block.y() >= sizeY || block.z() >= sizeZ) {
throw new IllegalArgumentException("Template block at " + block.x() + "," + block.y() + "," + block.z()
+ " lies outside the " + sizeX + "x" + sizeY + "x" + sizeZ + " template");
}
}
}
public int footprint() {
return Math.max(sizeX, sizeZ);
}
}
@@ -0,0 +1,324 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.volmlib.util.nbt.io.SNBTDeserializer;
import art.arcane.volmlib.util.nbt.tag.ByteTag;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import art.arcane.volmlib.util.nbt.tag.DoubleTag;
import art.arcane.volmlib.util.nbt.tag.EndTag;
import art.arcane.volmlib.util.nbt.tag.FloatTag;
import art.arcane.volmlib.util.nbt.tag.IntArrayTag;
import art.arcane.volmlib.util.nbt.tag.IntTag;
import art.arcane.volmlib.util.nbt.tag.ListTag;
import art.arcane.volmlib.util.nbt.tag.LongTag;
import art.arcane.volmlib.util.nbt.tag.ShortTag;
import art.arcane.volmlib.util.nbt.tag.StringTag;
import art.arcane.volmlib.util.nbt.tag.Tag;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
public final class TileEntityNbt {
private static final String SNBT_PROPERTY = "nbt";
private static final String ID = "id";
private static final String PROFILE = "profile";
private static final String UUID = "UUID";
private static final int MAX_DEPTH = 64;
private static final Set<String> POSITION_KEYS = Set.of("x", "y", "z");
private static final Map<String, String> BLOCK_ENTITIES = Map.ofEntries(
Map.entry("minecraft:chest", "minecraft:chest"),
Map.entry("minecraft:trapped_chest", "minecraft:trapped_chest"),
Map.entry("minecraft:ender_chest", "minecraft:ender_chest"),
Map.entry("minecraft:barrel", "minecraft:barrel"),
Map.entry("minecraft:furnace", "minecraft:furnace"),
Map.entry("minecraft:smoker", "minecraft:smoker"),
Map.entry("minecraft:blast_furnace", "minecraft:blast_furnace"),
Map.entry("minecraft:dispenser", "minecraft:dispenser"),
Map.entry("minecraft:dropper", "minecraft:dropper"),
Map.entry("minecraft:hopper", "minecraft:hopper"),
Map.entry("minecraft:brewing_stand", "minecraft:brewing_stand"),
Map.entry("minecraft:beacon", "minecraft:beacon"),
Map.entry("minecraft:lectern", "minecraft:lectern"),
Map.entry("minecraft:jukebox", "minecraft:jukebox"),
Map.entry("minecraft:enchanting_table", "minecraft:enchanting_table"),
Map.entry("minecraft:conduit", "minecraft:conduit"),
Map.entry("minecraft:bell", "minecraft:bell"),
Map.entry("minecraft:crafter", "minecraft:crafter"),
Map.entry("minecraft:daylight_detector", "minecraft:daylight_detector"),
Map.entry("minecraft:comparator", "minecraft:comparator"),
Map.entry("minecraft:end_gateway", "minecraft:end_gateway"),
Map.entry("minecraft:end_portal", "minecraft:end_portal"),
Map.entry("minecraft:sculk_sensor", "minecraft:sculk_sensor"),
Map.entry("minecraft:calibrated_sculk_sensor", "minecraft:calibrated_sculk_sensor"),
Map.entry("minecraft:sculk_catalyst", "minecraft:sculk_catalyst"),
Map.entry("minecraft:sculk_shrieker", "minecraft:sculk_shrieker"),
Map.entry("minecraft:chiseled_bookshelf", "minecraft:chiseled_bookshelf"),
Map.entry("minecraft:decorated_pot", "minecraft:decorated_pot"),
Map.entry("minecraft:creaking_heart", "minecraft:creaking_heart"),
Map.entry("minecraft:trial_spawner", "minecraft:trial_spawner"),
Map.entry("minecraft:vault", "minecraft:vault"),
Map.entry("minecraft:beehive", "minecraft:beehive"),
Map.entry("minecraft:bee_nest", "minecraft:beehive"),
Map.entry("minecraft:spawner", "minecraft:mob_spawner"),
Map.entry("minecraft:campfire", "minecraft:campfire"),
Map.entry("minecraft:soul_campfire", "minecraft:campfire"),
Map.entry("minecraft:command_block", "minecraft:command_block"),
Map.entry("minecraft:chain_command_block", "minecraft:command_block"),
Map.entry("minecraft:repeating_command_block", "minecraft:command_block"),
Map.entry("minecraft:suspicious_sand", "minecraft:brushable_block"),
Map.entry("minecraft:suspicious_gravel", "minecraft:brushable_block"));
private static final List<Map.Entry<String, String>> SUFFIX_BLOCK_ENTITIES = List.of(
Map.entry("_hanging_sign", "minecraft:hanging_sign"),
Map.entry("_sign", "minecraft:sign"),
Map.entry("_banner", "minecraft:banner"),
Map.entry("_head", "minecraft:skull"),
Map.entry("_skull", "minecraft:skull"),
Map.entry("_bed", "minecraft:bed"),
Map.entry("shulker_box", "minecraft:shulker_box"),
Map.entry("_shelf", "minecraft:shelf"),
Map.entry("copper_golem_statue", "minecraft:copper_golem_statue"));
private static final Set<String> BYTE_FIELDS = Set.of(
"Slot", "Count", "has_glowing_text", "is_waxed", "auto", "conditionMet", "powered", "TrackOutput",
"UpdateLastExecution", "OnGround", "Invulnerable", "Silent", "NoGravity", "Glowing",
"PersistenceRequired", "CanPickUpLoot", "LeftHanded", "NoAI", "ExactTeleport", "show_particles",
"show_icon", "ambient");
private static final Set<String> SHORT_FIELDS = Set.of(
"Delay", "MinSpawnDelay", "MaxSpawnDelay", "SpawnCount", "MaxNearbyEntities", "RequiredPlayerRange",
"SpawnRange", "BurnTime", "CookTime", "CookTimeTotal", "lit_time_remaining", "lit_total_time",
"cooking_time_spent", "cooking_total_time", "Fire", "Air", "HurtTime", "DeathTime");
private static final Set<String> LONG_FIELDS = Set.of("LootTableSeed", "Age", "LastExecution", "ticks_since_song_started");
private static final Set<String> FLOAT_FIELDS = Set.of("Health", "AbsorptionAmount", "Rotation", "HandDropChances", "ArmorDropChances");
private TileEntityNbt() {
}
public static Optional<String> blockEntityId(String blockKey) {
String key = normalizeBlockKey(blockKey);
if (key.isEmpty()) {
return Optional.empty();
}
String exact = BLOCK_ENTITIES.get(key);
if (exact != null) {
return Optional.of(exact);
}
if (!key.startsWith("minecraft:")) {
return Optional.empty();
}
for (Map.Entry<String, String> suffix : SUFFIX_BLOCK_ENTITIES) {
if (key.endsWith(suffix.getKey())) {
return Optional.of(suffix.getValue());
}
}
return Optional.empty();
}
public static Optional<CompoundTag> toNbt(String blockKey, Map<String, Object> properties) {
Optional<String> blockEntity = blockEntityId(blockKey);
if (blockEntity.isEmpty() || properties == null) {
return Optional.empty();
}
CompoundTag nbt = parseSnbt(properties.get(SNBT_PROPERTY));
if (nbt == null) {
nbt = compound(properties, "", 0);
}
for (String key : POSITION_KEYS) {
nbt.remove(key);
}
nbt.remove(SNBT_PROPERTY);
if (nbt.size() == 0) {
return Optional.empty();
}
if (!nbt.containsKey(ID)) {
nbt.putString(ID, blockEntity.get());
}
return Optional.of(nbt);
}
private static String normalizeBlockKey(String blockKey) {
if (blockKey == null) {
return "";
}
String trimmed = blockKey.trim().toLowerCase(Locale.ROOT);
int properties = trimmed.indexOf('[');
String base = properties < 0 ? trimmed : trimmed.substring(0, properties);
if (base.isEmpty()) {
return "";
}
return base.indexOf(':') < 0 ? "minecraft:" + base : base;
}
private static CompoundTag parseSnbt(Object snbt) {
if (!(snbt instanceof String text) || text.isBlank()) {
return null;
}
try {
Tag<?> parsed = new SNBTDeserializer().fromString(text);
return parsed instanceof CompoundTag compound ? compound : null;
} catch (IOException | RuntimeException exception) {
return null;
}
}
private static CompoundTag compound(Map<?, ?> values, String parent, int depth) {
CompoundTag compound = new CompoundTag();
if (depth > MAX_DEPTH) {
return compound;
}
Map<String, Object> sorted = new TreeMap<>();
for (Map.Entry<?, ?> entry : values.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
sorted.put(String.valueOf(entry.getKey()), entry.getValue());
}
}
if (depth == 0) {
sorted.remove(SNBT_PROPERTY);
}
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
Tag<?> tag = tag(entry.getKey(), parent, entry.getValue(), depth + 1);
if (tag != null) {
compound.put(entry.getKey(), tag);
}
}
return compound;
}
private static Tag<?> tag(String key, String parent, Object value, int depth) {
if (value instanceof Map<?, ?> map) {
return compound(map, key, depth);
}
if (value instanceof List<?> list) {
return list(key, parent, list, depth);
}
if (value instanceof Boolean bool) {
return new ByteTag(bool);
}
if (value instanceof Number number) {
return number(numberKind(key, number), number);
}
return new StringTag(String.valueOf(value));
}
private static Tag<?> list(String key, String parent, List<?> values, int depth) {
if (intArray(key, parent) && allNumbers(values)) {
int[] ints = new int[values.size()];
for (int index = 0; index < ints.length; index++) {
ints[index] = ((Number) values.get(index)).intValue();
}
return new IntArrayTag(ints);
}
NumberKind listKind = allNumbers(values) ? listNumberKind(key, values) : null;
ListTag<?> list = ListTag.createUnchecked(EndTag.class);
Class<?> elementType = null;
for (Object value : values) {
if (value == null) {
continue;
}
Tag<?> element = listKind == null ? tag(key, parent, value, depth + 1) : number(listKind, (Number) value);
if (element == null) {
continue;
}
if (elementType == null) {
elementType = element.getClass();
}
if (elementType != element.getClass()) {
return stringList(values);
}
list.addUnchecked(element);
}
return list;
}
private static ListTag<?> stringList(List<?> values) {
ListTag<?> list = ListTag.createUnchecked(EndTag.class);
for (Object value : values) {
if (value != null) {
list.addUnchecked(new StringTag(String.valueOf(value)));
}
}
return list;
}
private static boolean intArray(String key, String parent) {
return UUID.equals(key) || (ID.equals(key) && PROFILE.equals(parent));
}
private static boolean allNumbers(List<?> values) {
if (values.isEmpty()) {
return false;
}
for (Object value : values) {
if (!(value instanceof Number)) {
return false;
}
}
return true;
}
private static NumberKind listNumberKind(String key, List<?> values) {
NumberKind declared = declaredKind(key);
if (declared != null) {
return declared;
}
NumberKind widest = NumberKind.INT;
for (Object value : values) {
NumberKind kind = inferredKind((Number) value);
if (kind.ordinal() > widest.ordinal()) {
widest = kind;
}
}
return widest;
}
private static NumberKind numberKind(String key, Number number) {
NumberKind declared = declaredKind(key);
return declared == null ? inferredKind(number) : declared;
}
private static NumberKind declaredKind(String key) {
if (BYTE_FIELDS.contains(key)) {
return NumberKind.BYTE;
}
if (SHORT_FIELDS.contains(key)) {
return NumberKind.SHORT;
}
if (LONG_FIELDS.contains(key)) {
return NumberKind.LONG;
}
if (FLOAT_FIELDS.contains(key)) {
return NumberKind.FLOAT;
}
return null;
}
private static NumberKind inferredKind(Number number) {
if (number instanceof Double || number instanceof Float) {
return NumberKind.DOUBLE;
}
long value = number.longValue();
return value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE ? NumberKind.INT : NumberKind.LONG;
}
private static Tag<?> number(NumberKind kind, Number number) {
return switch (kind) {
case BYTE -> new ByteTag(number.byteValue());
case SHORT -> new ShortTag(number.shortValue());
case INT -> new IntTag(number.intValue());
case LONG -> new LongTag(number.longValue());
case FLOAT -> new FloatTag(number.floatValue());
case DOUBLE -> new DoubleTag(number.doubleValue());
};
}
private enum NumberKind {
BYTE,
SHORT,
INT,
LONG,
FLOAT,
DOUBLE
}
}
@@ -1,4 +1,4 @@
package art.arcane.iris.structure.export;
package art.arcane.iris.pack.datapack.export;
import art.arcane.volmlib.util.nbt.tag.CompoundTag;
import art.arcane.volmlib.util.nbt.mca.MCABlockStateCodecSupport;
@@ -9,15 +9,15 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
record VanillaBlockState(String name, Map<String, String> properties) {
public record VanillaBlockState(String name, Map<String, String> properties) {
private static final Pattern PROPERTY_NAME = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PROPERTY_VALUE = Pattern.compile("[a-z0-9_.-]+");
VanillaBlockState {
public VanillaBlockState {
properties = Collections.unmodifiableMap(new LinkedHashMap<>(properties));
}
static VanillaBlockState parse(String value) {
public static VanillaBlockState parse(String value) {
if (value == null) {
throw new IllegalArgumentException("Block state must not be null");
}
@@ -58,7 +58,18 @@ record VanillaBlockState(String name, Map<String, String> properties) {
return new VanillaBlockState(name, properties);
}
String canonical() {
public VanillaBlockState waterlogged(boolean submerged) {
String value = Boolean.toString(submerged);
String current = properties.get("waterlogged");
if (current == null || current.equals(value)) {
return this;
}
Map<String, String> changed = new LinkedHashMap<>(properties);
changed.put("waterlogged", value);
return new VanillaBlockState(name, changed);
}
public String canonical() {
if (properties.isEmpty()) {
return name;
}
@@ -74,7 +85,7 @@ record VanillaBlockState(String name, Map<String, String> properties) {
return builder.append(']').toString();
}
CompoundTag toNbt(MCABlockStateCodecSupport.Format format) {
public CompoundTag toNbt(MCABlockStateCodecSupport.Format format) {
CompoundTag state = new CompoundTag();
state.putString(format.nameKey(), name);
if (!properties.isEmpty()) {
@@ -0,0 +1,104 @@
package art.arcane.iris.pack.datapack.export;
import java.util.Locale;
import java.util.StringJoiner;
import java.util.regex.Pattern;
public final class VanillaResourceIdentifier {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9/._-]+");
private static final Pattern INVALID_PATH_CHARACTER = Pattern.compile("[^a-z0-9._-]");
private VanillaResourceIdentifier() {
}
public static boolean validNamespace(String value) {
return value != null && NAMESPACE.matcher(value).matches();
}
public static boolean validPath(String value) {
if (value == null
|| !PATH.matcher(value).matches()
|| value.startsWith("/")
|| value.endsWith("/")
|| value.contains("//")) {
return false;
}
for (String segment : value.split("/")) {
if (segment.equals(".") || segment.equals("..")) {
return false;
}
}
return true;
}
public static boolean validIdentifier(String value) {
if (value == null) {
return false;
}
int separator = value.indexOf(':');
if (separator <= 0 || separator != value.lastIndexOf(':')) {
return false;
}
return validNamespace(value.substring(0, separator)) && validPath(value.substring(separator + 1));
}
public static String requireNamespace(String value, String role) {
if (!validNamespace(value)) {
throw invalid(value, role);
}
return value;
}
public static String requirePath(String value, String role) {
if (!validPath(value)) {
throw invalid(value, role);
}
return value;
}
public static String requireIdentifier(String value, String role) {
if (!validIdentifier(value)) {
throw invalid(value, role);
}
return value;
}
public static String sanitizePath(String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Cannot derive a resource path from '" + value + "'");
}
String lowered = value.trim().replace('\\', '/').toLowerCase(Locale.ROOT);
StringJoiner path = new StringJoiner("/");
for (String segment : lowered.split("/")) {
if (segment.isEmpty()) {
continue;
}
String cleaned = INVALID_PATH_CHARACTER.matcher(segment).replaceAll("_");
path.add(cleaned.equals(".") || cleaned.equals("..") ? cleaned.replace('.', '_') : cleaned);
}
String result = path.toString();
if (result.isEmpty()) {
throw new IllegalArgumentException("Cannot derive a resource path from '" + value + "'");
}
return result;
}
public static String normalizeConnectorIdentifier(String value) {
if (value == null || value.isBlank()) {
return "minecraft:empty";
}
String normalized = value.trim();
if (normalized.indexOf(':') < 0) {
normalized = "minecraft:" + normalized;
}
if (!validIdentifier(normalized)) {
throw new IllegalArgumentException("Invalid resource identifier '" + value + "'");
}
return normalized;
}
private static IllegalArgumentException invalid(String value, String role) {
return new IllegalArgumentException("Invalid " + role + " '" + value + "'");
}
}
@@ -0,0 +1,170 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.PackCompiler;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseStyleCompiler;
import art.arcane.iris.pack.datapack.export.emit.UnusedResourcePruner;
import art.arcane.iris.pack.datapack.export.emit.WorldgenJsonWriter;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.datapack.export.lower.GenerationBudget;
import art.arcane.iris.pack.datapack.export.lower.GenerationCostCounter;
import art.arcane.iris.pack.datapack.export.lower.VanillaBounds;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.spi.IrisLogging;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.function.Function;
import java.util.regex.Pattern;
public final class WorldgenDatapackExporter implements WorldgenExportService {
private static final String STAGING_PREFIX = ".iris-worldgen-export-";
private static final Pattern UNSAFE_OUTPUT_CHARACTER = Pattern.compile("[^A-Za-z0-9._-]");
private final Function<DataVersion, WorldgenJsonWriter> writers;
private final PackCompiler compiler;
public WorldgenDatapackExporter(Function<DataVersion, WorldgenJsonWriter> writers, PackCompiler compiler) {
this.writers = Objects.requireNonNull(writers);
this.compiler = Objects.requireNonNull(compiler);
}
public static WorldgenDatapackExporter create() {
return new WorldgenDatapackExporter(WorldgenJsonWriter::forTarget, PackCompiler.create());
}
@Override
public WorldgenExportResult export(WorldgenExportRequest request, WorldgenExportProgress progress) {
Objects.requireNonNull(request);
Objects.requireNonNull(progress);
ExportPlan plan;
try {
plan = plan(request);
} catch (IllegalArgumentException exception) {
return WorldgenExportResult.rejected(null, exception.getMessage(), List.of());
}
Path destination = plan.destination();
if (Files.exists(destination) && !request.replace()) {
return rejected(destination, "Export output already exists: " + destination + ". Pass replace=true to overwrite it.");
}
if (!DatapackExportDestinations.claim(destination)) {
return rejected(destination, "An export to " + destination + " is already running.");
}
try {
return exportClaimed(request, plan, progress);
} finally {
DatapackExportDestinations.release(destination);
}
}
private ExportPlan plan(WorldgenExportRequest request) {
DataVersion target = WorldgenExportTargets.resolve(request.version());
WorldgenExportMode mode = WorldgenExportMode.parse(request.mode());
DatapackExportFormat format = DatapackExportDestinations.parseFormat(request.format());
String namespace = VanillaResourceIdentifier.requireNamespace(request.namespace(), "export namespace");
String output = request.output().isEmpty() ? defaultOutput(request.dimension(), target) : request.output();
return new ExportPlan(target, mode, format, namespace, DatapackExportDestinations.resolve(request.exportRoot(), output, format));
}
private WorldgenExportResult exportClaimed(WorldgenExportRequest request, ExportPlan plan, WorldgenExportProgress progress) {
Path destination = plan.destination();
File pack = request.pack().toFile();
try {
progress.stage("validate");
PackValidationResult validation = PackValidator.validateForPackaging(pack);
if (!validation.isLoadable()) {
return rejected(destination, "Pack '" + validation.getPackName() + "' failed validation: "
+ String.join("; ", validation.getBlockingErrors()));
}
progress.stage("load");
IrisData data = IrisData.openRuntime(pack);
try {
IrisDimension dimension = data.getDimensionLoader().load(request.dimension(), false);
if (dimension == null) {
return rejected(destination, "Dimension '" + request.dimension() + "' was not found in pack '" + pack.getName() + "'.");
}
PackCompileContext context = compileContext(data, dimension, plan, request.objects());
ExportIr ir = compiler.compile(context, progress);
return publish(request, plan, ir, context.biomeCodes().loadKeyByBiomeId(), progress);
} finally {
data.close();
}
} catch (IOException exception) {
IrisLogging.reportError("Worldgen datapack publication to " + destination + " failed", exception);
return WorldgenExportResult.failed(destination, "Datapack publication failed: " + exception.getMessage(), List.of());
} catch (RuntimeException exception) {
IrisLogging.reportError("Worldgen datapack export of dimension '" + request.dimension() + "' failed", exception);
return WorldgenExportResult.failed(destination, "Datapack export failed: " + exception.getMessage(), List.of());
}
}
private WorldgenExportResult publish(WorldgenExportRequest request, ExportPlan plan, ExportIr ir, Map<String, String> loadKeyByBiomeId,
WorldgenExportProgress progress) throws IOException {
progress.stage("write");
GenerationCost routerCost = GenerationCostCounter.count(ir.router(), VanillaBounds.of(ir.namespace(), ir.noises()), ir.target());
SortedMap<String, byte[]> files = writers.apply(plan.target()).write(ir);
progress.resources(files.size(), files.size());
progress.stage("prune");
UnusedResourcePruner.Pruned pruned = UnusedResourcePruner.prune(files);
progress.trimmed(pruned.trim());
GenerationCost cost = routerCost.withDensityFunctionBytes(GenerationCost.densityFunctionBytes(pruned.files()));
progress.stage("publish");
AtomicDatapackPublisher.Publication publication = new AtomicDatapackPublisher().publish(
pruned.files(),
plan.destination(),
plan.format(),
request.replace(),
STAGING_PREFIX);
List<ExportDiagnostic> costDiagnostics = GenerationBudget.check(cost, ir.dimension().name());
List<ExportDiagnostic> diagnostics = new ArrayList<>(ir.diagnostics().size() + pruned.diagnostics().size() + costDiagnostics.size());
diagnostics.addAll(ir.diagnostics());
diagnostics.addAll(costDiagnostics);
diagnostics.addAll(pruned.diagnostics());
return new WorldgenExportResult(
WorldgenExportResult.Status.EXPORTED,
plan.destination(),
String.join("; ", publication.cleanupWarnings()),
diagnostics,
loadKeyByBiomeId,
pruned.trim(),
cost);
}
private static PackCompileContext compileContext(IrisData data, IrisDimension dimension, ExportPlan plan, boolean objects) {
List<ExportDiagnostic> diagnostics = new ArrayList<>();
return PackCompileContext.builder()
.data(data)
.dimension(dimension)
.capabilities(ExportCapabilities.forTarget(plan.target()))
.namespace(plan.namespace())
.mode(plan.mode())
.objects(objects)
.diagnostics(diagnostics)
.styles(NoiseStyleCompiler.create(diagnostics))
.build();
}
private static String defaultOutput(String dimension, DataVersion target) {
return UNSAFE_OUTPUT_CHARACTER.matcher(dimension.replace('/', '-')).replaceAll("-") + "-" + target.getVersion();
}
private static WorldgenExportResult rejected(Path destination, String message) {
return WorldgenExportResult.rejected(destination, message, List.of());
}
private record ExportPlan(DataVersion target, WorldgenExportMode mode, DatapackExportFormat format, String namespace, Path destination) {
}
}
@@ -0,0 +1,21 @@
package art.arcane.iris.pack.datapack.export;
import java.util.Locale;
public enum WorldgenExportMode {
PRESET,
DIMENSION,
OVERWORLD;
public static WorldgenExportMode parse(String raw) {
if (raw == null || raw.isBlank()) {
return OVERWORLD;
}
return switch (raw.trim().toLowerCase(Locale.ROOT)) {
case "preset" -> PRESET;
case "dimension" -> DIMENSION;
case "overworld" -> OVERWORLD;
default -> throw new IllegalArgumentException("Unknown export mode '" + raw + "'. Expected: preset, dimension, overworld");
};
}
}
@@ -0,0 +1,20 @@
package art.arcane.iris.pack.datapack.export;
public interface WorldgenExportProgress {
WorldgenExportProgress NONE = new WorldgenExportProgress() {
@Override
public void stage(String stage) {
}
@Override
public void resources(int done, int total) {
}
};
void stage(String stage);
void resources(int done, int total);
default void trimmed(ContentTrim trim) {
}
}
@@ -0,0 +1,112 @@
package art.arcane.iris.pack.datapack.export;
import java.nio.file.Path;
import java.util.Objects;
public record WorldgenExportRequest(
Path pack,
String dimension,
String version,
String mode,
String namespace,
String output,
String format,
boolean objects,
boolean replace,
Path exportRoot
) {
public static final String DEFAULT_MODE = "overworld";
public static final String DEFAULT_NAMESPACE = "iris_export";
public static final String DEFAULT_FORMAT = "zip";
public WorldgenExportRequest {
if (pack == null) {
throw new IllegalArgumentException("Worldgen export request requires a pack directory");
}
if (dimension == null || dimension.isBlank()) {
throw new IllegalArgumentException("Worldgen export request requires a dimension");
}
if (exportRoot == null) {
throw new IllegalArgumentException("Worldgen export request requires an export root");
}
Objects.requireNonNull(version);
Objects.requireNonNull(mode);
Objects.requireNonNull(namespace);
Objects.requireNonNull(output);
Objects.requireNonNull(format);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private Path pack;
private String dimension = "";
private String version = "";
private String mode = DEFAULT_MODE;
private String namespace = DEFAULT_NAMESPACE;
private String output = "";
private String format = DEFAULT_FORMAT;
private boolean objects = true;
private boolean replace;
private Path exportRoot;
private Builder() {
}
public Builder pack(Path value) {
pack = Objects.requireNonNull(value);
return this;
}
public Builder dimension(String value) {
dimension = Objects.requireNonNull(value).trim();
return this;
}
public Builder version(String value) {
version = Objects.requireNonNull(value).trim();
return this;
}
public Builder mode(String value) {
mode = Objects.requireNonNull(value).trim();
return this;
}
public Builder namespace(String value) {
namespace = Objects.requireNonNull(value).trim();
return this;
}
public Builder output(String value) {
output = Objects.requireNonNull(value).trim();
return this;
}
public Builder format(String value) {
format = Objects.requireNonNull(value).trim();
return this;
}
public Builder objects(boolean value) {
objects = value;
return this;
}
public Builder replace(boolean value) {
replace = value;
return this;
}
public Builder exportRoot(Path value) {
exportRoot = Objects.requireNonNull(value);
return this;
}
public WorldgenExportRequest build() {
return new WorldgenExportRequest(pack, dimension, version, mode, namespace, output, format, objects, replace, exportRoot);
}
}
}
@@ -0,0 +1,48 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public record WorldgenExportResult(Status status, Path output, String message, List<ExportDiagnostic> diagnostics,
Map<String, String> loadKeyByBiomeId, ContentTrim trim, GenerationCost cost) {
public WorldgenExportResult {
Objects.requireNonNull(status);
if (status == Status.EXPORTED) {
Objects.requireNonNull(output);
}
message = message == null ? "" : message;
diagnostics = List.copyOf(diagnostics);
loadKeyByBiomeId = Collections.unmodifiableSortedMap(new TreeMap<>(loadKeyByBiomeId));
Objects.requireNonNull(trim);
Objects.requireNonNull(cost);
}
public static WorldgenExportResult exported(Path output, List<ExportDiagnostic> diagnostics, Map<String, String> loadKeyByBiomeId,
ContentTrim trim, GenerationCost cost) {
return new WorldgenExportResult(Status.EXPORTED, output, "", diagnostics, loadKeyByBiomeId, trim, cost);
}
public static WorldgenExportResult rejected(Path output, String message, List<ExportDiagnostic> diagnostics) {
return new WorldgenExportResult(Status.REJECTED, output, message, diagnostics, Map.of(), ContentTrim.NONE, GenerationCost.NONE);
}
public static WorldgenExportResult failed(Path output, String message, List<ExportDiagnostic> diagnostics) {
return new WorldgenExportResult(Status.FAILED, output, message, diagnostics, Map.of(), ContentTrim.NONE, GenerationCost.NONE);
}
public boolean isSuccess() {
return status == Status.EXPORTED;
}
public enum Status {
EXPORTED,
REJECTED,
FAILED
}
}
@@ -0,0 +1,5 @@
package art.arcane.iris.pack.datapack.export;
public interface WorldgenExportService {
WorldgenExportResult export(WorldgenExportRequest request, WorldgenExportProgress progress);
}
@@ -0,0 +1,23 @@
package art.arcane.iris.pack.datapack.export;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public final class WorldgenExportServices {
private static final AtomicReference<WorldgenExportService> SERVICE = new AtomicReference<>();
private WorldgenExportServices() {
}
public static void install(WorldgenExportService service) {
SERVICE.set(Objects.requireNonNull(service, "Datapack export service"));
}
public static WorldgenExportService get() {
WorldgenExportService service = SERVICE.get();
if (service != null) {
return service;
}
return SERVICE.updateAndGet(current -> current == null ? WorldgenDatapackExporter.create() : current);
}
}
@@ -0,0 +1,44 @@
package art.arcane.iris.pack.datapack.export;
import art.arcane.iris.pack.datapack.DataVersion;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public final class WorldgenExportTargets {
private static final DataVersion OLDEST = DataVersion.V26_3;
public static final List<DataVersion> SUPPORTED = supported();
private WorldgenExportTargets() {
}
public static DataVersion resolve(String raw) {
if (raw == null || raw.isBlank()) {
return SUPPORTED.getLast();
}
DataVersion version = DataVersion.forMinecraftVersion(raw.trim());
if (!SUPPORTED.contains(version)) {
throw unsupported(raw);
}
return version;
}
public static IllegalArgumentException unsupported(String raw) {
StringJoiner supported = new StringJoiner(", ");
for (DataVersion version : SUPPORTED) {
supported.add(version.getVersion());
}
return new IllegalArgumentException("Unsupported datapack export version '" + raw + "'. Supported: " + supported);
}
private static List<DataVersion> supported() {
List<DataVersion> versions = new ArrayList<>();
for (DataVersion version : DataVersion.values()) {
if (version.ordinal() >= OLDEST.ordinal()) {
versions.add(version);
}
}
return List.copyOf(versions);
}
}
@@ -0,0 +1,128 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.pack.ContentKeyValidator;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.validation.ContentGate;
import art.arcane.iris.pack.validation.LegacyBlockRenames;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformRegistries;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public final class BlockStateResolver {
private final IrisData data;
private final PlatformRegistries registries;
private final Set<String> knownBlocks;
private final List<ExportDiagnostic> diagnostics;
private final Map<String, Resolution> resolutions = new HashMap<>();
public BlockStateResolver(IrisData data, PlatformRegistries registries, List<ExportDiagnostic> diagnostics) {
this.data = Objects.requireNonNull(data);
this.registries = registries;
this.knownBlocks = registries == null ? Set.of() : knownBlocks(registries.blockTypeKeys());
this.diagnostics = Objects.requireNonNull(diagnostics);
}
public static BlockStateResolver forContext(PackCompileContext context) {
PlatformRegistries registries = IrisPlatforms.isBound() ? IrisPlatforms.get().registries() : null;
return new BlockStateResolver(context.data(), registries, context.diagnostics());
}
public Optional<VanillaBlockState> resolve(IrisBlockData block, String resource) {
if (block == null || block.getBlock() == null || block.getBlock().isBlank()) {
return Optional.empty();
}
return resolve(stateKey(block), resource);
}
public Optional<VanillaBlockState> resolve(String rawState, String resource) {
String normalized = ContentGate.normalizeState(rawState);
if (normalized == null) {
return Optional.empty();
}
Resolution resolution = resolutions.computeIfAbsent(normalized, this::parse);
if (resolution.problem() != null) {
ExportDiagnostic diagnostic = new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.BLOCK_STATE, resource, resolution.problem());
if (!diagnostics.contains(diagnostic)) {
diagnostics.add(diagnostic);
}
}
return Optional.ofNullable(resolution.state());
}
private String stateKey(IrisBlockData block) {
IrisBlockData custom = data.getBlockLoader() == null ? null : data.getBlockLoader().load(block.getBlock(), false);
if (custom == null || custom.getBlock() == null || custom.getBlock().equals(block.getBlock())) {
return block.stateKey();
}
IrisBlockData merged = IrisBlockData.from(custom.stateKey());
merged.getData().putAll(block.getData());
return merged.stateKey();
}
private Resolution parse(String normalized) {
String renamed = renamed(normalized);
if (!renamed.startsWith("minecraft:")) {
return new Resolution(null, "Block '" + renamed + "' is not a Minecraft block and is not exported");
}
String problem = null;
String validated = renamed;
List<String> propertyProblems = registries == null ? List.of() : ContentKeyValidator.validateBlockStateProperties(registries, List.of(renamed));
if (!propertyProblems.isEmpty()) {
validated = ContentGate.baseKey(renamed);
problem = String.join("; ", propertyProblems) + "; the block exports in its default state";
}
try {
return new Resolution(VanillaBlockState.parse(validated), problem);
} catch (IllegalArgumentException exception) {
return new Resolution(null, "Block state '" + renamed + "' is not exported: " + exception.getMessage());
}
}
private String renamed(String normalized) {
if (knownBlocks.isEmpty() || knownBlocks.contains(ContentGate.baseKey(normalized))) {
return normalized;
}
String properties = normalized.substring(ContentGate.baseKey(normalized).length());
String current = normalized;
for (int hop = 0; hop < LegacyBlockRenames.MAX_HOPS; hop++) {
String supplement = LegacyBlockRenames.supplementFor(current);
if (supplement == null) {
return normalized;
}
String next = ContentGate.normalizeState(supplement);
if (next == null) {
return normalized;
}
if (knownBlocks.contains(ContentGate.baseKey(next))) {
return ContentGate.baseKey(next) + properties;
}
current = next;
}
return normalized;
}
private static Set<String> knownBlocks(List<String> keys) {
Set<String> known = new HashSet<>(keys.size());
for (String key : keys) {
String normalized = ContentGate.normalizeState(key);
if (normalized != null) {
known.add(ContentGate.baseKey(normalized));
}
}
return known;
}
private record Resolution(VanillaBlockState state, String problem) {
}
}
@@ -0,0 +1,7 @@
package art.arcane.iris.pack.datapack.export.compile;
public interface CompileStage {
String name();
void apply(PackCompileContext context);
}
@@ -0,0 +1,75 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisDimensionType;
import art.arcane.iris.generation.terrain.IrisDimensionTypeOptions;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.List;
import java.util.Locale;
public final class DimensionStage implements CompileStage {
private static final String DEFAULT_ROCK = "minecraft:stone";
private static final String DEFAULT_FLUID = "minecraft:water";
private static final float FULLBRIGHT_AMBIENT_LIGHT = 1.0f;
@Override
public String name() {
return "dimension";
}
@Override
public void apply(PackCompileContext context) {
IrisDimension dimension = context.dimension();
int minY = dimension.getMinHeight();
DimensionDef aligned = DimensionDef.aligned(
VanillaResourceIdentifier.sanitizePath(dimension.getLoadKey()),
minY,
dimension.getMaxHeight() - minY,
dimension.getLogicalHeight(),
dimension.getFluidHeight() + minY,
paletteBlock(dimension.getRockPalette(), DEFAULT_ROCK, "rock"),
paletteBlock(dimension.getFluidPalette(), DEFAULT_FLUID, "fluid"),
new JsonObject(),
context.diagnostics());
IrisDimensionType type = new IrisDimensionType(
dimension.getBaseDimension(),
typeOptions(dimension),
aligned.logicalHeight(),
aligned.height(),
aligned.minY());
JsonObject typeJson = JsonParser.parseString(type.toJson(context.capabilities().target().get())).getAsJsonObject();
context.setDimensionDef(new DimensionDef(
aligned.name(),
aligned.minY(),
aligned.height(),
aligned.logicalHeight(),
aligned.fluidHeight(),
aligned.defaultBlock(),
aligned.defaultFluid(),
typeJson));
}
private static IrisDimensionTypeOptions typeOptions(IrisDimension dimension) {
IrisDimensionTypeOptions options = dimension.getDimensionOptions();
return dimension.isFullbright() ? options.copy().ambientLight(FULLBRIGHT_AMBIENT_LIGHT) : options;
}
private static String paletteBlock(IrisMaterialPalette palette, String fallback, String role) {
List<IrisBlockData> entries = palette == null ? null : palette.getPalette();
if (entries == null || entries.isEmpty() || entries.getFirst() == null) {
return fallback;
}
String raw = entries.getFirst().getBlock();
String block = raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT);
int properties = block.indexOf('[');
String id = properties < 0 ? block : block.substring(0, properties);
String namespaced = id.indexOf(':') < 0 ? "minecraft:" + id : id;
return VanillaResourceIdentifier.requireIdentifier(namespaced, "dimension " + role + " block");
}
}
@@ -0,0 +1,115 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
public final class ExportedBiomes {
private final SortedMap<String, IrisBiome> byId;
private final Map<String, String> loadKeys;
private final Map<String, Integer> codeOrder;
private final Map<String, IrisRegion> regionByLoadKey;
private ExportedBiomes(SortedMap<String, IrisBiome> byId, Map<String, String> loadKeys, Map<String, Integer> codeOrder,
Map<String, IrisRegion> regionByLoadKey) {
this.byId = Collections.unmodifiableSortedMap(byId);
this.loadKeys = Map.copyOf(loadKeys);
this.codeOrder = Map.copyOf(codeOrder);
this.regionByLoadKey = Map.copyOf(regionByLoadKey);
}
public static ExportedBiomes load(PackCompileContext context) {
SortedMap<String, IrisBiome> byId = new TreeMap<>();
Map<String, String> loadKeys = new HashMap<>();
for (Map.Entry<String, String> entry : context.biomeCodes().loadKeyByBiomeId().entrySet()) {
IrisBiome biome = Objects.requireNonNull(context.data().getBiomeLoader().load(entry.getValue(), false),
"Biome '" + entry.getValue() + "' could not be loaded");
byId.put(entry.getKey(), biome);
loadKeys.put(entry.getKey(), entry.getValue());
}
return new ExportedBiomes(byId, loadKeys, codeOrder(context.biomeCodes().layout(), byId.keySet()), regions(context));
}
public SortedMap<String, IrisBiome> byId() {
return byId;
}
public SortedSet<String> ids() {
return new TreeSet<>(byId.keySet());
}
public SortedSet<String> idsFor(Collection<String> loadKeys) {
SortedSet<String> ids = new TreeSet<>();
for (Map.Entry<String, String> entry : this.loadKeys.entrySet()) {
if (loadKeys.contains(entry.getValue())) {
ids.add(entry.getKey());
}
}
return ids;
}
public String loadKey(String biomeId) {
return loadKeys.get(biomeId);
}
public String resource(String biomeId) {
return "biomes/" + loadKeys.get(biomeId);
}
public IrisRegion region(String biomeId) {
return regionByLoadKey.get(loadKeys.get(biomeId));
}
public List<String> inCodeOrder(Iterable<String> biomeIds) {
List<String> ordered = new ArrayList<>();
for (String biomeId : biomeIds) {
ordered.add(biomeId);
}
ordered.sort(Comparator.comparingInt((String id) -> codeOrder.getOrDefault(id, Integer.MAX_VALUE)).thenComparing(Comparator.naturalOrder()));
return ordered;
}
private static Map<String, Integer> codeOrder(ClimateLayout layout, Iterable<String> biomeIds) {
List<ClimateLayout.ClimateEntry> entries = new ArrayList<>(layout.entries());
entries.sort(Comparator.comparingInt((ClimateLayout.ClimateEntry entry) -> entry.axis().ordinal())
.thenComparingDouble(ClimateLayout.ClimateEntry::min)
.thenComparing(ClimateLayout.ClimateEntry::biomeId));
Map<String, Integer> order = new LinkedHashMap<>();
for (ClimateLayout.ClimateEntry entry : entries) {
order.putIfAbsent(entry.biomeId(), order.size());
}
for (String biomeId : biomeIds) {
order.putIfAbsent(biomeId, order.size());
}
return order;
}
private static Map<String, IrisRegion> regions(PackCompileContext context) {
Map<String, IrisRegion> regions = new HashMap<>();
for (IrisRegion region : context.dimension().getAllRegions(() -> context.data())) {
if (region == null) {
continue;
}
for (IrisBiome biome : region.getAllBiomes(() -> context.data())) {
if (biome != null && biome.getLoadKey() != null) {
regions.putIfAbsent(biome.getLoadKey(), region);
}
}
}
return regions;
}
}
@@ -0,0 +1,117 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomeGeneratorLink;
import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.collection.KList;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
public final class ImageMapStage implements CompileStage {
private static final String DIMENSION_MESSAGE = "Image maps are not exported; the dimension generates from its procedural layers";
private static final String STYLE_MESSAGE = "Generator style image maps are not exported; the base noise style is used";
@Override
public String name() {
return "image-maps";
}
@Override
public void apply(PackCompileContext context) {
IrisDimension dimension = context.dimension();
IrisData data = context.data();
Gson gson = data.getGson();
if (usesImageMaps(gson.toJsonTree(dimension))) {
report(context, "dimensions/" + dimension.getLoadKey(), DIMENSION_MESSAGE);
}
dimension.setImageMaps(new KList<>());
SortedMap<String, IrisRegion> regions = new TreeMap<>();
for (IrisRegion region : dimension.getAllRegions(() -> data)) {
regions.put(region.getLoadKey(), region);
}
reportStyles(context, gson, "regions/", regions);
SortedMap<String, IrisBiome> biomes = new TreeMap<>();
SortedSet<String> generatorKeys = new TreeSet<>();
for (IrisBiome biome : dimension.getReachableBiomes(() -> data)) {
biomes.put(biome.getLoadKey(), biome);
collectGenerators(biome.getGenerators(), generatorKeys);
}
reportStyles(context, gson, "biomes/", biomes);
SortedMap<String, IrisGenerator> generators = new TreeMap<>();
for (String key : generatorKeys) {
IrisGenerator generator = data.getGeneratorLoader().load(key, false);
if (generator != null) {
generators.put(key, generator);
}
}
reportStyles(context, gson, "generators/", generators);
}
private static void collectGenerators(List<IrisBiomeGeneratorLink> links, SortedSet<String> generatorKeys) {
if (links == null) {
return;
}
for (IrisBiomeGeneratorLink link : links) {
if (link != null && link.getGenerator() != null && !link.getGenerator().isBlank()) {
generatorKeys.add(link.getGenerator().trim());
}
}
}
private static void reportStyles(PackCompileContext context, Gson gson, String folder, SortedMap<String, ?> resources) {
for (Map.Entry<String, ?> entry : resources.entrySet()) {
if (usesImageMaps(gson.toJsonTree(entry.getValue()))) {
report(context, folder + entry.getKey(), STYLE_MESSAGE);
}
}
}
private static void report(PackCompileContext context, String resource, String message) {
context.diagnostics().add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.IMAGE_MAP, resource, message));
}
private static boolean usesImageMaps(JsonElement element) {
if (element.isJsonArray()) {
for (JsonElement child : element.getAsJsonArray()) {
if (usesImageMaps(child)) {
return true;
}
}
return false;
}
if (!element.isJsonObject()) {
return false;
}
JsonObject object = element.getAsJsonObject();
if (namesImageMap(object.get("imageMap")) || bindsImageMaps(object.get("imageMaps"))) {
return true;
}
for (Map.Entry<String, JsonElement> member : object.entrySet()) {
if (usesImageMaps(member.getValue())) {
return true;
}
}
return false;
}
private static boolean namesImageMap(JsonElement value) {
return value != null && value.isJsonPrimitive() && !value.getAsString().isBlank();
}
private static boolean bindsImageMaps(JsonElement value) {
return value != null && value.isJsonArray() && !value.getAsJsonArray().isEmpty();
}
}
@@ -0,0 +1,390 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomeCustom;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.WorldgenExportMode;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeDecision;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeIdSanitizer;
import art.arcane.iris.pack.datapack.export.compile.decoration.BiomeFeatureLists;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.BinaryResource;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.datapack.export.ir.MaterialProgram;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.validation.ContentGate;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
public final class PackCompileContext {
private static final Field NEUTRAL_VOLUME = new Field.Const(0.0);
private static final Field NO_CAVES = new Field.Const(1.0e6);
private static final Field ZERO_CODE = new Field.Const(0.0);
private static final double CLIMATE_SPAN = 1.0;
private static final List<String> LEGACY_BIOME_KEYS = List.of("surface_builder", "depth", "scale", "precipitation", "category", "starts");
private static final StyleCompiler NO_STYLE_COMPILER = (style, seedSalt, registry, capabilities) -> {
throw new IllegalStateException("No style compiler installed");
};
private final IrisData data;
private final IrisDimension dimension;
private final ExportCapabilities capabilities;
private final String namespace;
private final WorldgenExportMode mode;
private final boolean objects;
private final StyleCompiler styles;
private final NoiseRegistry noises;
private final List<ExportDiagnostic> diagnostics;
private final BiomeFeatureLists features = new BiomeFeatureLists();
private final List<JsonResource> jsonResources = new ArrayList<>();
private final List<BinaryResource> binaryResources = new ArrayList<>();
private DimensionDef dimensionDef;
private BiomeCodes biomeCodes;
private BiomeDecision biomeDecision;
private BiomeCodes boundBiomeCodes;
private Field boundHeight;
private List<BiomeDef> biomes;
private Field height;
private Field carvedHeight;
private Field climateHeight;
private Field surfaceEstimate;
private Field volumetric;
private Field caves;
private Field.Shared caveField;
private double wallShellBand;
private Field.Shared deepCaves;
private AquiferDef aquifer;
private MaterialProgram material;
private DefaultBiome defaultBiome;
private PackCompileContext(Builder builder) {
data = Objects.requireNonNull(builder.data, "Pack compile context requires pack data");
dimension = Objects.requireNonNull(builder.dimension, "Pack compile context requires a dimension");
capabilities = Objects.requireNonNull(builder.capabilities, "Pack compile context requires export capabilities");
namespace = VanillaResourceIdentifier.requireNamespace(builder.namespace, "export namespace");
mode = Objects.requireNonNull(builder.mode, "Pack compile context requires an export mode");
objects = builder.objects;
styles = builder.styles;
diagnostics = builder.diagnostics;
noises = new NoiseRegistry(namespace);
}
public static Builder builder() {
return new Builder();
}
public IrisData data() {
return data;
}
public IrisDimension dimension() {
return dimension;
}
public ExportCapabilities capabilities() {
return capabilities;
}
public String namespace() {
return namespace;
}
public WorldgenExportMode mode() {
return mode;
}
public boolean objects() {
return objects;
}
public StyleCompiler styles() {
return styles;
}
public NoiseRegistry noises() {
return noises;
}
public List<ExportDiagnostic> diagnostics() {
return diagnostics;
}
public BiomeFeatureLists features() {
return features;
}
public List<JsonResource> jsonResources() {
return jsonResources;
}
public List<BinaryResource> binaryResources() {
return binaryResources;
}
public DimensionDef dimensionDef() {
if (dimensionDef == null) {
throw new IllegalStateException("Dimension definition for '" + dimension.getLoadKey() + "' is read before the dimension stage ran");
}
return dimensionDef;
}
public void setDimensionDef(DimensionDef value) {
dimensionDef = Objects.requireNonNull(value);
}
public BiomeCodes biomeCodes() {
if (biomeDecision != null) {
return height == null ? biomeDecision.base() : heightBoundBiomeCodes();
}
return biomeCodes == null ? defaultBiome().codes() : biomeCodes;
}
public BiomeCodes baseBiomeCodes() {
if (biomeDecision != null) {
return biomeDecision.base();
}
return biomeCodes == null ? defaultBiome().codes() : biomeCodes;
}
public void setBiomeCodes(BiomeCodes value) {
biomeCodes = Objects.requireNonNull(value);
biomeDecision = null;
}
public void setBiomeDecision(BiomeDecision value) {
biomeDecision = Objects.requireNonNull(value);
biomeCodes = null;
boundBiomeCodes = null;
boundHeight = null;
}
public List<BiomeDef> biomes() {
return biomes == null ? defaultBiome().biomes() : biomes;
}
public void setBiomes(List<BiomeDef> value) {
biomes = List.copyOf(value);
}
public Field height() {
return carvedHeight == null ? naturalHeight() : carvedHeight;
}
public Field naturalHeight() {
return height == null ? new Field.Const(dimensionDef().fluidHeight()) : height;
}
public void setHeight(Field value) {
FieldValidator.requireTwoDimensional(Objects.requireNonNull(value), "height");
height = value;
carvedHeight = null;
climateHeight = null;
surfaceEstimate = null;
}
public Field climateHeight() {
return climateHeight == null ? naturalHeight() : climateHeight;
}
public void setClimateHeight(Field value) {
FieldValidator.requireTwoDimensional(Objects.requireNonNull(value), "climate height");
climateHeight = value;
}
public void setCarvedHeight(Field value) {
FieldValidator.requireTwoDimensional(Objects.requireNonNull(value), "carved height");
carvedHeight = value;
}
public Field surfaceEstimate() {
return surfaceEstimate == null ? climateHeight() : surfaceEstimate;
}
public void setSurfaceEstimate(Field value) {
FieldValidator.requireTwoDimensional(Objects.requireNonNull(value), "surface estimate");
surfaceEstimate = value;
}
public Field volumetric() {
return volumetric == null ? NEUTRAL_VOLUME : volumetric;
}
public void setVolumetric(Field value) {
volumetric = Objects.requireNonNull(value);
}
public Field caves() {
return caves == null ? NO_CAVES : caves;
}
public void setCaves(Field value) {
caves = Objects.requireNonNull(value);
}
public Optional<Field.Shared> caveField() {
return Optional.ofNullable(caveField);
}
public void setCaveField(Field.Shared value, double wallBand) {
if (!(wallBand >= 0.0) || Double.isInfinite(wallBand)) {
throw new IllegalArgumentException("Wall shell band must be finite and non-negative, got " + wallBand);
}
caveField = Objects.requireNonNull(value);
wallShellBand = wallBand;
}
public double wallShellBand() {
return wallShellBand;
}
public Optional<Field.Shared> deepCaves() {
return Optional.ofNullable(deepCaves);
}
public void setDeepCaves(Field.Shared value) {
deepCaves = Objects.requireNonNull(value);
}
public AquiferDef aquifer() {
return aquifer == null ? AquiferDef.dry(surfaceEstimate()) : aquifer;
}
public void setAquifer(AquiferDef value) {
aquifer = Objects.requireNonNull(value);
}
public MaterialProgram material() {
return material == null ? MaterialProgram.rock(dimensionDef().defaultBlock()) : material;
}
public void setMaterial(MaterialProgram value) {
material = Objects.requireNonNull(value);
}
private BiomeCodes heightBoundBiomeCodes() {
Field bindingHeight = climateHeight();
if (boundHeight != bindingHeight) {
boundBiomeCodes = biomeDecision.bind(bindingHeight);
boundHeight = bindingHeight;
}
return boundBiomeCodes;
}
private DefaultBiome defaultBiome() {
if (defaultBiome == null) {
defaultBiome = createDefaultBiome();
}
return defaultBiome;
}
private DefaultBiome createDefaultBiome() {
String loadKey = firstLandBiome();
String id = BiomeIdSanitizer.sanitize(namespace, loadKey, new HashSet<>());
String body = new IrisBiomeCustom().generateJson(capabilities.target().get(), new ContentGate(null, Map.of(), null));
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
for (String key : LEGACY_BIOME_KEYS) {
json.remove(key);
}
BiomeDef biome = new BiomeDef(id.substring(namespace.length() + 1), json);
ClimateLayout layout = new ClimateLayout(List.of(
new ClimateLayout.ClimateEntry(id, ClimateLayout.ClimateAxis.TEMPERATURE, -CLIMATE_SPAN, CLIMATE_SPAN)));
BiomeCodes codes = new BiomeCodes(ZERO_CODE, ZERO_CODE, ZERO_CODE, layout, Map.of(id, loadKey));
return new DefaultBiome(List.of(biome), codes);
}
private String firstLandBiome() {
for (String regionKey : dimension.getRegions()) {
IrisRegion region = data.getRegionLoader().load(regionKey, false);
if (region == null || region.isCompatExcluded()) {
continue;
}
for (String biomeKey : region.getLandBiomes()) {
IrisBiome biome = biomeKey == null ? null : data.getBiomeLoader().load(biomeKey, false);
if (biome != null && !biome.isCompatExcluded()) {
return biome.getLoadKey();
}
}
}
throw new IllegalStateException("Dimension '" + dimension.getLoadKey() + "' has no exportable land biome in any of its regions");
}
private record DefaultBiome(List<BiomeDef> biomes, BiomeCodes codes) {
}
public static final class Builder {
private IrisData data;
private IrisDimension dimension;
private ExportCapabilities capabilities;
private String namespace;
private WorldgenExportMode mode = WorldgenExportMode.OVERWORLD;
private boolean objects = true;
private StyleCompiler styles = NO_STYLE_COMPILER;
private List<ExportDiagnostic> diagnostics = new ArrayList<>();
private Builder() {
}
public Builder data(IrisData value) {
data = Objects.requireNonNull(value);
return this;
}
public Builder dimension(IrisDimension value) {
dimension = Objects.requireNonNull(value);
return this;
}
public Builder capabilities(ExportCapabilities value) {
capabilities = Objects.requireNonNull(value);
return this;
}
public Builder namespace(String value) {
namespace = Objects.requireNonNull(value);
return this;
}
public Builder mode(WorldgenExportMode value) {
mode = Objects.requireNonNull(value);
return this;
}
public Builder objects(boolean value) {
objects = value;
return this;
}
public Builder styles(StyleCompiler value) {
styles = Objects.requireNonNull(value);
return this;
}
public Builder diagnostics(List<ExportDiagnostic> value) {
diagnostics = Objects.requireNonNull(value);
return this;
}
public PackCompileContext build() {
return new PackCompileContext(this);
}
}
}
@@ -0,0 +1,73 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.export.WorldgenExportProgress;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeStage;
import art.arcane.iris.pack.datapack.export.compile.cave.CaveStage;
import art.arcane.iris.pack.datapack.export.compile.decoration.DecorationStage;
import art.arcane.iris.pack.datapack.export.compile.object.ObjectStage;
import art.arcane.iris.pack.datapack.export.compile.structure.StructureStage;
import art.arcane.iris.pack.datapack.export.compile.subterrain.SubterrainStage;
import art.arcane.iris.pack.datapack.export.compile.surface.SurfaceStage;
import art.arcane.iris.pack.datapack.export.compile.terrain.RiverStage;
import art.arcane.iris.pack.datapack.export.compile.terrain.TerrainStage;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportIr;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
import java.util.List;
public final class PackCompiler {
private static final String ROUTER_STAGE = "router";
private final List<CompileStage> stages;
public PackCompiler(List<CompileStage> stages) {
this.stages = List.copyOf(stages);
}
public static PackCompiler create() {
return new PackCompiler(List.of(
new DimensionStage(),
new ImageMapStage(),
new BiomeStage(),
new TerrainStage(),
new RiverStage(),
new CaveStage(),
new SurfaceStage(),
new DecorationStage(),
new StructureStage(),
new SubterrainStage(),
new ObjectStage()));
}
public ExportIr compile(PackCompileContext context, WorldgenExportProgress progress) {
for (CompileStage stage : stages) {
progress.stage(stage.name());
stage.apply(context);
}
progress.stage(ROUTER_STAGE);
DimensionDef dimension = context.dimensionDef();
BiomeCodes codes = context.biomeCodes();
RouterDef router = RouterCompiler.compile(
context.height(),
context.volumetric(),
context.caves(),
context.aquifer(),
codes,
dimension);
return new ExportIr(
context.namespace(),
context.capabilities().target(),
context.mode(),
dimension,
context.noises().definitions(),
router,
codes.layout(),
context.features().apply(context.biomes(), context.namespace()),
context.material(),
context.diagnostics(),
context.jsonResources(),
context.binaryResources());
}
}
@@ -0,0 +1,44 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.ir.RouterDef;
public final class RouterCompiler {
private static final Field DENSITY_PER_BLOCK = new Field.Const(1.0);
private static final Field UNUSED_CLIMATE = new Field.Const(0.0);
private static final double HALF_BLOCK = 0.5;
private static final int VOLUME_CELL_XZ = 4;
private static final int VOLUME_CELL_Y = 8;
private static final int SURFACE_CELL_XZ = 16;
private static final int SURFACE_CELL_Y = 1;
private RouterCompiler() {
}
public static RouterDef compile(Field height, Field volumetric, Field caves, AquiferDef aquifer, BiomeCodes codes, DimensionDef dimension) {
FieldValidator.requireTwoDimensional(height, "height");
Field ramp = new Field.Binary(Field.BinaryOp.MUL, DENSITY_PER_BLOCK, new Field.Binary(Field.BinaryOp.SUB, height, blockCenterY(dimension)));
Field terrain = new Field.Binary(Field.BinaryOp.ADD, ramp, new Field.Grid(volumetric, VOLUME_CELL_XZ, VOLUME_CELL_Y));
return new RouterDef(
codes.surfaceCode(),
codes.caveCode(),
UNUSED_CLIMATE,
UNUSED_CLIMATE,
codes.class3d(),
UNUSED_CLIMATE,
new Field.Grid(height, SURFACE_CELL_XZ, SURFACE_CELL_Y),
new Field.Binary(Field.BinaryOp.MIN, terrain, caves),
aquifer);
}
private static Field blockCenterY(DimensionDef dimension) {
double bottom = dimension.minY();
double top = dimension.minY() + dimension.height();
return new Field.Coord(Axis.Y, Field.Tiling.CLAMP, bottom, top, bottom - HALF_BLOCK, top - HALF_BLOCK);
}
}
@@ -0,0 +1,14 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import java.util.Objects;
public record WeightedState(VanillaBlockState state, int weight) {
public WeightedState {
Objects.requireNonNull(state);
if (weight < 1) {
throw new IllegalArgumentException("Block state weight must be positive, got " + weight + " for " + state.canonical());
}
}
}
@@ -0,0 +1,76 @@
package art.arcane.iris.pack.datapack.export.compile;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.WorldgenExportTargets;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.List;
import java.util.Map;
public final class WorldgenSyntax {
private final DataVersion target;
private WorldgenSyntax(DataVersion target) {
this.target = target;
}
public static WorldgenSyntax forTarget(DataVersion target) {
if (!WorldgenExportTargets.SUPPORTED.contains(target)) {
throw WorldgenExportTargets.unsupported(target.getVersion());
}
return new WorldgenSyntax(target);
}
public DataVersion target() {
return target;
}
public String featureFolder() {
return "worldgen/feature";
}
public JsonObject blockState(VanillaBlockState state) {
JsonObject json = new JsonObject();
json.addProperty("id", state.name());
if (!state.properties().isEmpty()) {
JsonObject properties = new JsonObject();
for (Map.Entry<String, String> property : state.properties().entrySet()) {
properties.addProperty(property.getKey(), property.getValue());
}
json.add("properties", properties);
}
return json;
}
public JsonObject provider(List<WeightedState> entries) {
if (entries.isEmpty()) {
throw new IllegalArgumentException("A block state provider needs at least one state");
}
if (entries.size() == 1) {
return blockState(entries.getFirst().state());
}
JsonArray weighted = new JsonArray(entries.size());
for (WeightedState entry : entries) {
JsonObject item = new JsonObject();
item.add("data", blockState(entry.state()));
item.addProperty("weight", entry.weight());
weighted.add(item);
}
JsonObject provider = new JsonObject();
provider.addProperty("type", "minecraft:weighted");
provider.add("entries", weighted);
return provider;
}
public JsonObject feature(String type, JsonObject config) {
JsonObject feature = new JsonObject();
feature.addProperty("type", type);
for (Map.Entry<String, JsonElement> field : config.entrySet()) {
feature.add(field.getKey(), field.getValue().deepCopy());
}
return feature;
}
}
@@ -0,0 +1,31 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
public record BiomeCodes(Field surfaceCode, Field caveCode, Field class3d, ClimateLayout layout, Map<String, String> loadKeyByBiomeId) {
public static final String BASE_CODE = "biome/base_code";
public BiomeCodes {
Objects.requireNonNull(surfaceCode);
Objects.requireNonNull(caveCode);
Objects.requireNonNull(class3d);
Objects.requireNonNull(layout);
FieldValidator.requireTwoDimensional(surfaceCode, "surface code");
FieldValidator.requireTwoDimensional(caveCode, "cave code");
SortedMap<String, String> loadKeys = new TreeMap<>(loadKeyByBiomeId);
for (Map.Entry<String, String> entry : loadKeys.entrySet()) {
VanillaResourceIdentifier.requireIdentifier(entry.getKey(), "biome id");
Objects.requireNonNull(entry.getValue());
}
loadKeyByBiomeId = Collections.unmodifiableSortedMap(loadKeys);
}
}
@@ -0,0 +1,141 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class BiomeDecision {
static final int LAND = 0;
static final int SEA = 1;
static final int SHORE = 2;
static final int SURFACE_SLOT = 0;
private static final double UNDERGROUND_DEPTH = 8.0;
private static final int BRIDGE_WEIGHT = 8;
private static final int LEVEL_WEIGHT = 2;
private static final int ZONE_WEIGHT = 4;
private static final int DEPTH_WEIGHT = 2;
private static final Field UNUSED_CODE = new Field.Const(0.0);
private final BiomeCodes base;
private final Parts parts;
BiomeDecision(BiomeCodes base, Parts parts) {
this.base = Objects.requireNonNull(base);
this.parts = Objects.requireNonNull(parts);
}
public BiomeCodes base() {
return base;
}
public BiomeCodes bind(Field height) {
FieldValidator.requireTwoDimensional(Objects.requireNonNull(height), "height");
return new BiomeCodes(surfaceCode(height), base.caveCode(), class3d(height), base.layout(), base.loadKeyByBiomeId());
}
private Field surfaceCode(Field height) {
double fluid = parts.fluid();
double fluidTop = Math.nextUp((float) fluid);
IndexedField levels = IndexedField.partition(height, List.of(fluid - 1.0, fluid, fluidTop), List.of(0, LEVEL_WEIGHT, 2 * LEVEL_WEIGHT, 3 * LEVEL_WEIGHT));
IndexedField above = IndexedField.partition(new Field.Binary(Field.BinaryOp.SUB, height, parts.shoreHeight()), List.of(fluidTop), List.of(0, 1));
IndexedField key = IndexedField.sum(List.of(parts.bridge().remap(bridge -> bridge * BRIDGE_WEIGHT), levels, above));
IndexedField list = key.remap(BiomeDecision::listFor);
List<Field> codes = new ArrayList<>(parts.chains().size());
for (IndexedField chain : parts.chains()) {
codes.add(chain.lookup(index -> parts.surfaceCodes()[index]));
}
if (list.isConstant()) {
return codes.get(list.values().getFirst());
}
List<Field> cases = new ArrayList<>(list.values().getLast() + 1);
for (int value = 0; value <= list.values().getLast(); value++) {
cases.add(list.values().contains(value) ? codes.get(value) : UNUSED_CODE);
}
return new Field.Mux(list.field(), cases);
}
private Field class3d(Field height) {
if (parts.caveSlot().equals(IndexedField.constant(SURFACE_SLOT)) && parts.carvingSlots().isEmpty()) {
return new Field.Const(0.0);
}
IndexedField zones = parts.zoneKeys();
Field caveExtra = new Field.Binary(Field.BinaryOp.SUB, parts.requiredDepth(), new Field.Const(UNDERGROUND_DEPTH));
Field caveZone = zones.lookup(key -> key / ZONE_WEIGHT == CarvingZones.CAVE_ZONE ? 1.0 : 0.0);
Field depthGate = new Field.Binary(Field.BinaryOp.ADD, new Field.Const(UNDERGROUND_DEPTH), new Field.Gate(caveZone, caveExtra));
Field clearance = new Field.Binary(Field.BinaryOp.SUB, new Field.Binary(Field.BinaryOp.SUB, height, parts.y()), depthGate);
IndexedField deepEnough = IndexedField.partition(clearance, List.of(0.0), List.of(0, 1));
IndexedField key = IndexedField.sum(List.of(zones.remap(zone -> zone / ZONE_WEIGHT * DEPTH_WEIGHT), deepEnough));
IndexedField classIndex = key.remap(BiomeDecision::classFor);
List<IndexedField> cases = new ArrayList<>(parts.carvingSlots().size() + 2);
cases.add(IndexedField.constant(SURFACE_SLOT));
cases.add(parts.caveSlot());
cases.addAll(parts.carvingSlots());
IndexedField slot = IndexedField.select(classIndex, cases);
return slot.lookup(value -> value == SURFACE_SLOT ? 0.0 : parts.undergroundCodes()[value - 1]);
}
static int listFor(int key) {
boolean landBase = key / BRIDGE_WEIGHT == LAND;
int level = (key % BRIDGE_WEIGHT) / LEVEL_WEIGHT;
boolean aboveShoreBand = key % LEVEL_WEIGHT == 1;
boolean nearFluid = level >= 1;
boolean belowFluid = level <= 1;
boolean atFluid = level == 2;
int base = landBase ? LAND : SEA;
if (nearFluid) {
if (!aboveShoreBand) {
return SHORE;
}
if (!landBase) {
return LAND;
}
} else if (!landBase && aboveShoreBand) {
return LAND;
}
if (belowFluid && landBase) {
return SEA;
}
if (atFluid) {
return SHORE;
}
return base;
}
static int classFor(int key) {
int zone = key / DEPTH_WEIGHT;
boolean deepEnough = key % DEPTH_WEIGHT == 1;
if (zone == CarvingZones.SHALLOW_ZONE || !deepEnough) {
return 0;
}
return zone == CarvingZones.CAVE_ZONE ? 1 : zone;
}
record Parts(
double fluid,
IndexedField bridge,
Field shoreHeight,
List<IndexedField> chains,
double[] surfaceCodes,
Field y,
IndexedField zoneKeys,
IndexedField caveSlot,
Field requiredDepth,
List<IndexedField> carvingSlots,
double[] undergroundCodes) {
Parts {
Objects.requireNonNull(bridge);
Objects.requireNonNull(shoreHeight);
chains = List.copyOf(chains);
Objects.requireNonNull(surfaceCodes);
Objects.requireNonNull(y);
Objects.requireNonNull(zoneKeys);
Objects.requireNonNull(caveSlot);
Objects.requireNonNull(requiredDepth);
carvingSlots = List.copyOf(carvingSlots);
Objects.requireNonNull(undergroundCodes);
}
}
}
@@ -0,0 +1,299 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Function;
public final class BiomeDecisionCompiler {
private static final long REGION_SALT = 883L;
private static final long CONTINENT_SALT = 234_234_565L;
private static final long PICK_SALT = 1_000L;
private static final long CHILD_SALT = 123L;
private static final long SHORE_SALT = 3_458_612L;
private static final double SURFACE_SPAN = 1.0;
private static final double UNDERGROUND_MIN = 1.25;
private static final double UNDERGROUND_MAX = 2.0;
private static final double MINIMUM_CAVE_DEPTH = 8.0;
private static final double NO_CAVE_DEPTH = 100_000.0;
private static final int DEEP_FLOOR_Y = -8;
private static final int DEEP_ABOVE_MIN_Y = 40;
private final StyleCompiler styles;
public BiomeDecisionCompiler(StyleCompiler styles) {
this.styles = Objects.requireNonNull(styles);
}
public BiomeDecision compile(PackCompileContext context) {
IrisDimension dimension = context.dimension();
IrisData data = context.data();
DimensionDef dimensionDef = context.dimensionDef();
BiomePools pools = BiomePools.load(dimension, data);
CarvingZones carving = CarvingZones.plan(dimension, data, Math.max(DEEP_FLOOR_Y, dimensionDef.minY() + DEEP_ABOVE_MIN_Y));
List<String> surfaceKeys = List.copyOf(pools.surface());
SortedSet<String> undergroundSet = new TreeSet<>(pools.cave());
undergroundSet.addAll(carving.biomes());
List<String> undergroundKeys = List.copyOf(undergroundSet);
Map<String, Integer> surfaceIndex = indexOf(surfaceKeys);
Map<String, Integer> undergroundIndex = indexOf(undergroundKeys);
Map<String, String> ids = biomeIds(context.namespace(), surfaceKeys, undergroundKeys);
double[] surfaceCodes = codes(-SURFACE_SPAN, SURFACE_SPAN, surfaceKeys.size());
double[] undergroundCodes = codes(UNDERGROUND_MIN, UNDERGROUND_MAX, undergroundKeys.size());
Build build = new Build(pools, surfaceKeys, surfaceIndex,
new SelectorCompiler(styles.selectors(), new SelectorCompiler.Sources(data, context.noises(), context.capabilities())));
IndexedField region = build.region(dimension);
IndexedField bridge = build.selectors.scaled(dimension.getContinentalStyle(), 1.0 / dimension.getContinentZoom(), CONTINENT_SALT)
.partition(List.of(dimension.getLandChance()), List.of(BiomeDecision.LAND, BiomeDecision.SEA))
.shared("biome/bridge");
RegionPicks picks = build.regionPicks(dimension, bridge, undergroundIndex, context.diagnostics());
List<IndexedField> chains = List.of(
build.implode("biome/land", IndexedField.select(region, picks.land()).shared("biome/land/pick")),
build.implode("biome/sea", IndexedField.select(region, picks.sea()).shared("biome/sea/pick")),
build.implode("biome/shore", IndexedField.select(region, picks.shore()).shared("biome/shore/pick")));
IndexedField baseSurface = IndexedField.select(bridge, chains.subList(0, 2));
IndexedField caveSlot = IndexedField.select(region, picks.caves()).shared("biome/cave");
Field caveCode = caveSlot.lookup(value -> value == BiomeDecision.SURFACE_SLOT ? 0.0 : undergroundCodes[value - 1]);
Field requiredDepth = caveSlot.lookup(value -> value == BiomeDecision.SURFACE_SLOT
? NO_CAVE_DEPTH
: Math.max(MINIMUM_CAVE_DEPTH, pools.biome(undergroundKeys.get(value - 1)).getCaveMinDepthBelowSurface()));
Field y = blockY(dimensionDef);
List<IndexedField> carvingSlots = carving.slots(build.selectors, data, key -> undergroundIndex.get(key) + 1);
BiomeCodes base = new BiomeCodes(
new Field.Shared(BiomeCodes.BASE_CODE, baseSurface.lookup(index -> surfaceCodes[index])),
caveCode,
new Field.Const(0.0),
layout(ids, surfaceKeys, surfaceCodes, undergroundKeys, undergroundCodes),
loadKeys(ids));
BiomeDecision.Parts parts = new BiomeDecision.Parts(
dimensionDef.fluidHeight(),
bridge,
shoreHeight(region, picks.shoreHeights()),
chains,
surfaceCodes,
y,
carving.zoneKeys(y),
caveSlot,
requiredDepth,
carvingSlots,
undergroundCodes);
return new BiomeDecision(base, parts);
}
private static Field shoreHeight(IndexedField region, List<Field> heights) {
if (region.isConstant()) {
return heights.get(region.values().getFirst());
}
if (new HashSet<>(heights).size() == 1) {
return heights.getFirst();
}
return new Field.Shared("biome/shore_height", new Field.Mux(region.field(), heights));
}
private static SortedMap<String, String> loadKeys(Map<String, String> ids) {
SortedMap<String, String> loadKeys = new TreeMap<>();
for (Map.Entry<String, String> entry : ids.entrySet()) {
loadKeys.put(entry.getValue(), entry.getKey());
}
return loadKeys;
}
private static Map<String, Integer> indexOf(List<String> keys) {
Map<String, Integer> index = new HashMap<>(keys.size() * 2);
for (int position = 0; position < keys.size(); position++) {
index.put(keys.get(position), position);
}
return index;
}
private static Map<String, String> biomeIds(String namespace, List<String> surfaceKeys, List<String> undergroundKeys) {
SortedSet<String> all = new TreeSet<>(surfaceKeys);
all.addAll(undergroundKeys);
Set<String> taken = new HashSet<>();
Map<String, String> ids = new TreeMap<>();
for (String key : all) {
ids.put(key, BiomeIdSanitizer.sanitize(namespace, key, taken));
}
return ids;
}
private static double[] codes(double min, double max, int count) {
double[] codes = new double[count];
double half = (max - min) / (2.0 * Math.max(1, count));
for (int index = 0; index < count; index++) {
codes[index] = min + (2 * index + 1) * half;
}
return codes;
}
private static ClimateLayout layout(Map<String, String> ids, List<String> surfaceKeys, double[] surfaceCodes, List<String> undergroundKeys, double[] undergroundCodes) {
List<ClimateLayout.ClimateEntry> entries = new ArrayList<>(surfaceKeys.size() + undergroundKeys.size());
double surfaceHalf = SURFACE_SPAN / Math.max(1, surfaceKeys.size());
for (int index = 0; index < surfaceKeys.size(); index++) {
entries.add(new ClimateLayout.ClimateEntry(ids.get(surfaceKeys.get(index)), ClimateLayout.ClimateAxis.TEMPERATURE,
surfaceCodes[index] - surfaceHalf, surfaceCodes[index] + surfaceHalf));
}
double undergroundHalf = (UNDERGROUND_MAX - UNDERGROUND_MIN) / (2.0 * Math.max(1, undergroundKeys.size()));
for (int index = 0; index < undergroundKeys.size(); index++) {
entries.add(new ClimateLayout.ClimateEntry(ids.get(undergroundKeys.get(index)), ClimateLayout.ClimateAxis.DEPTH,
undergroundCodes[index] - undergroundHalf, Math.min(UNDERGROUND_MAX, undergroundCodes[index] + undergroundHalf)));
}
return new ClimateLayout(entries);
}
private static Field blockY(DimensionDef dimension) {
double bottom = dimension.minY();
double top = dimension.minY() + dimension.height();
return new Field.Coord(Axis.Y, Field.Tiling.CLAMP, bottom, top, bottom, top);
}
private static final class Build {
private final BiomePools pools;
private final List<String> surfaceKeys;
private final Map<String, Integer> surfaceIndex;
private final SelectorCompiler selectors;
private final Map<String, IndexedField> hops = new HashMap<>();
private Build(BiomePools pools, List<String> surfaceKeys, Map<String, Integer> surfaceIndex, SelectorCompiler selectors) {
this.pools = pools;
this.surfaceKeys = surfaceKeys;
this.surfaceIndex = surfaceIndex;
this.selectors = selectors;
}
private IndexedField region(IrisDimension dimension) {
List<IrisRegion> regions = new ArrayList<>(pools.regions().size());
List<Integer> leaves = new ArrayList<>(pools.regions().size());
for (BiomePools.RegionPools regionPools : pools.regions()) {
leaves.add(regions.size());
regions.add(regionPools.region());
}
if (regions.size() == 1) {
return IndexedField.constant(0);
}
return selectors.zoomed(dimension.getRegionStyle(), dimension.getRegionZoom(), REGION_SALT)
.partition(BiomePools.rarityCuts(regions), leaves)
.shared("biome/region");
}
private RegionPicks regionPicks(IrisDimension dimension, IndexedField bridge, Map<String, Integer> undergroundIndex, List<ExportDiagnostic> diagnostics) {
int count = pools.regions().size();
RegionPicks picks = new RegionPicks(new ArrayList<>(count), new ArrayList<>(count), new ArrayList<>(count), new ArrayList<>(count), new ArrayList<>(count));
for (int position = 0; position < count; position++) {
BiomePools.RegionPools regionPools = pools.regions().get(position);
IrisRegion region = regionPools.region();
IndexedField landPick = pick(dimension, regionPools, InferredType.LAND, surfaceIndex::get, 0);
IndexedField seaPick = pick(dimension, regionPools, InferredType.SEA, surfaceIndex::get, 0);
IndexedField land = landPick == null ? seaPick : landPick;
IndexedField sea = seaPick == null ? landPick : seaPick;
IndexedField shore = pick(dimension, regionPools, InferredType.SHORE, surfaceIndex::get, 0);
IndexedField cave = pick(dimension, regionPools, InferredType.CAVE, undergroundIndex::get, 1);
picks.land().add(land);
picks.sea().add(sea);
picks.shore().add(shore == null ? IndexedField.select(bridge, List.of(land, sea)) : shore);
picks.caves().add(cave == null ? IndexedField.constant(BiomeDecision.SURFACE_SLOT) : cave);
picks.shoreHeights().add(shoreHeight(region, position));
if (region.getShoreMinimumWidth() > 0.0) {
diagnostics.add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.SHORE_WIDTH, "regions/" + region.getLoadKey(),
"Shore widening by slope is not exported; the shore band follows the shore height only"));
}
}
return picks;
}
private IndexedField pick(IrisDimension dimension, BiomePools.RegionPools regionPools, InferredType type, Function<String, Integer> index, int offset) {
List<IrisBiome> pool = regionPools.of(type);
if (pool.isEmpty()) {
return null;
}
List<Integer> leaves = new ArrayList<>(pool.size());
for (IrisBiome biome : pool) {
leaves.add(index.apply(biome.getLoadKey()) + offset);
}
if (pool.size() == 1) {
return IndexedField.constant(leaves.getFirst());
}
IrisRegion region = regionPools.region();
double zoom = switch (type) {
case LAND -> dimension.getBiomeZoom() * dimension.getLandZoom() * region.getLandBiomeZoom();
case SEA -> dimension.getBiomeZoom() * dimension.getSeaZoom() * region.getSeaBiomeZoom();
case SHORE -> dimension.getBiomeZoom() * region.getShoreBiomeZoom();
case CAVE -> dimension.getBiomeZoom() * region.getCaveBiomeZoom();
};
IrisGeneratorStyle style = switch (type) {
case LAND -> dimension.getLandBiomeStyle();
case SEA -> dimension.getSeaBiomeStyle();
case SHORE -> dimension.getShoreBiomeStyle();
case CAVE -> dimension.getCaveBiomeStyle();
};
return selectors.zoomed(style, zoom, PICK_SALT + type.ordinal()).partition(BiomePools.rarityCuts(pool), leaves);
}
private Field shoreHeight(IrisRegion region, int position) {
if (region.getShoreHeightMin() == region.getShoreHeightMax()) {
return new Field.Const(region.getShoreHeightMin());
}
return selectors.sampled(NoiseStyle.IRIS.style(), region.getShoreHeightZoom(), SHORE_SALT + position, region::getShoreHeight).curve();
}
private IndexedField implode(String name, IndexedField start) {
IndexedField current = start;
for (int hop = 0; hop < BiomePools.MAX_CHILD_HOPS; hop++) {
List<Integer> movers = new ArrayList<>();
for (int value : current.values()) {
BiomePools.ChildPlan plan = pools.plan(surfaceKeys.get(value));
if (plan != null && plan.moves()) {
movers.add(value);
}
}
if (movers.isEmpty()) {
return current;
}
Map<Integer, IndexedField> moved = new HashMap<>(movers.size() * 2);
for (int mover : movers) {
moved.put(mover, hops.computeIfAbsent(surfaceKeys.get(mover), this::hop));
}
current = IndexedField.advance(current, moved).shared(name + "/hop" + (hop + 1));
}
return current;
}
private IndexedField hop(String parent) {
IrisBiome biome = pools.biome(parent);
BiomePools.ChildPlan plan = pools.plan(parent);
List<Integer> leaves = new ArrayList<>(plan.choiceByIndex().size());
for (String choice : plan.choiceByIndex()) {
leaves.add(surfaceIndex.get(choice));
}
return selectors.scaled(biome.getChildStyle(), biome.getChildShrinkFactor(), CHILD_SALT)
.partition(BiomePools.selectionCuts(plan.choiceByIndex().size()), leaves);
}
}
private record RegionPicks(List<IndexedField> land, List<IndexedField> sea, List<IndexedField> shore, List<IndexedField> caves, List<Field> shoreHeights) {
}
}
@@ -0,0 +1,299 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomeCustom;
import art.arcane.iris.generation.biome.IrisVanillaBiomeTags;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import art.arcane.iris.pack.validation.ContentGate;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.VanillaDataSource;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
public final class BiomeDefinitionCompiler {
private static final String VANILLA_NAMESPACE = "minecraft";
private static final String BIOME_FOLDER = "/worldgen/biome/";
private static final String TAG_FOLDER = "/tags/worldgen/biome";
private static final String JSON_SUFFIX = ".json";
private static final String SPAWNS_ATTRIBUTE = "minecraft:gameplay/natural_mob_spawns";
private static final String SPAWN_PROBABILITY_ATTRIBUTE = "minecraft:gameplay/creature_world_gen_spawn_probability";
private static final String SPAWN_PROBABILITY = "creature_spawn_probability";
private static final List<String> CLIMATE_KEYS = List.of("has_precipitation", "temperature", "downfall", "temperature_modifier");
private static final List<String> CUSTOM_KEYS = List.of("has_precipitation", "temperature", "downfall", "temperature_modifier",
"effects", "attributes", "spawners", "spawn_costs", SPAWN_PROBABILITY);
private final Optional<VanillaDataSource> vanilla;
public BiomeDefinitionCompiler(Optional<VanillaDataSource> vanilla) {
this.vanilla = Objects.requireNonNull(vanilla);
}
public static BiomeDefinitionCompiler forTarget(DataVersion target) {
if (!IrisPlatforms.isBound()) {
return new BiomeDefinitionCompiler(Optional.empty());
}
IrisPlatform platform = IrisPlatforms.get();
boolean running = DataVersion.forMinecraftVersion(platform.minecraftVersion()) == target;
return new BiomeDefinitionCompiler(running ? Optional.ofNullable(platform.vanillaData()) : Optional.empty());
}
public Definitions compile(PackCompileContext context, Map<String, String> loadKeyByBiomeId) {
DataVersion target = context.capabilities().target();
ContentGate gate = vanilla.isPresent() ? ContentGate.forData(context.data()) : new ContentGate(null, Map.of(), null);
if (vanilla.isEmpty()) {
diagnose(context, "dimensions/" + context.dimension().getLoadKey(), "Vanilla biome data for Minecraft " + target.getVersion()
+ " is not available on this server; biomes are built from their Iris fields without vanilla music, ambience, spawns or structure tags");
}
Map<String, List<String>> vanillaTags = vanilla.map(BiomeDefinitionCompiler::directTags).orElse(Map.of());
SortedMap<String, SortedSet<String>> members = new TreeMap<>();
List<BiomeDef> biomes = new ArrayList<>(loadKeyByBiomeId.size());
for (Map.Entry<String, String> entry : new TreeMap<>(loadKeyByBiomeId).entrySet()) {
String id = entry.getKey();
IrisBiome biome = Objects.requireNonNull(context.data().getBiomeLoader().load(entry.getValue(), false),
"Biome '" + entry.getValue() + "' could not be loaded");
IrisBiomeCustom custom = custom(context, biome);
String visualKey = biome.getBiomeScatter().isEmpty() ? biome.getDerivativeKey() : namespaced(biome.getBiomeScatter().getFirst());
Optional<JsonObject> base = vanilla.flatMap(source -> read(source, visualKey));
if (vanilla.isPresent() && base.isEmpty()) {
diagnose(context, "biomes/" + biome.getLoadKey(), "Vanilla biome '" + visualKey + "' has no data for Minecraft " + target.getVersion()
+ "; the biome is built from its Iris fields");
}
JsonObject overlay = custom == null ? null : customJson(custom, target, gate);
JsonObject json = base.isPresent()
? merge(base.get(), overlay, custom)
: retained(overlay == null ? customJson(new IrisBiomeCustom(), target, gate) : overlay);
json.add("carvers", new JsonArray());
json.add("features", new JsonArray());
biomes.add(new BiomeDef(id.substring(id.indexOf(':') + 1), json));
for (String tag : tags(biome, custom, vanillaTags)) {
members.computeIfAbsent(tag, ignored -> new TreeSet<>()).add(id);
}
}
List<JsonResource> tags = new ArrayList<>(members.size());
for (Map.Entry<String, SortedSet<String>> tag : members.entrySet()) {
JsonObject json = new JsonObject();
json.addProperty("replace", false);
JsonArray values = new JsonArray(tag.getValue().size());
for (String member : tag.getValue()) {
values.add(member);
}
json.add("values", values);
int separator = tag.getKey().indexOf(':');
tags.add(new JsonResource("data/" + tag.getKey().substring(0, separator) + TAG_FOLDER + "/" + tag.getKey().substring(separator + 1) + JSON_SUFFIX, json));
}
return new Definitions(biomes, tags);
}
private static IrisBiomeCustom custom(PackCompileContext context, IrisBiome biome) {
boolean customs = biome.getCustomDerivitives() != null && biome.getCustomDerivitives().size() > 1;
if (customs || biome.getBiomeScatter().size() > 1) {
context.diagnostics().add(new ExportDiagnostic(ExportDiagnostic.Severity.INFO, ExportLimit.BIOME_VARIANT, "biomes/" + biome.getLoadKey(),
"Biomes with several custom derivatives or scatter biomes export as one biome using the first entry"));
}
return biome.isCustom() ? biome.getCustomDerivitives().getFirst() : null;
}
private static JsonObject customJson(IrisBiomeCustom custom, DataVersion target, ContentGate gate) {
return JsonParser.parseString(custom.generateJson(target.get(), gate)).getAsJsonObject();
}
private static JsonObject merge(JsonObject base, JsonObject overlay, IrisBiomeCustom custom) {
JsonObject merged = base.deepCopy();
if (overlay == null) {
return merged;
}
for (String key : CLIMATE_KEYS) {
if (overlay.has(key)) {
merged.add(key, overlay.get(key).deepCopy());
}
}
boolean spawnRarity = custom.getSpawnRarity() > 0;
putAll(object(merged, "effects"), overlay.getAsJsonObject("effects"));
JsonObject overlayAttributes = overlay.getAsJsonObject("attributes");
if (overlayAttributes != null) {
JsonObject attributes = object(merged, "attributes");
for (Map.Entry<String, JsonElement> attribute : overlayAttributes.entrySet()) {
switch (attribute.getKey()) {
case SPAWNS_ATTRIBUTE -> mergeSpawnAttribute(attributes, attribute.getValue());
case SPAWN_PROBABILITY_ATTRIBUTE -> {
if (spawnRarity) {
attributes.add(attribute.getKey(), attribute.getValue().deepCopy());
}
}
default -> attributes.add(attribute.getKey(), attribute.getValue().deepCopy());
}
}
}
if (overlay.has("spawners")) {
mergeSpawns(merged, overlay);
}
if (spawnRarity && overlay.has(SPAWN_PROBABILITY)) {
merged.add(SPAWN_PROBABILITY, overlay.get(SPAWN_PROBABILITY).deepCopy());
}
return merged;
}
private static void mergeSpawnAttribute(JsonObject attributes, JsonElement overlay) {
JsonElement existing = attributes.get(SPAWNS_ATTRIBUTE);
if (existing == null || !existing.isJsonObject() || !overlay.isJsonObject()) {
attributes.add(SPAWNS_ATTRIBUTE, overlay.deepCopy());
return;
}
JsonObject target = spawnHolder(existing.getAsJsonObject());
JsonObject source = spawnHolder(overlay.getAsJsonObject());
appendCategories(object(target, "spawns_by_category"), source.getAsJsonObject("spawns_by_category"));
putAll(object(target, "spawn_costs"), source.getAsJsonObject("spawn_costs"));
}
private static void mergeSpawns(JsonObject merged, JsonObject overlay) {
appendCategories(object(merged, "spawners"), overlay.getAsJsonObject("spawners"));
putAll(object(merged, "spawn_costs"), overlay.getAsJsonObject("spawn_costs"));
}
private static JsonObject spawnHolder(JsonObject attribute) {
JsonElement argument = attribute.get("argument");
return argument != null && argument.isJsonObject() ? argument.getAsJsonObject() : attribute;
}
private static void appendCategories(JsonObject target, JsonObject source) {
if (source == null) {
return;
}
for (Map.Entry<String, JsonElement> category : source.entrySet()) {
JsonElement existing = target.get(category.getKey());
JsonArray spawns = existing != null && existing.isJsonArray() ? existing.getAsJsonArray() : new JsonArray();
spawns.addAll(category.getValue().deepCopy().getAsJsonArray());
target.add(category.getKey(), spawns);
}
}
private static void putAll(JsonObject target, JsonObject source) {
if (source == null) {
return;
}
for (Map.Entry<String, JsonElement> entry : source.entrySet()) {
target.add(entry.getKey(), entry.getValue().deepCopy());
}
}
private static JsonObject object(JsonObject parent, String key) {
JsonElement existing = parent.get(key);
if (existing != null && existing.isJsonObject()) {
return existing.getAsJsonObject();
}
JsonObject created = new JsonObject();
parent.add(key, created);
return created;
}
private static JsonObject retained(JsonObject custom) {
JsonObject retained = new JsonObject();
for (String key : CUSTOM_KEYS) {
if (custom.has(key)) {
retained.add(key, custom.get(key).deepCopy());
}
}
return retained;
}
private static SortedSet<String> tags(IrisBiome biome, IrisBiomeCustom custom, Map<String, List<String>> vanillaTags) {
SortedSet<String> tags = new TreeSet<>();
if (custom != null && custom.getTags() != null) {
for (String tag : custom.getTags()) {
String normalized = tagId(tag);
if (normalized != null) {
tags.add(normalized);
}
}
}
String structureKey = biome.getVanillaDerivativeKey();
tags.addAll(vanillaTags.isEmpty() ? IrisVanillaBiomeTags.tagsFor(structureKey) : vanillaTags.getOrDefault(structureKey, List.of()));
return tags;
}
private static Map<String, List<String>> directTags(VanillaDataSource source) {
String root = "data/" + VANILLA_NAMESPACE + TAG_FOLDER;
Map<String, List<String>> tags = new HashMap<>();
for (String path : source.list(root)) {
if (!path.endsWith(JSON_SUFFIX)) {
continue;
}
String tag = VANILLA_NAMESPACE + ":" + path.substring(root.length() + 1, path.length() - JSON_SUFFIX.length());
Optional<JsonObject> json = read(source, path);
JsonArray values = json.isEmpty() ? null : json.get().getAsJsonArray("values");
if (values == null) {
continue;
}
for (JsonElement value : values) {
String member = value.isJsonObject() ? value.getAsJsonObject().get("id").getAsString() : value.getAsString();
if (!member.startsWith("#")) {
tags.computeIfAbsent(namespaced(member), ignored -> new ArrayList<>()).add(tag);
}
}
}
return tags;
}
private static Optional<JsonObject> read(VanillaDataSource source, String biomeKeyOrPath) {
String path = biomeKeyOrPath.startsWith("data/") ? biomeKeyOrPath : biomePath(biomeKeyOrPath);
if (path == null) {
return Optional.empty();
}
return source.read(path).map(bytes -> JsonParser.parseString(new String(bytes, StandardCharsets.UTF_8)).getAsJsonObject());
}
private static String biomePath(String biomeKey) {
if (biomeKey == null || !VanillaResourceIdentifier.validIdentifier(biomeKey)) {
return null;
}
int separator = biomeKey.indexOf(':');
return "data/" + biomeKey.substring(0, separator) + BIOME_FOLDER + biomeKey.substring(separator + 1) + JSON_SUFFIX;
}
private static String namespaced(String key) {
String trimmed = key.trim().toLowerCase(Locale.ROOT);
return trimmed.indexOf(':') < 0 ? VANILLA_NAMESPACE + ":" + trimmed : trimmed;
}
private static String tagId(String tag) {
if (tag == null || tag.isBlank()) {
return null;
}
String trimmed = tag.trim();
String normalized = namespaced(trimmed.startsWith("#") ? trimmed.substring(1) : trimmed);
return VanillaResourceIdentifier.validIdentifier(normalized) ? normalized : null;
}
private static void diagnose(PackCompileContext context, String resource, String message) {
context.diagnostics().add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.VANILLA_BIOME_DATA, resource, message));
}
public record Definitions(List<BiomeDef> biomes, List<JsonResource> tags) {
public Definitions {
biomes = List.copyOf(biomes);
tags = List.copyOf(tags);
}
}
}
@@ -0,0 +1,27 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import java.util.Objects;
import java.util.Set;
public final class BiomeIdSanitizer {
private static final int FIRST_SUFFIX = 2;
private BiomeIdSanitizer() {
}
public static String sanitize(String namespace, String loadKey, Set<String> taken) {
VanillaResourceIdentifier.requireNamespace(namespace, "biome namespace");
Objects.requireNonNull(taken);
String path = VanillaResourceIdentifier.sanitizePath(loadKey);
String id = namespace + ":" + path;
int suffix = FIRST_SUFFIX;
while (taken.contains(id)) {
id = namespace + ":" + path + "_" + suffix;
suffix++;
}
taken.add(id);
return id;
}
}
@@ -0,0 +1,192 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.InferredType;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRaritySelection;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.Rarity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
final class BiomePools {
static final int MAX_CHILD_HOPS = 4;
static final List<InferredType> SURFACE_TYPES = List.of(InferredType.LAND, InferredType.SEA, InferredType.SHORE);
private final List<RegionPools> regions;
private final SortedMap<String, IrisBiome> biomes;
private final SortedSet<String> surface;
private final SortedSet<String> cave;
private final Map<String, ChildPlan> plans;
private BiomePools(List<RegionPools> regions, SortedMap<String, IrisBiome> biomes, SortedSet<String> surface, SortedSet<String> cave, Map<String, ChildPlan> plans) {
this.regions = regions;
this.biomes = biomes;
this.surface = surface;
this.cave = cave;
this.plans = plans;
}
static BiomePools load(IrisDimension dimension, IrisData data) {
List<RegionPools> regions = new ArrayList<>();
SortedMap<String, IrisBiome> biomes = new TreeMap<>();
for (IrisRegion region : data.getRegionLoader().loadAll(dimension.getRegions())) {
if (region.isCompatExcluded()) {
continue;
}
RegionPools pools = new RegionPools(
region,
pool(data, region.getLandBiomes(), biomes),
pool(data, region.getSeaBiomes(), biomes),
pool(data, region.getShoreBiomes(), biomes),
pool(data, region.getCaveBiomes(), biomes));
if (pools.land().isEmpty() && pools.sea().isEmpty()) {
throw new IllegalStateException("Region '" + region.getLoadKey() + "' has no land or sea biome to export");
}
regions.add(pools);
}
if (regions.isEmpty()) {
throw new IllegalStateException("Dimension '" + dimension.getLoadKey() + "' has no exportable region");
}
SortedSet<String> cave = new TreeSet<>();
SortedSet<String> frontier = new TreeSet<>();
for (RegionPools pools : regions) {
for (InferredType type : SURFACE_TYPES) {
for (IrisBiome biome : pools.of(type)) {
frontier.add(biome.getLoadKey());
}
}
for (IrisBiome biome : pools.cave()) {
cave.add(biome.getLoadKey());
}
}
Map<String, ChildPlan> plans = new HashMap<>();
SortedSet<String> surface = new TreeSet<>(frontier);
for (int hop = 0; hop < MAX_CHILD_HOPS && !frontier.isEmpty(); hop++) {
SortedSet<String> next = new TreeSet<>();
for (String key : frontier) {
ChildPlan plan = plans.computeIfAbsent(key, ignored -> ChildPlan.of(biomes.get(key), data, biomes));
for (String choice : plan.choices()) {
if (surface.add(choice)) {
next.add(choice);
}
}
}
frontier = next;
}
return new BiomePools(List.copyOf(regions), biomes, surface, cave, plans);
}
static List<Double> rarityCuts(List<? extends Rarity> options) {
double total = 0.0;
for (Rarity option : options) {
total += 1.0 / Rarity.get(option);
}
List<Double> cuts = new ArrayList<>(Math.max(0, options.size() - 1));
double cumulative = 0.0;
for (int index = 0; index + 1 < options.size(); index++) {
cumulative += 1.0 / Rarity.get(options.get(index));
cuts.add(cumulative / total);
}
return cuts;
}
static List<Double> selectionCuts(int size) {
int maximum = size - 1;
List<Double> cuts = new ArrayList<>(Math.max(0, maximum));
for (int index = 0; index < maximum; index++) {
cuts.add((index + 0.5) / maximum);
}
return cuts;
}
List<RegionPools> regions() {
return regions;
}
IrisBiome biome(String loadKey) {
return Objects.requireNonNull(biomes.get(loadKey), "Biome '" + loadKey + "' was not loaded");
}
SortedSet<String> surface() {
return surface;
}
SortedSet<String> cave() {
return cave;
}
ChildPlan plan(String loadKey) {
return plans.get(loadKey);
}
private static List<IrisBiome> pool(IrisData data, KList<String> keys, SortedMap<String, IrisBiome> biomes) {
List<IrisBiome> pool = new ArrayList<>();
for (IrisBiome biome : data.getBiomeLoader().loadAll(keys)) {
if (biome.isCompatExcluded()) {
continue;
}
biomes.putIfAbsent(biome.getLoadKey(), biome);
pool.add(biome);
}
return List.copyOf(pool);
}
record RegionPools(IrisRegion region, List<IrisBiome> land, List<IrisBiome> sea, List<IrisBiome> shore, List<IrisBiome> cave) {
List<IrisBiome> of(InferredType type) {
return switch (type) {
case LAND -> land;
case SEA -> sea;
case SHORE -> shore;
case CAVE -> cave;
};
}
}
record ChildPlan(String parent, List<String> choiceByIndex) {
static ChildPlan of(IrisBiome parent, IrisData data, SortedMap<String, IrisBiome> biomes) {
if (parent.getChildren().isEmpty()) {
return new ChildPlan(parent.getLoadKey(), List.of(parent.getLoadKey()));
}
KList<IrisBiome> options = new KList<>();
for (IrisBiome child : parent.getRealChildren(() -> data)) {
if (child != null) {
biomes.putIfAbsent(child.getLoadKey(), child);
options.add(child);
}
}
options.add(parent);
IrisRaritySelection<IrisBiome> selection = IrisRaritySelection.create(options);
long size = selection.size();
List<String> choices = new ArrayList<>((int) size);
for (long index = 0; index < size; index++) {
choices.add(selection.get(index).getLoadKey());
}
return new ChildPlan(parent.getLoadKey(), List.copyOf(choices));
}
boolean moves() {
for (String choice : choiceByIndex) {
if (!choice.equals(parent)) {
return true;
}
}
return false;
}
SortedSet<String> choices() {
return new TreeSet<>(choiceByIndex);
}
}
}
@@ -0,0 +1,21 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
public final class BiomeStage implements CompileStage {
@Override
public String name() {
return "biomes";
}
@Override
public void apply(PackCompileContext context) {
BiomeDecision decision = new BiomeDecisionCompiler(context.styles()).compile(context);
context.setBiomeDecision(decision);
BiomeDefinitionCompiler.Definitions definitions = BiomeDefinitionCompiler.forTarget(context.capabilities().target())
.compile(context, decision.base().loadKeyByBiomeId());
context.setBiomes(definitions.biomes());
context.jsonResources().addAll(definitions.tags());
}
}
@@ -0,0 +1,239 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.iris.pack.value.IrisRaritySelection;
import art.arcane.volmlib.util.math.Rarity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.ToIntFunction;
final class CarvingZones {
static final int SHALLOW_ZONE = 0;
static final int CAVE_ZONE = 1;
static final int FIRST_CARVING_ZONE = 2;
private static final int MAX_CHILD_DEPTH = 32;
private static final double MINIMUM_CHILD_SHRINK_FACTOR = 0.0001;
private static final long CARVING_SALT = 0x0CA4_7E00L;
private final List<Integer> cuts;
private final List<Integer> zoneByInterval;
private final List<Machine> machines;
private final SortedSet<String> biomes;
private CarvingZones(List<Integer> cuts, List<Integer> zoneByInterval, List<Machine> machines, SortedSet<String> biomes) {
this.cuts = cuts;
this.zoneByInterval = zoneByInterval;
this.machines = machines;
this.biomes = biomes;
}
static CarvingZones plan(IrisDimension dimension, IrisData data, int deepTop) {
List<IrisDimensionCarvingEntry> entries = new ArrayList<>();
if (dimension.getCarving() != null) {
for (IrisDimensionCarvingEntry entry : dimension.getCarving()) {
if (entry != null && entry.isEnabled() && entry.getRealBiome(data) != null) {
entries.add(entry);
}
}
}
SortedSet<Integer> cutSet = new TreeSet<>();
cutSet.add(deepTop + 1);
for (IrisDimensionCarvingEntry entry : entries) {
IrisRange range = entry.getWorldYRange();
if (range != null && range.getMin() <= range.getMax()) {
cutSet.add((int) Math.ceil(range.getMin()));
cutSet.add((int) Math.floor(range.getMax()) + 1);
}
}
List<Integer> cuts = List.copyOf(cutSet);
Map<String, IrisDimensionCarvingEntry> byId = dimension.getCarvingEntryIndex();
Map<ZoneKey, Integer> zones = new LinkedHashMap<>();
List<Machine> machines = new ArrayList<>();
SortedSet<String> biomes = new TreeSet<>();
List<Integer> zoneByInterval = new ArrayList<>(cuts.size() + 1);
for (int interval = 0; interval <= cuts.size(); interval++) {
int y = interval == 0 ? cuts.getFirst() - 1 : cuts.get(interval - 1);
if (y > deepTop) {
zoneByInterval.add(SHALLOW_ZONE);
continue;
}
IrisDimensionCarvingEntry root = null;
List<Integer> inRange = new ArrayList<>();
for (int position = 0; position < entries.size(); position++) {
IrisDimensionCarvingEntry entry = entries.get(position);
if (contains(entry, y)) {
root = entry;
inRange.add(position);
}
}
if (root == null) {
zoneByInterval.add(CAVE_ZONE);
continue;
}
ZoneKey key = new ZoneKey(entries.indexOf(root), List.copyOf(inRange));
Integer zone = zones.get(key);
if (zone == null) {
Machine machine = Machine.build(root, y, byId, data);
zone = FIRST_CARVING_ZONE + machines.size();
zones.put(key, zone);
machines.add(machine);
for (State state : machine.states()) {
biomes.add(state.entry().getRealBiome(data).getLoadKey());
}
}
zoneByInterval.add(zone);
}
return new CarvingZones(cuts, List.copyOf(zoneByInterval), List.copyOf(machines), biomes);
}
SortedSet<String> biomes() {
return biomes;
}
IndexedField zoneKeys(Field y) {
List<Double> thresholds = new ArrayList<>(cuts.size());
for (int cut : cuts) {
thresholds.add((double) cut);
}
List<Integer> leaves = new ArrayList<>(zoneByInterval.size());
for (int zone : zoneByInterval) {
leaves.add(zone * 4);
}
return IndexedField.partition(y, thresholds, leaves);
}
List<IndexedField> slots(SelectorCompiler selectors, IrisData data, ToIntFunction<String> undergroundSlot) {
List<IndexedField> slots = new ArrayList<>(machines.size());
for (int zone = 0; zone < machines.size(); zone++) {
slots.add(machines.get(zone).slot("biome/carving/" + zone, selectors, data, undergroundSlot));
}
return slots;
}
private static boolean contains(IrisDimensionCarvingEntry entry, int y) {
IrisRange range = entry.getWorldYRange();
return range == null || range.contains(y);
}
private static int clampDepth(int depth) {
return depth <= 0 ? 0 : Math.min(depth, MAX_CHILD_DEPTH);
}
private record ZoneKey(int root, List<Integer> inRange) {
}
private record State(IrisDimensionCarvingEntry entry, int depth) {
}
private record Move(IrisDimensionCarvingEntry entry, List<Integer> nextByIndex) {
}
private record CarvingOption(IrisDimensionCarvingEntry entry, int rarity) implements Rarity {
@Override
public int getRarity() {
return rarity;
}
}
private record Machine(List<State> states, Map<Integer, Move> moves, int hops) {
static Machine build(IrisDimensionCarvingEntry root, int y, Map<String, IrisDimensionCarvingEntry> byId, IrisData data) {
List<State> states = new ArrayList<>();
Map<State, Integer> ids = new HashMap<>();
Map<Integer, Move> moves = new HashMap<>();
int hops = clampDepth(root.getChildRecursionDepth());
State start = new State(root, terminal(root, byId, data) ? 0 : hops);
states.add(start);
ids.put(start, 0);
for (int cursor = 0; cursor < states.size(); cursor++) {
State state = states.get(cursor);
if (state.depth() <= 0) {
continue;
}
IrisRaritySelection<CarvingOption> selection = selection(state.entry(), byId, data);
if (selection.size() <= 1L) {
continue;
}
List<Integer> nextByIndex = new ArrayList<>((int) selection.size());
for (long index = 0; index < selection.size(); index++) {
IrisDimensionCarvingEntry chosen = selection.get(index).entry();
State next = chosen == state.entry() || !contains(chosen, y)
? new State(state.entry(), 0)
: new State(chosen, Math.min(state.depth() - 1, clampDepth(chosen.getChildRecursionDepth())));
Integer id = ids.get(next);
if (id == null) {
id = states.size();
ids.put(next, id);
states.add(next);
}
nextByIndex.add(id);
}
moves.put(cursor, new Move(state.entry(), List.copyOf(nextByIndex)));
}
return new Machine(List.copyOf(states), Map.copyOf(moves), hops);
}
IndexedField slot(String name, SelectorCompiler selectors, IrisData data, ToIntFunction<String> undergroundSlot) {
IndexedField current = IndexedField.constant(0);
for (int hop = 0; hop < hops; hop++) {
List<Integer> movers = new ArrayList<>();
for (int state : current.values()) {
if (moves.containsKey(state)) {
movers.add(state);
}
}
if (movers.isEmpty()) {
break;
}
Map<Integer, IndexedField> moved = new HashMap<>(movers.size() * 2);
for (int state : movers) {
Move move = moves.get(state);
IrisDimensionCarvingEntry entry = move.entry();
SelectorCompiler.Selector selector = selectors.scaled(
entry.getChildStyle(),
Math.max(MINIMUM_CHILD_SHRINK_FACTOR, entry.getChildShrinkFactor()),
CARVING_SALT + Objects.toString(entry.getId(), "").trim().hashCode());
moved.put(state, selector.partition(BiomePools.selectionCuts(move.nextByIndex().size()), move.nextByIndex()));
}
current = IndexedField.advance(current, moved).shared(name + "/hop" + (hop + 1));
}
return current.remap(state -> undergroundSlot.applyAsInt(states.get(state).entry().getRealBiome(data).getLoadKey()));
}
private static boolean terminal(IrisDimensionCarvingEntry entry, Map<String, IrisDimensionCarvingEntry> byId, IrisData data) {
return entry.getChildren() == null || entry.getChildren().isEmpty() || selection(entry, byId, data).size() <= 1L;
}
private static IrisRaritySelection<CarvingOption> selection(IrisDimensionCarvingEntry parent, Map<String, IrisDimensionCarvingEntry> byId, IrisData data) {
List<CarvingOption> options = new ArrayList<>();
if (parent.getChildren() != null) {
for (String childId : parent.getChildren()) {
if (childId == null || childId.isBlank()) {
continue;
}
IrisDimensionCarvingEntry child = byId.get(childId.trim());
if (child == null || !child.isEnabled()) {
continue;
}
IrisBiome childBiome = child.getRealBiome(data);
if (childBiome != null) {
options.add(new CarvingOption(child, Math.max(childBiome.getRarity(), 1)));
}
}
}
options.add(new CarvingOption(parent, Math.max(parent.getRealBiome(data).getRarity(), 1)));
return IrisRaritySelection.create(options);
}
}
}
@@ -0,0 +1,162 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.export.ir.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.IntToDoubleFunction;
import java.util.function.IntUnaryOperator;
record IndexedField(Field field, List<Integer> values) {
private static final Field UNUSED_CASE = new Field.Const(0.0);
IndexedField {
Objects.requireNonNull(field);
values = List.copyOf(new TreeSet<>(values));
if (values.isEmpty()) {
throw new IllegalArgumentException("An indexed field needs at least one value");
}
}
static IndexedField constant(int value) {
return new IndexedField(new Field.Const(value), List.of(value));
}
static IndexedField partition(Field input, List<Double> thresholds, List<Integer> leaves) {
if (leaves.size() != thresholds.size() + 1) {
throw new IllegalArgumentException("Partition needs " + (thresholds.size() + 1) + " leaves, got " + leaves.size());
}
List<Double> kept = new ArrayList<>(thresholds.size());
List<Integer> keptLeaves = new ArrayList<>(leaves.size());
keptLeaves.add(leaves.getFirst());
for (int index = 0; index < thresholds.size(); index++) {
int next = leaves.get(index + 1);
if (next == keptLeaves.getLast()) {
continue;
}
kept.add(thresholds.get(index));
keptLeaves.add(next);
}
if (keptLeaves.size() == 1) {
return constant(keptLeaves.getFirst());
}
List<Field> constants = new ArrayList<>(keptLeaves.size());
for (int leaf : keptLeaves) {
constants.add(new Field.Const(leaf));
}
return new IndexedField(new Field.Partition(input, kept, constants), keptLeaves);
}
static IndexedField select(IndexedField index, List<IndexedField> cases) {
if (index.isConstant()) {
return cases.get(index.values().getFirst());
}
IndexedField first = cases.get(index.values().getFirst());
boolean uniform = true;
SortedSet<Integer> reachable = new TreeSet<>();
for (int value : index.values()) {
IndexedField selected = cases.get(value);
uniform &= selected.equals(first);
reachable.addAll(selected.values());
}
if (uniform) {
return first;
}
int count = index.values().getLast() + 1;
List<Field> muxCases = new ArrayList<>(count);
for (int value = 0; value < count; value++) {
muxCases.add(index.values().contains(value) ? cases.get(value).field() : UNUSED_CASE);
}
return new IndexedField(new Field.Mux(index.field(), muxCases), List.copyOf(reachable));
}
static IndexedField advance(IndexedField current, Map<Integer, IndexedField> moved) {
int last = current.values().getLast();
List<IndexedField> cases = new ArrayList<>(last + 1);
for (int value = 0; value <= last; value++) {
IndexedField next = moved.get(value);
cases.add(next == null ? constant(value) : next);
}
return select(current, cases);
}
static IndexedField sum(List<IndexedField> terms) {
SortedSet<Integer> values = new TreeSet<>(List.of(0));
int offset = 0;
Field field = null;
for (IndexedField term : terms) {
SortedSet<Integer> combined = new TreeSet<>();
for (int value : values) {
for (int addend : term.values()) {
combined.add(value + addend);
}
}
values = combined;
if (term.isConstant()) {
offset += term.values().getFirst();
} else {
field = field == null ? term.field() : new Field.Binary(Field.BinaryOp.ADD, field, term.field());
}
}
if (field == null) {
return constant(offset);
}
Field total = offset == 0 ? field : new Field.Binary(Field.BinaryOp.ADD, field, new Field.Const(offset));
return new IndexedField(total, List.copyOf(values));
}
static List<Double> midpoints(List<Integer> sorted) {
List<Double> thresholds = new ArrayList<>(sorted.size() - 1);
for (int index = 0; index + 1 < sorted.size(); index++) {
thresholds.add((sorted.get(index) + sorted.get(index + 1)) / 2.0);
}
return thresholds;
}
boolean isConstant() {
return values.size() == 1;
}
IndexedField remap(IntUnaryOperator mapping) {
List<Integer> mapped = new ArrayList<>(values.size());
for (int value : values) {
mapped.add(mapping.applyAsInt(value));
}
if (isConstant()) {
return constant(mapped.getFirst());
}
return partition(field, midpoints(values), mapped);
}
Field lookup(IntToDoubleFunction table) {
if (isConstant()) {
return new Field.Const(table.applyAsDouble(values.getFirst()));
}
List<Double> thresholds = midpoints(values);
List<Double> keptThresholds = new ArrayList<>(thresholds.size());
List<Field> leaves = new ArrayList<>(values.size());
double previous = table.applyAsDouble(values.getFirst());
leaves.add(new Field.Const(previous));
for (int index = 1; index < values.size(); index++) {
double next = table.applyAsDouble(values.get(index));
if (next == previous) {
continue;
}
keptThresholds.add(thresholds.get(index - 1));
leaves.add(new Field.Const(next));
previous = next;
}
if (leaves.size() == 1) {
return leaves.getFirst();
}
return new Field.Partition(field, keptThresholds, leaves);
}
IndexedField shared(String name) {
return isConstant() ? this : new IndexedField(new Field.Shared(name, field), values);
}
}
@@ -0,0 +1,115 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SplittableRandom;
import java.util.function.DoubleBinaryOperator;
public final class RarityCalibrator {
private static final int SAMPLES = 8192;
private static final double WINDOW_FEATURES = 96.0;
private static final double MAX_WINDOW_BLOCKS = 4_000_000.0;
private static final long POSITION_SEED = 0x5EED_B10EL;
private static final long WORLD_SEED = 0x1215_B10EL;
private final NoiseRegistry registry;
private final DataVersion target;
public RarityCalibrator(NoiseRegistry registry, DataVersion target) {
this.registry = Objects.requireNonNull(registry);
this.target = Objects.requireNonNull(target);
}
public Calibration calibrate(DoubleBinaryOperator iris, Field compiled, double featureBlocks, long salt) {
Objects.requireNonNull(iris);
Objects.requireNonNull(compiled);
double window = Math.min(MAX_WINDOW_BLOCKS, Math.max(1.0, featureBlocks) * WINDOW_FEATURES);
Map<String, NoiseDef> noises = noiseDefinitions();
SplittableRandom positions = new SplittableRandom(POSITION_SEED ^ salt);
double[] irisSamples = new double[SAMPLES];
double[] compiledSamples = new double[SAMPLES];
for (int index = 0; index < SAMPLES; index++) {
int x = (int) Math.floor((positions.nextDouble() - 0.5) * window);
int z = (int) Math.floor((positions.nextDouble() - 0.5) * window);
irisSamples[index] = iris.applyAsDouble(x, z);
compiledSamples[index] = compiled instanceof Field.Const constant
? constant.value()
: FieldEvaluator.sample(compiled, noises, WORLD_SEED, target, x, 0, z);
}
Arrays.sort(irisSamples);
Arrays.sort(compiledSamples);
return new Calibration(irisSamples, compiledSamples);
}
private Map<String, NoiseDef> noiseDefinitions() {
List<NoiseDef> definitions = registry.definitions();
Map<String, NoiseDef> noises = new HashMap<>(definitions.size() * 2);
for (NoiseDef definition : definitions) {
noises.put(registry.namespace() + ":" + definition.id(), definition);
}
return noises;
}
public static final class Calibration {
private final double[] iris;
private final double[] compiled;
private Calibration(double[] iris, double[] compiled) {
this.iris = iris;
this.compiled = compiled;
}
public double cumulative(double irisValue) {
int low = 0;
int high = iris.length;
while (low < high) {
int middle = (low + high) >>> 1;
if (iris[middle] < irisValue) {
low = middle + 1;
} else {
high = middle;
}
}
return low / (double) iris.length;
}
public double threshold(double probability) {
return quantile(compiled, probability);
}
public double irisQuantile(double probability) {
return quantile(iris, probability);
}
public List<Double> thresholds(List<Double> irisCuts) {
List<Double> thresholds = new ArrayList<>(irisCuts.size());
for (double cut : irisCuts) {
thresholds.add(threshold(cumulative(cut)));
}
return thresholds;
}
private static double quantile(double[] sorted, double probability) {
double position = Math.clamp(probability, 0.0, 1.0) * sorted.length - 0.5;
if (position <= 0.0) {
return sorted[0];
}
if (position >= sorted.length - 1) {
return sorted[sorted.length - 1];
}
int lower = (int) Math.floor(position);
double fraction = position - lower;
return sorted[lower] + fraction * (sorted[lower + 1] - sorted[lower]);
}
}
}
@@ -0,0 +1,184 @@
package art.arcane.iris.pack.datapack.export.compile.biome;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.DoubleBinaryOperator;
public final class SelectorCompiler {
private static final double COHERENT_BLOCKS = 64.0;
private static final long CALIBRATION_SEED = 0x1215_5E1EL;
private static final int CURVE_KNOTS = 9;
private static final String SHARED_PREFIX = "biome/selector/";
private final StyleCompiler styles;
private final IrisData data;
private final NoiseRegistry registry;
private final ExportCapabilities capabilities;
private final RarityCalibrator calibrator;
private final Map<SelectorKey, Selector> selectors = new HashMap<>();
private int shared;
public SelectorCompiler(StyleCompiler styles, Sources sources) {
this.styles = Objects.requireNonNull(styles);
Objects.requireNonNull(sources);
data = sources.data();
registry = sources.registry();
capabilities = sources.capabilities();
calibrator = new RarityCalibrator(registry, capabilities.target());
}
public Selector zoomed(IrisGeneratorStyle style, double zoom, long salt) {
return selectors.computeIfAbsent(new SelectorKey(style, false, zoom, salt), this::create);
}
public Selector scaled(IrisGeneratorStyle style, double scale, long salt) {
return selectors.computeIfAbsent(new SelectorKey(style, true, scale, salt), this::create);
}
public Selector sampled(IrisGeneratorStyle style, double zoom, long salt, DoubleBinaryOperator iris) {
IrisGeneratorStyle exported = exportable(style);
exported.setZoom(exported.getZoom() * zoom);
return compile(exported, salt, iris, COHERENT_BLOCKS * exported.getZoom());
}
private Selector create(SelectorKey key) {
IrisGeneratorStyle exported = exportable(key.style());
RNG seed = new RNG(CALIBRATION_SEED).nextParallelRNG(key.salt());
if (key.scaled()) {
CNG iris = exported.createScaledGenerator(seed, data, key.factor());
IrisGeneratorStyle compiled = scaledCopy(exported, key.factor());
return compile(compiled, key.salt(), iris::noiseFast2D, COHERENT_BLOCKS * compiled.getZoom());
}
CNG iris = exported.create(seed, data);
double zoom = key.factor();
IrisGeneratorStyle compiled = copy(exported);
compiled.setZoom(exported.getZoom() * zoom);
return compile(compiled, key.salt(), (x, z) -> iris.noise(x / zoom, z / zoom), COHERENT_BLOCKS * compiled.getZoom());
}
private Selector compile(IrisGeneratorStyle style, long salt, DoubleBinaryOperator iris, double featureBlocks) {
Field field = styles.compile(style, salt, registry, capabilities);
FieldValidator.requireTwoDimensional(field, "biome selector");
RarityCalibrator.Calibration calibration = calibrator.calibrate(iris, field, featureBlocks, salt);
Field selector = field instanceof Field.Const ? field : new Field.Shared(SHARED_PREFIX + shared++, field);
return new Selector(selector, calibration);
}
private static IrisGeneratorStyle exportable(IrisGeneratorStyle style) {
IrisGeneratorStyle copy = copy(style);
for (IrisGeneratorStyle current = copy; current != null; current = current.getFracture()) {
current.setImageMap(null);
current.setCacheSize(0);
}
return copy;
}
private static IrisGeneratorStyle scaledCopy(IrisGeneratorStyle style, double scale) {
IrisGeneratorStyle copy = copy(style);
copy.setZoom(style.getZoom() / scale);
IrisGeneratorStyle fracture = copy.getFracture();
if (fracture != null) {
fracture.setZoom(fracture.getZoom() * scale);
fracture.setMultiplier(fracture.getMultiplier() * scale);
}
return copy;
}
private static IrisGeneratorStyle copy(IrisGeneratorStyle style) {
IrisGeneratorStyle copy = new IrisGeneratorStyle(style.getStyle());
copy.setCellularFrequency(style.getCellularFrequency());
copy.setCellularZoom(style.getCellularZoom());
copy.setZoom(style.getZoom());
copy.setExpression(style.getExpression());
copy.setImageMap(style.getImageMap());
copy.setMultiplier(style.getMultiplier());
copy.setExponent(style.getExponent());
copy.setCacheSize(style.getCacheSize());
copy.setFracture(style.getFracture() == null ? null : copy(style.getFracture()));
return copy;
}
public record Sources(IrisData data, NoiseRegistry registry, ExportCapabilities capabilities) {
public Sources {
Objects.requireNonNull(data);
Objects.requireNonNull(registry);
Objects.requireNonNull(capabilities);
}
}
public record Selector(Field field, RarityCalibrator.Calibration calibration) {
public Selector {
Objects.requireNonNull(field);
Objects.requireNonNull(calibration);
}
IndexedField partition(List<Double> irisCuts, List<Integer> leaves) {
if (leaves.size() != irisCuts.size() + 1) {
throw new IllegalArgumentException("Selector partition needs " + (irisCuts.size() + 1) + " leaves, got " + leaves.size());
}
List<Double> upper = new ArrayList<>(leaves.size());
List<Integer> kept = new ArrayList<>(leaves.size());
double lower = 0.0;
for (int index = 0; index < leaves.size(); index++) {
double bound = index == irisCuts.size() ? 1.0 : Math.max(lower, calibration.cumulative(irisCuts.get(index)));
if (bound > lower) {
upper.add(bound);
kept.add(leaves.get(index));
}
lower = bound;
}
if (kept.isEmpty()) {
return IndexedField.constant(leaves.getLast());
}
List<Double> thresholds = new ArrayList<>(kept.size() - 1);
for (int index = 0; index + 1 < kept.size(); index++) {
thresholds.add(calibration.threshold(upper.get(index)));
}
return IndexedField.partition(field, thresholds, kept);
}
Field curve() {
List<Field.Knot> knots = new ArrayList<>(CURVE_KNOTS);
double previousLocation = Double.NEGATIVE_INFINITY;
List<double[]> points = new ArrayList<>(CURVE_KNOTS);
for (int index = 0; index < CURVE_KNOTS; index++) {
double probability = (index + 0.5) / CURVE_KNOTS;
double location = calibration.threshold(probability);
if (location <= previousLocation) {
continue;
}
points.add(new double[]{location, calibration.irisQuantile(probability)});
previousLocation = location;
}
if (points.size() == 1) {
return new Field.Const(points.getFirst()[1]);
}
for (int index = 0; index < points.size(); index++) {
double derivative = 0.0;
if (index > 0 && index + 1 < points.size()) {
double[] before = points.get(index - 1);
double[] after = points.get(index + 1);
derivative = (after[1] - before[1]) / (after[0] - before[0]);
}
knots.add(new Field.Knot(points.get(index)[0], new Field.Const(points.get(index)[1]), derivative));
}
return new Field.Curve(field, knots);
}
}
private record SelectorKey(IrisGeneratorStyle style, boolean scaled, double factor, long salt) {
}
}
@@ -0,0 +1,135 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.pack.datapack.export.ir.AquiferDef;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
public final class AquiferCompiler {
private static final int LAVA_LIMIT_Y = -10;
private static final int LAVA_CENTER_MARGIN = 12;
private static final int FLUID_BAND_HEIGHT = 40;
private static final int FLUID_BAND_CENTER = 20;
private static final double SPREAD_LEVEL_SCALE = 10.0;
private static final double LEVEL_ROUNDING_MARGIN = 0.5;
private static final int OPEN_WATER_DEPTH = 8;
private static final int OPEN_WATER_HEADROOM = 8;
private static final int OPEN_WATER_REACH = 32;
private static final int OPEN_WATER_SHORE = 8;
private static final int OPEN_WATER_ESTIMATE_SLACK = 40;
private static final Field OPEN_WATER_LIFT = new Field.Const(2.0);
private static final Field DRY = new Field.Const(-1.0);
private static final Field PARTIAL = new Field.Const(0.6);
private static final Field LOW_BARRIER = new Field.Const(-1.0);
private static final Field NO_EXCLUSION = new Field.Const(-1.0);
private static final Field LAVA = new Field.Const(1.0);
private static final Field NO_LAVA = new Field.Const(0.0);
private static final Field OUTSIDE_BAND = new Field.Const(0.0);
private static final Field INSIDE_BAND = new Field.Const(1.0);
private final CaveInputs inputs;
private final Field blockY;
private final int lowFluidBand;
private final int highFluidBand;
public AquiferCompiler(CaveInputs inputs) {
this.inputs = Objects.requireNonNull(inputs);
this.blockY = inputs.blockY();
this.lowFluidBand = Math.floorDiv(inputs.minY(), FLUID_BAND_HEIGHT) - 1;
this.highFluidBand = Math.floorDiv(inputs.maxY(), FLUID_BAND_HEIGHT) + 1;
}
public AquiferDef compile(CaveSelection selection) {
AquiferDef dry = AquiferDef.dry(inputs.aquiferSurface());
boolean lavaWanted = any(selection, IrisCaveProfile::isAllowLava);
boolean lavaExported = lavaWanted && inputs.lavaY() <= LAVA_LIMIT_Y;
if (lavaWanted && !lavaExported) {
inputs.diagnostics().add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.LAVA_HEIGHT, inputs.resource(),
"Cave lava height Y " + inputs.lavaY() + " is above Y " + LAVA_LIMIT_Y + "; caves export without lava"));
}
boolean wet = any(selection, IrisCaveProfile::isAllowFluid);
if (!lavaExported && !wet) {
return new AquiferDef(dry.barrier(), openWater(dry.floodedness()), dry.spread(), dry.lava(), dry.exclusion(), dry.surfaceLevel());
}
Field spread = lavaExported ? lavaSpread(wet, dry.spread()) : dry.spread();
Field lava = lavaExported ? lavaBands() : NO_LAVA;
return new AquiferDef(LOW_BARRIER, openWater(floodedness(selection, lavaExported)), spread, lava, NO_EXCLUSION, inputs.aquiferSurface());
}
private Field openWater(Field caveFlood) {
Field surface = inputs.surface();
Field nearFluid = new Field.RangeIf(blockY, inputs.fluidHeight() - OPEN_WATER_REACH, inputs.fluidHeight() + OPEN_WATER_HEADROOM + 1.0, INSIDE_BAND, DRY);
Field lowEstimate = new Field.Binary(Field.BinaryOp.SUB, new Field.Const(inputs.fluidHeight() + OPEN_WATER_ESTIMATE_SLACK), inputs.aquiferSurface());
Field aboveFloor = new Field.Binary(Field.BinaryOp.ADD, new Field.Binary(Field.BinaryOp.SUB, blockY, surface), new Field.Const(OPEN_WATER_DEPTH));
Field lowColumn = new Field.Binary(Field.BinaryOp.SUB, new Field.Const(inputs.fluidHeight() + OPEN_WATER_SHORE + LEVEL_ROUNDING_MARGIN), surface);
Field lift = new Field.Gate(aboveFloor, new Field.Gate(lowColumn, OPEN_WATER_LIFT));
return new Field.Binary(Field.BinaryOp.ADD, caveFlood, new Field.Gate(nearFluid, new Field.Gate(lowEstimate, lift)));
}
private Field floodedness(CaveSelection selection, boolean lavaExported) {
Field flood = selection.profiles().isEmpty() ? DRY : selection.select(source -> flood(source, lavaExported), DRY);
for (CaveSource band : selection.bands()) {
Field banded = flood(band, lavaExported);
if (banded.equals(flood)) {
continue;
}
Field inside = new Field.Partition(blockY, List.of((double) band.minY(), band.maxY() + 1.0), List.of(OUTSIDE_BAND, INSIDE_BAND, OUTSIDE_BAND));
flood = new Field.Mux(inside, List.of(flood, banded));
}
return flood;
}
private Field flood(CaveSource source, boolean lavaExported) {
IrisCaveProfile profile = source.profile();
int top = Integer.MIN_VALUE;
if (lavaExported && profile.isAllowLava()) {
top = inputs.lavaY() + LAVA_CENTER_MARGIN;
}
if (profile.isAllowFluid()) {
top = Math.max(top, inputs.fluidHeight());
}
if (top < inputs.minY()) {
return DRY;
}
if (top >= inputs.maxY()) {
return PARTIAL;
}
return new Field.RangeIf(blockY, inputs.minY(), top + 1.0, PARTIAL, DRY);
}
private Field lavaSpread(boolean wet, Field vanillaSpread) {
Field levels = new Field.Coord(Axis.Y, Field.Tiling.CLAMP, lowFluidBand, highFluidBand, spreadAt(lowFluidBand), spreadAt(highFluidBand));
return wet ? new Field.RangeIf(fluidBand(), lowFluidBand, lavaBand() + 1.0, levels, vanillaSpread) : levels;
}
private Field lavaBands() {
return new Field.RangeIf(fluidBand(), lowFluidBand, lavaBand() + 1.0, LAVA, NO_LAVA);
}
private Field fluidBand() {
return new Field.Coord(Axis.Y, Field.Tiling.CLAMP, lowFluidBand, highFluidBand, lowFluidBand, highFluidBand);
}
private int lavaBand() {
return Math.floorDiv(inputs.lavaY() + LAVA_CENTER_MARGIN, FLUID_BAND_HEIGHT);
}
private double spreadAt(int band) {
return (inputs.lavaY() - FLUID_BAND_CENTER + LEVEL_ROUNDING_MARGIN) / SPREAD_LEVEL_SCALE - band * (FLUID_BAND_HEIGHT / SPREAD_LEVEL_SCALE);
}
private static boolean any(CaveSelection selection, Predicate<IrisCaveProfile> property) {
for (CaveSource source : selection.sources()) {
if (property.test(source.profile())) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,60 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public final class CaveFieldCompiler {
static final int CELL_XZ = 4;
static final int CELL_Y = 4;
static final double WALL_BAND = 0.03125;
private static final double MIN_GAIN = 1.0 / 64.0;
private static final double MAX_GAIN = 64.0;
private static final Field UNCOVERED = new Field.Const(CaveProfileCompiler.SOLID);
private final CaveProfileCompiler profiles;
private final CaveInputs inputs;
public CaveFieldCompiler(StyleCompiler styles, CaveInputs inputs) {
this.profiles = new CaveProfileCompiler(styles, inputs);
this.inputs = inputs;
}
public Optional<Field> compile(CaveSelection selection) {
return union(selection).map(union -> new Field.Grid(union, CELL_XZ, CELL_Y));
}
private Optional<Field> union(CaveSelection selection) {
List<Field> parts = new ArrayList<>(selection.bands().size() + 1);
if (!selection.profiles().isEmpty()) {
parts.add(selection.select(this::normalized, UNCOVERED));
}
for (CaveSource band : selection.bands()) {
parts.add(normalized(band));
}
if (parts.isEmpty()) {
return Optional.empty();
}
Field union = parts.getFirst();
for (int index = 1; index < parts.size(); index++) {
union = new Field.Binary(Field.BinaryOp.MIN, union, parts.get(index));
}
return Optional.of(union);
}
private Field normalized(CaveSource source) {
return profiles.compile(source, gain(source));
}
private double gain(CaveSource source) {
Optional<CaveInterior> interior = profiles.interior(source);
if (interior.isEmpty()) {
return 1.0;
}
double band = WallShellCalibrator.band(interior.get(), inputs.noises().byReference(), inputs.capabilities().target());
return band > 0.0 ? Math.clamp(WALL_BAND / band, MIN_GAIN, MAX_GAIN) : 1.0;
}
}
@@ -0,0 +1,60 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.noise.NoiseRegistry;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.ir.FieldValidator;
import art.arcane.iris.pack.datapack.export.lower.ExportCapabilities;
import java.util.List;
import java.util.Objects;
public record CaveInputs(
String resource,
int minY,
int maxY,
int fluidHeight,
int lavaY,
Field surface,
Field aquiferSurface,
NoiseRegistry noises,
ExportCapabilities capabilities,
List<ExportDiagnostic> diagnostics
) {
public CaveInputs {
Objects.requireNonNull(resource);
Objects.requireNonNull(surface);
Objects.requireNonNull(aquiferSurface);
Objects.requireNonNull(noises);
Objects.requireNonNull(capabilities);
Objects.requireNonNull(diagnostics);
if (maxY <= minY) {
throw new IllegalArgumentException("Cave bounds need maxY above minY, got " + minY + ".." + maxY);
}
FieldValidator.requireTwoDimensional(surface, "cave surface");
FieldValidator.requireTwoDimensional(aquiferSurface, "aquifer surface");
}
public static CaveInputs of(PackCompileContext context) {
IrisDimension dimension = context.dimension();
int minY = dimension.getMinHeight();
return new CaveInputs(
"dimensions/" + dimension.getLoadKey(),
minY,
dimension.getMaxHeight() - 1,
context.dimensionDef().fluidHeight(),
minY + dimension.getCaveLavaHeight(),
context.height(),
context.surfaceEstimate(),
context.noises(),
context.capabilities(),
context.diagnostics());
}
public Field blockY() {
return new Field.Coord(Axis.Y, Field.Tiling.CLAMP, minY, maxY + 1, minY, maxY + 1);
}
}
@@ -0,0 +1,14 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.export.ir.Field;
import java.util.Objects;
record CaveInterior(Field field, int minY, int maxY) {
CaveInterior {
Objects.requireNonNull(field);
if (maxY < minY) {
throw new IllegalArgumentException("Cave interior needs maxY at or above minY, got " + minY + ".." + maxY);
}
}
}
@@ -0,0 +1,294 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveFieldModule;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisStyledRange;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.export.compile.noise.StyleCompiler;
import art.arcane.iris.pack.datapack.export.ir.Axis;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.value.IrisRange;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public final class CaveProfileCompiler {
static final double SOLID = 1.0;
private static final long BASE_SALT = 934_447L;
private static final long DETAIL_SALT = 612_991L;
private static final long THRESHOLD_SALT = 489_112L;
private static final long SURFACE_BREAK_SALT = 341_219L;
private static final long MODULE_SALT = 1_000_003L;
private static final long MODULE_SALT_STEP = 65_537L;
private static final double LOW_WEIGHT = 0.1;
private static final int CEILING_FADE_DEPTH = 12;
private static final double CLOSURE_EPSILON = 1.0e-6;
private static final double SEALED_MARGIN = 1.0;
private static final Set<NoiseStyle> CELLULAR_STYLES = cellularStyles();
private final StyleCompiler styles;
private final CaveInputs inputs;
private final Field blockY;
public CaveProfileCompiler(StyleCompiler styles, CaveInputs inputs) {
this.styles = Objects.requireNonNull(styles);
this.inputs = Objects.requireNonNull(inputs);
this.blockY = inputs.blockY();
}
public Field compile(CaveSource source, double gain) {
if (!(gain > 0.0) || Double.isInfinite(gain)) {
throw new IllegalArgumentException("Cave field gain must be finite and positive, got " + gain);
}
IrisCaveProfile profile = source.profile();
IrisRange range = profile.getVerticalRange();
int floor = floor(inputs, source);
int ceiling = Math.min(source.maxY(), Math.min(inputs.maxY(), inputs.minY() + (int) Math.ceil(range.getMax())));
if (ceiling < floor) {
return new Field.Const(SOLID);
}
double normalization = normalization(profile) / gain;
List<Field> terms = densityTerms(source, normalization, floor, ceiling);
edgeFade(profile, floor, ceiling, gain).ifPresent(terms::add);
terms.add(surface(source, closure(profile, normalization), gain));
return bounded(sum(terms), floor, ceiling);
}
Optional<CaveInterior> interior(CaveSource source) {
IrisCaveProfile profile = source.profile();
int floor = floor(inputs, source);
int ceiling = Math.min(source.maxY(), Math.min(inputs.maxY(), inputs.minY() + (int) Math.ceil(profile.getVerticalRange().getMax())));
if (ceiling < floor) {
return Optional.empty();
}
List<Field> terms = densityTerms(source, normalization(profile), floor, ceiling);
terms.add(negativeThreshold(profile, 1.0));
return Optional.of(new CaveInterior(sum(terms), floor, ceiling));
}
static int floor(CaveInputs inputs, CaveSource source) {
return Math.max(source.minY(), inputs.minY() + Math.max(0, (int) Math.floor(source.profile().getVerticalRange().getMin())));
}
static boolean cellular(IrisGeneratorStyle style) {
if (style.getExpression() != null || style.getImageMap() != null) {
return false;
}
if (style.getCellularFrequency() > 0.0 || CELLULAR_STYLES.contains(style.getStyle())) {
return true;
}
return style.getFracture() != null && cellular(style.getFracture());
}
private List<Field> densityTerms(CaveSource source, double normalization, int floor, int ceiling) {
IrisCaveProfile profile = source.profile();
List<Field> terms = new ArrayList<>();
addTerm(terms, source, new Term(profile.getBaseDensityStyle(), BASE_SALT, profile.getBaseWeight(), 0.0, false), normalization);
addTerm(terms, source, new Term(profile.getDetailDensityStyle(), DETAIL_SALT, profile.getDetailWeight(), 0.0, false), normalization);
List<IrisCaveFieldModule> modules = profile.getModules();
for (int index = 0; index < modules.size(); index++) {
IrisCaveFieldModule module = modules.get(index);
IrisRange range = module.getVerticalRange();
int low = inputs.minY() + (int) Math.floor(range.getMin());
int high = inputs.minY() + (int) Math.ceil(range.getMax());
if (module.getWeight() == 0.0 || high < floor || low > ceiling) {
continue;
}
Field term = term(source, new Term(module.getStyle(), MODULE_SALT + index * MODULE_SALT_STEP, module.getWeight(), module.getThreshold(), module.isInvert()), normalization);
terms.add(low <= floor && high >= ceiling ? term : new Field.Gate(window(low, high), term));
}
return terms;
}
private void addTerm(List<Field> terms, CaveSource source, Term term, double normalization) {
if (term.weight() != 0.0) {
terms.add(term(source, term, normalization));
}
}
private Field term(CaveSource source, Term term, double normalization) {
double sign = term.invert() ? -1.0 : 1.0;
double scale = sign * term.weight() / normalization;
Field unit = volume(source, term.style(), term.salt(), Math.abs(term.weight()) < LOW_WEIGHT);
return affine(unit, 2.0 * scale, -scale * (1.0 + term.threshold()));
}
private Field volume(CaveSource source, IrisGeneratorStyle style, long salt, boolean lowWeight) {
boolean cellularStyle = cellular(style);
if (cellularStyle && lowWeight) {
return VolumeLift.lift(styles.compile(substitute(style), salt, inputs.noises(), inputs.capabilities()));
}
Field compiled = styles.compile(style, salt, inputs.noises(), inputs.capabilities());
if (compiled.axes().contains(Axis.Y)) {
return compiled;
}
if (!cellularStyle) {
return VolumeLift.lift(compiled);
}
inputs.diagnostics().add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.NOISE_STYLE, source.resource(),
"Cellular cave style " + style.getStyle() + " exports as smooth noise"));
return VolumeLift.lift(styles.compile(substitute(style), salt, inputs.noises(), inputs.capabilities()));
}
private Field planar(IrisGeneratorStyle style, long salt) {
Field compiled = styles.compile(style, salt, inputs.noises(), inputs.capabilities());
return compiled.axes().contains(Axis.Y) ? new Field.Slice(compiled, Axis.Y, 0) : compiled;
}
private Field surface(CaveSource source, double closure, double gain) {
IrisCaveProfile profile = source.profile();
Field negativeThreshold = negativeThreshold(profile, gain);
Field depthBelowClearance = new Field.Binary(Field.BinaryOp.SUB,
new Field.Binary(Field.BinaryOp.ADD, inputs.surface(), new Field.Const(-Math.max(0, profile.getSurfaceClearance()))),
blockY);
Field sealed = new Field.Curve(depthBelowClearance, List.of(
new Field.Knot(-1.0, new Field.Const(SEALED_MARGIN * gain - closure), 0.0),
new Field.Knot(0.0, new Field.Const(-closure), 0.0),
new Field.Knot(CEILING_FADE_DEPTH, negativeThreshold, 0.0)));
if (!profile.isAllowSurfaceBreak()) {
return sealed;
}
Field breaking = new Field.Binary(Field.BinaryOp.ADD, breakSteps(profile, closure, gain), negativeThreshold);
Field breakNoise = planar(profile.getSurfaceBreakStyle(), SURFACE_BREAK_SALT);
Field cutoff = new Field.Const((profile.getSurfaceBreakNoiseThreshold() + 1.0) / 2.0);
return new Field.Binary(Field.BinaryOp.ADD,
new Field.Gate(new Field.Binary(Field.BinaryOp.SUB, cutoff, breakNoise), sealed),
new Field.Gate(new Field.Binary(Field.BinaryOp.SUB, breakNoise, cutoff), breaking));
}
private Field breakSteps(IrisCaveProfile profile, double closure, double gain) {
int depth = Math.max(0, profile.getSurfaceBreakDepth());
double boost = Math.max(0.0, profile.getSurfaceBreakThresholdBoost()) * gain;
Field belowSurface = new Field.Binary(Field.BinaryOp.SUB, inputs.surface(), blockY);
List<Field.Knot> knots = new ArrayList<>();
knots.add(new Field.Knot(-1.0, new Field.Const((thresholdCeiling(profile) + SEALED_MARGIN) * gain - closure + boost), 0.0));
knots.add(new Field.Knot(0.0, new Field.Const(-boost), 0.0));
if (boost > 0.0) {
if (depth > 0) {
knots.add(new Field.Knot(depth, new Field.Const(-boost), 0.0));
}
knots.add(new Field.Knot(depth + 1.0, new Field.Const(0.0), 0.0));
}
return new Field.Curve(belowSurface, knots);
}
private Field negativeThreshold(IrisCaveProfile profile, double gain) {
IrisStyledRange range = profile.getDensityThreshold();
double bias = profile.getThresholdBias();
if (range.getMin() == range.getMax()) {
return new Field.Const(gain * (bias - range.getMin()));
}
if (range.getStyle().isFlat()) {
return new Field.Const(gain * (bias - (range.getMin() + 0.5 * (range.getMax() - range.getMin()))));
}
return affine(planar(range.getStyle(), THRESHOLD_SALT), gain * (range.getMin() - range.getMax()), gain * (bias - range.getMin()));
}
private Optional<Field> edgeFade(IrisCaveProfile profile, int floor, int ceiling, double gain) {
int fade = Math.max(0, profile.getVerticalEdgeFade());
double strength = Math.max(0.0, profile.getVerticalEdgeFadeStrength()) * gain;
if (fade <= 0 || strength <= 0.0 || ceiling <= floor) {
return Optional.empty();
}
List<Field.Knot> knots = new ArrayList<>();
knots.add(new Field.Knot(floor, new Field.Const(strength), 0.0));
if (floor + fade <= ceiling - fade) {
knots.add(new Field.Knot(floor + fade, new Field.Const(0.0), 0.0));
if (ceiling - fade > floor + fade) {
knots.add(new Field.Knot(ceiling - fade, new Field.Const(0.0), 0.0));
}
} else {
double middle = floor + (ceiling - floor) / 2.0;
double progress = Math.min(middle - floor, ceiling - middle) / fade;
knots.add(new Field.Knot(middle, new Field.Const((1.0 - smoothstep(progress)) * strength), 0.0));
}
knots.add(new Field.Knot(ceiling, new Field.Const(strength), 0.0));
return Optional.of(new Field.Curve(blockY, knots));
}
private Field bounded(Field core, int floor, int ceiling) {
if (floor <= inputs.minY() && ceiling >= inputs.maxY()) {
return core;
}
Field shifted = new Field.Binary(Field.BinaryOp.ADD, core, new Field.Const(-SOLID));
return new Field.Binary(Field.BinaryOp.ADD, new Field.Gate(window(floor, ceiling), shifted), new Field.Const(SOLID));
}
private Field window(int low, int high) {
return new Field.RangeIf(blockY, low, high + 1.0, new Field.Const(1.0), new Field.Const(0.0));
}
private static Field affine(Field input, double scale, double offset) {
if (input instanceof Field.Const constant) {
return new Field.Const(scale * constant.value() + offset);
}
if (scale == 0.0) {
return new Field.Const(offset);
}
return new Field.Curve(input, List.of(
new Field.Knot(0.0, new Field.Const(offset), scale),
new Field.Knot(1.0, new Field.Const(scale + offset), scale)));
}
private static Field sum(List<Field> terms) {
Field total = terms.getFirst();
for (int index = 1; index < terms.size(); index++) {
total = new Field.Binary(Field.BinaryOp.ADD, total, terms.get(index));
}
return total;
}
private static double normalization(IrisCaveProfile profile) {
double weight = Math.abs(profile.getBaseWeight()) + Math.abs(profile.getDetailWeight());
for (IrisCaveFieldModule module : profile.getModules()) {
weight += Math.abs(module.getWeight());
}
return weight <= 0.0 ? 1.0 : weight;
}
private static double closure(IrisCaveProfile profile, double normalization) {
double minimum = -Math.abs(profile.getBaseWeight()) - Math.abs(profile.getDetailWeight());
for (IrisCaveFieldModule module : profile.getModules()) {
double threshold = module.getThreshold();
double low = module.isInvert() ? threshold - 1.0 : -1.0 - threshold;
double high = module.isInvert() ? threshold + 1.0 : 1.0 - threshold;
minimum += Math.min(low * module.getWeight(), high * module.getWeight());
}
return minimum / normalization - CLOSURE_EPSILON;
}
private static double thresholdCeiling(IrisCaveProfile profile) {
IrisStyledRange range = profile.getDensityThreshold();
return Math.max(range.getMin(), range.getMax()) - profile.getThresholdBias();
}
private static double smoothstep(double progress) {
double clamped = Math.max(0.0, Math.min(1.0, progress));
return clamped * clamped * (3.0 - 2.0 * clamped);
}
private static IrisGeneratorStyle substitute(IrisGeneratorStyle style) {
return new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(style.getZoom());
}
private static Set<NoiseStyle> cellularStyles() {
Set<NoiseStyle> cellular = EnumSet.noneOf(NoiseStyle.class);
for (NoiseStyle style : NoiseStyle.values()) {
String name = style.name();
if (name.contains("CELL") || name.contains("VASCULAR") || name.contains("GLOB") || name.contains("HEX")) {
cellular.add(style);
}
}
return cellular;
}
private record Term(IrisGeneratorStyle style, long salt, double weight, double threshold, boolean invert) {
}
}
@@ -0,0 +1,185 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.compile.biome.BiomeCodes;
import art.arcane.iris.pack.datapack.export.ir.ClimateLayout;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.value.IrisRange;
import art.arcane.volmlib.util.mantle.flag.ReservedFlag;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
public record CaveSelection(Field index, List<CaveSource> profiles, boolean uncovered, List<CaveSource> bands) {
private static final int UNCOVERED = -1;
private static final Field NO_INDEX = new Field.Const(0.0);
private static final Comparator<ClimateLayout.ClimateEntry> CODE_ORDER = Comparator
.comparingDouble(ClimateLayout.ClimateEntry::min)
.thenComparingDouble(ClimateLayout.ClimateEntry::max)
.thenComparing(ClimateLayout.ClimateEntry::biomeId);
public CaveSelection {
Objects.requireNonNull(index);
profiles = List.copyOf(profiles);
bands = List.copyOf(bands);
}
public static CaveSelection resolve(CaveInputs inputs, IrisDimension dimension, IrisData data, BiomeCodes codes) {
if (!dimension.isCarvingEnabled() || dimension.getDisabledComponents().contains(ReservedFlag.CARVED)) {
return new CaveSelection(NO_INDEX, List.of(), false, List.of());
}
Map<IrisCaveProfile, Integer> caseByProfile = new LinkedHashMap<>();
List<CaveSource> sources = new ArrayList<>();
IrisCaveProfile dimensionProfile = dimension.getCaveProfile();
int fallback = enabled(dimensionProfile)
? caseOf(source(inputs, inputs.resource(), dimensionProfile), caseByProfile, sources)
: UNCOVERED;
List<Double> thresholds = new ArrayList<>();
List<Integer> leaves = new ArrayList<>();
leaves.add(fallback);
List<ClimateLayout.ClimateEntry> entries = caveEntries(codes, regionCaveBiomes(dimension, data));
for (int position = 0; position < entries.size(); position++) {
ClimateLayout.ClimateEntry entry = entries.get(position);
Optional<CaveSource> source = entrySource(inputs, dimension, data, codes.loadKeyByBiomeId().get(entry.biomeId()));
int selected = source.isPresent() ? caseOf(source.get(), caseByProfile, sources) : fallback;
append(thresholds, leaves, entry.min(), selected);
double nextMin = position + 1 < entries.size() ? entries.get(position + 1).min() : Double.POSITIVE_INFINITY;
if (entry.max() < nextMin) {
append(thresholds, leaves, entry.max(), fallback);
}
}
boolean uncovered = leaves.contains(UNCOVERED);
int uncoveredCase = sources.size();
List<Field> constants = new ArrayList<>(leaves.size());
for (int leaf : leaves) {
constants.add(new Field.Const(leaf == UNCOVERED ? uncoveredCase : leaf));
}
Field index = thresholds.isEmpty() ? constants.getFirst() : new Field.Partition(codes.caveCode(), thresholds, constants);
return new CaveSelection(index, sources, uncovered, bands(inputs, dimension, data));
}
public boolean isEmpty() {
return profiles.isEmpty() && bands.isEmpty();
}
public List<CaveSource> sources() {
List<CaveSource> all = new ArrayList<>(profiles.size() + bands.size());
all.addAll(profiles);
all.addAll(bands);
return all;
}
public Field select(Function<CaveSource, Field> compiler, Field uncoveredCase) {
List<Field> cases = new ArrayList<>(profiles.size() + 1);
for (CaveSource source : profiles) {
cases.add(compiler.apply(source));
}
if (uncovered || cases.isEmpty()) {
cases.add(uncoveredCase);
}
return cases.size() == 1 ? cases.getFirst() : new Field.Mux(index, cases);
}
private static void append(List<Double> thresholds, List<Integer> leaves, double start, int selected) {
if (leaves.getLast() == selected) {
return;
}
thresholds.add(start);
leaves.add(selected);
}
private static List<ClimateLayout.ClimateEntry> caveEntries(BiomeCodes codes, Set<String> caveBiomes) {
List<ClimateLayout.ClimateEntry> entries = new ArrayList<>();
for (ClimateLayout.ClimateEntry entry : codes.layout().entries()) {
if (entry.axis() == ClimateLayout.ClimateAxis.DEPTH && caveBiomes.contains(codes.loadKeyByBiomeId().get(entry.biomeId()))) {
entries.add(entry);
}
}
entries.sort(CODE_ORDER);
return entries;
}
private static Set<String> regionCaveBiomes(IrisDimension dimension, IrisData data) {
Set<String> caveBiomes = new HashSet<>();
for (String regionKey : dimension.getRegions()) {
IrisRegion region = regionKey == null ? null : data.getRegionLoader().load(regionKey, false);
if (region != null && !region.isCompatExcluded()) {
caveBiomes.addAll(region.getCaveBiomes());
}
}
return caveBiomes;
}
private static Optional<CaveSource> entrySource(CaveInputs inputs, IrisDimension dimension, IrisData data, String loadKey) {
IrisBiome biome = loadKey == null ? null : data.getBiomeLoader().load(loadKey, false);
if (biome == null || biome.isCompatExcluded()) {
return Optional.empty();
}
if (enabled(biome.getCaveProfile())) {
return Optional.of(source(inputs, "biomes/" + biome.getLoadKey(), biome.getCaveProfile()));
}
for (String regionKey : dimension.getRegions()) {
IrisRegion region = regionKey == null ? null : data.getRegionLoader().load(regionKey, false);
if (region == null || region.isCompatExcluded() || !region.getCaveBiomes().contains(loadKey) || !enabled(region.getCaveProfile())) {
continue;
}
return Optional.of(source(inputs, "regions/" + region.getLoadKey(), region.getCaveProfile()));
}
return Optional.empty();
}
private static List<CaveSource> bands(CaveInputs inputs, IrisDimension dimension, IrisData data) {
List<CaveSource> bands = new ArrayList<>();
List<IrisDimensionCarvingEntry> entries = dimension.getCarving();
if (entries == null) {
return bands;
}
for (IrisDimensionCarvingEntry entry : entries) {
if (entry == null || !entry.isEnabled()) {
continue;
}
IrisBiome biome = entry.getRealBiome(data);
if (biome == null || !enabled(biome.getCaveProfile())) {
continue;
}
IrisRange range = entry.getWorldYRange();
int low = range == null ? inputs.minY() : Math.max(inputs.minY(), (int) Math.ceil(range.getMin()));
int high = range == null ? inputs.maxY() : Math.min(inputs.maxY(), (int) Math.floor(range.getMax()));
if (high >= low) {
bands.add(new CaveSource("biomes/" + biome.getLoadKey(), biome.getCaveProfile(), low, high));
}
}
return bands;
}
private static int caseOf(CaveSource source, Map<IrisCaveProfile, Integer> caseByProfile, List<CaveSource> sources) {
Integer existing = caseByProfile.get(source.profile());
if (existing != null) {
return existing;
}
caseByProfile.put(source.profile(), sources.size());
sources.add(source);
return sources.size() - 1;
}
private static CaveSource source(CaveInputs inputs, String resource, IrisCaveProfile profile) {
return new CaveSource(resource, profile, inputs.minY(), inputs.maxY());
}
private static boolean enabled(IrisCaveProfile profile) {
return profile != null && profile.isEnabled();
}
}
@@ -0,0 +1,15 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.generation.cave.IrisCaveProfile;
import java.util.Objects;
public record CaveSource(String resource, IrisCaveProfile profile, int minY, int maxY) {
public CaveSource {
Objects.requireNonNull(resource);
Objects.requireNonNull(profile);
if (maxY < minY) {
throw new IllegalArgumentException("Cave source '" + resource + "' needs maxY at or above minY, got " + minY + ".." + maxY);
}
}
}
@@ -0,0 +1,61 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import art.arcane.iris.pack.datapack.export.ir.Field;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public final class CaveStage implements CompileStage {
private static final String CARVERS = "carvers";
@Override
public String name() {
return "caves";
}
@Override
public void apply(PackCompileContext context) {
CaveInputs inputs = CaveInputs.of(context);
CaveSelection selection = CaveSelection.resolve(inputs, context.dimension(), context.data(), context.biomeCodes());
CaveFieldCompiler compiler = new CaveFieldCompiler(context.styles(), inputs);
Optional<Field> caves = compiler.compile(selection);
if (caves.isPresent()) {
Field.Shared field = new Field.Shared(DeepCaveCompiler.FIELD, caves.get());
Optional<DeepCaveCompiler.DeepCaves> deep = new DeepCaveCompiler(inputs).compile(field, selection);
context.setCaveField(field, CaveFieldCompiler.WALL_BAND);
context.setCaves(deep.map(DeepCaveCompiler.DeepCaves::router).orElse(field));
deep.ifPresent(found -> context.setDeepCaves(found.opening()));
}
context.setAquifer(new AquiferCompiler(inputs).compile(selection));
List<BiomeDef> biomes = context.biomes();
if (biomes.stream().anyMatch(CaveStage::carves)) {
context.setBiomes(withoutCarvers(biomes));
}
}
private static List<BiomeDef> withoutCarvers(List<BiomeDef> biomes) {
List<BiomeDef> cleaned = new ArrayList<>(biomes.size());
for (BiomeDef biome : biomes) {
if (!carves(biome)) {
cleaned.add(biome);
continue;
}
JsonObject json = biome.json().deepCopy();
json.add(CARVERS, new JsonArray());
cleaned.add(new BiomeDef(biome.id(), json));
}
return cleaned;
}
private static boolean carves(BiomeDef biome) {
JsonElement carvers = biome.json().get(CARVERS);
return carvers != null && !(carvers.isJsonArray() && carvers.getAsJsonArray().isEmpty());
}
}
@@ -0,0 +1,78 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.export.ir.DimensionDef;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import art.arcane.iris.pack.datapack.export.ir.Field;
import art.arcane.iris.pack.datapack.export.lower.FieldDomains;
import java.util.Objects;
import java.util.Optional;
public final class DeepCaveCompiler {
static final int LAVA_LINE = -54;
static final String FIELD = "cave/field";
static final String OPENING = "cave/deep_opening";
private static final double OPEN_MARGIN = Math.nextUp(Float.MIN_VALUE);
private static final Field OPEN = new Field.Const(1.0);
private static final Field INSIDE = new Field.Const(0.0);
private static final Field CLOSED = new Field.Const(CaveProfileCompiler.SOLID);
private static final Field UNMASKED = new Field.Const(-FieldDomains.CONSTANT_LIMIT);
private final CaveInputs inputs;
private final Field blockY;
public DeepCaveCompiler(CaveInputs inputs) {
this.inputs = Objects.requireNonNull(inputs);
this.blockY = inputs.blockY();
}
public Optional<DeepCaves> compile(Field.Shared field, CaveSelection selection) {
Optional<Zone> found = zone(selection);
if (found.isEmpty()) {
return Optional.empty();
}
Zone zone = found.get();
inputs.diagnostics().add(new ExportDiagnostic(ExportDiagnostic.Severity.WARNING, ExportLimit.DEEP_CAVE_LAYERS, inputs.resource(),
"Caves between Y " + zone.low() + " and Y " + zone.high() + " open in the material pass, so they get wall palettes but no floor or ceiling layers"));
Field opened = new Field.Binary(Field.BinaryOp.MAX, field, inside(zone, INSIDE, CLOSED));
Field.Shared opening = new Field.Shared(OPENING,
new Field.Gate(new Field.Binary(Field.BinaryOp.SUB, new Field.Const(OPEN_MARGIN), opened), OPEN));
Field mask = new Field.Binary(Field.BinaryOp.ADD, opening, inside(zone, INSIDE, UNMASKED));
return Optional.of(new DeepCaves(new Field.Binary(Field.BinaryOp.MAX, field, mask), opening));
}
private Optional<Zone> zone(CaveSelection selection) {
int high = Math.min(line() - 1, inputs.maxY());
int low = inputs.minY();
int deepest = Integer.MAX_VALUE;
for (CaveSource source : selection.sources()) {
deepest = Math.min(deepest, CaveProfileCompiler.floor(inputs, source));
if (source.profile().isAllowLava()) {
low = Math.max(low, inputs.lavaY() + 1);
}
}
if (high < low || high < deepest) {
return Optional.empty();
}
return Optional.of(new Zone(low, high));
}
private int line() {
return Math.min(LAVA_LINE, DimensionDef.seaLevel(inputs.fluidHeight()));
}
private Field inside(Zone zone, Field inRange, Field outOfRange) {
return new Field.RangeIf(blockY, zone.low(), zone.high() + 1.0, inRange, outOfRange);
}
public record DeepCaves(Field router, Field.Shared opening) {
public DeepCaves {
Objects.requireNonNull(router);
Objects.requireNonNull(opening);
}
}
private record Zone(int low, int high) {
}
}
@@ -0,0 +1,67 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.export.ir.Field;
import java.util.ArrayList;
import java.util.List;
final class VolumeLift {
private static final String SHARED_SUFFIX = "/volume";
private VolumeLift() {
}
static Field lift(Field field) {
return switch (field) {
case Field.Const constant -> constant;
case Field.Coord coord -> coord;
case Field.Ref ref -> ref;
case Field.TopSurface topSurface -> topSurface;
case Field.Slice slice -> slice;
case Field.Noise noise -> noise(noise);
case Field.Binary binary -> new Field.Binary(binary.op(), lift(binary.left()), lift(binary.right()));
case Field.Unary unary -> new Field.Unary(unary.op(), lift(unary.input()));
case Field.Clamp clamp -> new Field.Clamp(lift(clamp.input()), clamp.min(), clamp.max());
case Field.Lerp lerp -> new Field.Lerp(lift(lerp.alpha()), lift(lerp.first()), lift(lerp.second()));
case Field.Round round -> new Field.Round(round.mode(), lift(round.input()), lift(round.multiple()));
case Field.Curve curve -> curve(curve);
case Field.Partition partition -> new Field.Partition(lift(partition.input()), partition.thresholds(), partition.leaves());
case Field.Mux mux -> new Field.Mux(lift(mux.index()), liftAll(mux.cases()));
case Field.Gate gate -> new Field.Gate(lift(gate.condition()), lift(gate.expr()));
case Field.RangeIf rangeIf -> new Field.RangeIf(lift(rangeIf.input()), rangeIf.min(), rangeIf.max(), lift(rangeIf.inRange()), lift(rangeIf.outOfRange()));
case Field.Grid grid -> new Field.Grid(lift(grid.expr()), grid.cellXZ(), grid.cellY());
case Field.Shared shared -> shared(shared);
};
}
private static Field noise(Field.Noise noise) {
double yScale = noise.yScale() == 0.0 ? noise.xzScale() : noise.yScale();
return new Field.Noise(noise.noiseId(), noise.xzScale(), yScale, liftShift(noise.shiftX()), liftShift(noise.shiftY()), liftShift(noise.shiftZ()));
}
private static Field liftShift(Field shift) {
return shift == null ? null : lift(shift);
}
private static Field.Curve curve(Field.Curve curve) {
List<Field.Knot> knots = new ArrayList<>(curve.knots().size());
for (Field.Knot knot : curve.knots()) {
Field value = knot.value() instanceof Field.Curve nested ? curve(nested) : knot.value();
knots.add(new Field.Knot(knot.location(), value, knot.derivative()));
}
return new Field.Curve(lift(curve.input()), knots);
}
private static List<Field> liftAll(List<Field> fields) {
List<Field> lifted = new ArrayList<>(fields.size());
for (Field field : fields) {
lifted.add(lift(field));
}
return lifted;
}
private static Field shared(Field.Shared shared) {
Field body = lift(shared.expr());
return body.equals(shared.expr()) ? shared : new Field.Shared(shared.name() + SHARED_SUFFIX, body);
}
}
@@ -0,0 +1,114 @@
package art.arcane.iris.pack.datapack.export.compile.cave;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.ir.FieldEvaluator;
import art.arcane.iris.pack.datapack.export.ir.NoiseDef;
import java.util.Arrays;
import java.util.Map;
import java.util.SplittableRandom;
final class WallShellCalibrator {
private static final long SEED = 0x5EED_3A11L;
private static final int PATCHES = 256;
private static final int PATCH_CELLS = 3;
private static final int SPREAD_CELLS = 1024;
private final Map<String, NoiseDef> noises;
private final DataVersion target;
private final int cellXZ;
private final int cellY;
private double[] solid = new double[4096];
private int solidCount;
private long walls;
private WallShellCalibrator(Map<String, NoiseDef> noises, DataVersion target, int cellXZ, int cellY) {
this.noises = noises;
this.target = target;
this.cellXZ = cellXZ;
this.cellY = cellY;
}
static double band(CaveInterior interior, Map<String, NoiseDef> noises, DataVersion target) {
WallShellCalibrator calibrator = new WallShellCalibrator(noises, target, CaveFieldCompiler.CELL_XZ, CaveFieldCompiler.CELL_Y);
SplittableRandom random = new SplittableRandom(SEED);
for (int patch = 0; patch < PATCHES; patch++) {
calibrator.sample(interior, random);
}
return calibrator.band();
}
private void sample(CaveInterior interior, SplittableRandom random) {
int x0 = cellXZ * (random.nextInt(2 * SPREAD_CELLS) - SPREAD_CELLS);
int z0 = cellXZ * (random.nextInt(2 * SPREAD_CELLS) - SPREAD_CELLS);
int lowCell = Math.floorDiv(interior.minY(), cellY);
int highCell = Math.max(lowCell, Math.floorDiv(interior.maxY(), cellY) - PATCH_CELLS);
int y0 = cellY * (lowCell + random.nextInt(highCell - lowCell + 1));
int corners = PATCH_CELLS + 1;
double[][][] lattice = new double[corners][corners][corners];
for (int i = 0; i < corners; i++) {
for (int j = 0; j < corners; j++) {
for (int k = 0; k < corners; k++) {
lattice[i][j][k] = FieldEvaluator.sample(interior.field(), noises, SEED, target, x0 + i * cellXZ, y0 + j * cellY, z0 + k * cellXZ);
}
}
}
int width = PATCH_CELLS * cellXZ;
int height = PATCH_CELLS * cellY;
double[][][] voxels = new double[width][height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < width; z++) {
voxels[x][y][z] = interpolate(lattice, x, y, z);
}
}
}
for (int x = 1; x < width - 1; x++) {
for (int y = 0; y < height; y++) {
for (int z = 1; z < width - 1; z++) {
double value = voxels[x][y][z];
if (value < 0.0) {
continue;
}
add(value);
if (voxels[x - 1][y][z] < 0.0 || voxels[x + 1][y][z] < 0.0 || voxels[x][y][z - 1] < 0.0 || voxels[x][y][z + 1] < 0.0) {
walls++;
}
}
}
}
}
private double interpolate(double[][][] lattice, int x, int y, int z) {
int i = x / cellXZ;
int j = y / cellY;
int k = z / cellXZ;
double fx = (x - i * cellXZ) / (double) cellXZ;
double fy = (y - j * cellY) / (double) cellY;
double fz = (z - k * cellXZ) / (double) cellXZ;
double bottom = lerp(fz, lerp(fx, lattice[i][j][k], lattice[i + 1][j][k]), lerp(fx, lattice[i][j][k + 1], lattice[i + 1][j][k + 1]));
double top = lerp(fz, lerp(fx, lattice[i][j + 1][k], lattice[i + 1][j + 1][k]), lerp(fx, lattice[i][j + 1][k + 1], lattice[i + 1][j + 1][k + 1]));
return lerp(fy, bottom, top);
}
private void add(double value) {
if (solidCount == solid.length) {
solid = Arrays.copyOf(solid, solid.length * 2);
}
solid[solidCount++] = value;
}
private double band() {
if (walls == 0L) {
return 0.0;
}
double[] sorted = Arrays.copyOf(solid, solidCount);
Arrays.sort(sorted);
int rank = (int) Math.min(solidCount - 1L, walls);
return sorted[rank];
}
private static double lerp(double delta, double start, double end) {
return start + delta * (end - start);
}
}
@@ -0,0 +1,69 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.ir.BiomeDef;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public final class BiomeFeatureLists {
private static final GenerationStep[] STEPS = GenerationStep.values();
private final Map<GenerationStep, Set<String>> order = new EnumMap<>(GenerationStep.class);
private final Map<String, Map<GenerationStep, Set<String>>> members = new HashMap<>();
public void add(String biomeId, GenerationStep step, String placedFeatureId) {
VanillaResourceIdentifier.requireIdentifier(biomeId, "feature list biome id");
Objects.requireNonNull(step);
VanillaResourceIdentifier.requireIdentifier(placedFeatureId, "placed feature id");
order.computeIfAbsent(step, ignored -> new LinkedHashSet<>()).add(placedFeatureId);
members.computeIfAbsent(biomeId, ignored -> new EnumMap<>(GenerationStep.class))
.computeIfAbsent(step, ignored -> new HashSet<>())
.add(placedFeatureId);
}
public List<BiomeDef> apply(List<BiomeDef> biomes, String namespace) {
VanillaResourceIdentifier.requireNamespace(namespace, "feature list namespace");
Set<String> defined = new HashSet<>(biomes.size());
List<BiomeDef> result = new ArrayList<>(biomes.size());
for (BiomeDef biome : biomes) {
String id = namespace + ":" + biome.id();
defined.add(id);
JsonObject json = biome.json().deepCopy();
json.add("features", features(members.getOrDefault(id, Map.of())));
result.add(new BiomeDef(biome.id(), json));
}
for (String biomeId : members.keySet()) {
if (!defined.contains(biomeId)) {
throw new IllegalArgumentException("Feature lists reference undefined biome '" + biomeId + "'");
}
}
return result;
}
private JsonArray features(Map<GenerationStep, Set<String>> biomeSteps) {
JsonArray steps = new JsonArray(STEPS.length);
for (GenerationStep step : STEPS) {
JsonArray features = new JsonArray();
Set<String> biomeFeatures = biomeSteps.get(step);
if (biomeFeatures != null) {
for (String feature : order.get(step)) {
if (biomeFeatures.contains(feature)) {
features.add(feature);
}
}
}
steps.add(features);
}
return steps;
}
}
@@ -0,0 +1,26 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.pack.datapack.export.compile.BlockStateResolver;
import art.arcane.iris.pack.datapack.export.compile.CompileStage;
import art.arcane.iris.pack.datapack.export.compile.ExportedBiomes;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.WorldgenSyntax;
import art.arcane.iris.pack.datapack.export.compile.surface.RepaintFeatureCompiler;
public final class DecorationStage implements CompileStage {
@Override
public String name() {
return "decoration";
}
@Override
public void apply(PackCompileContext context) {
ExportedBiomes biomes = ExportedBiomes.load(context);
BlockStateResolver blocks = BlockStateResolver.forContext(context);
FeatureCatalog catalog = new FeatureCatalog(context.namespace(), WorldgenSyntax.forTarget(context.capabilities().target()));
new RepaintFeatureCompiler(context, biomes, blocks, catalog).compile();
new DecoratorCompiler(context, biomes, blocks, catalog).compile();
new DepositCompiler(context, biomes, blocks, catalog).compile();
context.jsonResources().addAll(catalog.resources());
}
}
@@ -0,0 +1,498 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.NoiseStyle;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.compile.BlockStateResolver;
import art.arcane.iris.pack.datapack.export.compile.ExportedBiomes;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.WeightedState;
import art.arcane.iris.pack.datapack.export.compile.WorldgenSyntax;
import art.arcane.iris.pack.datapack.export.compile.surface.RepaintFeatureCompiler;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public final class DecoratorCompiler {
private static final int COLUMNS = 256;
private static final double CAVE_AIR_SHARE = 0.08;
private static final int CAVE_SCAN_STEPS = 12;
private static final int MAX_ATTEMPTS = 256;
private static final int MAX_PATTERN_STATES = 64;
private static final VanillaBlockState AIR_STATE = new VanillaBlockState("minecraft:air", Map.of());
private static final Set<String> AIR = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
private static final Set<String> AQUATIC = Set.of("minecraft:seagrass", "minecraft:tall_seagrass", "minecraft:kelp",
"minecraft:kelp_plant", "minecraft:sea_pickle");
private static final String STYLE_MESSAGE = "Decorators gated by a noise style keep the style's coverage, with its pattern fitted to Minecraft noise";
private static final String STYLE_STACK_MESSAGE = "Stacked, forced, underwater, and ceiling decorators gated by a noise style keep the style's coverage without its pattern";
private static final String VARIANCE_MESSAGE = "Decorator palettes varied by a noise style pick their blocks at random";
private static final String STACK_MESSAGE = "Decorator stacks scaled to cave height use their fixed stack range";
private static final String CAVE_MESSAGE = "Cave ceiling decorators place at an estimated density because features cannot enumerate every cave ceiling";
private final PackCompileContext context;
private final ExportedBiomes biomes;
private final BlockStateResolver blocks;
private final FeatureCatalog catalog;
private final WorldgenSyntax syntax;
private final Map<CoverageKey, DecoratorCoverage.Coverage> coverages = new HashMap<>();
private final Map<DecoratorCoverage.Coverage, DecoratorCoverage.Pattern> patterns = new HashMap<>();
public DecoratorCompiler(PackCompileContext context, ExportedBiomes biomes, BlockStateResolver blocks, FeatureCatalog catalog) {
this.context = context;
this.biomes = biomes;
this.blocks = blocks;
this.catalog = catalog;
this.syntax = catalog.syntax();
}
public void compile() {
for (Map.Entry<String, IrisBiome> entry : biomes.byId().entrySet()) {
compileBiome(entry.getKey(), entry.getValue());
}
}
static double[] columnShares(double[] chances) {
double[] shares = new double[chances.length];
for (int index = 0; index < chances.length; index++) {
double[] others = new double[chances.length];
others[0] = 1.0;
int size = 1;
for (int other = 0; other < chances.length; other++) {
if (other == index) {
continue;
}
double chance = chances[other];
for (int count = size; count >= 0; count--) {
double stays = others[count] * (1.0 - chance);
double grows = count > 0 ? others[count - 1] * chance : 0.0;
others[count] = stays + grows;
}
size++;
}
double expectation = 0.0;
for (int count = 0; count < size; count++) {
expectation += others[count] / (count + 1);
}
shares[index] = chances[index] * expectation;
}
return shares;
}
static double[] sequentialChances(double[] shares) {
double[] chances = new double[shares.length];
double claimed = 0.0;
for (int index = 0; index < shares.length; index++) {
double free = 1.0 - claimed;
chances[index] = free <= 0.0 ? 0.0 : Math.min(1.0, shares[index] / free);
claimed += shares[index];
}
return chances;
}
private void compileBiome(String biomeId, IrisBiome biome) {
if (biome.getDecorators() == null || biome.getDecorators().isEmpty()) {
return;
}
String resource = biomes.resource(biomeId);
Map<IrisDecorationPart, List<Candidate>> buckets = new EnumMap<>(IrisDecorationPart.class);
for (IrisDecorator decorator : biome.getDecorators()) {
if (decorator == null) {
continue;
}
Optional<Candidate> candidate = candidate(decorator, resource);
IrisDecorationPart part = decorator.getPartOf() == null ? IrisDecorationPart.NONE : decorator.getPartOf();
candidate.ifPresent(value -> buckets.computeIfAbsent(part, ignored -> new ArrayList<>()).add(value));
}
for (Map.Entry<IrisDecorationPart, List<Candidate>> bucket : buckets.entrySet()) {
List<Candidate> candidates = bucket.getValue();
double[] chances = new double[candidates.size()];
for (int index = 0; index < chances.length; index++) {
chances[index] = candidates.get(index).coverage().share();
}
double[] shares = columnShares(chances);
for (int index = 0; index < shares.length; index++) {
shares[index] *= 1.0 - candidates.get(index).airShare();
}
double[] sequential = sequentialChances(shares);
for (int index = 0; index < candidates.size(); index++) {
Candidate candidate = candidates.get(index);
if (candidate.entries().isEmpty() || shares[index] <= 0.0) {
continue;
}
if (bucket.getKey() == IrisDecorationPart.CEILING) {
report(resource, ExportLimit.CAVE_DECORATOR, CAVE_MESSAGE);
if (candidate.coverage().patterned()) {
report(resource, ExportLimit.DECORATOR_STYLE, STYLE_STACK_MESSAGE);
}
context.features().add(biomeId, GenerationStep.UNDERGROUND_DECORATION, ceiling(candidate, shares[index]));
} else {
context.features().add(biomeId, GenerationStep.VEGETAL_DECORATION, column(bucket.getKey(), candidate, sequential[index], resource));
}
}
}
}
private Optional<Candidate> candidate(IrisDecorator decorator, String resource) {
List<WeightedState> entries = new ArrayList<>();
int airWeight = 0;
int total = 0;
for (WeightedState entry : weighted(decorator.getPalette(), decorator.getVariance(), resource)) {
total += entry.weight();
if (AIR.contains(entry.state().name())) {
airWeight += entry.weight();
} else {
entries.add(entry);
}
}
if (total == 0) {
return Optional.empty();
}
if (entries.size() > 1 && !isStatic(decorator.getVariance())) {
report(resource, ExportLimit.DECORATOR_STYLE, VARIANCE_MESSAGE);
}
if (decorator.isScaleStack()) {
report(resource, ExportLimit.SCALE_STACK, STACK_MESSAGE);
}
if (decorator.getSlopeCondition() != null && !decorator.getSlopeCondition().isDefault()) {
report(resource, ExportLimit.SLOPE, RepaintFeatureCompiler.SLOPE_MESSAGE);
}
List<WeightedState> top = new ArrayList<>();
for (WeightedState entry : weighted(decorator.getTopPalette(), decorator.getVariance(), resource)) {
if (!AIR.contains(entry.state().name())) {
top.add(entry);
}
}
VanillaBlockState force = decorator.getForceBlock() == null ? null : blocks.resolve(decorator.getForceBlock(), resource).orElse(null);
return Optional.of(new Candidate(decorator, entries, top, (double) airWeight / total, force, aquatic(entries, top),
names(decorator.getWhitelist(), resource), names(decorator.getBlacklist(), resource), coverage(decorator)));
}
private List<WeightedState> weighted(List<IrisBlockData> palette, IrisGeneratorStyle variance, String resource) {
List<WeightedState> resolved = new ArrayList<>(palette.size());
int count = 0;
for (IrisBlockData block : palette) {
Optional<VanillaBlockState> state = blocks.resolve(block, resource);
if (state.isPresent()) {
int weight = Math.max(1, block.getWeight());
resolved.add(new WeightedState(state.get(), weight));
count += weight;
}
}
if (count <= 1 || !isStatic(variance)) {
return resolved;
}
List<WeightedState> rounded = new ArrayList<>(resolved.size());
int start = 0;
for (WeightedState entry : resolved) {
int end = start + entry.weight();
rounded.add(new WeightedState(entry.state(), 2 * entry.weight() - (start == 0 ? 1 : 0) - (end == count ? 1 : 0)));
start = end;
}
return rounded;
}
private String column(IrisDecorationPart part, Candidate candidate, double sequential, String resource) {
IrisDecorationPart target = candidate.aquatic() && part == IrisDecorationPart.NONE ? IrisDecorationPart.SEA_FLOOR : part;
boolean underwater = target == IrisDecorationPart.SEA_FLOOR;
boolean patterned = candidate.coverage().patterned() && !underwater && single(candidate);
if (candidate.coverage().patterned()) {
report(resource, ExportLimit.DECORATOR_STYLE, patterned ? STYLE_MESSAGE : STYLE_STACK_MESSAGE);
}
String featureId = patterned ? patterned(candidate) : feature(candidate, false, underwater);
double chance = patterned ? Math.min(1.0, sequential / candidate.coverage().share()) : sequential;
JsonArray placement = new JsonArray();
for (JsonObject modifier : Placements.everyColumn()) {
placement.add(modifier);
}
placement.add(Placements.heightmap(underwater ? Placements.OCEAN_FLOOR : Placements.WORLD_SURFACE));
if (chance < 1.0) {
placement.add(Placements.randomChance(chance));
}
placement.add(Placements.biome());
placement.add(Placements.filter(Placements.allOf(predicates(target, candidate))));
return catalog.placed(name(candidate), featureId, placement);
}
private String ceiling(Candidate candidate, double share) {
String featureId = feature(candidate, true, false);
JsonArray placement = new JsonArray();
placement.add(Placements.count(Placements.meanCount(Math.min(MAX_ATTEMPTS, COLUMNS * share / CAVE_AIR_SHARE))));
placement.add(Placements.inSquare());
placement.add(Placements.heightRange(Placements.fullHeight()));
placement.add(Placements.environmentScanUp(CAVE_SCAN_STEPS));
placement.add(Placements.verticalOffset(-1));
placement.add(Placements.biome());
placement.add(Placements.filter(Placements.air(0, 0, 0)));
return catalog.placed(name(candidate) + "_ceiling", featureId, placement);
}
private List<JsonObject> predicates(IrisDecorationPart part, Candidate candidate) {
List<JsonObject> predicates = new ArrayList<>();
switch (part) {
case SEA_FLOOR -> {
predicates.add(Placements.water(0, 0, 0));
if (tall(candidate)) {
predicates.add(Placements.water(0, 1, 0));
}
}
case SEA_SURFACE -> {
predicates.add(Placements.air(0, 0, 0));
predicates.add(Placements.water(0, -1, 0));
}
case SHORE_LINE -> {
predicates.add(Placements.air(0, 0, 0));
predicates.add(Placements.solid(0, -1, 0));
predicates.add(Placements.anyOf(List.of(Placements.water(1, -1, 0), Placements.water(-1, -1, 0), Placements.water(0, -1, 1),
Placements.water(0, -1, -1))));
}
default -> {
predicates.add(Placements.air(0, 0, 0));
predicates.add(Placements.solid(0, -1, 0));
}
}
if (!candidate.whitelist().isEmpty()) {
predicates.add(Placements.matchingBlocks(candidate.whitelist(), 0, -1, 0));
}
if (!candidate.blacklist().isEmpty()) {
predicates.add(Placements.not(Placements.matchingBlocks(candidate.blacklist(), 0, -1, 0)));
}
predicates.addAll(Placements.slopeLimits(candidate.decorator().getSlopeCondition()));
return predicates;
}
private String feature(Candidate candidate, boolean hanging, boolean underwater) {
IrisDecorator decorator = candidate.decorator();
int stackMax = stackMax(decorator);
int stackMin = Math.max(1, Math.min(decorator.getStackMin(), stackMax));
String name = name(candidate);
List<WeightedState> entries = waterlogged(candidate.entries(), underwater);
List<WeightedState> top = waterlogged(candidate.top(), underwater);
String main;
boolean tall = !hanging && tall(candidate);
if (tall || !hanging && stackMax == 1 && top.isEmpty()) {
JsonObject config = new JsonObject();
config.add("to_place", syntax.provider(tall ? lowerHalves(entries) : entries));
main = catalog.feature(name, "minecraft:simple_block", config);
} else {
JsonArray layers = new JsonArray(2);
if (top.isEmpty()) {
layers.add(layer(Placements.intRange(stackMin, stackMax), entries));
} else {
layers.add(layer(Placements.intRange(stackMin - 1, stackMax - 1), entries));
layers.add(layer(Placements.intRange(1, 1), top));
}
JsonObject config = new JsonObject();
config.add("layers", layers);
config.addProperty("direction", hanging ? "down" : "up");
config.add("allowed_placement", underwater ? Placements.water(0, 0, 0) : Placements.air(0, 0, 0));
config.addProperty("prioritize_tip", true);
main = catalog.feature(name, "minecraft:block_column", config);
}
if (candidate.force() == null) {
return main;
}
JsonObject forceConfig = new JsonObject();
forceConfig.add("to_place", syntax.provider(List.of(new WeightedState(candidate.force(), 1))));
String force = catalog.feature("decorator/ground_" + path(candidate.force()), "minecraft:simple_block", forceConfig);
JsonArray groundPlacement = new JsonArray(1);
groundPlacement.add(Placements.verticalOffset(-1));
JsonArray features = new JsonArray(2);
features.add(catalog.inlinePlaced(force, groundPlacement));
features.add(catalog.inlinePlaced(main, new JsonArray()));
JsonObject sequence = new JsonObject();
sequence.add("features", features);
return catalog.feature(name + "_forced", "minecraft:sequence", sequence);
}
private String patterned(Candidate candidate) {
IrisDecorator decorator = candidate.decorator();
DecoratorCoverage.Pattern pattern = patterns.computeIfAbsent(candidate.coverage(), coverage -> DecoratorCoverage.pattern(coverage, syntax.target()));
String salt = name(candidate) + "|" + decorator.getStyle().getStyle() + "|" + decorator.getStyle().getZoom() + "|" + decorator.getChance();
JsonObject provider = new JsonObject();
provider.addProperty("type", "minecraft:noise_threshold");
provider.addProperty("seed", (long) salt.hashCode());
provider.add("noise", patternNoise());
provider.addProperty("scale", (float) pattern.scale());
provider.addProperty("threshold", (float) pattern.threshold());
provider.addProperty("high_chance", 0.0f);
provider.add("default_state", syntax.blockState(AIR_STATE));
provider.add("low_states", expanded(waterlogged(candidate.entries(), false)));
JsonArray high = new JsonArray(1);
high.add(syntax.blockState(AIR_STATE));
provider.add("high_states", high);
JsonObject config = new JsonObject();
config.add("to_place", provider);
return catalog.feature(name(candidate), "minecraft:simple_block", config);
}
private JsonArray expanded(List<WeightedState> entries) {
int divisor = 0;
int total = 0;
for (WeightedState entry : entries) {
divisor = gcd(divisor, entry.weight());
total += entry.weight();
}
double shrink = Math.min(1.0, (double) MAX_PATTERN_STATES * divisor / total);
JsonArray states = new JsonArray();
for (WeightedState entry : entries) {
long copies = Math.max(1L, Math.round(entry.weight() / (double) divisor * shrink));
for (long copy = 0; copy < copies; copy++) {
states.add(syntax.blockState(entry.state()));
}
}
return states;
}
private static JsonObject patternNoise() {
JsonArray amplitudes = new JsonArray(DecoratorCoverage.PATTERN_AMPLITUDES.size());
for (double amplitude : DecoratorCoverage.PATTERN_AMPLITUDES) {
amplitudes.add(amplitude);
}
JsonObject noise = new JsonObject();
noise.addProperty("base_octave", DecoratorCoverage.PATTERN_OCTAVE);
noise.addProperty("octave_count", DecoratorCoverage.PATTERN_AMPLITUDES.size());
noise.add("amplitude_modifiers", amplitudes);
noise.addProperty("base_amplitude", 1.0);
noise.addProperty("normalize", false);
return noise;
}
private DecoratorCoverage.Coverage coverage(IrisDecorator decorator) {
double chance = Math.max(0.0, Math.min(1.0, decorator.getChance()));
if (isStatic(decorator.getStyle())) {
return new DecoratorCoverage.Coverage(chance, 0.0);
}
return coverages.computeIfAbsent(new CoverageKey(decorator.getStyle(), chance),
key -> DecoratorCoverage.measure(key.style(), key.chance(), context.data()));
}
private static boolean single(Candidate candidate) {
IrisDecorator decorator = candidate.decorator();
return Math.min(decorator.getStackMax(), decorator.getAbsoluteMaxStack()) <= 1 && candidate.top().isEmpty() && candidate.force() == null;
}
private static int gcd(int first, int second) {
return second == 0 ? first : gcd(second, first % second);
}
private static List<WeightedState> waterlogged(List<WeightedState> entries, boolean underwater) {
List<WeightedState> placed = new ArrayList<>(entries.size());
for (WeightedState entry : entries) {
placed.add(new WeightedState(entry.state().waterlogged(underwater), entry.weight()));
}
return placed;
}
private static int stackMax(IrisDecorator decorator) {
return Math.max(1, Math.min(decorator.getStackMax(), Math.max(1, decorator.getAbsoluteMaxStack())));
}
private static boolean tall(Candidate candidate) {
if (stackMax(candidate.decorator()) != 1) {
return false;
}
for (WeightedState entry : candidate.entries()) {
String half = entry.state().properties().get("half");
if (!"lower".equals(half) && !"upper".equals(half)) {
return false;
}
}
return true;
}
private static List<WeightedState> lowerHalves(List<WeightedState> entries) {
List<WeightedState> lower = new ArrayList<>(entries.size());
for (WeightedState entry : entries) {
Map<String, String> properties = new TreeMap<>(entry.state().properties());
properties.put("half", "lower");
lower.add(new WeightedState(new VanillaBlockState(entry.state().name(), properties), entry.weight()));
}
return lower;
}
private JsonObject layer(JsonElement height, List<WeightedState> entries) {
JsonObject layer = new JsonObject();
layer.add("height", height);
layer.add("provider", syntax.provider(entries));
return layer;
}
private List<String> names(List<IrisBlockData> list, String resource) {
TreeSet<String> names = new TreeSet<>();
if (list == null) {
return List.of();
}
for (IrisBlockData block : list) {
blocks.resolve(block, resource).ifPresent(state -> names.add(state.name()));
}
return List.copyOf(names);
}
private void report(String resource, ExportLimit limit, String message) {
ExportDiagnostic diagnostic = new ExportDiagnostic(ExportDiagnostic.Severity.INFO, limit, resource, message);
if (!context.diagnostics().contains(diagnostic)) {
context.diagnostics().add(diagnostic);
}
}
private static String name(Candidate candidate) {
return "decorator/" + path(candidate.entries().getFirst().state());
}
private static String path(VanillaBlockState state) {
return state.name().substring(state.name().indexOf(':') + 1);
}
private static boolean isStatic(IrisGeneratorStyle style) {
return style == null || style.getStyle() == null || style.getStyle() == NoiseStyle.STATIC;
}
private static boolean aquatic(List<WeightedState> entries, List<WeightedState> top) {
if (entries.isEmpty()) {
return false;
}
for (WeightedState entry : entries) {
if (!aquatic(entry.state())) {
return false;
}
}
for (WeightedState entry : top) {
if (!aquatic(entry.state())) {
return false;
}
}
return true;
}
private static boolean aquatic(VanillaBlockState state) {
String name = state.name();
if ("true".equals(state.properties().get("waterlogged")) || AQUATIC.contains(name)) {
return true;
}
return name.startsWith("minecraft:") && name.contains("_coral") && !name.startsWith("minecraft:dead_");
}
private record Candidate(IrisDecorator decorator, List<WeightedState> entries, List<WeightedState> top, double airShare,
VanillaBlockState force, boolean aquatic, List<String> whitelist, List<String> blacklist,
DecoratorCoverage.Coverage coverage) {
}
private record CoverageKey(IrisGeneratorStyle style, double chance) {
}
}
@@ -0,0 +1,113 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.datapack.DataVersion;
import art.arcane.iris.pack.datapack.export.compile.noise.VanillaNoiseModel;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
import java.util.Arrays;
import java.util.List;
final class DecoratorCoverage {
static final int PATTERN_OCTAVE = 0;
static final List<Double> PATTERN_AMPLITUDES = List.of(1.0);
private static final long STYLE_SEED = 0x0DEC_0A7EL;
private static final String PATTERN_NOISE = "iris_export:decorator_pattern";
private static final int GRID = 128;
private static final double STEP_X = 211.0;
private static final double STEP_Z = 157.0;
private static final int[] LAGS = {1, 2, 4, 8, 16, 32, 64, 128};
private static final double HALF_EXCESS = 0.5;
private static final double MIN_PATCH = 2.0;
private static final int MIN_HITS = 64;
private static final double VANILLA_SCALE = 1.0 / 64.0;
private static final double VANILLA_Y = 64.0;
private static final double MAX_THRESHOLD = 1.0;
private DecoratorCoverage() {
}
static Coverage measure(IrisGeneratorStyle style, double chance, IrisData data) {
CNG generator = style.createNoCache(new RNG(STYLE_SEED), data);
double zoom = style.getZoom();
return measure((x, z) -> generator.fitDouble(0.0, 1.0, x / zoom, z / zoom) <= chance);
}
static Pattern pattern(Coverage coverage, DataVersion target) {
VanillaNoiseModel model = VanillaNoiseModel.create(PATTERN_NOISE, PATTERN_OCTAVE, PATTERN_AMPLITUDES, 0L, target);
double[] sorted = new double[GRID * GRID];
int index = 0;
for (int i = 0; i < GRID; i++) {
for (int j = 0; j < GRID; j++) {
sorted[index++] = model.sample(i * STEP_X * VANILLA_SCALE, VANILLA_Y * VANILLA_SCALE, j * STEP_Z * VANILLA_SCALE);
}
}
Arrays.sort(sorted);
double position = coverage.share() * (sorted.length - 1);
int lower = (int) Math.floor(position);
int upper = Math.min(sorted.length - 1, lower + 1);
double threshold = sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);
double clamped = Math.max(-MAX_THRESHOLD, Math.min(MAX_THRESHOLD, threshold));
Coverage vanilla = measure((x, z) -> model.sample(x * VANILLA_SCALE, VANILLA_Y * VANILLA_SCALE, z * VANILLA_SCALE) < clamped);
return new Pattern(clamped, VANILLA_SCALE * vanilla.patch() / coverage.patch());
}
private static Coverage measure(Gate gate) {
int hits = 0;
int[] both = new int[LAGS.length];
for (int i = 0; i < GRID; i++) {
for (int j = 0; j < GRID; j++) {
double x = i * STEP_X;
double z = j * STEP_Z;
if (!gate.passes(x, z)) {
continue;
}
hits++;
for (int lag = 0; lag < LAGS.length; lag++) {
both[lag] += gate.passes(x + LAGS[lag], z) ? 1 : 0;
both[lag] += gate.passes(x, z + LAGS[lag]) ? 1 : 0;
}
}
}
double share = (double) hits / (GRID * GRID);
if (hits < MIN_HITS || share >= 1.0) {
return new Coverage(share, 0.0);
}
return new Coverage(share, patch(both, hits, share));
}
private static double patch(int[] both, int hits, double share) {
double previousLag = 0.0;
double previousExcess = 1.0;
for (int lag = 0; lag < LAGS.length; lag++) {
double excess = ((double) both[lag] / (2.0 * hits) - share) / (1.0 - share);
if (excess < HALF_EXCESS) {
double fraction = (previousExcess - HALF_EXCESS) / (previousExcess - excess);
if (previousLag == 0.0) {
return LAGS[lag] * fraction;
}
double low = Math.log(previousLag);
return Math.exp(low + (Math.log(LAGS[lag]) - low) * fraction);
}
previousLag = LAGS[lag];
previousExcess = excess;
}
return LAGS[LAGS.length - 1];
}
record Coverage(double share, double patch) {
boolean patterned() {
return share > 0.0 && share < 1.0 && patch >= MIN_PATCH;
}
}
record Pattern(double threshold, double scale) {
}
@FunctionalInterface
private interface Gate {
boolean passes(double x, double z);
}
}
@@ -0,0 +1,292 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.biome.IrisBiomePaletteLayer;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.IrisDepositBiomeScope;
import art.arcane.iris.generation.decoration.IrisDepositGenerator;
import art.arcane.iris.generation.decoration.IrisDepositHeightDistribution;
import art.arcane.iris.generation.decoration.IrisDepositPlacementScope;
import art.arcane.iris.generation.decoration.IrisDepositShape;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.pack.datapack.export.VanillaBlockState;
import art.arcane.iris.pack.datapack.export.compile.BlockStateResolver;
import art.arcane.iris.pack.datapack.export.compile.ExportedBiomes;
import art.arcane.iris.pack.datapack.export.compile.PackCompileContext;
import art.arcane.iris.pack.datapack.export.compile.WorldgenSyntax;
import art.arcane.iris.pack.datapack.export.ir.ExportDiagnostic;
import art.arcane.iris.pack.datapack.export.ir.ExportLimit;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public final class DepositCompiler {
private static final int MAX_ORE_SIZE = 64;
private static final int MAX_COUNT = 256;
private static final int MIN_ANCHOR = -2032;
private static final int MAX_ANCHOR = 2031;
private static final String HOST_TAG = "deposit_host";
private static final List<String> HOST_TAG_BASE = List.of("#minecraft:base_stone_overworld", "#minecraft:dirt", "#minecraft:sand");
private static final String DEEPSLATE = "minecraft:deepslate";
private static final String DEEPSLATE_PREFIX = "minecraft:deepslate_";
private static final Set<String> DEEPSLATE_ORES = Set.of("coal", "emerald", "diamond", "copper", "gold", "iron", "lapis", "redstone");
private static final Set<String> DEEPSLATE_HOSTS = Set.of(DEEPSLATE, "minecraft:deepslate_bricks", "minecraft:deepslate_brick_slab",
"minecraft:deepslate_brick_stairs", "minecraft:deepslate_brick_wall", "minecraft:deepslate_tiles", "minecraft:deepslate_tile_slab",
"minecraft:deepslate_tile_stairs", "minecraft:deepslate_tile_wall", "minecraft:cracked_deepslate_tiles", "minecraft:deepslate_coal_ore",
"minecraft:deepslate_iron_ore", "minecraft:deepslate_copper_ore", "minecraft:deepslate_diamond_ore", "minecraft:deepslate_emerald_ore",
"minecraft:deepslate_gold_ore", "minecraft:deepslate_lapis_ore", "minecraft:deepslate_redstone_ore");
private final PackCompileContext context;
private final ExportedBiomes biomes;
private final BlockStateResolver blocks;
private final FeatureCatalog catalog;
private final WorldgenSyntax syntax;
private String hostTag;
public DepositCompiler(PackCompileContext context, ExportedBiomes biomes, BlockStateResolver blocks, FeatureCatalog catalog) {
this.context = context;
this.biomes = biomes;
this.blocks = blocks;
this.catalog = catalog;
this.syntax = catalog.syntax();
}
public void compile() {
List<String> everyBiome = biomes.inCodeOrder(biomes.byId().keySet());
String dimensionResource = "dimensions/" + context.dimension().getLoadKey();
for (IrisDepositGenerator deposit : list(context.dimension().getDeposits())) {
place(deposit, everyBiome, dimensionResource);
}
TreeMap<String, List<String>> regionBiomes = new TreeMap<>();
TreeMap<String, IrisRegion> regions = new TreeMap<>();
for (String biomeId : everyBiome) {
IrisRegion region = biomes.region(biomeId);
if (region != null) {
regions.put(region.getLoadKey(), region);
regionBiomes.computeIfAbsent(region.getLoadKey(), ignored -> new ArrayList<>()).add(biomeId);
}
}
for (Map.Entry<String, IrisRegion> region : regions.entrySet()) {
for (IrisDepositGenerator deposit : list(region.getValue().getDeposits())) {
place(deposit, regionBiomes.get(region.getKey()), "regions/" + region.getKey());
}
}
for (Map.Entry<String, IrisBiome> biome : biomes.byId().entrySet()) {
for (IrisDepositGenerator deposit : list(biome.getValue().getDeposits())) {
place(deposit, List.of(biome.getKey()), biomes.resource(biome.getKey()));
}
}
}
private void place(IrisDepositGenerator deposit, List<String> candidates, String resource) {
List<String> biomeIds = filtered(deposit, candidates);
if (biomeIds.isEmpty() || deposit.getMaxPerChunk() <= 0 || deposit.getSpawnChance() <= 0 || deposit.getPerClumpSpawnChance() <= 0) {
return;
}
List<VanillaBlockState> states = new ArrayList<>();
for (IrisBlockData block : list(deposit.getPalette())) {
blocks.resolve(block, resource).ifPresent(state -> {
if (!states.contains(state)) {
states.add(state);
}
});
}
if (states.isEmpty()) {
return;
}
String feature = feature(deposit, states, resource);
String placed = catalog.placed("deposit/" + path(states.getFirst()), feature, placement(deposit, biomeIds, resource));
for (String biomeId : biomeIds) {
context.features().add(biomeId, GenerationStep.UNDERGROUND_ORES, placed);
}
}
private String feature(IrisDepositGenerator deposit, List<VanillaBlockState> states, String resource) {
String type = deposit.getShape() == IrisDepositShape.VANILLA_SCATTERED ? "minecraft:scattered_ore" : "minecraft:ore";
int size = (int) Math.round((Math.max(0, deposit.getMinSize()) + Math.max(0, deposit.getMaxSize())) / 2.0);
if (size > MAX_ORE_SIZE) {
report(resource, ExportLimit.DEPOSIT_SIZE, ExportDiagnostic.Severity.WARNING,
"Deposit clumps of " + size + " blocks export as Minecraft ore veins of " + MAX_ORE_SIZE + " blocks");
size = MAX_ORE_SIZE;
}
List<JsonObject> hosts = hosts(deposit, resource);
List<String> ores = new ArrayList<>(states.size());
for (VanillaBlockState state : states) {
JsonArray targets = new JsonArray(hosts.size() + 1);
VanillaBlockState deepslateOre = stoneVariant(state, true);
if (hosts.size() == 1 && "minecraft:tag_match".equals(hosts.getFirst().get("predicate_type").getAsString()) && !deepslateOre.equals(state)) {
JsonObject deepslate = new JsonObject();
deepslate.addProperty("predicate_type", "minecraft:block_match");
deepslate.addProperty("block", DEEPSLATE);
targets.add(target(deepslate, deepslateOre));
}
for (JsonObject host : hosts) {
boolean deepslateHost = host.has("block") && DEEPSLATE_HOSTS.contains(host.get("block").getAsString());
targets.add(target(host, stoneVariant(state, deepslateHost)));
}
JsonObject config = new JsonObject();
config.addProperty("size", Math.max(0, size));
config.addProperty("discard_chance_on_air_exposure", (float) Math.max(0.0, Math.min(1.0, deposit.getDiscardChanceOnAirExposure())));
config.add("targets", targets);
ores.add(catalog.feature("deposit/" + path(state), type, config));
}
if (ores.size() == 1) {
return ores.getFirst();
}
JsonArray features = new JsonArray(ores.size());
for (String ore : ores) {
features.add(catalog.inlinePlaced(ore, new JsonArray()));
}
JsonObject selector = new JsonObject();
selector.add("features", features);
return catalog.feature("deposit/" + path(states.getFirst()) + "_mix", "minecraft:simple_random_selector", selector);
}
private JsonObject target(JsonObject host, VanillaBlockState state) {
JsonObject target = new JsonObject();
target.add("target", host.deepCopy());
target.add("state", syntax.blockState(state));
return target;
}
private static VanillaBlockState stoneVariant(VanillaBlockState ore, boolean deepslate) {
String name = ore.name();
boolean deep = name.startsWith(DEEPSLATE_PREFIX);
String base = deep ? name.substring(DEEPSLATE_PREFIX.length()) : name.substring(name.indexOf(':') + 1);
if (deep == deepslate || !base.endsWith("_ore") || !DEEPSLATE_ORES.contains(base.substring(0, base.length() - "_ore".length()))) {
return ore;
}
return new VanillaBlockState(deepslate ? DEEPSLATE_PREFIX + base : "minecraft:" + base, ore.properties());
}
private JsonArray placement(IrisDepositGenerator deposit, List<String> biomeIds, String resource) {
int minCount = Math.max(0, Math.min(deposit.getMinPerChunk(), deposit.getMaxPerChunk()));
int maxCount = Math.max(minCount, deposit.getMaxPerChunk());
if (maxCount > MAX_COUNT) {
report(resource, ExportLimit.DEPOSIT_SIZE, ExportDiagnostic.Severity.WARNING,
"Deposits place at most " + MAX_COUNT + " clumps per chunk");
maxCount = MAX_COUNT;
minCount = Math.min(minCount, maxCount);
}
double spawnChance = Math.min(1.0, deposit.getSpawnChance());
double clumpChance = Math.min(1.0, deposit.getPerClumpSpawnChance());
JsonArray placement = new JsonArray();
if (spawnChance < 1.0) {
placement.add(Placements.randomChance(spawnChance));
}
placement.add(Placements.count(Placements.intRange(minCount, maxCount)));
placement.add(Placements.inSquare());
boolean surfaceScope = deposit.getBiomeScope() == IrisDepositBiomeScope.SURFACE;
if (surfaceScope) {
placement.add(Placements.heightmap(Placements.OCEAN_FLOOR));
placement.add(Placements.filter(Placements.matchingBiomes(biomeIds)));
}
placement.add(Placements.heightRange(height(deposit)));
IrisDepositPlacementScope scope = deposit.getPlacementScope() == null ? IrisDepositPlacementScope.TERRAIN : deposit.getPlacementScope();
if (scope == IrisDepositPlacementScope.TERRAIN) {
placement.add(Placements.surfaceRelative(Placements.OCEAN_FLOOR, -(Math.max(0, deposit.getSurfaceClearance()) + 1)));
} else if (scope == IrisDepositPlacementScope.ABOVE_TERRAIN) {
report(resource, ExportLimit.DEPOSIT_SCOPE, ExportDiagnostic.Severity.INFO,
"Deposits limited to above-terrain placement also generate inside overhangs and floating terrain within their height band");
}
if (clumpChance < 1.0) {
placement.add(Placements.randomChance(clumpChance));
}
if (!surfaceScope) {
placement.add(Placements.biome());
}
return placement;
}
private JsonObject height(IrisDepositGenerator deposit) {
int min = clampAnchor(Math.min(deposit.getMinHeight(), deposit.getMaxHeight()));
int max = clampAnchor(Math.max(deposit.getMinHeight(), deposit.getMaxHeight()));
return deposit.getHeightDistribution() == IrisDepositHeightDistribution.TRIANGLE
? Placements.trapezoidHeight(min, max)
: Placements.uniformHeight(min, max);
}
private List<JsonObject> hosts(IrisDepositGenerator deposit, String resource) {
List<JsonObject> hosts = new ArrayList<>();
TreeSet<String> names = new TreeSet<>();
for (String raw : list(deposit.getReplaceableBlocks())) {
blocks.resolve(raw, resource).ifPresent(state -> names.add(state.name()));
}
for (String name : names) {
JsonObject host = new JsonObject();
host.addProperty("predicate_type", "minecraft:block_match");
host.addProperty("block", name);
hosts.add(host);
}
if (!hosts.isEmpty()) {
return hosts;
}
JsonObject host = new JsonObject();
host.addProperty("predicate_type", "minecraft:tag_match");
host.addProperty("tag", hostTag());
return List.of(host);
}
private String hostTag() {
if (hostTag != null) {
return hostTag;
}
TreeSet<String> layerBlocks = new TreeSet<>();
for (Map.Entry<String, IrisBiome> biome : biomes.byId().entrySet()) {
for (IrisBiomePaletteLayer layer : list(biome.getValue().getLayers())) {
for (IrisBlockData block : list(layer.getPalette())) {
Optional<VanillaBlockState> state = blocks.resolve(block, biomes.resource(biome.getKey()));
state.ifPresent(value -> layerBlocks.add(value.name()));
}
}
}
List<String> values = new ArrayList<>(HOST_TAG_BASE);
values.add(context.dimensionDef().defaultBlock());
for (String block : layerBlocks) {
if (!values.contains(block) && !block.equals("minecraft:bedrock")) {
values.add(block);
}
}
hostTag = catalog.blockTag(HOST_TAG, values);
return hostTag;
}
private List<String> filtered(IrisDepositGenerator deposit, List<String> candidates) {
List<String> included = list(deposit.getIncludedBiomes());
List<String> excluded = list(deposit.getExcludedBiomes());
List<String> biomeIds = new ArrayList<>(candidates.size());
for (String biomeId : candidates) {
String loadKey = biomes.loadKey(biomeId);
if ((included.isEmpty() || included.contains(loadKey)) && !excluded.contains(loadKey)) {
biomeIds.add(biomeId);
}
}
return biomeIds;
}
private void report(String resource, ExportLimit limit, ExportDiagnostic.Severity severity, String message) {
ExportDiagnostic diagnostic = new ExportDiagnostic(severity, limit, resource, message);
if (!context.diagnostics().contains(diagnostic)) {
context.diagnostics().add(diagnostic);
}
}
private static <T> List<T> list(List<T> values) {
return values == null ? List.of() : values;
}
private static int clampAnchor(int value) {
return Math.max(MIN_ANCHOR, Math.min(MAX_ANCHOR, value));
}
private static String path(VanillaBlockState state) {
return state.name().substring(state.name().indexOf(':') + 1);
}
}
@@ -0,0 +1,114 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
import art.arcane.iris.pack.datapack.export.VanillaResourceIdentifier;
import art.arcane.iris.pack.datapack.export.compile.WorldgenSyntax;
import art.arcane.iris.pack.datapack.export.ir.JsonResource;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public final class FeatureCatalog {
private static final String PLACED_FOLDER = "worldgen/placed_feature";
private static final String BLOCK_TAG_FOLDER = "tags/block";
private final String namespace;
private final WorldgenSyntax syntax;
private final Map<String, String> idsByBody = new HashMap<>();
private final SortedMap<String, JsonElement> files = new TreeMap<>();
public FeatureCatalog(String namespace, WorldgenSyntax syntax) {
this.namespace = VanillaResourceIdentifier.requireNamespace(namespace, "feature namespace");
this.syntax = syntax;
}
public WorldgenSyntax syntax() {
return syntax;
}
public String namespace() {
return namespace;
}
public String feature(String name, String type, JsonObject config) {
return register(syntax.featureFolder(), name, syntax.feature(type, config));
}
public String placed(String name, String featureId, JsonArray placement) {
JsonObject placed = new JsonObject();
placed.addProperty("feature", featureId);
placed.add("placement", placement);
return register(PLACED_FOLDER, name, placed);
}
public JsonObject inlinePlaced(String featureId, JsonArray placement) {
JsonObject placed = new JsonObject();
placed.addProperty("feature", featureId);
placed.add("placement", placement);
return placed;
}
public String blockTag(String name, List<String> values) {
JsonArray entries = new JsonArray(values.size());
for (String value : values) {
entries.add(value);
}
JsonObject tag = new JsonObject();
tag.add("values", entries);
return register(BLOCK_TAG_FOLDER, name, tag);
}
public List<JsonResource> resources() {
List<JsonResource> resources = new ArrayList<>(files.size());
for (Map.Entry<String, JsonElement> file : files.entrySet()) {
resources.add(new JsonResource(file.getKey(), file.getValue()));
}
return resources;
}
private String register(String folder, String name, JsonElement body) {
String key = folder + "|" + canonical(body);
String existing = idsByBody.get(key);
if (existing != null) {
return existing;
}
String base = VanillaResourceIdentifier.sanitizePath(name);
String path = base;
int suffix = 2;
while (files.containsKey(file(folder, path))) {
path = base + "_" + suffix++;
}
files.put(file(folder, path), body.deepCopy());
String id = namespace + ":" + path;
idsByBody.put(key, id);
return id;
}
private String file(String folder, String path) {
return "data/" + namespace + "/" + folder + "/" + path + ".json";
}
private static String canonical(JsonElement element) {
if (element.isJsonObject()) {
StringBuilder builder = new StringBuilder("{");
for (Map.Entry<String, JsonElement> member : new TreeMap<>(element.getAsJsonObject().asMap()).entrySet()) {
builder.append('"').append(member.getKey()).append("\":").append(canonical(member.getValue())).append(',');
}
return builder.append('}').toString();
}
if (element.isJsonArray()) {
StringBuilder builder = new StringBuilder("[");
for (JsonElement item : element.getAsJsonArray()) {
builder.append(canonical(item)).append(',');
}
return builder.append(']').toString();
}
return element.toString();
}
}
@@ -0,0 +1,15 @@
package art.arcane.iris.pack.datapack.export.compile.decoration;
public enum GenerationStep {
RAW_GENERATION,
LAKES,
LOCAL_MODIFICATIONS,
UNDERGROUND_STRUCTURES,
SURFACE_STRUCTURES,
STRONGHOLDS,
UNDERGROUND_ORES,
UNDERGROUND_DECORATION,
FLUID_SPRINGS,
VEGETAL_DECORATION,
TOP_LAYER_MODIFICATION
}
Loaded 100 of 498 files, more files were not shown because too many files have changed in this diff. Show more