Pin persisted enum codes

- Give HydrologyFeatureType, ReachStyle and PondKind explicit codes equal to their old ordinals
- Add PersistedCodes lookup tables that reject duplicate, out-of-range and unknown codes
- Write and read codes in HydrologyPlanCodec; unknown codes decode as malformed plans
- Write and read codes in GenerationSemanticIndex shard records and region summaries
- Order summary river types and the river feature comparator by code
- Pin the code tables and a captured plan byte fixture in tests
This commit is contained in:
Brian Neumann-Fopiano committed 2026-11-01 18:31:01 -05:00
1 parent f6fbf9147f
commit 9c95e7901c
10 files changed
+351 -44

No files matched your search

@@ -0,0 +1,48 @@
package art.arcane.iris.generation.hydrology;
import java.util.Arrays;
import java.util.function.ToIntFunction;
public final class PersistedCodes<E extends Enum<E>> {
private static final int MAX_CODE = 255;
private final String type;
private final E[] byCode;
private PersistedCodes(String type, E[] byCode) {
this.type = type;
this.byCode = byCode;
}
public static <E extends Enum<E>> PersistedCodes<E> of(Class<E> type, ToIntFunction<E> code) {
E[] constants = type.getEnumConstants();
int size = 0;
for (E constant : constants) {
int value = code.applyAsInt(constant);
if (value < 0 || value > MAX_CODE) {
throw new IllegalStateException(type.getSimpleName() + "." + constant.name() + " has code " + value
+ ", outside 0.." + MAX_CODE);
}
size = Math.max(size, value + 1);
}
E[] byCode = Arrays.copyOf(constants, size);
Arrays.fill(byCode, null);
for (E constant : constants) {
int value = code.applyAsInt(constant);
if (byCode[value] != null) {
throw new IllegalStateException(type.getSimpleName() + "." + constant.name() + " reuses code " + value + " of "
+ type.getSimpleName() + "." + byCode[value].name());
}
byCode[value] = constant;
}
return new PersistedCodes<>(type.getSimpleName(), byCode);
}
public E decode(int code) {
E constant = code >= 0 && code < byCode.length ? byCode[code] : null;
if (constant == null) {
throw new IllegalStateException("Unknown " + type + " code " + code);
}
return constant;
}
}
@@ -28,8 +28,6 @@ public final class HydrologyPlanCodec {
private static final int POND_BYTES = 2 * Long.BYTES + 1 + 15 * Integer.BYTES;
private static final int STATION_BYTES = 5 * Integer.BYTES;
private static final int INLET_BYTES = Long.BYTES + 5 * Integer.BYTES + 2 * STATION_BYTES;
private static final ReachStyle[] STYLES = ReachStyle.values();
private static final PondKind[] KINDS = PondKind.values();
private HydrologyPlanCodec() {
}
@@ -102,13 +100,13 @@ public final class HydrologyPlanCodec {
writeFloats(out, reach.halfWidth());
writeFloats(out, reach.depth());
for (ReachStyle style : reach.style()) {
out.writeByte(style.ordinal());
out.writeByte(style.code());
}
}
private static void writePond(DataOutputStream out, Pond pond) throws IOException {
out.writeLong(pond.id());
out.writeByte(pond.kind().ordinal());
out.writeByte(pond.kind().code());
out.writeInt(pond.level());
out.writeInt(pond.floor());
out.writeInt(pond.spillX());
@@ -190,7 +188,7 @@ public final class HydrologyPlanCodec {
return Optional.empty();
}
return Optional.of(new Body(x, z, reaches, ponds, inlets));
} catch (BufferUnderflowException | IllegalArgumentException malformed) {
} catch (BufferUnderflowException | IllegalArgumentException | IllegalStateException malformed) {
return Optional.empty();
}
}
@@ -211,14 +209,14 @@ public final class HydrologyPlanCodec {
float[] depth = readFloats(in, points);
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
style[point] = STYLES[index(in.get(), STYLES.length)];
style[point] = ReachStyle.fromCode(Byte.toUnsignedInt(in.get()));
}
return new Reach(id, tier, downstreamId, xs, zs, grade, halfWidth, depth, style, catchment);
}
private static Pond readPond(ByteBuffer in) {
long id = in.getLong();
PondKind kind = KINDS[index(in.get(), KINDS.length)];
PondKind kind = PondKind.fromCode(Byte.toUnsignedInt(in.get()));
int level = in.getInt();
int floor = in.getInt();
int spillX = in.getInt();
@@ -1,23 +1,41 @@
package art.arcane.iris.generation.hydrology.query;
import art.arcane.iris.generation.hydrology.PersistedCodes;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public enum HydrologyFeatureType {
STREAM,
RIVER,
MAJOR_RIVER,
CASCADE,
WATERFALL,
MOUTH,
POND,
LAKE,
DAM,
SEA_INLET,
CAVE_POOL;
STREAM(0),
RIVER(1),
MAJOR_RIVER(2),
CASCADE(3),
WATERFALL(4),
MOUTH(5),
POND(6),
LAKE(7),
DAM(8),
SEA_INLET(9),
CAVE_POOL(10);
private static final List<String> KEYS = keyList();
private static final PersistedCodes<HydrologyFeatureType> CODES =
PersistedCodes.of(HydrologyFeatureType.class, HydrologyFeatureType::code);
private final int code;
HydrologyFeatureType(int code) {
this.code = code;
}
public int code() {
return code;
}
public static HydrologyFeatureType fromCode(int code) {
return CODES.decode(code);
}
public String key() {
return name().toLowerCase(Locale.ROOT);
@@ -1,8 +1,26 @@
package art.arcane.iris.generation.hydrology.water;
import art.arcane.iris.generation.hydrology.PersistedCodes;
public enum PondKind {
NATURAL,
SEEDED,
CHAINED,
LAKE
NATURAL(0),
SEEDED(1),
CHAINED(2),
LAKE(3);
private static final PersistedCodes<PondKind> CODES = PersistedCodes.of(PondKind.class, PondKind::code);
private final int code;
PondKind(int code) {
this.code = code;
}
public int code() {
return code;
}
public static PondKind fromCode(int code) {
return CODES.decode(code);
}
}
@@ -1,10 +1,28 @@
package art.arcane.iris.generation.hydrology.water;
import art.arcane.iris.generation.hydrology.PersistedCodes;
public enum ReachStyle {
RUN,
RIFFLE,
CASCADE,
WATERFALL,
POND_OUTLET,
MOUTH
RUN(0),
RIFFLE(1),
CASCADE(2),
WATERFALL(3),
POND_OUTLET(4),
MOUTH(5);
private static final PersistedCodes<ReachStyle> CODES = PersistedCodes.of(ReachStyle.class, ReachStyle::code);
private final int code;
ReachStyle(int code) {
this.code = code;
}
public int code() {
return code;
}
public static ReachStyle fromCode(int code) {
return CODES.decode(code);
}
}
@@ -28,7 +28,7 @@ public final class ChunkGenerationSemantics {
.thenComparingInt(point -> point.position().y());
private static final Comparator<RiverFeatureOccurrence> RIVER_FEATURE_COMPARATOR = Comparator
.comparing(RiverFeatureOccurrence::profileKey)
.thenComparing(RiverFeatureOccurrence::type)
.thenComparingInt(occurrence -> occurrence.type().code())
.thenComparingInt(occurrence -> occurrence.position().x())
.thenComparingInt(occurrence -> occurrence.position().z())
.thenComparingInt(occurrence -> occurrence.position().y())
@@ -1750,14 +1750,14 @@ public final class GenerationSemanticIndex {
} else if (riverTypeCount > HydrologyFeatureType.values().length) {
throw invalid(source, "invalid summary river type count " + riverTypeCount);
}
int previousOrdinal = -1;
int previousCode = -1;
for (int index = 0; index < riverTypeCount; index++) {
int ordinal = input.readUnsignedByte();
if (ordinal <= previousOrdinal || ordinal >= HydrologyFeatureType.values().length) {
throw invalid(source, "invalid summary river type ordinal " + ordinal);
int code = input.readUnsignedByte();
if (code <= previousCode) {
throw invalid(source, "summary river type codes are not in canonical order");
}
riverTypes.add(HydrologyFeatureType.values()[ordinal]);
previousOrdinal = ordinal;
riverTypes.add(RegionShard.riverFeatureType(source, code));
previousCode = code;
}
LongOpenHashSet activations = readActivations(source, input, "summary activation");
LongOpenHashSet sealedActivations = readActivations(source, input, "sealed summary activation");
@@ -1791,8 +1791,8 @@ public final class GenerationSemanticIndex {
}
}
output.writeByte(riverTypes.size());
for (HydrologyFeatureType type : riverTypes) {
output.writeByte(type.ordinal());
for (int code : riverTypes.stream().mapToInt(HydrologyFeatureType::code).sorted().toArray()) {
output.writeByte(code);
}
writeActivations(output, activations);
writeActivations(output, sealedActivations);
@@ -2707,7 +2707,7 @@ public final class GenerationSemanticIndex {
output.writeShort(semantics.riverFeatures().size());
for (ChunkGenerationSemantics.RiverFeatureOccurrence occurrence : semantics.riverFeatures()) {
output.writeShort(paletteIndexes.get(occurrence.profileKey()));
output.writeByte(occurrence.type().ordinal());
output.writeByte(occurrence.type().code());
output.writeLong(occurrence.featureId());
output.writeInt(occurrence.position().x());
output.writeInt(occurrence.position().y());
@@ -2916,21 +2916,17 @@ public final class GenerationSemanticIndex {
return;
}
ChunkGenerationSemantics.RiverFeatureOccurrence previous = null;
HydrologyFeatureType[] types = HydrologyFeatureType.values();
for (int index = 0; index < count; index++) {
int paletteIndex = input.readUnsignedShort();
if (paletteIndex >= palette.length) {
throw invalid(file, "river profile key palette index is out of range");
}
int typeOrdinal = input.readUnsignedByte();
if (typeOrdinal >= types.length) {
throw invalid(file, "river feature type ordinal is out of range");
}
HydrologyFeatureType type = riverFeatureType(file, input.readUnsignedByte());
paletteUsed[paletteIndex] = true;
ChunkGenerationSemantics.RiverFeatureOccurrence occurrence =
new ChunkGenerationSemantics.RiverFeatureOccurrence(
palette[paletteIndex],
types[typeOrdinal],
type,
input.readLong(),
new ChunkGenerationSemantics.BlockPosition(
input.readInt(),
@@ -2948,6 +2944,14 @@ public final class GenerationSemanticIndex {
}
}
private static HydrologyFeatureType riverFeatureType(Path file, int code) throws IOException {
try {
return HydrologyFeatureType.fromCode(code);
} catch (IllegalStateException unknown) {
throw invalid(file, unknown.getMessage(), unknown);
}
}
private static void skipLegacyRiverFeatures(
Path file,
DataInputStream input,
@@ -0,0 +1,129 @@
package art.arcane.iris.generation.hydrology;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PersistedCodesTest {
private static final Map<HydrologyFeatureType, Integer> FEATURE_TYPE_CODES = Map.ofEntries(
Map.entry(HydrologyFeatureType.STREAM, 0),
Map.entry(HydrologyFeatureType.RIVER, 1),
Map.entry(HydrologyFeatureType.MAJOR_RIVER, 2),
Map.entry(HydrologyFeatureType.CASCADE, 3),
Map.entry(HydrologyFeatureType.WATERFALL, 4),
Map.entry(HydrologyFeatureType.MOUTH, 5),
Map.entry(HydrologyFeatureType.POND, 6),
Map.entry(HydrologyFeatureType.LAKE, 7),
Map.entry(HydrologyFeatureType.DAM, 8),
Map.entry(HydrologyFeatureType.SEA_INLET, 9),
Map.entry(HydrologyFeatureType.CAVE_POOL, 10));
private static final Map<ReachStyle, Integer> REACH_STYLE_CODES = Map.of(
ReachStyle.RUN, 0,
ReachStyle.RIFFLE, 1,
ReachStyle.CASCADE, 2,
ReachStyle.WATERFALL, 3,
ReachStyle.POND_OUTLET, 4,
ReachStyle.MOUTH, 5);
private static final Map<PondKind, Integer> POND_KIND_CODES = Map.of(
PondKind.NATURAL, 0,
PondKind.SEEDED, 1,
PondKind.CHAINED, 2,
PondKind.LAKE, 3);
@Test
public void codesAreUniqueAndPinned() {
assertPinned(HydrologyFeatureType.class, FEATURE_TYPE_CODES, HydrologyFeatureType::code, HydrologyFeatureType::fromCode);
assertPinned(ReachStyle.class, REACH_STYLE_CODES, ReachStyle::code, ReachStyle::fromCode);
assertPinned(PondKind.class, POND_KIND_CODES, PondKind::code, PondKind::fromCode);
}
@Test
public void unknownCodesFailClosed() {
assertUnknown("HydrologyFeatureType", FEATURE_TYPE_CODES, HydrologyFeatureType::fromCode);
assertUnknown("ReachStyle", REACH_STYLE_CODES, ReachStyle::fromCode);
assertUnknown("PondKind", POND_KIND_CODES, PondKind::fromCode);
}
@Test
public void conflictingCodesAreRejected() {
try {
PersistedCodes.of(SharedCode.class, SharedCode::code);
fail("two constants share code 7");
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains("SharedCode") && expected.getMessage().contains("7"));
}
try {
PersistedCodes.of(WideCode.class, WideCode::code);
fail("code 256 does not fit one byte");
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains("WideCode") && expected.getMessage().contains("256"));
}
}
private static <E extends Enum<E>> void assertPinned(Class<E> type, Map<E, Integer> pins, ToIntFunction<E> code,
IntFunction<E> fromCode) {
assertEquals(type.getSimpleName() + " constants need a pinned code", EnumSet.allOf(type), pins.keySet());
Set<Integer> seen = new HashSet<>();
for (E constant : type.getEnumConstants()) {
int pinned = pins.get(constant);
assertEquals(type.getSimpleName() + "." + constant.name(), pinned, code.applyAsInt(constant));
assertTrue(type.getSimpleName() + " reuses code " + pinned, seen.add(pinned));
assertSame(constant, fromCode.apply(pinned));
}
}
private static <E extends Enum<E>> void assertUnknown(String name, Map<E, Integer> pins, IntFunction<E> fromCode) {
int unused = Collections.max(pins.values()) + 1;
for (int code : new int[]{-1, unused, 256}) {
try {
fromCode.apply(code);
fail(name + " decoded unknown code " + code);
} catch (IllegalStateException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains(name) && expected.getMessage().contains(Integer.toString(code)));
}
}
}
private enum SharedCode {
FIRST(7),
SECOND(7);
private final int code;
SharedCode(int code) {
this.code = code;
}
private int code() {
return code;
}
}
private enum WideCode {
ONLY(256);
private final int code;
WideCode(int code) {
this.code = code;
}
private int code() {
return code;
}
}
}
@@ -15,8 +15,10 @@ import art.arcane.iris.generation.hydrology.water.ReachShaper;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.SplittableRandom;
@@ -33,6 +35,20 @@ public class HydrologyPlanCodecTest {
private static final float NAN_PAYLOAD = Float.intBitsToFloat(0x7fc00123);
private static final float NEGATIVE_NAN = Float.intBitsToFloat(0xffa00001);
private static final WindowKey LAND = new WindowKey(4, 4);
private static final int FINGERPRINT_OFFSET = Integer.BYTES + 1;
private static final String PINNED_WINDOW = """
4948595057000000000000000000000002fffffffd000000010000000000000029000000000000006100000000444b20
0000000006000000004080000041000000414000004180000041a00000c1000000c0c00000c0800000c0000000000000
0040000000000000480000004700000046000000420000003f0000003e3f8000003fa000003fc000003fe00000400000
00402000003f8000003f8000003fc0000040000000400000003f80000000010203040500000004000000000000000500
00000046000000420000000cfffffffc428d0000fffffffc000000080000000400000000000000000000000000000000
0000002900000000ffffffff0000000afffffffa0000000000000006010000004a000000470000001e00000008429480
0000000003fffffffd000000010000004000000001000000018000000000000001ffffffffffffffff00000001000000
0577617465720000001c000000060000000000000007020000004400000040ffffffec0000001042898000fffffffc00
00000800000004000000000000000000000000000000000000002900000002000000046c617661ffffffea0000000e00
0000000000000803000000500000003c00000040ffffffc042a10000fffffffc00000008000000040000000000000000
00000000ffffffffffffffff00000000ffffffff0000003cffffffc400000000
""";
@Test
public void codecRoundTripsBitExact() {
@@ -138,6 +154,29 @@ public class HydrologyPlanCodecTest {
}
}
@Test
public void decodesPinnedBytes() {
HydrologySettings settings = settings(new IrisHydrology());
WindowPlan expected = pinnedWindow(settings.tiers().get(0));
byte[] fixture = HexFormat.of().parseHex(PINNED_WINDOW.replaceAll("\\s", ""));
ByteBuffer.wrap(fixture).putLong(FINGERPRINT_OFFSET, settings.fingerprint());
assertBitExact(expected, HydrologyPlanCodec.decodeWindow(settings, fixture).orElseThrow(), settings.tiers());
assertArrayEquals(fixture, HydrologyPlanCodec.encode(settings, expected));
}
private static WindowPlan pinnedWindow(HydrologyTier tier) {
Reach reach = new Reach(41L, tier, 97L, new float[]{0f, 4f, 8f, 12f, 16f, 20f}, new float[]{-8f, -6f, -4f, -2f, 0f, 2f},
new int[]{72, 71, 70, 66, 63, 62}, new float[]{1f, 1.25f, 1.5f, 1.75f, 2f, 2.5f}, new float[]{1f, 1f, 1.5f, 2f, 2f, 1f},
new ReachStyle[]{ReachStyle.RUN, ReachStyle.RIFFLE, ReachStyle.CASCADE, ReachStyle.WATERFALL, ReachStyle.POND_OUTLET,
ReachStyle.MOUTH}, 812.5f);
List<Pond> ponds = List.of(
new Pond(5L, PondKind.NATURAL, 70, 66, 12, -4, 70.5f, mask(0), 41L, 0, null, 10, -6),
new Pond(6L, PondKind.SEEDED, 74, 71, 30, 8, 74.25f, mask(2), -1L, 1, "water", 28, 6),
new Pond(7L, PondKind.CHAINED, 68, 64, -20, 16, 68.75f, mask(0), 41L, 2, "lava", -22, 14),
new Pond(8L, PondKind.LAKE, 80, 60, 64, -64, 80.5f, mask(0), -1L, 0, null, 60, -60));
return new WindowPlan(new WindowKey(2, -3), List.of(reach), ponds, List.of());
}
private static void assertBitExact(WindowPlan expected, WindowPlan actual, List<HydrologyTier> tiers) {
assertEquals(expected, actual);
assertReachesBitExact(expected.reaches(), actual.reaches(), tiers);
@@ -568,6 +568,31 @@ public final class GenerationSemanticIndexTest {
assertEquals(Set.of("temperate"), semantics.regionKeys());
}
@Test
public void unknownRiverFeatureCodesFailClosed() throws Exception {
Path recordRoot = temporaryFolder.newFolder("unknown-record-river-code").toPath();
Path recordShard = streamShard(recordRoot);
byte[] record = Files.readAllBytes(recordShard);
record[firstRiverTypeOffset(record)] = (byte) 200;
rewriteChecksum(record);
replaceReferencedShard(recordRoot, recordShard, record);
GenerationSemanticIndex recordIndex = GenerationSemanticIndex.load(recordRoot);
IllegalStateException recordError = assertThrows(IllegalStateException.class, () -> recordIndex.get(0, 0));
assertTrue(recordError.getCause().getMessage(),
recordError.getCause().getMessage().contains("Unknown HydrologyFeatureType code 200"));
Path summaryRoot = temporaryFolder.newFolder("unknown-summary-river-code").toPath();
Path summaryShard = streamShard(summaryRoot);
byte[] summary = Files.readAllBytes(summaryShard);
summary[summaryRiverTypeOffset(summary)] = (byte) 200;
rewriteChecksum(summary);
replaceReferencedShard(summaryRoot, summaryShard, summary);
GenerationSemanticIndex summaryIndex = GenerationSemanticIndex.load(summaryRoot);
IllegalStateException summaryError = assertThrows(IllegalStateException.class, () -> summaryIndex.get(0, 0));
assertTrue(summaryError.getCause().getMessage(),
summaryError.getCause().getMessage().contains("Unknown HydrologyFeatureType code 200"));
}
@Test
public void currentShardKeepsEveryHydrologyFeatureType() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("current-hydrology").toPath();
@@ -879,6 +904,16 @@ public final class GenerationSemanticIndexTest {
.build();
}
private static Path streamShard(Path dimensionRoot) throws Exception {
GenerationSemanticIndex index = GenerationSemanticIndex.load(dimensionRoot);
index.recordAndPersist(ChunkGenerationSemantics.builder(0, 0, 1L)
.addRegion("temperate")
.addRiverFeature("water", HydrologyFeatureType.STREAM, 9L, 3, 70, 4)
.seal()
.build());
return onlyShard(index.storageDirectory());
}
private static Path onlyShard(Path directory) throws Exception {
try (Stream<Path> files = Files.list(directory)) {
List<Path> shards = files.filter(path -> path.getFileName().toString().endsWith(".isem")).toList();