Merge lane B

- Land force place, unknown hydrology key warnings and the river fluid warning
- Rename dryDrawdown, minHeadKeep and waterfallMinDrop across new code
- Drop minCliffHeight with the old sea inlet passages
- Keep per-placement failure containment on forced and replaced pieces
- Repin the schema digest
This commit is contained in:
Brian Fopiano committed 2026-11-04 10:50:16 -05:00
commit 335b02f276
67 files changed
+2088 -340

No files matched your search

@@ -28,7 +28,7 @@ public class IrisHydrologyDrainage {
@MinNumber(0)
@MaxNumber(1)
@Description("Smallest share of stream heads kept in the driest areas when wetness thinning is on.")
private double minimumHeadKeep = 0.25D;
private double minHeadKeep = 0.25D;
@MinNumber(0)
@MaxNumber(64)
@@ -9,7 +9,7 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Large lakes that fill the biggest hollows in the terrain. Each lake has one water level across its whole surface. A hollow becomes a lake only when it is at least ponds.natural.minDepth deep and no more than 2048 blocks across. Lakes take their freeboard, climateDrawdown, shore roundness, materials, decorators and fluid from ponds.")
@Description("Large lakes that fill the biggest hollows in the terrain. Each lake has one water level across its whole surface. A hollow becomes a lake only when it is at least ponds.natural.minDepth deep and no more than 2048 blocks across. Lakes take their freeboard, dryDrawdown, shore roundness, materials, decorators and fluid from ponds.")
@Data
public class IrisHydrologyLakes {
@Description("Turns large hollows into lakes.")
@@ -13,7 +13,7 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Standing water above sea level. Ponds fill natural hollows, seeded cups and optional dams, each with its own level, so ponds sit at many heights and streams link them into chains. Lakes take their freeboard, climateDrawdown, shore roundness, materials, decorators and fluid from here as well.")
@Description("Standing water above sea level. Ponds fill natural hollows, seeded cups and optional dams, each with its own level, so ponds sit at many heights and streams link them into chains. Lakes take their freeboard, dryDrawdown, shore roundness, materials, decorators and fluid from here as well.")
@Data
public class IrisHydrologyPonds {
@Description("Ponds that fill hollows already present in the terrain.")
@@ -32,7 +32,7 @@ public class IrisHydrologyPonds {
@MinNumber(0)
@MaxNumber(32)
@Description("Most extra blocks a pond or lake surface drops below its freeboard, in the driest areas. The drop is this value times the dryness at the floor, rounded: one minus the zone wetness, after the area's wetness bounds, where the dimension's wet and dry zones apply, and one minus the area's rainfall elsewhere, so water at a wetness or rainfall of 1 or more stays full.")
private int climateDrawdown = 6;
private int dryDrawdown = 6;
@Description("Shape of pond shores and floors. Lakes take only its roundness.")
private IrisPondShore shore = new IrisPondShore();
@@ -44,13 +44,13 @@ public class IrisHydrologyTier {
@Description("Blocks the water surface sits below the ground it flows through.")
private int inset = 1;
@Description("Groups the drops of a run into step-pools: the drops within 2.5 to 5 channel widths, from 6 to 32 blocks, join into one step. A step that starts with a cascade is at most waterfallMinimumDrop plus 2 blocks, and that limit ends the group early on steep ground. A step that starts with a waterfall is that waterfall plus the small drops it gathers below it. When false, drops are spread into a gentler slope where the terrain allows, including the step where a channel joins lower water; drops that cannot be spread, such as a junction right below a pond outlet, stay as small cascades below the waterfall minimum.")
@Description("Groups the drops of a run into step-pools: the drops within 2.5 to 5 channel widths, from 6 to 32 blocks, join into one step. A step that starts with a cascade is at most waterfallMinDrop plus 2 blocks, and that limit ends the group early on steep ground. A step that starts with a waterfall is that waterfall plus the small drops it gathers below it. When false, drops are spread into a gentler slope where the terrain allows, including the step where a channel joins lower water; drops that cannot be spread, such as a junction right below a pond outlet, stay as small cascades below the waterfall minimum.")
private boolean cascades = true;
@MinNumber(2)
@MaxNumber(64)
@Description("Smallest drop in blocks that becomes a waterfall.")
private int waterfallMinimumDrop = 6;
private int waterfallMinDrop = 6;
@MinNumber(1)
@MaxNumber(2)
@@ -9,16 +9,16 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Bounds on how wet the dimension's wet and dry zones make this area. The zone wetness runs from the climate's dryRainfall in dry zones to 1 in wet zones and is held between min and max here. The bounded wetness scales rainfall and pond density, and a pond or lake whose floor lies here drops ponds.climateDrawdown times one minus it, rounded, below its freeboard.")
@Description("Bounds on how wet the dimension's wet and dry zones make this area. The zone wetness runs from the climate's dryRainfall in dry zones to 1 in wet zones and is held between min and max here. The bounded wetness scales rainfall and pond density, and a pond or lake whose floor lies here drops ponds.dryDrawdown times one minus it, rounded, below its freeboard.")
@Data
public class IrisHydrologyWetness {
@MinNumber(0)
@MaxNumber(1)
@Description("Lowest wetness this area falls to, even inside a dry zone. 0.7 keeps 70% of the rainfall and pond density in dry zones and lowers ponds and lakes by at most 30% of ponds.climateDrawdown. Left out, it is 0.")
@Description("Lowest wetness this area falls to, even inside a dry zone. 0.7 keeps 70% of the rainfall and pond density in dry zones and lowers ponds and lakes by at most 30% of ponds.dryDrawdown. Left out, it is 0.")
private double min = 0D;
@MinNumber(0)
@MaxNumber(1)
@Description("Highest wetness this area reaches, even inside a wet zone. 0.35 keeps at most 35% of the rainfall and pond density and lowers ponds and lakes by at least 65% of ponds.climateDrawdown. Must not be below min. Left out, it is 1.")
@Description("Highest wetness this area reaches, even inside a wet zone. 0.35 keeps at most 35% of the rainfall and pond density and lowers ponds and lakes by at least 65% of ponds.dryDrawdown. Must not be below min. Left out, it is 1.")
private double max = 1D;
}
@@ -235,7 +235,7 @@ public final class HydrologySettings {
private static HydrologyTier tidalTier(HydrologyTier base, SeaInlets inlets) {
return new HydrologyTier(TIDAL_TIER_NAME, base.minCatchment(), inlets.meanderWidth(), inlets.meanderWidth(), 0f, base.depthRatio(), 0, false,
base.waterfallMinimumDrop(), base.stepHeight(), inlets.bankBand(), inlets.bankStyle(), new HydrologyTier.Estuary(0, 1f),
base.waterfallMinDrop(), base.stepHeight(), inlets.bankBand(), inlets.bankStyle(), new HydrologyTier.Estuary(0, 1f),
new HydrologyTier.Delta(0, 0f, 0), base.materials(), base.fluid(), base.decorators());
}
@@ -257,7 +257,7 @@ public final class HydrologySettings {
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());
(float) config.getMinHeadKeep(), (float) config.getHeadRelief(), (float) config.getSaturationCatchment());
}
private static List<HydrologyTier> tiers(List<IrisHydrologyTier> configs) {
@@ -308,7 +308,7 @@ public final class HydrologySettings {
}
return new HydrologyTier(config.getName(), (float) config.getMinCatchment(), halfWidth.min(), halfWidth.max(),
(float) config.getWidthFactor(), (float) config.getDepthRatio(), config.getInset(), config.isCascades(),
config.getWaterfallMinimumDrop(), config.getStepHeight(), config.getBankBand(), config.getBankStyle(),
config.getWaterfallMinDrop(), config.getStepHeight(), config.getBankBand(), config.getBankStyle(),
estuary(config.getEstuary(), field + ".estuary"), delta(config, halfWidth.max(), field + ".delta"),
materials(config.getMaterials(), field + ".materials"), config.getFluid(), decorators(config.getDecorators(), field + ".decorators"));
}
@@ -360,7 +360,7 @@ public final class HydrologySettings {
return new Ponds(naturalPonds(config.getNatural()), seededPonds(config.getSeeded()),
new PondDams(dams.isEnabled(), dams.getMaxRaise()),
intRange(config.getFreeboard(), "ponds.freeboard", RangeFloor.NON_NEGATIVE),
config.getClimateDrawdown(), pondShore(config.getShore()), materials(config.getMaterials(), "ponds.materials"), config.getFluid(),
config.getDryDrawdown(), pondShore(config.getShore()), materials(config.getMaterials(), "ponds.materials"), config.getFluid(),
decorators(config.getDecorators(), "ponds.decorators"));
}
@@ -675,7 +675,7 @@ public final class HydrologySettings {
private static void requireTierBounds(IrisHydrologyTier config, String field) {
requireNonNegative(config.getWidthFactor(), field + ".widthFactor");
requireNonNegative(config.getDepthRatio(), field + ".depthRatio");
requireAtLeast(config.getWaterfallMinimumDrop(), MIN_WATERFALL_DROP, field + ".waterfallMinimumDrop");
requireAtLeast(config.getWaterfallMinDrop(), MIN_WATERFALL_DROP, field + ".waterfallMinDrop");
requireWithin(config.getStepHeight(), 1, WaterHeads.STANDING_STEP, field + ".stepHeight");
requireShoreDepth(config.getMaterials(), field + ".materials");
}
@@ -782,7 +782,7 @@ public final class HydrologySettings {
private void addDrainage(Fingerprint hash) {
hash.add(drainage.fillEpsilon()).add(drainage.breachDepth()).add(drainage.wetnessThinning())
.add(drainage.minimumHeadKeep()).add(drainage.headRelief()).add(drainage.saturationCatchment());
.add(drainage.minHeadKeep()).add(drainage.headRelief()).add(drainage.saturationCatchment());
}
private void addTiers(Fingerprint hash) {
@@ -790,7 +790,7 @@ public final class HydrologySettings {
for (HydrologyTier tier : tiers) {
hash.add(tier.name()).add(tier.minCatchment()).add(tier.minHalfWidth()).add(tier.maxHalfWidth())
.add(tier.widthFactor()).add(tier.depthRatio()).add(tier.inset()).add(tier.cascades())
.add(tier.waterfallMinimumDrop()).add(tier.stepHeight()).add(tier.bankBand()).add(tier.bankStyle())
.add(tier.waterfallMinDrop()).add(tier.stepHeight()).add(tier.bankBand()).add(tier.bankStyle())
.add(tier.estuary().length()).add(tier.estuary().flare())
.add(tier.delta().channels()).add(tier.delta().spreadDegrees()).add(tier.delta().length())
.add(tier.materials()).add(tier.fluid());
@@ -806,7 +806,7 @@ public final class HydrologySettings {
.add(seeded.enabled()).add(seeded.density()).add(seeded.radius()).add(seeded.depth())
.add(seeded.maxSlope()).add(seeded.alongChannels()).add(seeded.channelSpacing())
.add(ponds.dams().enabled()).add(ponds.dams().maxRaise())
.add(ponds.freeboard()).add(ponds.climateDrawdown())
.add(ponds.freeboard()).add(ponds.dryDrawdown())
.add(shore.roundness()).add(shore.shelf()).add(shore.taper()).add(shore.maxDepth())
.add(ponds.materials()).add(ponds.fluid());
}
@@ -863,7 +863,7 @@ public final class HydrologySettings {
}
}
public record Drainage(float fillEpsilon, int breachDepth, boolean wetnessThinning, float minimumHeadKeep, float headRelief,
public record Drainage(float fillEpsilon, int breachDepth, boolean wetnessThinning, float minHeadKeep, float headRelief,
float saturationCatchment) {
}
@@ -881,7 +881,7 @@ public final class HydrologySettings {
}
public record Ponds(NaturalPonds natural, SeededPonds seeded, PondDams dams, IntRange freeboard,
int climateDrawdown, PondShore shore, IrisHydrologyMaterials materials, String fluid,
int dryDrawdown, PondShore shore, IrisHydrologyMaterials materials, String fluid,
List<IrisDecorator> decorators) {
}
@@ -294,7 +294,7 @@ public final class WindowPlanner {
private boolean keepHead(DemGrid surface, int cell, float rainfall) {
HydrologySettings.Drainage drainage = settings.drainage();
float keep = drainage.wetnessThinning() ? Math.clamp(Math.max(drainage.minimumHeadKeep(), rainfall), 0f, 1f) : 1f;
float keep = drainage.wetnessThinning() ? Math.clamp(Math.max(drainage.minHeadKeep(), rainfall), 0f, 1f) : 1f;
keep *= settings.density();
return CellHash.unit(CellHash.mix(settings.seed(), SALT_HEAD, surface.blockX(cell), surface.blockZ(cell))) < keep;
}
@@ -60,13 +60,13 @@ public final class LinkBlend {
int[] grade = feeder.grade();
int level = junction.level();
boolean[] fixed = fixed(feeder, lips, junction.fed() && grade[0] - level > ConfluenceGrader.MAX_START_LOWERING);
int waterfallMinimumDrop = feeder.tier().waterfallMinimumDrop();
int[] settled = ConfluenceGrader.settle(footprint(feeder), grade, fixed, receiving, level, waterfallMinimumDrop);
int waterfallMinDrop = feeder.tier().waterfallMinDrop();
int[] settled = ConfluenceGrader.settle(footprint(feeder), grade, fixed, receiving, level, waterfallMinDrop);
if (settled == grade) {
return feeder;
}
if (!feeder.tier().cascades()) {
ConfluenceGrader.spreadJunction(settled, grade, fixed, waterfallMinimumDrop, Integer.MIN_VALUE);
ConfluenceGrader.spreadJunction(settled, grade, fixed, waterfallMinDrop, Integer.MIN_VALUE);
}
return regraded(feeder, settled, feeder.halfWidth(), feeder.depth(), seaLevel);
}
@@ -101,19 +101,19 @@ public final class LinkBlend {
}
private static Reach regraded(Reach reach, int[] grade, float[] halfWidth, float[] depth, int seaLevel) {
ReachStyle[] style = grade == reach.grade() ? reach.style() : restyled(reach.style(), grade, reach.tier().waterfallMinimumDrop(), seaLevel, reach.tier().stepHeight());
ReachStyle[] style = grade == reach.grade() ? reach.style() : restyled(reach.style(), grade, reach.tier().waterfallMinDrop(), seaLevel, reach.tier().stepHeight());
return new Reach(reach.id(), reach.tier(), reach.downstreamId(), reach.xs(), reach.zs(), grade, halfWidth, depth, style,
reach.catchment());
}
private static ReachStyle[] restyled(ReachStyle[] style, int[] grade, int waterfallMinimumDrop, int seaLevel, int stepHeight) {
private static ReachStyle[] restyled(ReachStyle[] style, int[] grade, int waterfallMinDrop, int seaLevel, int stepHeight) {
boolean[] mouth = new boolean[style.length];
boolean[] outlet = new boolean[style.length];
for (int point = 0; point < style.length; point++) {
mouth[point] = style[point] == ReachStyle.MOUTH;
outlet[point] = style[point] == ReachStyle.POND_OUTLET;
}
return ReachShaper.styles(grade, mouth, outlet, waterfallMinimumDrop, seaLevel, stepHeight);
return ReachShaper.styles(grade, mouth, outlet, waterfallMinDrop, seaLevel, stepHeight);
}
private static int lowestEnd(List<Reach> feeders) {
@@ -322,7 +322,7 @@ final class RasterComposer {
continue;
}
int drop = 0;
int waterfallMinimumDrop = Integer.MAX_VALUE;
int waterfallMinDrop = Integer.MAX_VALUE;
for (int side : SIDES) {
int upper = cell + side;
if (!role[upper].flowing() || feature[upper] == feature[cell]) {
@@ -331,11 +331,11 @@ final class RasterComposer {
int step = head[upper] - head[cell];
if (step >= 2 && step > drop) {
drop = step;
waterfallMinimumDrop = tier[upper].waterfallMinimumDrop();
waterfallMinDrop = tier[upper].waterfallMinDrop();
}
}
if (drop > 0) {
role[cell] = drop >= waterfallMinimumDrop ? WaterRole.WATERFALL : WaterRole.CASCADE;
role[cell] = drop >= waterfallMinDrop ? WaterRole.WATERFALL : WaterRole.CASCADE;
}
}
}
@@ -18,7 +18,7 @@ public final class ConfluenceGrader {
public record Footprint(float[] xs, float[] zs, float[] halfWidth) {
}
public static int[] settle(Footprint feeder, int[] grade, boolean[] fixed, List<Footprint> receiving, int level, int waterfallMinimumDrop) {
public static int[] settle(Footprint feeder, int[] grade, boolean[] fixed, List<Footprint> receiving, int level, int waterfallMinDrop) {
int last = grade.length - 1;
double[] arc = arcFromEnd(feeder);
int[] settled = lower(grade, grade, last, level);
@@ -27,20 +27,20 @@ public final class ConfluenceGrader {
settled = lower(settled, grade, point, level);
edge = point;
}
int meet = approach(grade, fixed, arc, edge, level, waterfallMinimumDrop);
int meet = approach(grade, fixed, arc, edge, level, waterfallMinDrop);
for (int point = edge - 1; point > meet; point--) {
settled = lower(settled, grade, point, envelope(arc, edge, point, level));
}
return settled;
}
public static void spreadJunction(int[] settled, int[] grade, boolean[] fixed, int waterfallMinimumDrop, int startLimit) {
public static void spreadJunction(int[] settled, int[] grade, boolean[] fixed, int waterfallMinDrop, int startLimit) {
int lowered = 0;
while (settled[lowered] == grade[lowered]) {
lowered++;
}
for (int point = settled.length - 2; point >= 0; point--) {
if (!ReachGrader.spreadPoint(settled, point, waterfallMinimumDrop, startLimit, fixed) && point < lowered) {
if (!ReachGrader.spreadPoint(settled, point, waterfallMinDrop, startLimit, fixed) && point < lowered) {
return;
}
}
@@ -55,14 +55,14 @@ public final class ConfluenceGrader {
requireJunction(window, draft, downstream);
boolean[] fixed = draft.fixed();
fixed[0] |= draft.incoming.length > 0 && draft.grade[0] - downstream.grade[0] > MAX_START_LOWERING;
int waterfallMinimumDrop = draft.tier.waterfallMinimumDrop();
int waterfallMinDrop = draft.tier.waterfallMinDrop();
int[] settled = settle(footprint(draft), draft.grade, fixed, receiving(drafts, downstream, feeder), downstream.grade[0],
waterfallMinimumDrop);
waterfallMinDrop);
if (settled == draft.grade) {
continue;
}
if (!draft.tier.cascades()) {
spreadJunction(settled, draft.grade, fixed, waterfallMinimumDrop, ReachGrader.startLimit(drafts, draft));
spreadJunction(settled, draft.grade, fixed, waterfallMinDrop, ReachGrader.startLimit(drafts, draft));
}
draft.grade = settled;
touched[feeder] = true;
@@ -116,8 +116,8 @@ public final class ConfluenceGrader {
return beside && lowering <= MARGIN_LOWERING;
}
private static int approach(int[] grade, boolean[] fixed, double[] arc, int edge, int level, int waterfallMinimumDrop) {
double window = (waterfallMinimumDrop - 1) / (double) APPROACH_SLOPE;
private static int approach(int[] grade, boolean[] fixed, double[] arc, int edge, int level, int waterfallMinDrop) {
double window = (waterfallMinDrop - 1) / (double) APPROACH_SLOPE;
for (int point = edge - 1; point >= 0 && arc[point] - arc[edge] <= window; point--) {
if (grade[point] <= envelope(arc, edge, point, level)) {
return point;
@@ -15,7 +15,7 @@ public record HydrologyTier(
float depthRatio,
int inset,
boolean cascades,
int waterfallMinimumDrop,
int waterfallMinDrop,
int stepHeight,
int bankBand,
IrisBankStyle bankStyle,
@@ -776,7 +776,7 @@ public final class PondPlanner {
}
private int drawdown(float dryness) {
return Math.round(settings.ponds().climateDrawdown() * dryness);
return Math.round(settings.ponds().dryDrawdown() * dryness);
}
private static int radius(DemGrid raw, Basin basin) {
@@ -297,7 +297,7 @@ final class ReachFitter {
Tangents tangents = tangents(fitted.xs(), fitted.zs());
float[] ahead = lowestColumnsAhead(fitted);
float[] edgesAhead = lowestEdgesAhead(fitted, tangents, tier);
float drop = tier.waterfallMinimumDrop();
float drop = tier.waterfallMinDrop();
for (int point = 0; point < points; point++) {
float lowest = Float.POSITIVE_INFINITY;
float lowestLand = Float.POSITIVE_INFINITY;
@@ -83,7 +83,7 @@ final class ReachGrader {
for (int position = upstreamFirst.length - 1; position >= 0; position--) {
ReachDraft draft = drafts.get(upstreamFirst[position]);
if (!draft.tier.cascades()) {
spread(draft.grade, draft.tier.waterfallMinimumDrop(), startLimit(drafts, draft), draft.held);
spread(draft.grade, draft.tier.waterfallMinDrop(), startLimit(drafts, draft), draft.held);
}
lowerIncomingEnds(drafts, draft);
}
@@ -185,16 +185,16 @@ final class ReachGrader {
int limit = Integer.MIN_VALUE;
for (int upstream : draft.incoming) {
ReachDraft feeder = drafts.get(upstream);
limit = Math.max(limit, carryLimit(feeder.grade, feeder.grade.length - 1, feeder.tier.waterfallMinimumDrop()));
limit = Math.max(limit, carryLimit(feeder.grade, feeder.grade.length - 1, feeder.tier.waterfallMinDrop()));
}
return limit;
}
private static int carryLimit(int[] grade, int point, int waterfallMinimumDrop) {
if (point == 0 || grade[point - 1] - grade[point] >= waterfallMinimumDrop) {
private static int carryLimit(int[] grade, int point, int waterfallMinDrop) {
if (point == 0 || grade[point - 1] - grade[point] >= waterfallMinDrop) {
return Integer.MIN_VALUE;
}
return grade[point - 1] - (waterfallMinimumDrop - 1);
return grade[point - 1] - (waterfallMinDrop - 1);
}
private static int[] profile(List<ReachDraft> drafts, ReachDraft draft) {
@@ -237,18 +237,18 @@ final class ReachGrader {
return sorted[Math.max(0, (int) Math.ceil(POOL_QUANTILE * sorted.length) - 1)];
}
private static void spread(int[] grade, int waterfallMinimumDrop, int startLimit, boolean[] held) {
private static void spread(int[] grade, int waterfallMinDrop, int startLimit, boolean[] held) {
for (int point = grade.length - 2; point >= 0; point--) {
spreadPoint(grade, point, waterfallMinimumDrop, startLimit, held);
spreadPoint(grade, point, waterfallMinDrop, startLimit, held);
}
}
static boolean spreadPoint(int[] grade, int point, int waterfallMinimumDrop, int startLimit, boolean[] held) {
static boolean spreadPoint(int[] grade, int point, int waterfallMinDrop, int startLimit, boolean[] held) {
int drop = grade[point] - grade[point + 1];
if (drop < 2 || drop >= waterfallMinimumDrop || held != null && held[point]) {
if (drop < 2 || drop >= waterfallMinDrop || held != null && held[point]) {
return false;
}
int limit = point == 0 ? startLimit : carryLimit(grade, point, waterfallMinimumDrop);
int limit = point == 0 ? startLimit : carryLimit(grade, point, waterfallMinDrop);
int spread = Math.min(grade[point], Math.max(grade[point + 1] + 1, limit));
boolean lowered = spread < grade[point];
grade[point] = spread;
@@ -390,7 +390,7 @@ public final class ReachShaper {
}
private static void restyle(ReachDraft draft, int seaLevel) {
draft.style = styles(draft.grade, draft.ocean, draft.fixed(), draft.tier.waterfallMinimumDrop(), seaLevel, draft.tier.stepHeight());
draft.style = styles(draft.grade, draft.ocean, draft.fixed(), draft.tier.waterfallMinDrop(), seaLevel, draft.tier.stepHeight());
}
private static void chaikin(ReachDraft draft) {
@@ -505,7 +505,7 @@ public final class ReachShaper {
Opening estuary = draft.chain.end() == ReachTracer.End.OCEAN ? estuaryOpening(draft.tier.estuary(), draft.ocean, distance)
: Opening.closed(count);
float widening = (draft.tier.estuary().flare() - 1f) * estuary.share();
float[] plunge = plungeFlare(draft.grade, draft.style, draft.ocean, distance, ReachGrader.protectedStart(draft), draft.tier.waterfallMinimumDrop());
float[] plunge = plungeFlare(draft.grade, draft.style, draft.ocean, distance, ReachGrader.protectedStart(draft), draft.tier.waterfallMinDrop());
float running = upstream;
draft.halfWidth = new float[count];
draft.depth = new float[count];
@@ -528,12 +528,12 @@ public final class ReachShaper {
draft.maxHalfWidth = running;
}
static float[] plungeFlare(int[] grade, ReachStyle[] style, boolean[] ocean, float[] distance, float protectedLength, int waterfallMinimumDrop) {
static float[] plungeFlare(int[] grade, ReachStyle[] style, boolean[] ocean, float[] distance, float protectedLength, int waterfallMinDrop) {
int count = grade.length;
float[] flare = new float[count];
for (int foot = 1; foot < count - 1; foot++) {
int drop = grade[foot - 1] - grade[foot];
if (style[foot] != ReachStyle.WATERFALL || drop < waterfallMinimumDrop) {
if (style[foot] != ReachStyle.WATERFALL || drop < waterfallMinDrop) {
continue;
}
float length = StepPools.plungeLength(drop);
@@ -574,11 +574,11 @@ public final class ReachShaper {
return Math.clamp(1f - remaining / length, 0f, 1f);
}
public static ReachStyle[] styles(int[] grade, boolean[] ocean, boolean[] outletZone, int waterfallMinimumDrop, int seaLevel, int stepHeight) {
public static ReachStyle[] styles(int[] grade, boolean[] ocean, boolean[] outletZone, int waterfallMinDrop, int seaLevel, int stepHeight) {
ReachStyle[] styles = new ReachStyle[grade.length];
for (int point = 0; point < grade.length; point++) {
int drop = point == 0 ? 0 : grade[point - 1] - grade[point];
styles[point] = style(drop, waterfallMinimumDrop, ocean[point], outletZone[point]);
styles[point] = style(drop, waterfallMinDrop, ocean[point], outletZone[point]);
if (drop == 1 && !ocean[point] && outletZone[point - 1]
&& WaterHeads.snap(grade[point - 1], seaLevel, stepHeight) - WaterHeads.snap(grade[point], seaLevel, stepHeight) >= 2) {
styles[point] = ReachStyle.CASCADE;
@@ -586,18 +586,18 @@ public final class ReachShaper {
}
for (int point = 1; point < grade.length; point++) {
if (styles[point] == ReachStyle.MOUTH && styles[point - 1] != ReachStyle.MOUTH
&& grade[point - 1] - grade[point] >= waterfallMinimumDrop) {
&& grade[point - 1] - grade[point] >= waterfallMinDrop) {
styles[point - 1] = ReachStyle.WATERFALL;
}
}
return styles;
}
private static ReachStyle style(int drop, int waterfallMinimumDrop, boolean mouth, boolean outlet) {
private static ReachStyle style(int drop, int waterfallMinDrop, boolean mouth, boolean outlet) {
if (mouth) {
return ReachStyle.MOUTH;
}
if (drop >= waterfallMinimumDrop) {
if (drop >= waterfallMinDrop) {
return ReachStyle.WATERFALL;
}
if (drop >= 2) {
@@ -167,7 +167,7 @@ public final class SeaApproach {
if (reach.style()[point] == ReachStyle.POND_OUTLET || besidePond(reach, point)) {
return true;
}
if (level - below < reach.tier().waterfallMinimumDrop()) {
if (level - below < reach.tier().waterfallMinDrop()) {
return false;
}
return along > COAST_REACH || level - seaLevel >= CLIFF_HEIGHT;
@@ -204,7 +204,7 @@ public final class SeaApproach {
ocean[point] = reach.style()[point] == ReachStyle.MOUTH;
outlet[point] = reach.style()[point] == ReachStyle.POND_OUTLET;
}
ReachStyle[] styled = ReachShaper.styles(grade, ocean, outlet, reach.tier().waterfallMinimumDrop(), seaLevel, reach.tier().stepHeight());
ReachStyle[] styled = ReachShaper.styles(grade, ocean, outlet, reach.tier().waterfallMinDrop(), seaLevel, reach.tier().stepHeight());
ReachStyle[] style = reach.style().clone();
for (int point = 0; point < count; point++) {
boolean touched = grade[point] != reach.grade()[point] || point > 0 && grade[point - 1] != reach.grade()[point - 1]
@@ -23,7 +23,7 @@ final class StepPools {
}
static int stepMaxDrop(HydrologyTier tier) {
return tier.waterfallMinimumDrop() + STEP_EXTRA;
return tier.waterfallMinDrop() + STEP_EXTRA;
}
static float plungeLength(int drop) {
@@ -45,7 +45,7 @@ final class StepPools {
}
int top = grade[point - 1];
int first = top - grade[point];
boolean cliff = first >= tier.waterfallMinimumDrop();
boolean cliff = first >= tier.waterfallMinDrop();
float width = 2f * (tier.halfWidth(catchments[point]) + 1f);
float span = cliff ? plungeLength(first)
: Math.clamp(width * poolWidths(seed, xs[point], zs[point]), POOL_MIN, POOL_MAX);
@@ -56,14 +56,14 @@ final class StepPools {
if (grade[next] >= grade[end]) {
continue;
}
int limit = cliff ? grade[point] - tier.waterfallMinimumDrop() : top - stepMaxDrop(tier) - 1;
int limit = cliff ? grade[point] - tier.waterfallMinDrop() : top - stepMaxDrop(tier) - 1;
if (grade[next] <= limit || highestFloor > grade[next]) {
break;
}
end = next;
}
Arrays.fill(grade, point, end, grade[end]);
if (cliff && first >= 2 * tier.waterfallMinimumDrop()) {
if (cliff && first >= 2 * tier.waterfallMinDrop()) {
rollover(grade, floors, along, point, width, start);
}
point = end + 1;
@@ -23,6 +23,7 @@ import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.structure.object.IObjectPlacer;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.iris.generation.block.B;
@@ -44,18 +45,18 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer {
private final ObjectContinuationBundle.PlacementKey placementKey;
private final KList<BufferedMutation> mutations;
private final Map<PositionKey, NativeBlockState> bufferedBlocks;
private final boolean entersWater;
private final ObjectWaterRule waterRule;
private ObjectHydrologyVeto waterVeto;
private int blockWrites;
private BlockPosition canopyPosition;
FloatingObjectPlacementTransaction(IObjectPlacer delegate, ObjectContinuationBundle.PlacementKey placementKey,
boolean entersWater) {
ObjectWaterRule waterRule) {
this.delegate = Objects.requireNonNull(delegate);
this.placementKey = Objects.requireNonNull(placementKey);
this.mutations = new KList<>();
this.bufferedBlocks = new HashMap<>();
this.entersWater = entersWater;
this.waterRule = waterRule;
}
CommitResult commit() {
@@ -161,7 +162,7 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer {
@Override
public void set(int x, int y, int z, NativeBlockState state) {
if (state == null || waterVeto().keepsBlock(x, y, z, state, entersWater)) {
if (state == null || waterVeto().keepsBlock(x, y, z, state, waterRule)) {
return;
}
mutations.add(new BlockMutation(x, y, z, state, isCanopy(x, y, z)));
@@ -251,9 +252,9 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer {
private boolean keepsWater(int x, int y, int z, Object data) {
if (data instanceof NativeBlockState state) {
return waterVeto().keepsBlock(x, y, z, state, entersWater);
return waterVeto().keepsBlock(x, y, z, state, waterRule);
}
return data instanceof MatterCavern && waterVeto().keeps(x, y, z, false, entersWater);
return data instanceof MatterCavern && waterVeto().keeps(x, y, z, false, waterRule);
}
private ObjectHydrologyVeto waterVeto() {
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.util.structure.StructureCarvingFootprint;
import art.arcane.volmlib.util.structure.StructureCarveEnvelope;
@@ -167,36 +168,24 @@ public class IrisStructureComponent extends IrisMantleComponent {
KList<PlacedStructurePiece> pieces, RNG rng) {
IrisStructureStiltSettings stilt = placement.getStilt();
PieceRun run = new PieceRun(structure, rng, stilt == null ? null : new Long2IntOpenHashMap(),
stilt != null && stilt.isSupportNonOccluding(), placement.isAllowWater(),
placement.getNativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE);
ObjectPlaceMode mode = structure.getPlaceMode();
stilt != null && stilt.isSupportNonOccluding(), placement.getNativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE);
ObjectPlaceMode mode = placement.pieceMode(structure, pieces.size());
boolean forced = placement.forcesPieces(structure, pieces.size());
ObjectWaterRule rule = forced ? ObjectWaterRule.FORCED
: placement.isAllowWater() ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT;
int failedPieces = 0;
int water = writer.beginObjectPlacement(run.allowWater());
writer.beginObjectPlacement(rule);
try {
if (placement.isAnchoredUnderground()) {
ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG)
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, run, p, undergroundMode, false) == -1) {
failedPieces++;
}
}
} else if (pieces.size() == 1 && mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) {
if (placeObject(writer, run, pieces.getFirst(), mode, true) == -1) {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, run, p, mode, forced) == -1) {
failedPieces++;
}
} else {
for (PlacedStructurePiece p : pieces) {
if (placeObject(writer, run, p, ObjectPlaceMode.STRUCTURE_PIECE, false) == -1) {
failedPieces++;
}
}
}
if (failedPieces == 0 && stilt != null) {
placeFoundation(writer, run.foundationColumns(), stilt, rng, !placement.isAnchoredUnderground());
}
} finally {
writer.endObjectPlacement(water);
writer.endObjectPlacement();
}
return failedPieces;
}
@@ -567,7 +556,7 @@ public class IrisStructureComponent extends IrisMantleComponent {
boolean sampledHeight) {
IrisObject object = p.getObject();
String objectKey = object.getLoadKey();
IrisObjectPlacement config = piecePlacement(run.structure(), p, mode, run.allowWater());
IrisObjectPlacement config = piecePlacement(run.structure(), p, mode);
String marker = structurePlacementMarker(run.structure(), p, objectKey);
BiConsumer<BlockPosition, NativeBlockState> listener = (position, state) -> {
StructureFoundationPlanner.recordBaseCell(
@@ -591,8 +580,7 @@ public class IrisStructureComponent extends IrisMantleComponent {
}
}
static IrisObjectPlacement piecePlacement(IrisStructure structure, PlacedStructurePiece piece, ObjectPlaceMode mode,
boolean allowWater) {
static IrisObjectPlacement piecePlacement(IrisStructure structure, PlacedStructurePiece piece, ObjectPlaceMode mode) {
IrisObjectPlacement config = structure.createLootPlacement(piece.getObject().getLoadKey());
config.setMode(mode);
config.setRotation(piece.getRotation());
@@ -601,7 +589,6 @@ public class IrisStructureComponent extends IrisMantleComponent {
}
if (mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) {
config.setForcePlace(true);
config.setForcedByStructure(!allowWater);
}
return config;
}
@@ -728,6 +715,6 @@ public class IrisStructureComponent extends IrisMantleComponent {
}
private record PieceRun(IrisStructure structure, RNG rng, Long2IntOpenHashMap foundationColumns,
boolean supportNonOccluding, boolean allowWater, boolean replacesSource) {
boolean supportNonOccluding, boolean replacesSource) {
}
}
@@ -217,7 +217,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
int id = rng.i(0, Integer.MAX_VALUE);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(
writer, placements.next(minX >> 4, minZ >> 4), placement.entersWater());
writer, placements.next(minX >> 4, minZ >> 4), placement.waterRule());
try {
int resultY = obj.place(xx, zz, transaction, floatingPlacement, rng, (b, bd) -> {
String marker = placementMarker(obj, id);
@@ -311,7 +311,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
IslandObjectPlacer islandPlacer = IslandObjectPlacer.top(writer, sampleProvider, entry, pickTopY);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(
islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.entersWater());
islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.waterRule());
int id = rng.i(0, Integer.MAX_VALUE);
try {
@@ -424,7 +424,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent {
IslandObjectPlacer islandPlacer = IslandObjectPlacer.bottom(writer, sampleProvider, entry, pickBottomY);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(
islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.entersWater());
islandPlacer, placements.next(minX >> 4, minZ >> 4), placement.waterRule());
int id = rng.i(0, Integer.MAX_VALUE);
try {
@@ -735,7 +735,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
try {
int placeResult = -1;
CaveObjectPlacementTransaction.CommitResult commitResult = CaveObjectPlacementTransaction.CommitResult.EMPTY;
int continuation = writer.beginObjectPlacement(placement.entersWater());
int continuation = writer.beginObjectPlacement(placement.waterRule());
if (carving) {
int caveFloorY = caveAnchor.y();
if (golden) {
@@ -778,7 +778,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
}, null, getData());
}
if (placeResult >= 0 && (!carving || commitResult == CaveObjectPlacementTransaction.CommitResult.COMMITTED)) {
writer.endObjectPlacement(continuation);
writer.recordObjectPlacement(continuation);
}
if (golden) {
IrisLogging.debug("Goldendebug procedural result: chunk=" + x + "," + z
@@ -791,6 +791,8 @@ public class MantleObjectComponent extends IrisMantleComponent {
}
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "procedural object", p.getName(), x << 4, -1, z << 4, scope);
} finally {
writer.endObjectPlacement();
}
}
}
@@ -995,7 +997,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
}
try {
String marker = placementMarker(v, id, "surface");
int continuation = writer.beginObjectPlacement(effectivePlacement.entersWater());
int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule());
int result = v.place(xx, zz, placePlacer, effectivePlacement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
@@ -1009,7 +1011,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
}, null, getData());
if (result >= 0) {
writer.endObjectPlacement(continuation);
writer.recordObjectPlacement(continuation);
placed++;
} else {
rejected++;
@@ -1037,6 +1039,8 @@ public class MantleObjectComponent extends IrisMantleComponent {
} catch (Throwable e) {
GenerationFailures.skipPlacement(e, "object", v.getLoadKey(), chunkX << 4, -1, chunkZ << 4, scope);
errors++;
} finally {
writer.endObjectPlacement();
}
}
@@ -1173,7 +1177,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
IrisObjectPlacement effectivePlacement = resolveCavePlacement(objectPlacement, object, caveProfile);
try {
int continuation = writer.beginObjectPlacement(effectivePlacement.entersWater());
int continuation = writer.beginObjectPlacement(effectivePlacement.waterRule());
ContainedPlacementResult contained = placeContainedCaveObject(
writer,
object,
@@ -1191,7 +1195,7 @@ public class MantleObjectComponent extends IrisMantleComponent {
int result = contained.resultY();
boolean wroteBlocks = contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.COMMITTED;
if (wroteBlocks) {
writer.endObjectPlacement(continuation);
writer.recordObjectPlacement(continuation);
placed++;
} else {
rejected++;
@@ -1252,6 +1256,8 @@ public class MantleObjectComponent extends IrisMantleComponent {
y,
e
);
} finally {
writer.endObjectPlacement();
}
}
@@ -1356,21 +1362,25 @@ public class MantleObjectComponent extends IrisMantleComponent {
}
boolean treePlacement = isTreePlacement(v, objectPlacement);
String marker = placementMarker(v, id, "upper");
int continuation = writer.beginObjectPlacement(placement.entersWater());
int result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
int continuation = writer.beginObjectPlacement(placement.waterRule());
int result;
try {
result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> {
if (marker != null) {
writer.setData(b.getX(), b.getY(), b.getZ(), marker);
}
if (treePlacement && marker != null) {
writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data);
}
if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) {
writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE);
}
}, null, getData());
if (result >= 0) {
writer.recordObjectPlacement(continuation);
}
if (treePlacement && marker != null) {
writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data);
}
if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) {
writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE);
}
}, null, getData());
if (result >= 0) {
writer.endObjectPlacement(continuation);
} finally {
writer.endObjectPlacement();
}
if (traceRegen) {
IrisLogging.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ
@@ -20,6 +20,7 @@ package art.arcane.iris.generation.mantle;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.world.storage.matter.TileWrapper;
import art.arcane.iris.world.storage.matter.PreObjectMatterCell;
import art.arcane.iris.configuration.IrisSettings;
@@ -221,13 +222,13 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
}
@Override
public int beginObjectPlacement(boolean entersWater) {
objectWater.set(new ObjectWater(ObjectHydrologyVeto.of(getEngine()), entersWater));
public int beginObjectPlacement(ObjectWaterRule rule) {
objectWater.set(new ObjectWater(ObjectHydrologyVeto.of(getEngine()), rule));
return -1;
}
@Override
public void endObjectPlacement(int checkpoint) {
public void endObjectPlacement() {
objectWater.remove();
}
@@ -237,9 +238,9 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
return false;
}
if (value instanceof NativeBlockState state) {
return water.veto().keepsBlock(x, y, z, state, water.entersWater());
return water.veto().keepsBlock(x, y, z, state, water.rule());
}
return value instanceof MatterCavern && water.veto().keeps(x, y, z, false, water.entersWater());
return value instanceof MatterCavern && water.veto().keeps(x, y, z, false, water.rule());
}
private void recordObjectValue(int x, int y, int z, Class<?> type, Object value) {
@@ -1034,7 +1035,7 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
naturalOpening ? ALWAYS : NEVER, cavern ? ALWAYS : NEVER) ? (byte) 1 : 0;
}
private record ObjectWater(ObjectHydrologyVeto veto, boolean entersWater) {
private record ObjectWater(ObjectHydrologyVeto veto, ObjectWaterRule rule) {
}
public final class ObjectPlacementCapture implements AutoCloseable {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import java.util.Arrays;
@@ -10,6 +11,7 @@ final class MutationLog {
private static final byte CUSTOM = 1;
private static final byte CANOPY = 2;
private static final byte ENTERS_WATER = 4;
private static final byte FORCED = 8;
private int size;
private int[] x = new int[32];
@@ -30,16 +32,16 @@ final class MutationLog {
throw new IllegalArgumentException("Object mutation type " + key.type().getName()
+ " does not match its value " + value.getClass().getName());
}
log.add(key.x(), key.y(), key.z(), value, false, set.canopy(), false);
log.add(key.x(), key.y(), key.z(), value, false, set.canopy(), ObjectWaterRule.KEEP_OUT);
}
case ObjectDestinationTransaction.CustomBlockMutation block -> log.add(key.x(), key.y(), key.z(),
Objects.requireNonNull(block.state(), "custom block state"), true, block.canopy(), false);
Objects.requireNonNull(block.state(), "custom block state"), true, block.canopy(), ObjectWaterRule.KEEP_OUT);
}
}
return log;
}
void add(int blockX, int blockY, int blockZ, Object value, boolean custom, boolean canopy, boolean entersWater) {
void add(int blockX, int blockY, int blockZ, Object value, boolean custom, boolean canopy, ObjectWaterRule rule) {
if (size == values.length) {
int capacity = size * 2;
x = Arrays.copyOf(x, capacity);
@@ -52,7 +54,7 @@ final class MutationLog {
y[size] = blockY;
z[size] = blockZ;
values[size] = value;
flags[size] = (byte) ((custom ? CUSTOM : 0) | (canopy ? CANOPY : 0) | (entersWater ? ENTERS_WATER : 0));
flags[size] = (byte) ((custom ? CUSTOM : 0) | (canopy ? CANOPY : 0) | (rule == ObjectWaterRule.ENTERS_WATER ? ENTERS_WATER : 0) | (rule == ObjectWaterRule.FORCED ? FORCED : 0));
size++;
}
@@ -84,8 +86,11 @@ final class MutationLog {
return (flags[index] & CANOPY) != 0;
}
boolean entersWater(int index) {
return (flags[index] & ENTERS_WATER) != 0;
ObjectWaterRule waterRule(int index) {
if ((flags[index] & FORCED) != 0) {
return ObjectWaterRule.FORCED;
}
return (flags[index] & ENTERS_WATER) != 0 ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT;
}
Class<?> type(int index) {
@@ -7,6 +7,7 @@ import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.subterrain.SubterrainRasterizer;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.iris.generation.block.B;
@@ -41,7 +42,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
private int subterrainZ;
private boolean subterrainProtects;
private ObjectHydrologyVeto waterVeto;
private boolean waterPlacement;
private ObjectWaterRule waterRule = ObjectWaterRule.KEEP_OUT;
ObjectDestinationTransaction(MantleWriter writer, int destinationChunkX, int destinationChunkZ) {
this.writer = writer;
@@ -73,19 +74,23 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
}
@Override
public int beginObjectPlacement(boolean entersWater) {
waterPlacement = entersWater;
public int beginObjectPlacement(ObjectWaterRule rule) {
waterRule = rule;
return log.size();
}
@Override
public void endObjectPlacement(int checkpoint) {
waterPlacement = false;
public void recordObjectPlacement(int checkpoint) {
if (checkpoint >= 0 && checkpoint < log.size()) {
placements.add(new PlacementRange(checkpoint, log.size()));
}
}
@Override
public void endObjectPlacement() {
waterRule = ObjectWaterRule.KEEP_OUT;
}
void apply(ObjectSourcePlan plan) {
int slot = plan.destinationSlot(destinationChunkX, destinationChunkZ);
if (slot < 0) {
@@ -103,7 +108,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
Object value = plan.valueAt(index);
boolean custom = ObjectSourcePlan.isCustom(cell);
boolean canopy = ObjectSourcePlan.isCanopy(cell);
boolean entersWater = ObjectSourcePlan.entersWater(cell);
ObjectWaterRule rule = ObjectSourcePlan.waterRule(cell);
if (custom || value instanceof NativeBlockState) {
NativeBlockState existing = canopy ? get(x, y, z) : null;
skipCanopy = existing != null && existing.isSolid();
@@ -112,9 +117,9 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
continue;
}
if (custom) {
set(x, y, z, (NativeBlockState) value, canopy, entersWater);
set(x, y, z, (NativeBlockState) value, canopy, rule);
} else {
setData(x, y, z, value, canopy, entersWater);
setData(x, y, z, value, canopy, rule);
}
}
}
@@ -179,17 +184,17 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
@Override
public void set(int x, int y, int z, NativeBlockState state) {
set(x, y, z, state, isCanopy(x, y, z), waterPlacement);
set(x, y, z, state, isCanopy(x, y, z), waterRule);
}
private void set(int x, int y, int z, NativeBlockState state, boolean canopy, boolean entersWater) {
private void set(int x, int y, int z, NativeBlockState state, boolean canopy, ObjectWaterRule rule) {
if (state == null) {
return;
}
String placementKey = state.deferredPlacementKey();
NativeBlockState baseState = state.placementBaseState();
if (state.isCustom() && placementKey != null && baseState != null) {
if (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, baseState.isSolid(), entersWater)) {
if (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, baseState.isSolid(), rule)) {
return;
}
Identifier identifier = Identifier.fromString(placementKey);
@@ -197,10 +202,10 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
cell.block = baseState;
cell.tile = CLEARED;
cell.identifier = identifier;
log.add(x, y, z, state, true, canopy, entersWater);
log.add(x, y, z, state, true, canopy, rule);
return;
}
setData(x, y, z, state, canopy, entersWater);
setData(x, y, z, state, canopy, rule);
}
@Override
@@ -291,18 +296,18 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
@Override
public <T> void setData(int x, int y, int z, T data) {
setData(x, y, z, data, isCanopy(x, y, z), waterPlacement);
setData(x, y, z, data, isCanopy(x, y, z), waterRule);
}
private void setData(int x, int y, int z, Object data, boolean canopy, boolean entersWater) {
private void setData(int x, int y, int z, Object data, boolean canopy, ObjectWaterRule rule) {
if (data == null || y < 0 || y >= worldHeight
|| protectsSubterrain(x, y, z)) {
return;
}
if (data instanceof NativeBlockState state && (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, state.isSolid(), entersWater))) {
if (data instanceof NativeBlockState state && (!canSetBlock(x, y, z) || hydrologyKeeps(x, y, z, state.isSolid(), rule))) {
return;
}
if (data instanceof MatterCavern && (hasProtectedHydrology(x, y, z) || hydrologyKeeps(x, y, z, false, entersWater))) {
if (data instanceof MatterCavern && (hasProtectedHydrology(x, y, z) || hydrologyKeeps(x, y, z, false, rule))) {
return;
}
Class<?> type = data instanceof NativeBlockState ? NativeBlockState.class : data.getClass();
@@ -314,7 +319,7 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
} else {
cell.put(type, data);
}
log.add(x, y, z, data, false, canopy, entersWater);
log.add(x, y, z, data, false, canopy, rule);
}
@Override
@@ -411,11 +416,11 @@ final class ObjectDestinationTransaction implements ObjectPassPlacer {
&& !protectsSubterrain(x, y, z);
}
private boolean hydrologyKeeps(int x, int y, int z, boolean solid, boolean entersWater) {
private boolean hydrologyKeeps(int x, int y, int z, boolean solid, ObjectWaterRule rule) {
if (waterVeto == null) {
waterVeto = ObjectHydrologyVeto.of(getEngine());
}
return waterVeto.keeps(x, y, z, solid, entersWater);
return waterVeto.keeps(x, y, z, solid, rule);
}
private boolean protectsSubterrain(int x, int y, int z) {
@@ -5,6 +5,7 @@ import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
final class ObjectHydrologyVeto {
@@ -25,13 +26,13 @@ final class ObjectHydrologyVeto {
return runtime != null && runtime.enabled() ? new ObjectHydrologyVeto(complex, runtime) : NONE;
}
boolean keepsBlock(int x, int y, int z, NativeBlockState state, boolean entersWater) {
boolean keepsBlock(int x, int y, int z, NativeBlockState state, ObjectWaterRule rule) {
NativeBlockState base = state.isCustom() && state.placementBaseState() != null ? state.placementBaseState() : state;
return keeps(x, y, z, base.isSolid(), entersWater);
return keeps(x, y, z, base.isSolid(), rule);
}
boolean keeps(int x, int y, int z, boolean solid, boolean entersWater) {
if (runtime == null) {
boolean keeps(int x, int y, int z, boolean solid, ObjectWaterRule rule) {
if (runtime == null || rule == ObjectWaterRule.FORCED) {
return false;
}
ChunkWaterRaster raster = runtime.raster(x >> 4, z >> 4);
@@ -42,7 +43,7 @@ final class ObjectHydrologyVeto {
if (role == WaterRole.INLET && y >= raster.waterHead(x & 15, z & 15) && y <= complex.naturalTrueHeight(x, z)) {
return true;
}
if (solid && !entersWater && fillsWater(x, y, z)) {
if (solid && rule != ObjectWaterRule.ENTERS_WATER && fillsWater(x, y, z)) {
return true;
}
if (role.wet()) {
@@ -1,6 +1,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.structure.object.IObjectPlacer;
import art.arcane.iris.structure.object.ObjectWaterRule;
import org.jetbrains.annotations.Nullable;
public interface ObjectPassPlacer extends IObjectPlacer {
@@ -8,11 +9,14 @@ public interface ObjectPassPlacer extends IObjectPlacer {
byte[] getCarvedColumn(int x, int z, int height);
default int beginObjectPlacement(boolean entersWater) {
default int beginObjectPlacement(ObjectWaterRule rule) {
return -1;
}
default void endObjectPlacement(int checkpoint) {
default void recordObjectPlacement(int checkpoint) {
}
default void endObjectPlacement() {
}
@Override
@@ -3,6 +3,7 @@ package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
import art.arcane.iris.world.storage.matter.TileWrapper;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
@@ -33,7 +34,8 @@ final class ObjectSourcePlan {
private static final int CUSTOM_BIT = 1 << 8;
private static final int CANOPY_BIT = 1 << 9;
private static final int ENTERS_WATER_BIT = 1 << 10;
private static final int Y_SHIFT = 11;
private static final int FORCED_BIT = 1 << 11;
private static final int Y_SHIFT = 12;
private static final int MAXIMUM_Y = (1 << (31 - Y_SHIFT)) - 1;
private final long[] destinations;
@@ -91,7 +93,7 @@ final class ObjectSourcePlan {
throw new IllegalArgumentException("Object mutation height is outside the plan range: " + y);
}
cells[position] = (y << Y_SHIFT) | (log.custom(logged) ? CUSTOM_BIT : 0) | (log.canopy(logged) ? CANOPY_BIT : 0)
| (log.entersWater(logged) ? ENTERS_WATER_BIT : 0) | ((log.z(logged) & 15) << 4) | (log.x(logged) & 15);
| waterBits(log.waterRule(logged)) | ((log.z(logged) & 15) << 4) | (log.x(logged) & 15);
valueIndexes[position] = table.indexOf(log.value(logged));
}
values = table.values.toArray();
@@ -242,8 +244,19 @@ final class ObjectSourcePlan {
return (cell & CANOPY_BIT) != 0;
}
static boolean entersWater(int cell) {
return (cell & ENTERS_WATER_BIT) != 0;
static ObjectWaterRule waterRule(int cell) {
if ((cell & FORCED_BIT) != 0) {
return ObjectWaterRule.FORCED;
}
return (cell & ENTERS_WATER_BIT) != 0 ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT;
}
private static int waterBits(ObjectWaterRule rule) {
return switch (rule) {
case KEEP_OUT -> 0;
case ENTERS_WATER -> ENTERS_WATER_BIT;
case FORCED -> FORCED_BIT;
};
}
ObjectDestinationTransaction.Mutation mutationAt(int chunkX, int chunkZ, int index) {
@@ -1,8 +1,10 @@
package art.arcane.iris.pack;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.HydrologyVegetation;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.hydrology.config.IrisFluidProfile;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier;
@@ -10,30 +12,45 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.underground.CavePoolFiller;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import art.arcane.volmlib.util.mantle.flag.ReservedFlag;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
final class PackHydrologyValidator {
private static final String CONFIG = "hydrology";
private static final String POLICY = "hydrologyPolicy";
private static final String DEFAULT_FLUID = "water";
private static final String SNIPPET_ROOT = "snippet/";
private static final List<RangeField> RANGES = List.of(
new RangeField("ponds.freeboard", Floor.NON_NEGATIVE, true),
new RangeField("ponds.seeded.radius", Floor.POSITIVE, true),
@@ -51,6 +68,7 @@ final class PackHydrologyValidator {
);
private static final List<String> FLUID_REFERENCES = List.of("ponds.fluid", "underground.cavePools.fluid");
private static final IrisHydrologyTier DEFAULT_TIER = new IrisHydrologyTier();
private static final Set<String> WATER_BLOCKS = Set.of("minecraft:water");
private static final String MANTLE_WATER = "the falling water at waterfalls and cascades and cave pools";
private PackHydrologyValidator() {
@@ -90,6 +108,7 @@ final class PackHydrologyValidator {
errors.add(path + " must be an object.");
return data;
}
warnUnknownKeys(path, hydrology, IrisHydrology.class, packFolder, findings.warnings());
if (!hydrology.optBoolean("enabled", false)) {
return data;
}
@@ -105,14 +124,107 @@ final class PackHydrologyValidator {
return loaded;
}
warnMantleOff("Dimension '" + dimensionKey + "'", loadedDimension, findings.warnings());
validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors);
validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors, findings.warnings());
warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings());
if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) {
validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors);
warnFluidsWithoutSeam(dimensionKey, loaded, loadedDimension, findings.warnings());
}
return loaded;
}
static void warnUnknownKeys(String field, Object value, Type type, File packFolder, List<String> warnings) {
warnUnknownKeys(field, value, type, new KeyScan(packFolder, warnings, new HashSet<>()));
}
private static void warnUnknownKeys(String field, Object value, Type type, KeyScan scan) {
Class<?> raw = TypeToken.get(type).getRawType();
if (value instanceof JSONArray array) {
Type element = elementType(type, raw);
for (int index = 0; index < array.length(); index++) {
warnUnknownKeys(field + "[" + index + "]", array.opt(index), element, scan);
}
} else if (value instanceof JSONObject object) {
if (Map.class.isAssignableFrom(raw)) {
Type entry = typeArgument(type, 1);
for (String key : new TreeSet<>(object.keySet())) {
warnUnknownKeys(field + "." + key, object.opt(key), entry, scan);
}
} else if (hasDeclaredKeys(raw)) {
warnUnknownFields(field, object, raw, scan);
}
} else if (value instanceof String reference && reference.startsWith(SNIPPET_ROOT) && raw.isAnnotationPresent(Snippet.class)) {
warnUnknownSnippetKeys(field, reference, raw, scan);
}
}
private static void warnUnknownFields(String field, JSONObject object, Class<?> type, KeyScan scan) {
Map<String, Type> declared = declaredKeys(type);
for (String key : new TreeSet<>(object.keySet())) {
String child = field + "." + key;
Type declaredType = declared.get(key);
if (declaredType == null) {
scan.warnings().add(child + " is not a known key, so its value is ignored. Known keys there: " + declared.keySet() + ".");
} else {
warnUnknownKeys(child, object.opt(key), declaredType, scan);
}
}
}
private static void warnUnknownSnippetKeys(String field, String reference, Class<?> type, KeyScan scan) {
String base = SNIPPET_ROOT + type.getDeclaredAnnotation(Snippet.class).value() + "/";
String snippet = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_ROOT.length());
if (!scan.activeSnippets().add(snippet)) {
return;
}
File file = new File(scan.packFolder(), snippet + ".json");
JSONObject object = file.isFile() ? PackValidationIo.readJson(file) : null;
if (object != null) {
warnUnknownFields(field + " (" + snippet + ")", object, type, scan);
}
scan.activeSnippets().remove(snippet);
}
private static Type elementType(Type type, Class<?> raw) {
if (raw.isArray()) {
return raw.getComponentType();
}
return Collection.class.isAssignableFrom(raw) ? typeArgument(type, 0) : Object.class;
}
private static Type typeArgument(Type type, int index) {
if (type instanceof ParameterizedType parameterized && index < parameterized.getActualTypeArguments().length) {
return parameterized.getActualTypeArguments()[index];
}
return Object.class;
}
private static boolean hasDeclaredKeys(Class<?> type) {
return !type.isPrimitive() && !type.isEnum() && !type.isArray() && !type.isInterface()
&& !Modifier.isAbstract(type.getModifiers()) && !Collection.class.isAssignableFrom(type)
&& !type.getPackageName().startsWith("java.");
}
private static Map<String, Type> declaredKeys(Class<?> type) {
Map<String, Type> keys = new TreeMap<>();
for (Class<?> current = type; current != null && current != Object.class; current = current.getSuperclass()) {
for (Field field : current.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || field.isSynthetic()) {
continue;
}
SerializedName serialized = field.getAnnotation(SerializedName.class);
keys.putIfAbsent(serialized == null ? field.getName() : serialized.value(), field.getGenericType());
if (serialized != null) {
for (String alternate : serialized.alternate()) {
keys.putIfAbsent(alternate, field.getGenericType());
}
}
}
}
return keys;
}
private static boolean validateCompile(String path, IrisDimension dimension, List<String> errors) {
try {
HydrologySettings settings = HydrologySettings.compile(dimension.getHydrology(), 0L, dimension.getFluidHeight(), 0,
@@ -278,12 +390,14 @@ final class PackHydrologyValidator {
}
private static void validatePolicies(String path, String dimensionKey, IrisData data, IrisDimension dimension, PolicyFluids fluids,
List<String> errors) {
List<String> errors, List<String> warnings) {
warnUnknownPolicyKeys("Dimension '" + dimensionKey + "'." + POLICY, dimension, data, warnings);
validatePolicy("Dimension '" + dimensionKey + "'." + POLICY, dimension.getHydrologyPolicy(), data, fluids, path, errors);
List<IrisRegion> regions = new ArrayList<>(dimension.getAllRegions(() -> data));
regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder())));
for (IrisRegion region : regions) {
if (region != null) {
warnUnknownPolicyKeys("Region '" + region.getLoadKey() + "'." + POLICY, region, data, warnings);
validatePolicy("Region '" + region.getLoadKey() + "'." + POLICY, region.getHydrologyPolicy(), data, fluids, path, errors);
}
}
@@ -291,11 +405,20 @@ final class PackHydrologyValidator {
biomes.sort(Comparator.comparing(IrisBiome::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder())));
for (IrisBiome biome : biomes) {
if (biome != null) {
warnUnknownPolicyKeys("Biome '" + biome.getLoadKey() + "'." + POLICY, biome, data, warnings);
validatePolicy("Biome '" + biome.getLoadKey() + "'." + POLICY, biome.getHydrologyPolicy(), data, fluids, path, errors);
}
}
}
private static void warnUnknownPolicyKeys(String field, IrisRegistrant owner, IrisData data, List<String> warnings) {
File file = owner.getLoadFile();
JSONObject json = file == null ? null : PackValidationIo.readJson(file);
if (json != null) {
warnUnknownKeys(field, json.opt(POLICY), IrisHydrologyPolicy.class, data.getDataFolder(), warnings);
}
}
private static void validatePolicy(String field, IrisHydrologyPolicy policy, IrisData data, PolicyFluids fluids, String configPath,
List<String> errors) {
if (policy == null) {
@@ -359,6 +482,90 @@ final class PackHydrologyValidator {
}
}
private static void warnFluidsWithoutSeam(String dimensionKey, IrisData data, IrisDimension dimension, List<String> warnings) {
String path = "Dimension '" + dimensionKey + "'." + CONFIG;
Map<String, IrisFluidProfile> profiles = new HashMap<>();
for (IrisFluidProfile profile : dimension.getHydrology().getFluids()) {
profiles.put(profile.getName(), profile);
}
Map<String, Set<String>> rivers = riverFluidSources(dimensionKey, data, dimension);
rivers.keySet().retainAll(profiles.keySet());
for (Map.Entry<String, Set<String>> river : rivers.entrySet()) {
IrisFluidProfile profile = profiles.get(river.getKey());
Set<String> blocks = blockIds(profile.getPalette());
if (hasSeam(profile) || blocks.equals(WATER_BLOCKS)) {
continue;
}
List<String> met = new ArrayList<>();
if (dimension.getFluidHeight() > 0 && !blocks.equals(blockIds(dimension.getFluidPalette()))) {
met.add("the sea");
}
for (String other : rivers.keySet()) {
IrisFluidProfile otherProfile = profiles.get(other);
if (!hasSeam(otherProfile) && !blocks.equals(blockIds(otherProfile.getPalette()))) {
met.add("fluid '" + other + "'");
}
}
if (!met.isEmpty()) {
warnings.add(path + ".fluids profile '" + river.getKey() + "' sets no seam, so where its rivers meet " + String.join(" or ", met)
+ " the fluids lie side by side. Set seam on the profile to line that edge. Its rivers come from "
+ String.join(", ", river.getValue()) + ".");
}
}
}
private static Map<String, Set<String>> riverFluidSources(String dimensionKey, IrisData data, IrisDimension dimension) {
Map<String, Set<String>> sources = new TreeMap<>();
List<IrisRegion> regions = new ArrayList<>(dimension.getAllRegions(() -> data));
ShoreBiomeLineages.visit(dimension, regions, () -> data, (lineage, region) -> {
String fluid = IrisHydrologyPolicy.inherited(lineage, region, dimension, IrisHydrologyPolicy::getFluid);
if (fluid == null) {
addTierSources(dimensionKey, dimension, sources);
} else {
sources.computeIfAbsent(fluid, name -> new TreeSet<>()).add(policyFluidOwner(dimensionKey, lineage, region));
}
});
if (sources.isEmpty()) {
addTierSources(dimensionKey, dimension, sources);
}
return sources;
}
private static void addTierSources(String dimensionKey, IrisDimension dimension, Map<String, Set<String>> sources) {
List<IrisHydrologyTier> tiers = dimension.getHydrology().getTiers();
for (int index = 0; index < tiers.size(); index++) {
sources.computeIfAbsent(tiers.get(index).getFluid(), name -> new TreeSet<>())
.add("Dimension '" + dimensionKey + "'." + CONFIG + ".tiers[" + index + "].fluid");
}
}
private static String policyFluidOwner(String dimensionKey, List<IrisBiome> lineage, IrisRegion region) {
for (IrisBiome biome : lineage) {
if (biome.getHydrologyPolicy() != null && biome.getHydrologyPolicy().getFluid() != null) {
return "Biome '" + biome.getLoadKey() + "'." + POLICY + ".fluid";
}
}
if (region != null && region.getHydrologyPolicy() != null && region.getHydrologyPolicy().getFluid() != null) {
return "Region '" + region.getLoadKey() + "'." + POLICY + ".fluid";
}
return "Dimension '" + dimensionKey + "'." + POLICY + ".fluid";
}
private static boolean hasSeam(IrisFluidProfile profile) {
return profile.getSeam() != null && !profile.getSeam().isBlank();
}
private static Set<String> blockIds(IrisMaterialPalette palette) {
Set<String> blocks = new TreeSet<>();
for (IrisBlockData block : palette.getPalette()) {
String id = block.getBlock().toLowerCase(Locale.ROOT);
int state = id.indexOf('[');
String name = state < 0 ? id : id.substring(0, state);
blocks.add(name.contains(":") ? name : "minecraft:" + name);
}
return blocks;
}
private static void requireMultiplier(String field, Double value, List<String> errors) {
if (value != null && !IrisHydrologyPolicy.validMultiplier(value)) {
errors.add(field + " must be a finite value from 0 to " + (int) IrisHydrologyPolicy.MAX_MULTIPLIER + ", got " + value + ".");
@@ -414,4 +621,7 @@ final class PackHydrologyValidator {
private record Findings(List<String> errors, List<String> warnings) {
}
private record KeyScan(File packFolder, List<String> warnings, Set<String> activeSnippets) {
}
}
@@ -223,6 +223,7 @@ final class PackStructurePlacementValidator {
path, placement, "maxHeight", Integer.MIN_VALUE, Integer.MAX_VALUE, blockingErrors);
PackJsonFieldChecks.validateOptionalBoolean(path, placement, "underground", blockingErrors);
PackJsonFieldChecks.validateOptionalBoolean(path, placement, "underwater", blockingErrors);
PackJsonFieldChecks.validateOptionalBoolean(path, placement, "allowWater", blockingErrors);
PackJsonFieldChecks.validateOptionalEnum(path, placement, "nativeSuppression",
Set.of("NONE", "REPLACE_SOURCE"), blockingErrors);
@@ -299,6 +300,9 @@ final class PackStructurePlacementValidator {
appendIdentity(identity, integerValue(placement, "maxHeight", 2032));
appendIdentity(identity, placement.opt("underground") instanceof Boolean underground && underground);
appendIdentity(identity, placement.opt("underwater") instanceof Boolean underwater && underwater);
if (placement.opt("allowWater") instanceof Boolean allowWater && allowWater) {
appendIdentity(identity, "allowWater");
}
JSONArray structures = placement.optJSONArray("structures");
JSONArray nativeStructures = placement.optJSONArray("nativeStructures");
if (structures != null && structures.length() > 0) {
@@ -201,7 +201,6 @@ public class IrisObjectPlacement {
@Description("Ignore any placement restrictions for this object")
@SerializedName(value = "forcePlace", alternate = {"force"})
private boolean forcePlace = false;
private transient boolean forcedByStructure = false;
private transient AtomicCache<TableCache> cache = new AtomicCache<>();
private transient AtomicCache<CompatStatus> compatCache = new AtomicCache<>();
@Getter(AccessLevel.NONE)
@@ -307,8 +306,11 @@ public class IrisObjectPlacement {
return place.size() == 1 ? place.getFirst() : place.toString(", ");
}
public boolean entersWater() {
return underwater || onwater || forcePlace && !forcedByStructure;
public ObjectWaterRule waterRule() {
if (forcePlace) {
return ObjectWaterRule.FORCED;
}
return underwater || onwater ? ObjectWaterRule.ENTERS_WATER : ObjectWaterRule.KEEP_OUT;
}
public IrisObjectPlacement toPlacement(String... place) {
@@ -354,7 +356,6 @@ public class IrisObjectPlacement {
p.setAllowedCollisions(allowedCollisions);
p.setForbiddenCollisions(forbiddenCollisions);
p.setForcePlace(forcePlace);
p.setForcedByStructure(forcedByStructure);
return p;
}
@@ -0,0 +1,7 @@
package art.arcane.iris.structure.object;
public enum ObjectWaterRule {
KEEP_OUT,
ENTERS_WATER,
FORCED
}
@@ -56,12 +56,12 @@ final class PlacementModuleSurfaceSupport implements PlacementModule {
private static String hydrologyRejection(PlacementContext context, PlacementState state) {
IrisObjectPlacement config = state.config;
if (!context.automatic || !config.getCarvingSupport().supportsSurface()
if (!context.automatic || config.isForcePlace() || !config.getCarvingSupport().supportsSurface()
|| config.getMode() == ObjectPlaceMode.FLOATING || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE) {
return null;
}
boolean painted = state.paintProjection != null;
if (config.entersWater()) {
if (config.waterRule() == ObjectWaterRule.ENTERS_WATER) {
return (painted
? IrisSurfaceSupport.intersectsUnevenWater(context.placer, context.x, context.z, null, null, 0, 0, 0, state.paintSupport)
: IrisSurfaceSupport.intersectsUnevenWater(context.placer, context.x, context.z, config.getTranslate(),
@@ -100,7 +100,7 @@ public class IrisStructure extends IrisRegistrant {
@Description("Whether every open connector must close with a real terminal piece through a mandatory direct fallback.")
private boolean requireCaps = false;
@Description("The place mode used when stamping each piece object into the world.")
@Description("The place mode used when stamping each piece object into the world. A surface structure with a mode other than STRUCTURE_PIECE or FLOATING that assembles to one piece is force placed: it ignores the river limit and the submerged start check and writes through river, pond and sea water.")
private ObjectPlaceMode placeMode = ObjectPlaceMode.STRUCTURE_PIECE;
@ArrayType(min = 1, type = IrisObjectReplace.class)
@@ -524,12 +524,20 @@ public final class IrisStructureLocator {
originZ = anchor.z();
int baseY = anchor.y();
boolean submerged = !placement.resolvedAnchor().isCave() && !placement.isUnderwater()
&& NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ);
String selectedKey = selectStructureKey(placement, rng);
if (selectedKey == null || selectedKey.isBlank()) {
if (submerged) {
return null;
}
throw new IllegalStateException("Iris structure placement selected a blank structure key");
}
IrisStructure structure = engine.getData().load(IrisStructure.class, selectedKey, false);
if (structure == null) {
if (submerged) {
return null;
}
throw new IllegalStateException("Iris structure placement references missing structure '"
+ selectedKey + "'");
}
@@ -537,15 +545,13 @@ public final class IrisStructureLocator {
// Gated out on this Minecraft version; the pack report already says why.
return null;
}
StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure);
if (!compilation.isAssemblyViable()) {
throw new IllegalStateException("Iris structure '" + selectedKey
+ "' has no runtime-viable assembly graph");
if (submerged && !placement.forcesPieces(structure, 1)) {
return null;
}
StructureAssemblyResult assembly = assemble(engine, structure, selectedKey, new IrisPosition(originX, baseY, originZ), rng);
if (submerged && !placement.forcesPieces(structure, assembly.pieces().size())) {
return null;
}
StructureAssembler assembler = StructureAssembler.forData(
engine.getData(), structure, new IrisPosition(originX, baseY, originZ));
StructureAssemblyResult assembly = assembler.assemble(rng);
if (!placementOutput(placement, selectedKey, cx, cz,
assembly.hasOutput(), "assembly " + assembly.status(), assembly.detail())) {
return null;
@@ -594,6 +600,7 @@ public final class IrisStructureLocator {
return null;
}
if (!placement.isAnchoredUnderground() && !placement.isAllowWater()
&& !placement.forcesPieces(structure, pieces.size())
&& !StructureWaterRules.admitsFootprint(IrisStructureWater.mantle(engine.getComplex()), pieceFootprints(pieces))) {
return null;
}
@@ -603,6 +610,14 @@ public final class IrisStructureLocator {
return new ResolvedPlacement(placement, selectedKey, structure, pieces, rng, originX, baseY, originZ, exactY);
}
private static StructureAssemblyResult assemble(Engine engine, IrisStructure structure, String key, IrisPosition origin, RNG rng) {
StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure);
if (!compilation.isAssemblyViable()) {
throw new IllegalStateException("Iris structure '" + key + "' has no runtime-viable assembly graph");
}
return StructureAssembler.forData(engine.getData(), structure, origin).assemble(rng);
}
public static boolean allowsResolvedFootprint(Engine engine, ResolvedPlacement resolved) {
Objects.requireNonNull(resolved, "resolved placement");
return allowsResolvedFootprint(engine, resolved.placement(), resolved.structure(), resolved.pieces());
@@ -682,10 +697,6 @@ public final class IrisStructureLocator {
if (worldMin > worldMax) {
return null;
}
if (!placement.isUnderwater()
&& NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ)) {
return null;
}
if (placement.resolvedAnchor() == IrisStructureAnchorMode.SURFACE) {
int surfaceY = Engine.hostHeight(engine, originX, originZ, true) + engine.getMinHeight();
return surfaceY < placement.getMinHeight() || surfaceY > placement.getMaxHeight() ? null : surfaceY;
@@ -18,6 +18,7 @@
package art.arcane.iris.structure.placement;
import art.arcane.iris.structure.object.ObjectPlaceMode;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.pack.validation.CompatPools;
import art.arcane.iris.structure.nativegen.IrisNativeStructure;
@@ -127,10 +128,10 @@ public class IrisStructurePlacement {
@Description("Optional foundation columns placed beneath the assembled structure's occupied bottom cells. Columns pass through air and fluids until they reach solid ground, up to maxDepth.")
private IrisStructureStiltSettings stilt = null;
@Description("If false, the placement is skipped when its selected surface or cave column is submerged.")
@Description("If false, the placement is skipped when its selected surface or cave column is submerged. A force placed surface structure, as described on the structure's placeMode, ignores this.")
private boolean underwater = false;
@Description("If true, a surface structure may cover river, stream, pond and lake water, and its pieces and stilts may fill it. If false, a surface placement is skipped when more than 10% of its footprint columns are channel, pond, cascade or waterfall water, and its pieces keep their solid blocks out of the water they touch.")
@Description("If true, a surface structure may cover river, stream, pond and lake water, and its pieces and stilts may fill it. If false, a surface placement is skipped when more than 10% of its footprint columns are channel, pond, cascade or waterfall water, and its pieces keep their solid blocks out of the water they touch. A force placed surface structure, as described on the structure's placeMode, ignores the limit and writes through the water whatever this is set to.")
private boolean allowWater = false;
public IrisStructureTerrain resolvedTerrain() {
@@ -152,6 +153,19 @@ public class IrisStructurePlacement {
return anchor;
}
public ObjectPlaceMode pieceMode(IrisStructure structure, int pieces) {
ObjectPlaceMode mode = structure.getPlaceMode();
if (isAnchoredUnderground()) {
return mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG
? mode : ObjectPlaceMode.STRUCTURE_PIECE;
}
return pieces == 1 && mode != ObjectPlaceMode.FLOATING ? mode : ObjectPlaceMode.STRUCTURE_PIECE;
}
public boolean forcesPieces(IrisStructure structure, int pieces) {
return !isAnchoredUnderground() && pieceMode(structure, pieces) != ObjectPlaceMode.STRUCTURE_PIECE;
}
public boolean isAnchoredUnderground() {
IrisStructureAnchorMode activeAnchor = resolvedAnchor();
return activeAnchor == IrisStructureAnchorMode.HEIGHT_BAND || activeAnchor.isCave();
@@ -16,17 +16,17 @@ public class IrisHydrologyDefaultsTest {
private static final String PLAN_JSON = """
{
"enabled": false,
"drainage": { "fillEpsilon": 0.001, "breachDepth": 24, "wetnessThinning": true, "minimumHeadKeep": 0.25, "saturationCatchment": 4194304 },
"drainage": { "fillEpsilon": 0.001, "breachDepth": 24, "wetnessThinning": true, "minHeadKeep": 0.25, "saturationCatchment": 4194304 },
"tiers": [
{ "name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "widthFactor": 1.0, "depthRatio": 0.4, "inset": 1, "cascades": true, "waterfallMinimumDrop": 6, "bankBand": 0, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" },
{ "name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "widthFactor": 1.0, "depthRatio": 0.45, "inset": 2, "cascades": true, "waterfallMinimumDrop": 6, "bankBand": 32, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" },
{ "name": "major", "minCatchment": 320000, "halfWidth": [8, 16], "widthFactor": 1.0, "depthRatio": 0.5, "inset": 3, "cascades": true, "waterfallMinimumDrop": 6, "bankBand": 48, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" }
{ "name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "widthFactor": 1.0, "depthRatio": 0.4, "inset": 1, "cascades": true, "waterfallMinDrop": 6, "bankBand": 0, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" },
{ "name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "widthFactor": 1.0, "depthRatio": 0.45, "inset": 2, "cascades": true, "waterfallMinDrop": 6, "bankBand": 32, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" },
{ "name": "major", "minCatchment": 320000, "halfWidth": [8, 16], "widthFactor": 1.0, "depthRatio": 0.5, "inset": 3, "cascades": true, "waterfallMinDrop": 6, "bankBand": 48, "bankStyle": "SMOOTH", "estuary": { "length": 48, "flare": 2.5 }, "delta": { "channels": 0, "spreadDegrees": 35, "length": 64 }, "materials": {}, "fluid": "water" }
],
"ponds": {
"natural": { "enabled": true, "keep": 1.0, "minArea": 256, "maxArea": 65536, "minDepth": 2 },
"seeded": { "enabled": true, "density": 4.0, "radius": [6, 24], "depth": [3, 8], "maxSlope": 0.6, "alongChannels": true, "channelSpacing": [96, 256] },
"dams": { "enabled": false, "maxRaise": 4 },
"freeboard": [1, 3], "climateDrawdown": 6,
"freeboard": [1, 3], "dryDrawdown": 6,
"shore": { "roundness": 0.5, "shelf": 6, "taper": 14, "maxDepth": 8 },
"materials": {}, "fluid": "water"
},
@@ -263,7 +263,7 @@ public class IrisHydrologyTerrainSourceTest {
Pond swamp = floorPond(fixture, settings, column);
spires.setHydrologyPolicy(new IrisHydrologyPolicy().setPondDensity(16D).setWetness(new IrisHydrologyWetness().setMin(1D)));
Pond kept = floorPond(fixture, settings, column);
int drawdown = settings.ponds().climateDrawdown();
int drawdown = settings.ponds().dryDrawdown();
assertEquals((int) Math.floor(kept.spillHeight()) - 1, kept.level());
assertEquals(kept.level() - Math.round(drawdown * 0.3f), swamp.level());
assertEquals(kept.level() - Math.round(drawdown * 0.85f), dry.level());
@@ -98,7 +98,7 @@ public class ConfluenceIncisionTest {
}
String label = "seed " + seed + " foot " + foot + " " + major;
assertTrue(label + " is cut " + cut + " into the wall", cut <= MAX_WALL_CUT);
double tallestFall = WALL_HEIGHT / 2D + major.tier().waterfallMinimumDrop() + (seed == SEED ? 0D : OTHER_SEED_FALL_MARGIN);
double tallestFall = WALL_HEIGHT / 2D + major.tier().waterfallMinDrop() + (seed == SEED ? 0D : OTHER_SEED_FALL_MARGIN);
assertTrue(label + " falls " + largest + " blocks at once down a " + WALL_HEIGHT + "-block wall", largest <= tallestFall);
totalCut += cut;
cases++;
@@ -98,9 +98,9 @@ final class PlannedScene {
new IrisHydrologyTier().setName("river").setMinCatchment(5000D).setHalfWidth(new KList<>(2.5D, 9D)).setWidthFactor(1.2D)
.setDepthRatio(0.45D).setInset(2).setBankBand(32),
new IrisHydrologyTier().setName("major").setMinCatchment(200000D).setHalfWidth(new KList<>(9D, 18D)).setWidthFactor(1.2D)
.setDepthRatio(0.5D).setInset(3).setBankBand(48).setWaterfallMinimumDrop(8)));
.setDepthRatio(0.5D).setInset(3).setBankBand(48).setWaterfallMinDrop(8)));
config.getPonds().setFreeboard(new KList<>(1, 2));
config.getPonds().setClimateDrawdown(3);
config.getPonds().setDryDrawdown(3);
config.getPonds().getSeeded().setDensity(10D).setRadius(new KList<>(6, 22)).setMaxSlope(0.7D).setChannelSpacing(new KList<>(80, 192));
config.getPonds().getShore().setRoundness(0.5D).setShelf(6).setTaper(14).setMaxDepth(8);
return config;
@@ -339,7 +339,7 @@ public class PlannedSceneTest {
}
zone[point] = along <= OUTLET_LENGTH;
}
ReachStyle[] style = ReachShaper.styles(reach.grade(), new boolean[zone.length], zone, reach.tier().waterfallMinimumDrop(), seaLevel, reach.tier().stepHeight());
ReachStyle[] style = ReachShaper.styles(reach.grade(), new boolean[zone.length], zone, reach.tier().waterfallMinDrop(), seaLevel, reach.tier().stepHeight());
return new Reach(reach.id(), reach.tier(), reach.downstreamId(), reach.xs(), reach.zs(), reach.grade(), reach.halfWidth(), reach.depth(),
style, reach.catchment());
}
@@ -365,7 +365,7 @@ public class PlannedSceneTest {
halfWidths[point] = halfWidth;
depths[point] = tier.depth(halfWidth);
int drop = point == 0 ? 0 : grades[point - 1] - grades[point];
styles[point] = drop >= tier.waterfallMinimumDrop() ? ReachStyle.WATERFALL
styles[point] = drop >= tier.waterfallMinDrop() ? ReachStyle.WATERFALL
: drop >= 2 ? ReachStyle.CASCADE : drop == 1 ? ReachStyle.RIFFLE : ReachStyle.RUN;
}
return new Reach(id, tier, downstreamId, xs, zs, grades, halfWidths, depths, styles, 1000f);
@@ -1204,7 +1204,7 @@ public class WindowPlannerTest {
int last = feeder.xs().length - 1;
int drop = feeder.grade()[last] - downstream.grade()[0];
assertTrue(feeder + " meets " + downstream + " across the window line with a drop of " + drop,
drop >= 0 && drop < downstream.tier().waterfallMinimumDrop());
drop >= 0 && drop < downstream.tier().waterfallMinDrop());
}
assertTrue("reaches near the window line " + westOwned.size() + " + " + eastOwned.size(), westOwned.size() + eastOwned.size() >= 3);
assertTrue("reach links between the two windows' plans " + links, links >= 1);
@@ -898,7 +898,7 @@ public class ChunkWaterRasterTest {
public void clampedSeamDropsAreStyledAsFalls() {
HydrologyTier narrow = tier("river", 2f, 0.5f, 4, IrisBankStyle.SMOOTH);
HydrologyTier wide = tier("river", 3f, 0.5f, 4, IrisBankStyle.SMOOTH);
assertEquals(6, narrow.waterfallMinimumDrop());
assertEquals(6, narrow.waterfallMinDrop());
Reach low = line(232L, wide, 0L, 504f, 200f, 600f, 200f, (x, z) -> 62);
Reach hanging = line(231L, narrow, low.id(), 440f, 200f, 504f, 200f, (x, z) -> 70);
Scene falls = new Scene(settings(new IrisHydrology()), (x, z) -> 90).reach(hanging).reach(low);
@@ -1003,7 +1003,7 @@ public class ChunkWaterRasterTest {
for (int point = 0; point < zone.length; point++) {
zone[point] = drawn.xs()[point] - drawn.xs()[0] <= 8f;
}
ReachStyle[] style = ReachShaper.styles(drawn.grade(), new boolean[zone.length], zone, narrow.waterfallMinimumDrop(), SEA_LEVEL, narrow.stepHeight());
ReachStyle[] style = ReachShaper.styles(drawn.grade(), new boolean[zone.length], zone, narrow.waterfallMinDrop(), SEA_LEVEL, narrow.stepHeight());
assertEquals("the last outlet zone point steps down one block, shown as two", ReachStyle.CASCADE, style[4]);
assertTrue("the step lies at the end of the outlet zone", zone[4] && !zone[5]);
Reach outlet = new Reach(drawn.id(), narrow, drawn.downstreamId(), drawn.xs(), drawn.zs(), drawn.grade(), drawn.halfWidth(), drawn.depth(),
@@ -2526,7 +2526,7 @@ public class ChunkWaterRasterTest {
halfWidth[point] = tier.minHalfWidth();
depth[point] = tier.depth(tier.minHalfWidth());
int drop = point == 0 ? 0 : grades[point - 1] - grades[point];
style[point] = drop >= tier.waterfallMinimumDrop() ? ReachStyle.WATERFALL
style[point] = drop >= tier.waterfallMinDrop() ? ReachStyle.WATERFALL
: drop >= 2 ? ReachStyle.CASCADE : drop == 1 ? ReachStyle.RIFFLE : ReachStyle.RUN;
}
return new Reach(id, tier, downstreamId, xs, zs, grades, halfWidth, depth, style, 1000f);
@@ -509,7 +509,7 @@ public class PondPlannerTest {
Pond dry = single(plan(settings, new Terrain(terrain, 0f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of()));
Pond damp = single(plan(settings, new Terrain(terrain, 0.5f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of()));
assertEquals(wet.id(), dry.id());
assertEquals(settings.ponds().climateDrawdown(), wet.level() - dry.level());
assertEquals(settings.ponds().dryDrawdown(), wet.level() - dry.level());
assertTrue(damp.level() < wet.level() && damp.level() > dry.level());
assertContained(dry, terrain);
}
@@ -518,7 +518,7 @@ public class PondPlannerTest {
public void drawdownFollowsClimateDryness() {
HydrologySettings settings = settings(PondPlannerTest::naturalOnly, MIN_Y, MAX_Y);
DoubleBinaryOperator terrain = bowl(256, 256, 60, 100, 12, 0.1);
int drawdown = settings.ponds().climateDrawdown();
int drawdown = settings.ponds().dryDrawdown();
Pond full = single(plan(settings, new Terrain(terrain, 1f, ALLOW_ALL, null, MIN_Y, MAX_Y), 0, 0, 64, 64, null, List.of()));
Pond wetZone = single(plan(settings, new Terrain(terrain, 0.5f, ALLOW_ALL, null, MIN_Y, MAX_Y).climateZoned((x, z) -> 1D),
0, 0, 64, 64, null, List.of()));
@@ -75,7 +75,7 @@ public class ReachShaperTest {
for (Reach reach : spread.reaches()) {
Reach twin = steppedById.get(reach.id());
assertNotNull(twin);
int fall = reach.tier().waterfallMinimumDrop();
int fall = reach.tier().waterfallMinDrop();
int junction = twin.downstreamId() == 0L ? Integer.MIN_VALUE : twin.grade()[twin.grade().length - 1];
assertTrue("trial " + trial + " " + reach + " gained a waterfall against " + Arrays.toString(twin.grade()),
dropsAbove(reach, junction, fall, Integer.MAX_VALUE) <= dropsAbove(twin, Integer.MIN_VALUE, fall, Integer.MAX_VALUE));
@@ -231,7 +231,7 @@ public class ReachShaperTest {
public void dropAtWaterfallMinimumBecomesWaterfall() {
HydrologySettings cascading = settings(config -> {
});
int minimum = cascading.tiers().get(1).waterfallMinimumDrop();
int minimum = cascading.tiers().get(1).waterfallMinDrop();
List<Drop> waterfall = drops(cascading, steppedValley(minimum));
assertEquals("drops " + waterfall, 1, waterfall.size());
assertEquals(minimum, waterfall.get(0).size());
@@ -294,9 +294,9 @@ public class ReachShaperTest {
int[] grade = steep.grade;
for (int index = 1; index < grade.length; index++) {
int drop = grade[index - 1] - grade[index];
assertTrue(Arrays.toString(grade), drop >= 0 && drop < tier.waterfallMinimumDrop());
assertTrue(Arrays.toString(grade), drop >= 0 && drop < tier.waterfallMinDrop());
}
assertTrue(Arrays.toString(grade), grade[0] > (int) ground[0] - tier.inset() - tier.waterfallMinimumDrop());
assertTrue(Arrays.toString(grade), grade[0] > (int) ground[0] - tier.inset() - tier.waterfallMinDrop());
assertEquals((int) ground[ground.length - 1] - tier.inset(), grade[grade.length - 1]);
}
@@ -336,9 +336,9 @@ public class ReachShaperTest {
assertTrue(label + " pools " + pools, pools >= 3);
assertTrue(label + " drops " + drops, drops <= Math.ceil(STATION * last / StepPools.POOL_MIN));
int[] spread = graded(withSteps(tier, false, tier.waterfallMinimumDrop()), ground);
int[] spread = graded(withSteps(tier, false, tier.waterfallMinDrop()), ground);
for (int index = 1; index < spread.length; index++) {
assertTrue("spread " + Arrays.toString(spread), spread[index - 1] - spread[index] < tier.waterfallMinimumDrop());
assertTrue("spread " + Arrays.toString(spread), spread[index - 1] - spread[index] < tier.waterfallMinDrop());
}
}
@@ -357,7 +357,7 @@ public class ReachShaperTest {
for (int index = 1; index < grade.length; index++) {
int drop = grade[index - 1] - grade[index];
assertTrue(label, drop >= 0);
if (drop >= tier.waterfallMinimumDrop()) {
if (drop >= tier.waterfallMinDrop()) {
falls++;
foot = index;
}
@@ -574,7 +574,7 @@ public class ReachShaperTest {
for (Reach reach : shaped.reaches()) {
for (int index = 1; index < reach.xs().length; index++) {
if (reach.xs()[index] >= WINDOW_MIN_X && reach.xs()[index] <= WINDOW_MAX_X
&& reach.grade()[index - 1] - reach.grade()[index] >= reach.tier().waterfallMinimumDrop()) {
&& reach.grade()[index - 1] - reach.grade()[index] >= reach.tier().waterfallMinDrop()) {
return Math.toDegrees(Math.atan2(Math.abs(reach.zs()[index] - reach.zs()[index - 1]), Math.abs(reach.xs()[index] - reach.xs()[index - 1])));
}
}
@@ -675,7 +675,7 @@ public class ReachShaperTest {
draft.catchments = new float[points];
Arrays.fill(draft.catchments, 40000f);
draft.outletZone = new boolean[points];
draft.style = ReachShaper.styles(draft.grade, draft.ocean, draft.outletZone, tier.waterfallMinimumDrop(), SEA_LEVEL, 2);
draft.style = ReachShaper.styles(draft.grade, draft.ocean, draft.outletZone, tier.waterfallMinDrop(), SEA_LEVEL, 2);
ReachShaper.widths(draft, 0f, 0f);
float law = tier.halfWidth(40000f);
assertEquals("the foot flares", 1.5f * law, draft.halfWidth[foot], 1e-3f);
@@ -687,7 +687,7 @@ public class ReachShaperTest {
for (int point = 0; point < mouth.length; point++) {
mouth[point] = reach.style()[point] == ReachStyle.MOUTH;
}
return ReachShaper.plungeFlare(reach.grade(), reach.style(), mouth, ReachShaper.distances(reach.xs(), reach.zs()), 0f, reach.tier().waterfallMinimumDrop());
return ReachShaper.plungeFlare(reach.grade(), reach.style(), mouth, ReachShaper.distances(reach.xs(), reach.zs()), 0f, reach.tier().waterfallMinDrop());
}
private static float channelMaximum(Reach reach) {
@@ -730,7 +730,7 @@ public class ReachShaperTest {
private static int footOf(Reach reach) {
for (int point = 1; point < reach.xs().length; point++) {
if (reach.grade()[point - 1] - reach.grade()[point] >= reach.tier().waterfallMinimumDrop()) {
if (reach.grade()[point - 1] - reach.grade()[point] >= reach.tier().waterfallMinDrop()) {
return point;
}
}
@@ -745,7 +745,7 @@ public class ReachShaperTest {
if (reach.xs()[index] < WINDOW_MIN_X || reach.xs()[index] > WINDOW_MAX_X) {
continue;
}
if (reach.grade()[index - 1] - reach.grade()[index] >= reach.tier().waterfallMinimumDrop()) {
if (reach.grade()[index - 1] - reach.grade()[index] >= reach.tier().waterfallMinDrop()) {
falls++;
midpoint = (reach.xs()[index - 1] + reach.xs()[index]) / 2f;
}
@@ -2279,7 +2279,7 @@ public class ReachShaperTest {
for (int index = 1; index <= entry && fall < 0; index++) {
fall = reach.grade()[index] == SEA_LEVEL ? index : -1;
}
if (reach.grade()[fall - 1] - SEA_LEVEL >= reach.tier().waterfallMinimumDrop()) {
if (reach.grade()[fall - 1] - SEA_LEVEL >= reach.tier().waterfallMinDrop()) {
falls++;
int lip = fall == entry ? entry - 1 : fall;
assertEquals(reach.toString(), ReachStyle.WATERFALL, reach.style()[lip]);
@@ -3093,13 +3093,13 @@ public class ReachShaperTest {
private static void ungrouped(IrisHydrology config) {
for (IrisHydrologyTier tier : config.getTiers()) {
tier.setCascades(false);
tier.setWaterfallMinimumDrop(2);
tier.setWaterfallMinDrop(2);
}
}
private static HydrologyTier withSteps(HydrologyTier tier, boolean cascades, int waterfallMinimumDrop) {
private static HydrologyTier withSteps(HydrologyTier tier, boolean cascades, int waterfallMinDrop) {
return new HydrologyTier(tier.name(), tier.minCatchment(), tier.minHalfWidth(), tier.maxHalfWidth(), tier.widthFactor(), tier.depthRatio(),
tier.inset(), cascades, waterfallMinimumDrop, 2, tier.bankBand(), tier.bankStyle(), tier.estuary(), tier.delta(), tier.materials(),
tier.inset(), cascades, waterfallMinDrop, 2, tier.bankBand(), tier.bankStyle(), tier.estuary(), tier.delta(), tier.materials(),
tier.fluid(), tier.decorators());
}
@@ -24,6 +24,7 @@ import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.util.stream.ProceduralStream;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.BlockPosition;
@@ -54,7 +55,7 @@ public class FloatingObjectPlacementTransactionTest {
public void canopyCommitRechecksSolidsAndSkipsAssociatedMetadata() {
IslandObjectPlacer delegate = createPlacer(true);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate,
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false);
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT);
NativeBlockState canopy = mock(NativeBlockState.class);
NativeBlockState trunk = mock(NativeBlockState.class);
when(trunk.isSolid()).thenReturn(true);
@@ -76,7 +77,7 @@ public class FloatingObjectPlacementTransactionTest {
public void unsupportedFinalTerrainRejectsBlocksTilesAndMarkersTogether() {
IslandObjectPlacer delegate = createPlacer(false);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate,
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false);
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT);
NativeBlockState first = mock(NativeBlockState.class);
NativeBlockState second = mock(NativeBlockState.class);
TileData tile = mock(TileData.class);
@@ -103,7 +104,7 @@ public class FloatingObjectPlacementTransactionTest {
public void supportedNeighborChunkCommitsBlocksTilesAndMarkers() {
IslandObjectPlacer delegate = createPlacer(true);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate,
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false);
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT);
NativeBlockState first = mock(NativeBlockState.class);
NativeBlockState second = mock(NativeBlockState.class);
TileData tile = mock(TileData.class);
@@ -149,7 +150,7 @@ public class FloatingObjectPlacementTransactionTest {
NativeBlockState state = mock(NativeBlockState.class);
when(state.key()).thenReturn("minecraft:oak_log");
ObjectContinuationBundle.PlacementKey key = new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 7);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, key, false);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.KEEP_OUT);
transaction.set(15, 101, 8, state);
transaction.set(16, 101, 8, state);
transaction.setData(16, 101, 8, "floating-tree@7");
@@ -166,7 +167,7 @@ public class FloatingObjectPlacementTransactionTest {
@Test
@SuppressWarnings("unchecked")
public void floatingObjectsKeepSolidBlocksOutOfRiverWaterUnlessTheyEnterWater() {
public void floatingObjectsFollowTheirWaterRuleInRiverWater() {
IObjectPlacer delegate = mock(IObjectPlacer.class);
Engine engine = mock(Engine.class);
IrisComplex complex = mock(IrisComplex.class);
@@ -196,17 +197,25 @@ public class FloatingObjectPlacementTransactionTest {
when(stone.isSolid()).thenReturn(true);
ObjectContinuationBundle.PlacementKey key = new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0);
FloatingObjectPlacementTransaction land = new FloatingObjectPlacementTransaction(delegate, key, false);
FloatingObjectPlacementTransaction land = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.KEEP_OUT);
land.set(3, 7, 3, stone);
land.set(3, 10, 3, stone);
assertEquals(FloatingObjectPlacementTransaction.CommitResult.COMMITTED, land.commit());
verify(delegate, never()).set(3, 7, 3, stone);
verify(delegate).set(3, 10, 3, stone);
FloatingObjectPlacementTransaction water = new FloatingObjectPlacementTransaction(delegate, key, true);
FloatingObjectPlacementTransaction water = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.ENTERS_WATER);
water.set(3, 7, 3, stone);
assertEquals(FloatingObjectPlacementTransaction.CommitResult.COMMITTED, water.commit());
verify(delegate).set(3, 7, 3, stone);
NativeBlockState air = mock(NativeBlockState.class);
FloatingObjectPlacementTransaction forced = new FloatingObjectPlacementTransaction(delegate, key, ObjectWaterRule.FORCED);
forced.set(3, 8, 3, stone);
forced.set(3, 6, 3, air);
assertEquals(FloatingObjectPlacementTransaction.CommitResult.COMMITTED, forced.commit());
verify(delegate).set(3, 8, 3, stone);
verify(delegate).set(3, 6, 3, air);
}
private static int local(Object coordinate) {
@@ -6,6 +6,7 @@ import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.structure.object.ObjectPlaceMode;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.structure.placement.IrisStructure;
import art.arcane.iris.structure.placement.IrisStructurePlacement;
import art.arcane.iris.structure.object.IrisObject;
@@ -26,11 +27,15 @@ import org.junit.Rule;
import org.junit.Test;
import org.mockito.InOrder;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.intThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.calls;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -116,12 +121,36 @@ public class IrisStructureComponentCarveWaterTest {
component.placePieces(writer, placement, structure, slab(), new RNG(3L));
InOrder order = inOrder(writer);
order.verify(writer).beginObjectPlacement(false);
order.verify(writer).beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
order.verify(writer, calls(1)).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class));
order.verify(writer).endObjectPlacement(anyInt());
order.verify(writer).beginObjectPlacement(true);
order.verify(writer).endObjectPlacement();
order.verify(writer).beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
order.verify(writer, calls(1)).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class));
order.verify(writer).endObjectPlacement(anyInt());
order.verify(writer).endObjectPlacement();
}
@Test
public void aPieceAtWorldYMinusOneKeepsItsExplicitHeight() {
KList<PlacedStructurePiece> pieces = slabAt(-1);
IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE);
component.placePieces(writer, new IrisStructurePlacement(), structure, pieces, new RNG(3L));
verify(writer, atLeastOnce()).set(anyInt(), eq(63), anyInt(), any(NativeBlockState.class));
verify(writer, never()).set(anyInt(), intThat(y -> y != 63), anyInt(), any(NativeBlockState.class));
}
@Test
public void aFailureInsidePlacePiecesStillEndsTheObjectPlacement() {
IllegalStateException failure = new IllegalStateException("piece failed");
doThrow(failure).when(writer).set(anyInt(), anyInt(), anyInt(), any(NativeBlockState.class));
IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE);
assertEquals(1, component.placePieces(writer, new IrisStructurePlacement(), structure, slab(), new RNG(3L)));
InOrder order = inOrder(writer);
order.verify(writer).beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
order.verify(writer).endObjectPlacement();
}
private void assertRiverKept() {
@@ -154,6 +183,10 @@ public class IrisStructureComponentCarveWaterTest {
}
private static KList<PlacedStructurePiece> slab() {
return slabAt(-4);
}
private static KList<PlacedStructurePiece> slabAt(int y) {
NativeBlockState stone = mock(NativeBlockState.class);
when(stone.isSolid()).thenReturn(true);
when(stone.key()).thenReturn("minecraft:stone");
@@ -164,7 +197,7 @@ public class IrisStructureComponentCarveWaterTest {
object.setUnsigned(x, 0, z, stone);
}
}
return new KList<>(new PlacedStructurePiece(null, object, 4, -4, 1, IrisObjectRotation.of(0, 0, 0),
0, -4, 0, 8, -4, 2));
return new KList<>(new PlacedStructurePiece(null, object, 4, y, 1, IrisObjectRotation.of(0, 0, 0),
0, y, 0, 8, y, 2));
}
}
@@ -1,84 +1,309 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.structure.nativegen.NativeStructureSuppression;
import art.arcane.iris.structure.object.HydrologyWaterFixture;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.structure.object.IrisObjectRotation;
import art.arcane.iris.structure.object.ObjectPlaceMode;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.structure.placement.IrisStructure;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.structure.placement.IrisStructurePlacement;
import art.arcane.iris.structure.placement.PlacedStructurePiece;
import art.arcane.iris.testsupport.PlatformBinding;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterSlice;
import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class IrisStructureComponentWaterTest {
private static final int X = 4;
private static final int Z = 4;
@Rule
public final PlatformBinding platform = PlatformBinding.mockPlatform();
private final HydrologyWaterFixture world = new HydrologyWaterFixture();
private final List<Write> writes = new ArrayList<>();
private final Map<Integer, Matter> sections = new HashMap<>();
private IrisSettings previousSettings;
private MantleWriter writer;
private IrisStructureComponent component;
@Test
public void forcedSinglePieceStructureStaysOutOfRiverWater() {
world.water(WaterRole.CHANNEL, 9, 13);
HydrologyWaterFixture.Placer placer = world.placer();
IrisObject object = HydrologyWaterFixture.raft();
IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, false);
@Before
@SuppressWarnings("unchecked")
public void setUp() {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
Engine engine = world.data().getEngine();
IrisComplex complex = world.complex();
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
ChunkWaterRaster raster = mock(ChunkWaterRaster.class);
ProceduralStream<Integer> floors = mock(ProceduralStream.class);
when(floors.get(anyDouble(), anyDouble())).thenAnswer(call -> world.floorAt(block(call.getArgument(0)), block(call.getArgument(1))));
when(complex.getRoundedHeighteightStream()).thenReturn(floors);
when(complex.getHydrologyRuntime()).thenReturn(runtime);
when(runtime.enabled()).thenReturn(true);
when(runtime.raster(anyInt(), anyInt())).thenReturn(raster);
when(raster.role(anyInt(), anyInt())).thenAnswer(call -> complex.getWaterRoleStream().get((double) call.<Integer>getArgument(0), (double) call.<Integer>getArgument(1)));
when(raster.waterHead(anyInt(), anyInt())).thenAnswer(call -> world.headAt(call.getArgument(0), call.getArgument(1)));
when(raster.terrainHeight(anyInt(), anyInt())).thenAnswer(call -> world.floorAt(call.getArgument(0), call.getArgument(1)));
EngineMantle engineMantle = mock(EngineMantle.class);
when(engineMantle.getEngine()).thenReturn(engine);
when(engineMantle.getComplex()).thenReturn(complex);
when(engineMantle.getData()).thenReturn(world.data());
HydrologyWaterFixture.Placer heights = world.placer();
when(engineMantle.getHighest(anyInt(), anyInt(), any(), anyBoolean())).thenAnswer(call -> heights.getHighest(call.getArgument(0), call.getArgument(1), world.data(), call.<Boolean>getArgument(3)));
Mantle<Matter> mantle = mock(Mantle.class);
MantleChunk<Matter> chunk = mock(MantleChunk.class);
when(mantle.getWorldHeight()).thenReturn(256);
when(mantle.getChunk(0, 0)).thenReturn(chunk);
when(mantle.useChunk(0, 0)).thenAnswer(call -> chunk.use());
when(chunk.use()).thenReturn(chunk);
when(chunk.getOrCreate(anyInt())).thenAnswer(call -> section(call.getArgument(0)));
writer = new MantleWriter(engineMantle, mantle, 0, 0, 0, false);
component = new IrisStructureComponent(engineMantle);
}
assertTrue(config.isForcePlace());
assertEquals(-1, object.place(0, 0, placer, config, new RNG(7L), world.data()));
assertTrue(placer.writes().isEmpty());
@After
public void tearDown() {
writer.close();
IrisSettings.settings = previousSettings;
}
@Test
public void forcedSinglePieceStructureTurnedTowardsTheSlopeStaysOutOfRiverWater() {
public void aForcedPieceFullyInsideARiverWritesEveryBlock() {
world.water(WaterRole.CHANNEL, 9, 13);
int failed = placeSinglePiece(new IrisStructurePlacement());
assertEquals(0, failed);
assertEquals("every block of the raft lands", 10, writes.size());
assertEquals(world.headAt(X, Z), lowestWriteAt(X, Z));
assertEquals(world.headAt(X - 1, Z - 1), lowestWriteAt(X - 1, Z - 1));
}
@Test
public void aForcedPieceTurnedTowardsTheSlopeWritesThroughTheRiver() {
world.water(WaterRole.CHANNEL, 9, 13);
@SuppressWarnings("unchecked")
ProceduralStream<Double> heights = mock(ProceduralStream.class);
when(heights.get(anyDouble(), anyDouble())).thenAnswer(invocation -> (double) world.floorAt(
(int) Math.floor((Double) invocation.getArgument(0)), (int) Math.floor((Double) invocation.getArgument(1))));
block(invocation.getArgument(0)), block(invocation.getArgument(1))));
when(world.complex().getHeightStream()).thenReturn(heights);
HydrologyWaterFixture.Placer placer = world.placer();
IrisObject object = HydrologyWaterFixture.raft();
IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, false);
IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT);
config.setRotateTowardsSlope(true);
assertEquals(-1, object.place(0, 0, placer, config, new RNG(7L), world.data()));
assertTrue(placer.writes().isEmpty());
writer.beginObjectPlacement(config.waterRule());
int result = object.place(X, Z, writer, config, new RNG(7L), world.data());
writer.endObjectPlacement();
assertTrue(result >= 0);
assertEquals(10, writes.size());
}
@Test
public void forcedSinglePieceStructureThatAllowsWaterPlacesOnFlatRiverWater() {
public void aForcedPieceWritesAcrossWetSupportColumns() {
world.column(X + 1, Z, WaterRole.CHANNEL, 15, 19);
world.column(X - 1, Z, WaterRole.SHORE, 15, 19);
world.column(X, Z + 1, WaterRole.DAM, 15, 19);
int failed = placeSinglePiece(new IrisStructurePlacement());
assertEquals(0, failed);
int anchorLayer = lowestWriteAt(X, Z);
assertEquals(world.floorAt(X, Z), anchorLayer);
assertEquals("the river column keeps the piece's block", anchorLayer, lowestWriteAt(X + 1, Z));
}
@Test
public void replaceSourceKeepsAForcedPieceOverWaterWithoutFailingTheChunk() {
world.water(WaterRole.CHANNEL, 9, 13);
HydrologyWaterFixture.Placer placer = world.placer();
IrisObject object = HydrologyWaterFixture.raft();
IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, true);
IrisStructurePlacement placement = new IrisStructurePlacement()
.setNativeSuppression(NativeStructureSuppression.REPLACE_SOURCE);
assertTrue(config.entersWater());
assertTrue(object.place(0, 0, placer, config, new RNG(7L), world.data()) >= 0);
assertEquals(world.headAt(0, 0), placer.lowestWrite());
int failed = placeSinglePiece(placement);
assertEquals(0, failed);
assertEquals(10, writes.size());
}
@Test
public void forcedSinglePieceStructureStillPlacesOnDryLand() {
HydrologyWaterFixture.Placer placer = world.placer();
IrisObject object = HydrologyWaterFixture.raft();
IrisObjectPlacement config = IrisStructureComponent.piecePlacement(new IrisStructure(), piece(object), ObjectPlaceMode.CENTER_HEIGHT, false);
public void aForcedPieceWritesAcrossAFallWhetherOrNotItAllowsWater() {
world.water(WaterRole.CHANNEL, 9, 13);
world.column(X + 1, Z, WaterRole.CHANNEL, 9, 16);
assertTrue(object.place(0, 0, placer, config, new RNG(7L), world.data()) >= 0);
assertFalse(placer.writes().isEmpty());
assertEquals(0, placeSinglePiece(new IrisStructurePlacement()));
assertEquals(10, writes.size());
writes.clear();
assertEquals(0, placeSinglePiece(new IrisStructurePlacement().setAllowWater(true)));
assertEquals(10, writes.size());
}
@Test
public void aForcedPiecePlacesOnDryLand() {
int failed = placeSinglePiece(new IrisStructurePlacement());
assertEquals(0, failed);
assertEquals(10, writes.size());
}
@Test
public void objectsThatForcePlaceThemselvesWriteThroughUnevenWater() {
world.water(WaterRole.CHANNEL, 9, 13);
world.column(X + 1, Z, WaterRole.CHANNEL, 9, 16);
IrisObject object = HydrologyWaterFixture.raft();
IrisObjectPlacement config = new IrisObjectPlacement().setForcePlace(true);
writer.beginObjectPlacement(config.waterRule());
int result = object.place(X, Z, writer, config, new RNG(7L), world.data());
writer.endObjectPlacement();
assertTrue(result >= 0);
assertEquals("every block lands over the channel", 10, writes.size());
assertEquals(world.headAt(X, Z), lowestWriteAt(X, Z));
}
@Test
public void unforcedPiecesKeepTheVeto() {
world.water(WaterRole.CHANNEL, 9, 13);
IrisObject object = HydrologyWaterFixture.raft();
IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE);
int head = world.headAt(X, Z);
PlacedStructurePiece explicit = new PlacedStructurePiece(null, object, X, head + 1, Z, IrisObjectRotation.of(0, 0, 0),
X - 1, head, Z - 1, X + 1, head + 2, Z + 1);
assertEquals(0, component.placePieces(writer, new IrisStructurePlacement(), structure, new KList<>(explicit), new RNG(7L)));
assertFalse("the block above the water places", writes.isEmpty());
assertNoWaterOverwritten();
writes.clear();
assertEquals(0, component.placePieces(writer, new IrisStructurePlacement().setAllowWater(true), structure, new KList<>(explicit), new RNG(7L)));
assertTrue("allowWater fills the water", writes.stream().anyMatch(write -> write.y() == head));
}
@Test
public void undergroundPiecesKeepTheVeto() {
world.water(WaterRole.CHANNEL, 9, 13);
IrisObject object = HydrologyWaterFixture.raft();
int head = world.headAt(X, Z);
PlacedStructurePiece explicit = new PlacedStructurePiece(null, object, X, head + 1, Z, IrisObjectRotation.of(0, 0, 0),
X - 1, head, Z - 1, X + 1, head + 2, Z + 1);
for (ObjectPlaceMode mode : List.of(ObjectPlaceMode.ORGANIC_STILT, ObjectPlaceMode.CEILING_HANG)) {
writes.clear();
IrisStructure structure = new IrisStructure().setPlaceMode(mode);
IrisStructurePlacement placement = new IrisStructurePlacement().setUnderground(true);
assertEquals(mode.name(), 0, component.placePieces(writer, placement, structure, new KList<>(explicit), new RNG(7L)));
assertFalse(mode.name(), writes.isEmpty());
assertNoWaterOverwritten();
}
}
@Test
public void unforcedObjectsStayOffRiverWater() {
world.water(WaterRole.CHANNEL, 9, 13);
IrisObject object = HydrologyWaterFixture.raft();
int result = object.place(X, Z, writer, new IrisObjectPlacement(), new RNG(7L), world.data());
assertEquals(-1, result);
assertTrue(writes.isEmpty());
}
private int placeSinglePiece(IrisStructurePlacement placement) {
IrisObject object = HydrologyWaterFixture.raft();
IrisStructure structure = new IrisStructure().setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
return component.placePieces(writer, placement, structure, new KList<>(piece(object)), new RNG(7L));
}
private IrisStructureLocator.ResolvedPlacement resolved(IrisStructurePlacement placement) {
IrisObject object = HydrologyWaterFixture.raft();
return new IrisStructureLocator.ResolvedPlacement(placement, "test/raft", new IrisStructure(),
new KList<>(piece(object)), new RNG(7L), X, 0, Z, false);
}
private void assertNoWaterOverwritten() {
for (Write write : writes) {
WaterRole role = world.complex().getWaterRoleStream().get((double) write.x(), (double) write.z());
if (role.wet()) {
assertFalse(write + " overwrites river water",
write.y() > world.floorAt(write.x(), write.z()) && write.y() <= world.headAt(write.x(), write.z()));
}
}
}
private int lowestWriteAt(int x, int z) {
int lowest = Integer.MAX_VALUE;
for (Write write : writes) {
if (write.x() == x && write.z() == z) {
lowest = Math.min(lowest, write.y());
}
}
return lowest;
}
@SuppressWarnings("unchecked")
private Matter section(int index) {
return sections.computeIfAbsent(index, ignored -> {
Matter matter = mock(Matter.class);
MatterSlice<NativeBlockState> blocks = mock(MatterSlice.class);
doAnswer(call -> {
writes.add(new Write(call.getArgument(0), (index << 4) | call.<Integer>getArgument(1), call.getArgument(2)));
return null;
}).when(blocks).set(anyInt(), anyInt(), anyInt(), any());
when(matter.getClass(any())).thenAnswer(call -> call.getArgument(0).getClass());
doReturn(blocks).when(matter).slice(NativeBlockState.class);
doReturn(mock(MatterSlice.class)).when(matter).getSlice(Identifier.class);
return matter;
});
}
private static PlacedStructurePiece piece(IrisObject object) {
return new PlacedStructurePiece(null, object, 0, 0, 0, IrisObjectRotation.of(0, 0, 0), -1, 0, -1, 1, 2, 1);
return new PlacedStructurePiece(null, object, X, 0, Z, IrisObjectRotation.of(0, 0, 0), X - 1, 0, Z - 1, X + 1, 2, Z + 1);
}
private static int block(Object coordinate) {
return (int) Math.floor(((Number) coordinate).doubleValue());
}
private record Write(int x, int y, int z) {
}
}
@@ -0,0 +1,299 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.cave.CarvingMode;
import art.arcane.iris.generation.context.ChunkContext;
import art.arcane.iris.generation.decoration.IrisProceduralObjects;
import art.arcane.iris.generation.decoration.IrisProceduralPlacement;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.SeedManager;
import art.arcane.iris.generation.runtime.UpperDimensionContext;
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.structure.object.IObjectPlacer;
import art.arcane.iris.structure.object.IrisObject;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.stubbing.Answer;
import java.util.Arrays;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MantleObjectComponentWaterPlacementTest {
private static final Answer<Integer> PLACES = call -> 64;
private static final Answer<Integer> REJECTS = call -> -1;
private static final Answer<Integer> THROWS = call -> {
throw new IllegalArgumentException("malformed object");
};
private IrisSettings previousSettings;
@Before
public void bindSettings() {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
}
@After
public void restoreSettings() {
IrisSettings.settings = previousSettings;
}
@Test
public void acceptedSurfacePlacementIsRecordedThenEnded() {
Fixture fixture = new Fixture(PLACES);
fixture.biome.setObjects(new KList<>(fixture.surfacePlacement()));
fixture.generate();
fixture.assertRecordedThenEnded();
}
@Test
public void rejectedSurfacePlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(REJECTS);
fixture.biome.setObjects(new KList<>(fixture.surfacePlacement()));
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void thrownSurfacePlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(THROWS);
fixture.biome.setObjects(new KList<>(fixture.surfacePlacement()));
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void rejectedCavePlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(REJECTS);
fixture.biome.setObjects(new KList<>(fixture.cavePlacement()));
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void thrownCavePlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(THROWS);
fixture.biome.setObjects(new KList<>(fixture.cavePlacement()));
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void proceduralPlacementOutsideTheTransitionFootprintEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(PLACES);
fixture.biome.setProceduralObjects(fixture.proceduralObjects());
when(fixture.complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(false);
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void rejectedProceduralPlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(REJECTS);
fixture.biome.setProceduralObjects(fixture.proceduralObjects());
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void thrownProceduralPlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(THROWS);
fixture.biome.setProceduralObjects(fixture.proceduralObjects());
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void rejectedUpperPlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(REJECTS);
fixture.upperObjects();
fixture.generate();
fixture.assertEndedUnrecorded();
}
@Test
public void thrownUpperPlacementEndsWithoutBeingRecorded() {
Fixture fixture = new Fixture(THROWS);
fixture.upperObjects();
fixture.generate();
fixture.assertEndedUnrecorded();
}
private static final class Fixture {
private final IrisBiome biome = new IrisBiome();
private final IrisComplex complex = mock(IrisComplex.class);
private final IrisObject object = mock(IrisObject.class);
private final Engine engine = mock(Engine.class);
private final IrisDimension dimension = mock(IrisDimension.class);
private final ObjectPassPlacer placer = mock(ObjectPassPlacer.class);
private final ChunkContext context = mock(ChunkContext.class);
private final MantleObjectComponent component;
@SuppressWarnings("unchecked")
private Fixture(Answer<Integer> placement) {
when(dimension.getAllRegions(any())).thenReturn(new KList<>());
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>());
when(engine.getDimension()).thenReturn(dimension);
when(engine.getSeedManager()).thenReturn(mock(SeedManager.class));
when(engine.getHeight()).thenReturn(256);
when(engine.getComplex()).thenReturn(complex);
EngineMantle engineMantle = mock(EngineMantle.class);
when(engineMantle.getEngine()).thenReturn(engine);
when(engineMantle.getData()).thenReturn(mock(IrisData.class));
when(engineMantle.getComplex()).thenReturn(complex);
when(engineMantle.trueHeight(anyInt(), anyInt())).thenReturn(120);
when(object.getLoadKey()).thenReturn("trees/water");
when(object.getW()).thenReturn(1);
when(object.getH()).thenReturn(1);
when(object.getD()).thenReturn(1);
doAnswer(placement).when(object).place(anyInt(), anyInt(), any(IObjectPlacer.class), any(IrisObjectPlacement.class),
any(RNG.class), any(), any(), any());
doAnswer(placement).when(object).place(anyInt(), anyInt(), anyInt(), any(IObjectPlacer.class), any(IrisObjectPlacement.class),
any(RNG.class), any(), any(), any());
biome.setLoadKey("water-biome");
IrisRegion region = new IrisRegion();
region.setLoadKey("water-region");
ProceduralStream<IrisRegion> regions = mock(ProceduralStream.class);
when(regions.get(anyDouble(), anyDouble())).thenReturn(region);
ProceduralStream<IrisBiome> biomes = mock(ProceduralStream.class);
when(biomes.get(anyDouble(), anyDouble())).thenReturn(biome);
ProceduralStream<Integer> heights = mock(ProceduralStream.class);
when(heights.get(anyDouble(), anyDouble())).thenReturn(64);
when(complex.allowsNewGenerationChunk(anyInt(), anyInt())).thenReturn(true);
when(complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(true);
when(complex.getRegionStream()).thenReturn(regions);
when(complex.getTrueBiomeStream()).thenReturn(biomes);
when(complex.getRoundedHeighteightStream()).thenReturn(heights);
when(context.getComplex()).thenReturn(complex);
when(placer.getEngine()).thenReturn(engine);
when(placer.getCarvedColumn(anyInt(), anyInt(), anyInt())).thenAnswer(call -> {
byte[] column = new byte[call.<Integer>getArgument(2)];
Arrays.fill(column, 20, 28, (byte) 1);
return column;
});
when(placer.getDataIfPresent(anyInt(), anyInt(), anyInt(), eq(MatterCavern.class)))
.thenReturn(new MatterCavern(true, "", (byte) 0));
component = new MantleObjectComponent(engineMantle);
}
private IrisObjectPlacement surfacePlacement() {
IrisObjectPlacement placement = placement(CarvingMode.SURFACE_ONLY);
when(placement.getDensity(any(RNG.class), anyDouble(), anyDouble(), any())).thenReturn(1);
when(placement.getObject(any(), any(RNG.class))).thenReturn(object);
return placement;
}
private IrisObjectPlacement cavePlacement() {
IrisObjectPlacement placement = placement(CarvingMode.CARVING_ONLY);
when(placement.getDensity(any(RNG.class), anyDouble(), anyDouble(), any())).thenReturn(1);
when(placement.getObject(any(), any(RNG.class))).thenReturn(object);
return placement;
}
private IrisProceduralObjects proceduralObjects() {
IrisObjectPlacement placement = placement(CarvingMode.SURFACE_ONLY);
IrisProceduralPlacement procedural = mock(IrisProceduralPlacement.class);
when(procedural.getChance()).thenReturn(2D);
when(procedural.getName()).thenReturn("water-procedural");
when(procedural.getDensity()).thenReturn(1);
when(procedural.asPlacement()).thenReturn(placement);
when(procedural.getVariantObject(any(), any(), any())).thenReturn(object);
IrisProceduralObjects objects = mock(IrisProceduralObjects.class);
when(objects.isEmpty()).thenReturn(false);
when(objects.getAllPlacements()).thenReturn(new KList<>(procedural));
return objects;
}
private void upperObjects() {
IrisObjectPlacement forced = placement(CarvingMode.ANYWHERE);
IrisObjectPlacement source = placement(CarvingMode.SURFACE_ONLY);
when(source.getDensity(any(RNG.class), anyDouble(), anyDouble(), any())).thenReturn(1);
when(source.getObject(any(UpperDimensionContext.class), any(RNG.class))).thenReturn(object);
when(source.toPlacement(anyString())).thenReturn(forced);
IrisBiome upperBiome = new IrisBiome();
upperBiome.setLoadKey("upper-biome");
upperBiome.setObjects(new KList<>(source));
UpperDimensionContext upper = mock(UpperDimensionContext.class);
when(upper.getUpperBiome(anyInt(), anyInt())).thenReturn(upperBiome);
when(upper.getDimension()).thenReturn(dimension);
when(upper.getEffectiveSurfaceY(anyInt(), anyInt())).thenReturn(64);
when(engine.getUpperContext()).thenReturn(upper);
when(dimension.isUpperDimensionObjects()).thenReturn(true);
}
private IrisObjectPlacement placement(CarvingMode carving) {
IrisObjectPlacement placement = mock(IrisObjectPlacement.class);
when(placement.getChance()).thenReturn(2D);
when(placement.getCarvingSupport()).thenReturn(carving);
when(placement.getPlace()).thenReturn(new KList<>("trees/water"));
when(placement.getAllowedCollisions()).thenReturn(new KList<>());
when(placement.getForbiddenCollisions()).thenReturn(new KList<>());
when(placement.scaleObject(any(RNG.class), any(), any())).thenReturn(object);
when(placement.waterRule()).thenReturn(ObjectWaterRule.ENTERS_WATER);
return placement;
}
private void generate() {
component.generateOrigin(placer, 0, 0, context);
}
private void assertEndedUnrecorded() {
InOrder order = inOrder(placer);
order.verify(placer).beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
order.verify(placer).endObjectPlacement();
verify(placer, never()).recordObjectPlacement(anyInt());
}
private void assertRecordedThenEnded() {
InOrder order = inOrder(placer);
order.verify(placer).beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
order.verify(placer).recordObjectPlacement(anyInt());
order.verify(placer).endObjectPlacement();
}
}
}
@@ -8,6 +8,7 @@ import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.testsupport.PlatformBinding;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
@@ -93,14 +94,14 @@ public class MantleWriterObjectWaterTest {
@Test
public void structurePiecesKeepOutOfRiverWaterUnlessTheyAllowIt() {
MatterCavern cavern = new MatterCavern(true, "", (byte) 3);
int land = writer.beginObjectPlacement(false);
int land = writer.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
writer.set(3, 7, 3, stone);
writer.set(3, 8, 3, air);
writer.setData(3, 6, 3, cavern);
writer.set(3, 5, 3, stone);
writer.set(3, 10, 3, stone);
writer.set(8, 7, 8, stone);
writer.endObjectPlacement(land);
writer.endObjectPlacement();
verify(blocks, never()).set(3, 7, 3, stone);
verify(blocks, never()).set(3, 8, 3, air);
@@ -109,19 +110,33 @@ public class MantleWriterObjectWaterTest {
verify(blocks).set(3, 10, 3, stone);
verify(blocks).set(8, 7, 8, stone);
int water = writer.beginObjectPlacement(true);
int water = writer.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
writer.set(3, 6, 3, stone);
writer.set(3, 9, 3, air);
writer.endObjectPlacement(water);
writer.endObjectPlacement();
verify(blocks).set(3, 6, 3, stone);
verify(blocks, never()).set(3, 9, 3, air);
}
@Test
public void forcedPlacementsWriteThroughRiverWater() {
MatterCavern cavern = new MatterCavern(true, "", (byte) 3);
writer.beginObjectPlacement(ObjectWaterRule.FORCED);
writer.set(3, 7, 3, stone);
writer.set(3, 8, 3, air);
writer.setData(3, 6, 3, cavern);
writer.endObjectPlacement();
verify(blocks).set(3, 7, 3, stone);
verify(blocks).set(3, 8, 3, air);
verify(caverns).set(3, 6, 3, cavern);
}
@Test
public void writesOutsideAnObjectPlacementAreNotVetoed() {
int land = writer.beginObjectPlacement(false);
writer.endObjectPlacement(land);
int land = writer.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
writer.endObjectPlacement();
writer.set(3, 7, 3, stone);
writer.set(3, 8, 3, air);
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.testsupport.KeyedBlockState;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import org.junit.Test;
@@ -21,7 +22,8 @@ public class MutationLogTest {
new ObjectDestinationTransaction.SetMutation(new ObjectDestinationTransaction.DataKey(3, 70, -2, String.class), "marker", true),
new ObjectDestinationTransaction.CustomBlockMutation(new ObjectDestinationTransaction.DataKey(-17, 4, 40, NativeBlockState.class), state, false)));
for (int index = 0; index < 100; index++) {
log.add(index, index + 1, -index, "grow" + index, (index & 1) == 0, (index & 2) == 0, (index & 4) == 0);
log.add(index, index + 1, -index, "grow" + index, (index & 1) == 0, (index & 2) == 0,
(index & 4) == 0 ? ObjectWaterRule.ENTERS_WATER : (index & 8) == 0 ? ObjectWaterRule.FORCED : ObjectWaterRule.KEEP_OUT);
}
assertEquals(102, log.size());
@@ -41,9 +43,10 @@ public class MutationLogTest {
assertFalse(log.custom(101));
assertTrue(log.canopy(98));
assertFalse(log.canopy(100));
assertFalse(log.entersWater(0));
assertTrue(log.entersWater(98));
assertFalse(log.entersWater(6));
assertEquals(ObjectWaterRule.KEEP_OUT, log.waterRule(0));
assertEquals(ObjectWaterRule.ENTERS_WATER, log.waterRule(98));
assertEquals(ObjectWaterRule.FORCED, log.waterRule(6));
assertEquals(ObjectWaterRule.KEEP_OUT, log.waterRule(14));
}
@Test
@@ -62,7 +65,7 @@ public class MutationLogTest {
int z = (index * 5) - 20;
String value = "value" + (index % 9);
boolean canopy = index % 4 == 0;
log.add(x, y, z, value, false, canopy, false);
log.add(x, y, z, value, false, canopy, ObjectWaterRule.KEEP_OUT);
if (index >= 10) {
tail.add(new ObjectDestinationTransaction.SetMutation(new ObjectDestinationTransaction.DataKey(x, y, z, String.class), value, canopy));
}
@@ -8,6 +8,7 @@ import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.spi.PlatformRegistries;
import art.arcane.iris.structure.object.IObjectPlacer;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.testsupport.PlatformLeakGuard;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
import art.arcane.iris.world.storage.matter.TileWrapper;
@@ -173,7 +174,7 @@ public class ObjectContinuationCanopyTest {
when(firstChunk.getOrCreate(0)).thenReturn(first);
when(secondChunk.getOrCreate(0)).thenReturn(second);
FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(delegate,
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), false);
new ObjectContinuationBundle.PlacementKey(ObjectContinuationBundle.Kind.FLOATING, 0, 0, 0), ObjectWaterRule.KEEP_OUT);
transaction.set(15, 5, 1, trunk);
assertTrue(transaction.beginTreeCanopy(new BlockPosition(16, 5, 1)));
transaction.set(16, 5, 1, custom);
@@ -8,6 +8,7 @@ import art.arcane.iris.integration.Identifier;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.pack.loading.ResourceLoader;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.world.entity.IrisSpawner;
import art.arcane.iris.world.storage.matter.IrisMatterContext;
import art.arcane.iris.spi.IrisPlatform;
@@ -58,17 +59,20 @@ public class ObjectContinuationTest {
public void onlyAcceptedCrossingPlacementsLeaveFutureFragments() throws Exception {
Fixture fixture = new Fixture();
ObjectDestinationTransaction source = new ObjectDestinationTransaction(fixture.writer, 0, 0);
int checkpoint = source.beginObjectPlacement(false);
int checkpoint = source.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
source.setData(1, 5, 1, "inside");
source.endObjectPlacement(checkpoint);
checkpoint = source.beginObjectPlacement(false);
source.recordObjectPlacement(checkpoint);
source.endObjectPlacement();
checkpoint = source.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
source.setData(15, 5, 1, "crossing");
source.setData(16, 5, 1, "crossing");
source.endObjectPlacement(checkpoint);
checkpoint = source.beginObjectPlacement(false);
source.recordObjectPlacement(checkpoint);
source.endObjectPlacement();
checkpoint = source.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
source.setData(32, 5, 1, "unrelated");
source.setData(48, 5, 1, "unrelated");
source.endObjectPlacement(checkpoint);
source.recordObjectPlacement(checkpoint);
source.endObjectPlacement();
source.setData(17, 5, 1, "rejected");
ObjectSourcePlan plan = source.sourcePlanSince(0);
@@ -16,6 +16,7 @@ import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.Terrain3DColumnFixtures;
import art.arcane.iris.spi.IrisPlatform;
import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.math.BlockPosition;
import art.arcane.iris.structure.object.DecayControlPlacer;
@@ -193,14 +194,14 @@ public class ObjectDestinationTransactionTest {
transaction.set(3, 9, 3, pier);
transaction.set(6, 18, 6, pier);
assertEquals("a pier keeps its blocks on the river bed and the shore", start + 2, transaction.mutationCheckpoint());
transaction.beginObjectPlacement(true);
transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
transaction.set(3, 10, 3, pier);
transaction.set(4, 15, 3, pier);
assertEquals("an underwater pier keeps its blocks in the river", start + 4, transaction.mutationCheckpoint());
transaction.set(3, 12, 3, pier);
transaction.set(3, 10, 3, vine);
assertEquals("an underwater object still keeps out of falls and open water", start + 4, transaction.mutationCheckpoint());
transaction.beginObjectPlacement(false);
transaction.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
transaction.set(3, 16, 3, vine);
transaction.set(3, 8, 3, vine);
transaction.set(6, 19, 6, vine);
@@ -239,12 +240,12 @@ public class ObjectDestinationTransactionTest {
transaction.set(3, 10, 3, boulder);
assertEquals("nothing an object places roofs or fills the slot between its water and the cliff top", start,
transaction.mutationCheckpoint());
transaction.beginObjectPlacement(true);
transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
transaction.set(3, 10, 3, boulder);
transaction.set(3, 12, 3, boulder);
assertEquals("an underwater object's solid block below the water may still sit on the slot bed", start + 1,
transaction.mutationCheckpoint());
transaction.beginObjectPlacement(false);
transaction.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
transaction.set(3, 31, 3, leaves);
transaction.set(3, 36, 3, leaves);
transaction.set(3, 33, 3, boulder);
@@ -289,12 +290,13 @@ public class ObjectDestinationTransactionTest {
setCanopy(transaction, 5, 14, 3, leaves);
assertEquals("the bed, the air above the surface and dry land keep their leaves", start + 4,
transaction.mutationCheckpoint());
int underwater = transaction.beginObjectPlacement(true);
int underwater = transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
transaction.set(3, 12, 3, leaves);
transaction.set(4, 9, 3, leaves);
assertEquals("an underwater object keeps its solid blocks in the water", underwater + 2,
transaction.mutationCheckpoint());
transaction.endObjectPlacement(underwater);
transaction.recordObjectPlacement(underwater);
transaction.endObjectPlacement();
ObjectDestinationTransaction destination = new ObjectDestinationTransaction(writer, 0, 0);
destination.apply(transaction.sourcePlanSince(start));
assertEquals("the destination replay keeps the underwater blocks", 6, destination.mutationCheckpoint());
@@ -303,7 +305,7 @@ public class ObjectDestinationTransactionTest {
}
@Test
public void onwaterRaftsAndOwnForcedObjectsKeepTheirLayerOnRiversButForcedStructurePiecesDoNot() {
public void onwaterRaftsAndForcedPlacementsKeepTheirWritesThroughReplay() {
MantleWriter writer = writer();
IrisComplex complex = mock(IrisComplex.class);
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
@@ -325,25 +327,32 @@ public class ObjectDestinationTransactionTest {
IrisObjectPlacement raft = new IrisObjectPlacement().setOnwater(true);
IrisObjectPlacement forced = new IrisObjectPlacement().setForcePlace(true);
IrisObjectPlacement piece = IrisStructureComponent.piecePlacement(new IrisStructure(), new PlacedStructurePiece(null,
new IrisObject(1, 1, 1), 4, 14, 3, IrisObjectRotation.of(0, 0, 0), 4, 14, 3, 4, 14, 3), ObjectPlaceMode.CENTER_HEIGHT, false);
new IrisObject(1, 1, 1), 4, 14, 3, IrisObjectRotation.of(0, 0, 0), 4, 14, 3, 4, 14, 3), ObjectPlaceMode.CENTER_HEIGHT);
assertTrue(piece.isForcePlace());
ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0);
int raftStart = transaction.beginObjectPlacement(raft.entersWater());
int raftStart = transaction.beginObjectPlacement(raft.waterRule());
for (int x = 3; x <= 5; x++) {
transaction.set(x, 14, 3, plank);
}
assertEquals("a one-block onwater raft keeps its layer on the river surface", raftStart + 3, transaction.mutationCheckpoint());
int forcedStart = transaction.beginObjectPlacement(forced.entersWater());
assertEquals(ObjectWaterRule.FORCED, forced.waterRule());
assertEquals(ObjectWaterRule.FORCED, piece.waterRule());
int forcedStart = transaction.beginObjectPlacement(forced.waterRule());
transaction.set(3, 13, 3, plank);
assertEquals("an object's own forcePlace keeps its solid blocks in the river", forcedStart + 1, transaction.mutationCheckpoint());
int pieceStart = transaction.beginObjectPlacement(piece.entersWater());
transaction.set(3, 12, 3, mock(NativeBlockState.class));
transaction.setData(3, 11, 3, new MatterCavern(true, "", (byte) 3));
assertEquals("a forced object writes solid blocks, open blocks and carves through the river", forcedStart + 3, transaction.mutationCheckpoint());
int pieceStart = transaction.beginObjectPlacement(piece.waterRule());
transaction.set(4, 13, 3, plank);
transaction.set(5, 11, 3, plank);
assertEquals("a forced structure piece still keeps its solid blocks out of the river", pieceStart, transaction.mutationCheckpoint());
assertEquals("a forced structure piece writes through the river", pieceStart + 2, transaction.mutationCheckpoint());
int landStart = transaction.beginObjectPlacement(ObjectWaterRule.KEEP_OUT);
transaction.set(4, 12, 3, plank);
assertEquals("an unforced object stays out of the river", landStart, transaction.mutationCheckpoint());
ObjectDestinationTransaction destination = new ObjectDestinationTransaction(writer, 0, 0);
destination.apply(transaction.sourcePlanSince(raftStart));
assertEquals("the destination replay keeps the raft and the forced block", 4, destination.mutationCheckpoint());
assertEquals("the destination replay keeps the forced writes beside the raft", 8, destination.mutationCheckpoint());
}
@Test
@@ -366,15 +375,49 @@ public class ObjectDestinationTransactionTest {
when(pier.isSolid()).thenReturn(true);
ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0);
int raft = transaction.beginObjectPlacement(true);
int raft = transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
transaction.set(3, 12, 3, pier);
transaction.endObjectPlacement(raft);
transaction.recordObjectPlacement(raft);
transaction.endObjectPlacement();
int afterRaft = transaction.mutationCheckpoint();
transaction.set(3, 13, 3, pier);
assertEquals("a write after the water placement ends follows land rules", afterRaft, transaction.mutationCheckpoint());
}
@Test
public void aRejectedWaterPlacementReturnsToLandRules() {
MantleWriter writer = writer();
waterAtColumnThree(writer);
NativeBlockState pier = mock(NativeBlockState.class);
when(pier.isSolid()).thenReturn(true);
ObjectDestinationTransaction transaction = new ObjectDestinationTransaction(writer, 0, 0);
transaction.beginObjectPlacement(ObjectWaterRule.ENTERS_WATER);
transaction.set(3, 12, 3, pier);
transaction.endObjectPlacement();
int afterRaft = transaction.mutationCheckpoint();
transaction.set(3, 13, 3, pier);
assertEquals("a write after a rejected water placement follows land rules", afterRaft, transaction.mutationCheckpoint());
}
private static void waterAtColumnThree(MantleWriter writer) {
IrisComplex complex = mock(IrisComplex.class);
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
ChunkWaterRaster raster = mock(ChunkWaterRaster.class);
when(writer.getEngine().getComplex()).thenReturn(complex);
when(complex.getHydrologyRuntime()).thenReturn(runtime);
when(runtime.enabled()).thenReturn(true);
when(runtime.raster(anyInt(), anyInt())).thenReturn(raster);
when(raster.role(anyInt(), anyInt())).thenReturn(WaterRole.NONE);
when(raster.waterHead(anyInt(), anyInt())).thenReturn(Integer.MIN_VALUE);
when(raster.role(3, 3)).thenReturn(WaterRole.CHANNEL);
when(raster.waterHead(3, 3)).thenReturn(14);
when(raster.terrainHeight(3, 3)).thenReturn(10);
followRasterStreams(complex, raster);
}
@Test
public void sourceCaptureCannotReplaceAuthoredRoomSolids() {
MantleWriter writer = writer();
@@ -1,10 +1,19 @@
package art.arcane.iris.pack;
import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPermission;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -13,7 +22,9 @@ import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -22,6 +33,10 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class PackHydrologyValidatorTest {
private static final String WATER = "{\"name\": \"water\", \"palette\": {\"palette\": [{\"block\": \"minecraft:water\"}]}}";
private static final String LAVA = "{\"name\": \"lava\", \"palette\": {\"palette\": [{\"block\": \"minecraft:lava\"}]}}";
private static final String CRUST = "{\"name\": \"crust\", \"palette\": {\"palette\": [{\"block\": \"minecraft:obsidian\"}]}}";
private static final String SEA_IS_LAVA = "\"fluidPalette\": {\"palette\": [{\"block\": \"minecraft:lava\"}]},";
private static final String WATER_ONLY = "{\"enabled\": true, \"fluids\": [{\"name\": \"water\"}]}";
@Rule
@@ -45,7 +60,8 @@ public class PackHydrologyValidatorTest {
},
"fluids": [
{"name": "water", "palette": {"palette": [{"block": "minecraft:water"}]}},
{"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}}
{"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}, "seam": "crust"},
{"name": "crust", "palette": {"palette": [{"block": "minecraft:obsidian"}]}}
]
}
""", "\"hydrologyPolicy\": {\"fluid\": \"lava\"},")));
@@ -277,45 +293,214 @@ public class PackHydrologyValidatorTest {
}
@Test
public void unknownHydrologyKeysAreIgnoredAndAMissingEnabledFlagLoadsAsOff() throws Exception {
public void warnsAboutAnUnknownKeyAtTheTopOfHydrology() throws Exception {
List<String> warnings = unknownKeyWarnings(validate(pack(dimension("{\"enabled\": true, \"unknownSection\": {\"enabled\": true, \"tiers\": 4}}", ""))));
assertContains(warnings, "Dimension 'main'.hydrology.unknownSection is not a known key, so its value is ignored.");
assertContains(warnings, "prefetchRings");
assertEquals(warnings.toString(), 1, warnings.size());
}
@Test
public void warnsAboutAMisspeltEnabledFlagThoughTheBlockLoadsAsOff() throws Exception {
File pack = pack(dimension("{\"enable\": true, \"ponds\": {\"dryDrawdon\": 3}}", ""));
List<String> warnings = unknownKeyWarnings(validate(pack));
assertContains(warnings, "Dimension 'main'.hydrology.enable is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.ponds.dryDrawdon is not a known key");
assertEquals(warnings.toString(), 2, warnings.size());
assertFalse(loadHydrology(pack).isEnabled());
}
@Test
public void warnsAboutUnknownKeysInNestedObjects() throws Exception {
List<String> warnings = unknownKeyWarnings(validate(pack(dimension("""
{
"enabled": true,
"ponds": {"seeded": {"radiusRange": [4, 12]}},
"underground": {"cavePools": {"surface": 3}, "seaInlets": {"length": [24, 96], "chamber": {"radius": 4}}}
}
""", ""))));
assertContains(warnings, "Dimension 'main'.hydrology.ponds.seeded.radiusRange is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.underground.cavePools.surface is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.underground.seaInlets.chamber is not a known key");
assertEquals(warnings.toString(), 3, warnings.size());
}
@Test
public void warnsAboutUnknownKeysInsideTierArrayElements() throws Exception {
File pack = pack(dimension("""
{"unknownSection": {"enabled": true, "tiers": 4}, "unknownList": [{"enabled": true}]}
{"enabled": true, "fluids": [{"name": "water", "palette": {"palette": [{"block": "minecraft:water", "bloc": 1}]}, "sealed": true}],
"tiers": [
{"name": "stream", "minCatchment": 900, "halfWidth": [0.5, 2.5], "bankBand": 8},
{"name": "major", "minCatchment": 200000, "halfWidth": [9, 18], "bankBand": 48, "notATierField": {"depth": 3},
"estuary": {"flair": 2},
"decorators": [{"partOf": "SEA_FLOOR", "palette": [{"block": "minecraft:kelp"}], "stacks": 1}]}
]}
""", ""));
assertTrue(validate(pack).errors().isEmpty());
IrisData data = IrisData.openDatapackCompiler(pack);
try {
IrisHydrology hydrology = data.getDimensionLoader().load("main").getHydrology();
assertNotNull(hydrology);
assertFalse(hydrology.isEnabled());
} finally {
data.close();
List<String> warnings = unknownKeyWarnings(validate(pack));
assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].notATierField is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].estuary.flair is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].decorators[0].stacks is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.fluids[0].sealed is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.fluids[0].palette.palette[0].bloc is not a known key");
assertEquals(warnings.toString(), 5, warnings.size());
for (IrisHydrologyTier tier : loadHydrology(pack).getTiers()) {
assertEquals(tier.getName(), 48, tier.getEstuary().getLength());
assertEquals(tier.getName(), 2.5D, tier.getEstuary().getFlare(), 0D);
}
}
@Test
public void unknownTierKeysAreIgnoredAndTiersKeepTheDefaultEstuary() throws Exception {
String written = """
{"enabled": true, "tiers": [
{"name": "stream", "minCatchment": 900, "halfWidth": [0.5, 2.5], "bankBand": 8%s},
{"name": "major", "minCatchment": 200000, "halfWidth": [9, 18], "bankBand": 48%s}
]}
""";
File extra = pack(dimension(written.formatted(", \"notATierField\": false", ", \"notATierField\": {\"depth\": 3}"), ""));
File current = pack(dimension(written.formatted("", ""), ""));
public void treatsMapKeysAsDataAndChecksTheObjectsInside() throws Exception {
List<String> warnings = new ArrayList<>();
JSONObject written = new JSONObject("""
{"zones": {"swamp": {"min": 0.7, "max": 1}, "desert": {"minimum": 0.1}}}
""");
PackHydrologyValidator.Validation validation = validate(extra);
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().isEmpty());
PackValidationResult packaging = PackValidator.validateForPackaging(extra);
assertEquals(PackValidator.validateForPackaging(current).getBlockingErrors(), packaging.getBlockingErrors());
IrisHydrology loaded = loadHydrology(extra);
for (IrisHydrologyTier tier : loaded.getTiers()) {
assertEquals(tier.getName(), 48, tier.getEstuary().getLength());
assertEquals(tier.getName(), 2.5D, tier.getEstuary().getFlare(), 0D);
PackHydrologyValidator.warnUnknownKeys("root", written, NamedZones.class, temporaryFolder.getRoot(), warnings);
assertContains(warnings, "root.zones.desert.minimum is not a known key");
assertEquals(warnings.toString(), 1, warnings.size());
}
@Test
public void acceptsAnyKeyInsideABlockDataMap() throws Exception {
PackHydrologyValidator.Validation validation = validate(pack(dimension("""
{"enabled": true, "fluids": [{"name": "water", "palette": {"palette": [
{"block": "minecraft:water", "data": {"level": 0, "anything": {"at": "all"}}, "tileData": {"SpawnData": {"entity": {}}}}
]}}]}
""", "")));
assertEquals(List.of(), unknownKeyWarnings(validation));
}
@Test
public void acceptsEveryKeyGsonWritesForTheConfigClasses() throws Exception {
Gson gson = new Gson();
PackHydrologyValidator.Validation defaults = validate(pack(dimension(gson.toJson(new IrisHydrology().setEnabled(true)), "")));
assertEquals(List.of(), unknownKeyWarnings(defaults));
IrisHydrology hydrology = new IrisHydrology().setEnabled(true);
hydrology.getTiers().get(0).getMaterials().setBed(new IrisMaterialPalette()).setShore(new IrisMaterialPalette()).setBank(new IrisMaterialPalette());
IrisDecorator decorator = new IrisDecorator().setForceBlock(new IrisBlockData("minecraft:stone"));
decorator.getStyle().setFracture(new IrisGeneratorStyle());
hydrology.getTiers().get(0).getDecorators().add(decorator);
IrisHydrologyPolicy policy = new IrisHydrologyPolicy().setRainfall(1D).setWetness(new IrisHydrologyWetness()).setStreams(IrisHydrologyPermission.ALLOW);
PackHydrologyValidator.Validation written = validate(pack(dimension(gson.toJson(hydrology), "\"hydrologyPolicy\": " + gson.toJson(policy) + ",")));
assertEquals(List.of(), keyWarnings(written));
}
@Test
public void warnsAboutEachRenamedKeyByItsOldName() throws Exception {
List<String> warnings = unknownKeyWarnings(validate(pack(dimension("""
{
"enabled": true,
"drainage": {"minimumHeadKeep": 0.6},
"tiers": [
{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinimumDrop": 6},
{"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinimumDrop": 8}
],
"ponds": {"climateDrawdown": 3},
"underground": {"seaInlets": {"minimumCliffHeight": 8}}
}
""", ""))));
assertContains(warnings, "Dimension 'main'.hydrology.drainage.minimumHeadKeep is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.tiers[0].waterfallMinimumDrop is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.tiers[1].waterfallMinimumDrop is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.ponds.climateDrawdown is not a known key");
assertContains(warnings, "Dimension 'main'.hydrology.underground.seaInlets.minimumCliffHeight is not a known key");
assertEquals(warnings.toString(), 5, warnings.size());
}
@Test
public void warnsAboutUnknownKeysInHydrologyPoliciesAtEveryScope() throws Exception {
File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"rainFall\": 1},"));
write(pack, "regions/region.json", """
{"landBiomes": ["biome"], "hydrologyPolicy": {"streamz": "BLOCK"}}
""");
write(pack, "biomes/biome.json", """
{"name": "Biome", "hydrologyPolicy": {"wetness": {"middle": 0.5},
"decorators": [{"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:fern"}], "odds": 2}]}}
""");
List<String> warnings = unknownKeyWarnings(validate(pack));
assertContains(warnings, "Dimension 'main'.hydrologyPolicy.rainFall is not a known key");
assertContains(warnings, "Region 'region'.hydrologyPolicy.streamz is not a known key");
assertContains(warnings, "Biome 'biome'.hydrologyPolicy.wetness.middle is not a known key");
assertContains(warnings, "Biome 'biome'.hydrologyPolicy.decorators[0].odds is not a known key");
assertEquals(warnings.toString(), 4, warnings.size());
}
@Test
public void followsSnippetsAndNamesThemInThePath() throws Exception {
File pack = pack(dimension("""
{"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0,
"decorators": ["snippet/reeds", "snippet/decorator/fern", "snippet/decorator/missing"]}]}
""", ""));
write(pack, "snippet/decorator/reeds.json", """
{"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:sugar_cane"}], "odds": 2}
""");
write(pack, "snippet/decorator/fern.json", """
{"partOf": "SHORE_LINE", "palette": [{"block": "minecraft:fern"}]}
""");
List<String> warnings = keyWarnings(validate(pack));
assertContains(warnings, "Dimension 'main'.hydrology.tiers[0].decorators[0] (snippet/decorator/reeds).odds is not a known key");
assertEquals(warnings.toString(), 1, warnings.size());
}
@Test
public void aSnippetThatRefersToItselfEnds() throws Exception {
File pack = temporaryFolder.newFolder("cycle");
write(pack, "snippet/style/loop.json", """
{"fracture": "snippet/style/loop", "fractures": 1}
""");
List<String> warnings = new ArrayList<>();
PackHydrologyValidator.warnUnknownKeys("style", "snippet/style/loop", IrisGeneratorStyle.class, pack, warnings);
assertContains(warnings, "style (snippet/style/loop).fractures is not a known key");
assertEquals(warnings.toString(), 1, warnings.size());
}
@Test
public void leavesKeysOutsideTheHydrologyBlockAlone() throws Exception {
File pack = pack("{\"regions\": [\"region\"], \"notADimensionKey\": 1, \"hydrology\": " + WATER_ONLY + "}");
write(pack, "biomes/biome.json", "{\"name\": \"Biome\", \"notABiomeKey\": {\"a\": 1}}");
assertEquals(List.of(), unknownKeyWarnings(validate(pack)));
}
@Test
public void unknownKeysNeverBlockAPackOnAnyValidationPath() throws Exception {
File pack = pack(dimension("{\"enabled\": true, \"ponds\": {\"climateDrawdown\": 3}}", "\"hydrologyPolicy\": {\"rainFall\": 1},"));
String key = "not a known key";
for (PackValidationResult result : List.of(PackValidator.validate(pack), PackValidator.validateForPackaging(pack), PackValidator.validateForDatapackBootstrap(pack))) {
assertFalse(result.getBlockingErrors().toString(), result.getBlockingErrors().stream().anyMatch(message -> message.contains(key)));
assertContains(result.getWarnings(), "Dimension 'main'.hydrology.ponds.climateDrawdown is " + key);
assertContains(result.getWarnings(), "Dimension 'main'.hydrologyPolicy.rainFall is " + key);
}
assertEquals(HydrologySettings.compile(loadHydrology(current), 1337L, 62, -64, 320).fingerprint(),
HydrologySettings.compile(loaded, 1337L, 62, -64, 320).fingerprint());
}
@Test
public void anObjectWhereAListIsDeclaredReportsNoListInternals() throws Exception {
List<String> warnings = new ArrayList<>();
JSONObject written = new JSONObject("{\"tiers\": {\"name\": \"stream\"}, \"fluids\": {\"elementData\": 1}}");
PackHydrologyValidator.warnUnknownKeys("root", written, IrisHydrology.class, temporaryFolder.getRoot(), warnings);
assertEquals(List.of(), warnings);
}
@Test
@@ -525,16 +710,16 @@ public class PackHydrologyValidatorTest {
}
@Test
public void rejectsWaterfallMinimumDropBelowTwo() throws Exception {
public void rejectsWaterfallMinDropBelowTwo() throws Exception {
File pack = pack(dimension("""
{"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0},
{"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinimumDrop": 1}]}
{"name": "river", "minCatchment": 20000, "halfWidth": [2, 8], "bankBand": 32, "waterfallMinDrop": 1}]}
""", ""));
write(pack, "dimensions/edge.json", dimension("""
{"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinimumDrop": 2}]}
{"enabled": true, "tiers": [{"name": "stream", "halfWidth": [0.5, 2], "bankBand": 0, "waterfallMinDrop": 2}]}
""", ""));
assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology tiers[1].waterfallMinimumDrop must be at least 2, got 1"),
assertEquals(List.of("Dimension 'main'.hydrology does not compile: Hydrology tiers[1].waterfallMinDrop must be at least 2, got 1"),
validate(pack).errors());
}
@@ -677,6 +862,140 @@ public class PackHydrologyValidatorTest {
assertTrue(widened.warnings().toString(), widened.warnings().isEmpty());
}
@Test
public void warnsWhenALavaRiverWithoutASeamCanMeetTheSea() throws Exception {
File pack = pack(dimension(hydrology("lava", "lava", LAVA), ""));
PackHydrologyValidator.Validation validation = validate(pack);
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertEquals(List.of("Dimension 'main'.hydrology.fluids profile 'lava' sets no seam, so where its rivers meet the sea"
+ " the fluids lie side by side. Set seam on the profile to line that edge. Its rivers come from"
+ " Dimension 'main'.hydrology.tiers[0].fluid, Dimension 'main'.hydrology.tiers[1].fluid."), validation.warnings());
}
@Test
public void warnsAgainstADifferentRiverFluidAndNamesTheBiomeItComesFrom() throws Exception {
File pack = pack(dimension(hydrology("water", "water", WATER + ", " + LAVA), SEA_IS_LAVA));
write(pack, "biomes/biome.json", """
{"name": "Biome", "hydrologyPolicy": {"fluid": "lava"}}
""");
write(pack, "regions/region.json", """
{"landBiomes": ["biome", "plain"]}
""");
write(pack, "biomes/plain.json", "{\"name\": \"Plain\"}");
PackHydrologyValidator.Validation validation = validate(pack);
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertEquals(List.of("Dimension 'main'.hydrology.fluids profile 'lava' sets no seam, so where its rivers meet fluid 'water'"
+ " the fluids lie side by side. Set seam on the profile to line that edge. Its rivers come from"
+ " Biome 'biome'.hydrologyPolicy.fluid."), validation.warnings());
}
@Test
public void aSeamOnTheOtherRiverFluidLinesTheEdgeBetweenThem() throws Exception {
String fluids = WATER + ", " + LAVA + ", " + """
{"name": "tar", "palette": {"palette": [{"block": "mod:tar"}]}, "seam": "crust"}, %s
""".formatted(CRUST);
File pack = pack(dimension(hydrology("lava", "tar", fluids), SEA_IS_LAVA));
PackHydrologyValidator.Validation validation = validate(pack);
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void silentWhenTheFluidHasASeam() throws Exception {
String fluids = """
{"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}, "seam": "crust"}, %s, %s
""".formatted(CRUST, WATER);
PackHydrologyValidator.Validation validation = validate(pack(dimension(hydrology("lava", "water", fluids), "")));
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void silentForWaterRiversWhateverTheProfileIsCalled() throws Exception {
String fluids = """
{"name": "marsh", "palette": {"palette": [{"block": "water"}]}}, %s
""".formatted(WATER);
File pack = pack(dimension(hydrology("marsh", "water", fluids), SEA_IS_LAVA));
PackHydrologyValidator.Validation validation = validate(pack);
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void silentWhenTheFluidsAreTheSame() throws Exception {
String fluids = LAVA + ", " + """
{"name": "magma", "palette": {"palette": [{"block": "lava"}]}}
""";
PackHydrologyValidator.Validation validation = validate(pack(dimension(hydrology("lava", "magma", fluids), SEA_IS_LAVA)));
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void silentWhenAPolicyFluidReplacesEveryTierFluid() throws Exception {
String config = hydrology("water", "water", WATER + ", " + LAVA);
PackHydrologyValidator.Validation validation = validate(pack(dimension(config,
SEA_IS_LAVA + " \"hydrologyPolicy\": {\"fluid\": \"lava\"},")));
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void aCaveBiomePolicyFluidIsNotARiverFluid() throws Exception {
File pack = pack(dimension(hydrology("water", "water", WATER + ", " + LAVA), ""));
write(pack, "regions/region.json", """
{"landBiomes": ["biome"], "caveBiomes": ["hollow"]}
""");
write(pack, "biomes/hollow.json", """
{"name": "Hollow", "hydrologyPolicy": {"fluid": "lava"}}
""");
PackHydrologyValidator.Validation validation = validate(pack);
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void silentAboutTheSeaWhenTheDimensionHasNoFluidHeight() throws Exception {
PackHydrologyValidator.Validation validation = validate(pack(dimension(hydrology("lava", "lava", LAVA), "\"fluidHeight\": -64,")));
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertTrue(validation.warnings().toString(), validation.warnings().isEmpty());
}
@Test
public void warnsAboutTheSeaOneBlockAboveTheDimensionFloor() throws Exception {
String noInlets = hydrology("lava", "lava", LAVA).replace("\"underground\": {", "\"underground\": {\"seaInlets\": {\"enabled\": false}, ");
PackHydrologyValidator.Validation validation = validate(pack(dimension(noInlets, "\"fluidHeight\": -63,")));
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertContains(validation.warnings(), "where its rivers meet the sea");
}
private static String hydrology(String streamFluid, String riverFluid, String fluids) {
return """
{"enabled": true,
"tiers": [
{"name": "stream", "minCatchment": 1500, "halfWidth": [0.5, 2], "bankBand": 0, "fluid": "%s"},
{"name": "river", "minCatchment": 20000, "halfWidth": [2, 16], "bankBand": 8, "fluid": "%s"}],
"ponds": {"fluid": "%s"},
"underground": {"cavePools": {"fluid": "%s"}},
"fluids": [%s]}
""".formatted(streamFluid, riverFluid, streamFluid, streamFluid, fluids);
}
private File shorePack(String dimensionWidth) throws Exception {
File pack = pack(dimension(WATER_ONLY, "\"hydrologyPolicy\": {\"shoreBiomes\": [\"beach\"]" + dimensionWidth + "},"));
write(pack, "regions/region.json", """
@@ -692,6 +1011,10 @@ public class PackHydrologyValidatorTest {
return pack;
}
private static final class NamedZones {
private Map<String, IrisHydrologyWetness> zones;
}
private PackHydrologyValidator.Validation validate(File pack) {
File[] dimensions = new File(pack, "dimensions").listFiles(
file -> file.isFile() && file.getName().endsWith(".json"));
@@ -718,6 +1041,15 @@ public class PackHydrologyValidatorTest {
return pack;
}
private List<String> unknownKeyWarnings(PackHydrologyValidator.Validation validation) {
assertEquals(List.of(), validation.errors());
return keyWarnings(validation);
}
private List<String> keyWarnings(PackHydrologyValidator.Validation validation) {
return validation.warnings().stream().filter(warning -> warning.contains("not a known key")).toList();
}
private void assertContains(List<String> messages, String fragment) {
for (String message : messages) {
if (message.contains(fragment)) {
@@ -251,6 +251,38 @@ public class PackValidatorStructureGraphTest {
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("duplicates an anonymous placement grid")));
}
@Test
public void allowWaterMustBeABoolean() throws Exception {
File pack = temporaryFolder.newFolder("invalid-allow-water");
write(pack, "dimensions/main.json", "{\"structures\":[{"
+ "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}],"
+ "\"allowWater\":\"yes\"}]}");
List<String> errors = PackObjectSurfaceValidator.validateStructureGraph(pack);
assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("allowWater must be a boolean")));
}
@Test
public void allowWaterSeparatesAnonymousGridsOnlyWhenTrue() throws Exception {
File separate = temporaryFolder.newFolder("allow-water-grid");
write(separate, "dimensions/main.json", "{\"structures\":[{"
+ "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}");
write(separate, "regions/river.json", "{\"structures\":[{\"allowWater\":true,"
+ "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}");
File duplicate = temporaryFolder.newFolder("allow-water-false-grid");
write(duplicate, "dimensions/main.json", "{\"structures\":[{"
+ "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}");
write(duplicate, "regions/river.json", "{\"structures\":[{\"allowWater\":false,"
+ "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}");
List<String> separateErrors = PackObjectSurfaceValidator.validateStructureGraph(separate);
List<String> duplicateErrors = PackObjectSurfaceValidator.validateStructureGraph(duplicate);
assertTrue(separateErrors.toString(), separateErrors.stream().noneMatch(message -> message.contains("duplicates an anonymous placement grid")));
assertTrue(duplicateErrors.toString(), duplicateErrors.stream().anyMatch(message -> message.contains("duplicates an anonymous placement grid")));
}
@Test
public void rejectsDuplicateEditableStructureKeysIgnoringCase() throws Exception {
File pack = temporaryFolder.newFolder("duplicate-editable-key");
@@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String EXPECTED_SCHEMA_DIGEST = "86ef7692e01b99a240bb4a4d86186eab1aaec81b98e7e87859fd61f8ced972a8";
private static final String EXPECTED_SCHEMA_DIGEST = "89641e077a85bec8a27681f2ce6166150cc37277bc6f58793081b669432782f2";
private static final List<Class<?>> SCHEMA_ROOTS = List.of(
IrisDimension.class,
@@ -198,7 +198,7 @@ public class NativeStructurePlacementPlannerTest {
}
@Test
public void riverInTheStartChunkLeavesTheDecisionToThePieces() {
public void waterAroundAStartColumnAboveItsHeadLeavesTheDecisionToThePieces() {
Engine engine = engine(77L, -64, 384, 150);
Map<Long, WaterRole> roles = new HashMap<>();
waterComplex(engine, roles, false);
@@ -88,7 +88,6 @@ public class IrisObjectPlacementToPlacementTest {
source.setAllowedCollisions(allowedCollisions);
source.setForbiddenCollisions(forbiddenCollisions);
source.setForcePlace(true);
source.setForcedByStructure(true);
IrisObjectPlacement copy = source.toPlacement("objects/replaced");
@@ -133,6 +132,5 @@ public class IrisObjectPlacementToPlacementTest {
assertSame(allowedCollisions, copy.getAllowedCollisions());
assertSame(forbiddenCollisions, copy.getForbiddenCollisions());
assertTrue(copy.isForcePlace());
assertTrue(copy.isForcedByStructure());
}
}
@@ -1,6 +1,9 @@
package art.arcane.iris.structure.object;
import art.arcane.iris.generation.block.TileData;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.mantle.ObjectContinuationBundle;
import art.arcane.iris.integration.Identifier;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
@@ -32,6 +35,7 @@ import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.IrisMatter;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.matter.MatterSlice;
import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
@@ -50,6 +54,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@@ -206,6 +211,56 @@ public class IrisStaticObjectLayerTest {
verify(tiles).set(15, 0, 15, null);
}
@Test
@SuppressWarnings("unchecked")
public void staticObjectOverPlannedRiverOrPondWaterWritesEveryBlock() {
for (WaterRole role : List.of(WaterRole.CHANNEL, WaterRole.POND)) {
IrisObject object = object("through-water", 3, 3, 1);
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
object.getBlocks().put(new IrisBlockVector(x, y, 0), state("minecraft:stone"));
}
}
IrisStaticObjectLayer layer = compile(entry("through-water", 8, 0, 8));
Engine engine = mock(Engine.class);
IrisComplex complex = mock(IrisComplex.class);
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
ChunkWaterRaster raster = mock(ChunkWaterRaster.class);
ProceduralStream<WaterRole> roles = mock(ProceduralStream.class);
ProceduralStream<Double> heads = mock(ProceduralStream.class);
ProceduralStream<Integer> floors = mock(ProceduralStream.class);
when(engine.getComplex()).thenReturn(complex);
when(complex.getHydrologyRuntime()).thenReturn(runtime);
when(complex.getWaterRoleStream()).thenReturn(roles);
when(complex.getWaterHeadStream()).thenReturn(heads);
when(complex.getRoundedHeighteightStream()).thenReturn(floors);
when(runtime.enabled()).thenReturn(true);
when(runtime.raster(anyInt(), anyInt())).thenReturn(raster);
when(raster.role(anyInt(), anyInt())).thenReturn(role);
when(raster.waterHead(anyInt(), anyInt())).thenReturn(70);
when(raster.terrainHeight(anyInt(), anyInt())).thenReturn(60);
when(roles.get(anyDouble(), anyDouble())).thenReturn(role);
when(heads.getDouble(anyDouble(), anyDouble())).thenReturn(70D);
when(floors.get(anyDouble(), anyDouble())).thenReturn(60);
EngineMantle engineMantle = mock(EngineMantle.class);
Mantle<Matter> mantle = mock(Mantle.class);
MantleChunk<Matter> chunk = mock(MantleChunk.class);
when(engine.getMantle()).thenReturn(engineMantle);
when(engineMantle.getMantle()).thenReturn(mantle);
when(mantle.useChunk(anyInt(), anyInt())).thenReturn(chunk);
when(chunk.getOrCreate(anyInt())).thenReturn(mock(Matter.class));
Hunk<NativeBlockState> output = Hunk.newArrayHunk(16, 384, 16);
layer.apply(engine, 0, 0, output);
for (int x = 7; x <= 9; x++) {
for (int y = 63; y <= 65; y++) {
assertSame(role + " " + x + "," + y, state("minecraft:stone"), output.get(x, y, 8));
}
}
}
}
@Test
public void transitionRejectsWholeRotatedPlacementBeforeChunkWrites() {
IrisObject object = object("rotated", 1, 1, 5);
@@ -131,7 +131,7 @@ public class PlacementModuleSurfaceSupportTest {
world.water(WaterRole.CHANNEL, 9, 13);
world.column(1, 0, WaterRole.CHANNEL, 8, 12);
for (IrisObjectPlacement placement : List.of(underwater(), onwater(), forced())) {
for (IrisObjectPlacement placement : List.of(underwater(), onwater())) {
HydrologyWaterFixture.Placer placer = world.placer();
assertEquals(-1, place(HydrologyWaterFixture.raft(), placer, placement));
@@ -139,6 +139,17 @@ public class PlacementModuleSurfaceSupportTest {
}
}
@Test
public void forcedObjectsPlaceOnWaterAtAnotherHeadAndOnDams() {
world.water(WaterRole.CHANNEL, 9, 13);
world.column(1, 0, WaterRole.CHANNEL, 8, 12);
world.column(0, 1, WaterRole.DAM, 8, 12);
HydrologyWaterFixture.Placer placer = world.placer();
assertTrue(place(HydrologyWaterFixture.raft(), placer, forced()) >= 0);
assertFalse(placer.writes().isEmpty());
}
@Test
public void waterObjectsNeverPlaceOnProvisionalHydrology() {
world.water(WaterRole.POND, 7, 13);
@@ -47,6 +47,7 @@ import art.arcane.volmlib.util.stream.ProceduralStream;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
@@ -54,6 +55,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -500,6 +502,169 @@ public class IrisStructureLocatorContractTest {
assertNotNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void forcedSinglePiecesPlaceInTheMiddleOfARiver() {
Engine engine = submergedEngine(WaterRole.CHANNEL, false, -2032, 2032);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
assertNull("an unforced structure stays off a submerged start",
IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
placement.setUnderwater(true);
assertNull("an unforced structure keeps the 10% limit",
IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
placement.setUnderwater(false);
structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
assertNotNull("a forced piece places on a river column and over a river footprint",
IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void forcedSurfacePiecesPlaceOnOpenSea() {
Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
assertFalse(placement.isUnderwater());
assertNull("an unforced structure stays off the sea",
IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
assertNotNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void unforcedMultiPieceStartsStayOffSeaColumns() {
Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
registerTwoPieceGraph(engine.getData(), structure, "test:density");
placement.setUnderwater(true);
IrisStructureLocator.ResolvedPlacement allowed = IrisStructureLocator.resolvePlacement(engine, placement, 3, 4);
assertNotNull(allowed);
assertEquals(2, allowed.pieces().size());
placement.setUnderwater(false);
assertNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void undergroundPiecesKeepTheSubmergedCheck() {
for (ObjectPlaceMode mode : List.of(ObjectPlaceMode.ORGANIC_STILT, ObjectPlaceMode.CEILING_HANG)) {
Engine engine = submergedEngine(WaterRole.CHANNEL, true, -40, -20);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
structure.setPlaceMode(mode);
assertFalse(placement.forcesPieces(structure, 1));
assertNull(mode.name(), IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
}
@Test
public void anUnforcedStructureNeverAssemblesOnASubmergedStart() {
Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
structure.setStartPool("test:missing-pool");
assertNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void aForcedModeStructureWithABrokenGraphThrowsOnASubmergedStart() {
Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT);
structure.setStartPool("test:missing-pool");
assertThrows(IllegalStateException.class, () -> IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void aMissingStructureOnASubmergedStartReturnsNull() {
Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
placement.getStructures().clear();
placement.getStructures().add("test:missing-structure");
assertNull(IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
@Test
public void brokenReferencesOnADryStartStillThrow() {
Engine engine = submergedEngine(WaterRole.NONE, false, -2032, 2032);
when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(180);
IrisStructurePlacement placement = engine.getDimension().getStructures().get(0);
IrisStructure structure = engine.getData().load(IrisStructure.class, "test:density", false);
structure.setStartPool("test:missing-pool");
assertThrows(IllegalStateException.class, () -> IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
placement.getStructures().clear();
placement.getStructures().add("test:missing-structure");
assertThrows(IllegalStateException.class, () -> IrisStructureLocator.resolvePlacement(engine, placement, 3, 4));
}
private Engine submergedEngine(WaterRole role, boolean underground, int placementMin, int placementMax) {
Engine engine = densityEngine(1.0, underground, -64, 384, placementMin, placementMax);
IrisObject object = engine.getData().load(IrisObject.class, "test:density/object", false);
when(object.getW()).thenReturn(10);
when(object.getD()).thenReturn(10);
IrisComplex complex = mock(IrisComplex.class);
when(engine.getComplex()).thenReturn(complex);
when(complex.allowsNewGenerationFootprint(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(true);
@SuppressWarnings("unchecked")
ProceduralStream<Double> waterHead = mock(ProceduralStream.class);
when(complex.getWaterHeadStream()).thenReturn(waterHead);
when(waterHead.get(anyDouble(), anyDouble())).thenReturn(124D);
when(waterHead.getDouble(anyDouble(), anyDouble())).thenReturn(124D);
@SuppressWarnings("unchecked")
ProceduralStream<WaterRole> roles = mock(ProceduralStream.class);
when(complex.getWaterRoleStream()).thenReturn(roles);
when(roles.get(anyDouble(), anyDouble())).thenReturn(role);
@SuppressWarnings("unchecked")
ProceduralStream<Integer> beds = mock(ProceduralStream.class);
when(beds.get(anyDouble(), anyDouble())).thenReturn(120);
when(complex.getRoundedHeighteightStream()).thenReturn(beds);
when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(120);
when(engine.getDimension().getFluidHeight()).thenReturn(63);
return engine;
}
private void registerTwoPieceGraph(IrisData data, IrisStructure structure, String prefix) {
registerSinglePieceGraph(data, structure, prefix);
String targetPool = prefix + "/target";
String targetPiece = prefix + "/target-piece";
IrisJigsawPiece start = data.load(IrisJigsawPiece.class, prefix + "/piece", false);
start.setRotatable(false);
start.getConnectors().add(new IrisJigsawConnector()
.setPosition(new IrisPosition(0, 0, 0))
.setDirection(IrisDirection.EAST_POSITIVE_X)
.setPool(targetPool)
.setName("source")
.setTargetName("door"));
IrisJigsawPiece target = new IrisJigsawPiece().setObject(prefix + "/object").setRotatable(false);
target.getConnectors().add(new IrisJigsawConnector()
.setPosition(new IrisPosition(0, 0, 0))
.setDirection(IrisDirection.WEST_NEGATIVE_X)
.setPool(targetPool)
.setName("door")
.setTargetName("unused"));
IrisJigsawPool pool = new IrisJigsawPool();
pool.getPieces().add(new IrisJigsawPieceEntry(targetPiece, 1));
when(data.load(IrisJigsawPool.class, targetPool, false)).thenReturn(pool);
when(data.load(IrisJigsawPiece.class, targetPiece, false)).thenReturn(target);
structure.setMaxDepth(1);
}
@Test
public void undergroundIrisStructuresIgnoreRiversAbove() {
Engine engine = densityEngine(1.0, true, -64, 384, -40, -20);
@@ -80,8 +80,8 @@ public class IrisRiverSchemaTest {
assertTrue(section, properties.getJSONObject(section).has("$ref"));
}
assertEquals("array", tier.getJSONObject("halfWidth").getString("type"));
assertEquals(2, tier.getJSONObject("waterfallMinimumDrop").getInt("minimum"));
assertEquals(64, tier.getJSONObject("waterfallMinimumDrop").getInt("maximum"));
assertEquals(2, tier.getJSONObject("waterfallMinDrop").getInt("minimum"));
assertEquals(64, tier.getJSONObject("waterfallMinDrop").getInt("maximum"));
assertEquals(64, tier.getJSONObject("bankBand").getInt("maximum"));
assertEquals(0.05D, tier.getJSONObject("depthRatio").getDouble("minimum"), 0D);
assertEquals(List.of("SMOOTH", "LINEAR", "CONCAVE", "TERRACED", "CLIFF"),
@@ -51,7 +51,7 @@ public final class DeltaCoast {
IrisHydrology config = config(channels);
for (IrisHydrologyTier tier : config.getTiers()) {
tier.setCascades(false);
tier.setWaterfallMinimumDrop(2);
tier.setWaterfallMinDrop(2);
}
return HydrologySettings.compile(config, SEED, SEA_LEVEL, MIN_Y, MAX_Y);
}
@@ -101,7 +101,7 @@ public final class WaterScene {
halfWidth[point] = tier.minHalfWidth();
depth[point] = tier.depth(tier.minHalfWidth());
int drop = point == 0 ? 0 : grades[point - 1] - grades[point];
style[point] = drop >= tier.waterfallMinimumDrop() ? ReachStyle.WATERFALL
style[point] = drop >= tier.waterfallMinDrop() ? ReachStyle.WATERFALL
: drop >= 2 ? ReachStyle.CASCADE : drop == 1 ? ReachStyle.RIFFLE : ReachStyle.RUN;
}
return new Reach(id, tier, 0L, xs, zs, grades, halfWidth, depth, style, 1000f);