diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java index 67f7d440e..997c2ec62 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStudio.java @@ -348,7 +348,7 @@ public class CommandStudio implements DirectorExecutor { boolean progressShown = false; int c = -1; try { - engine.getDimension().getRegions().forEach(key -> data.put(key, new AtomicInteger(0))); + engine.getDimension().getRegionKeys().forEach(key -> data.put(key, new AtomicInteger(0))); multiBurst = new MultiBurst("Region Sampler"); var executor = multiBurst.burst(Math.min(radius * radius, 1 << 20)); sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_GENERATING_DATA)); @@ -370,8 +370,7 @@ public class CommandStudio implements DirectorExecutor { executor.complete(); sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_DONE)); - var loader = engine.getData().getRegionLoader(); - data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", loader.load(k).getRarity()), MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2))))); + data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", engine.getDimension().getRegionWeight(k)),MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2))))); } catch (Throwable e) { Iris.reportError(e); sender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_REGIONS_SCAN_FAILED, diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java index 88467a5a8..6691b7cf4 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/IrisWorldGeneratorResolverTest.java @@ -526,11 +526,11 @@ public class IrisWorldGeneratorResolverTest { Files.createDirectories(packRoot.resolve("biomes")); Files.writeString( packRoot.resolve("dimensions/main.json"), - "{\"regions\":[\"region\"]}", + "{\"regions\":[{\"region\":\"region\"}]}", StandardCharsets.UTF_8); Files.writeString( packRoot.resolve("regions/region.json"), - "{\"landBiomes\":[\"biome\"]}", + "{\"landBiomes\":[{\"biome\":\"biome\"}]}", StandardCharsets.UTF_8); Files.writeString( packRoot.resolve("biomes/biome.json"), diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java index e1bc143cb..f637b9a78 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandSuggestions.java @@ -91,7 +91,7 @@ final class ModdedCommandSuggestions { try { Engine engine = IrisModdedCommands.engineFor(context.getSource().getLevel()); if (engine != null) { - return SharedSuggestionProvider.suggest(engine.getDimension().getRegions(), builder); + return SharedSuggestionProvider.suggest(engine.getDimension().getRegionKeys(), builder); } } catch (Throwable e) { warnTabFailure("region keys", context.getSource(), e); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index 6c88ec510..e2731467d 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -788,7 +788,7 @@ public final class ModdedStudioCommands { int diameter = radius * 2; int totalTasks = diameter * diameter; KMap counts = new KMap<>(); - engine.getDimension().getRegions().forEach((String key) -> counts.put(key, new AtomicInteger(0))); + engine.getDimension().getRegionKeys().forEach((String key) -> counts.put(key, new AtomicInteger(0))); // finally-scoped: a throw mid-scan previously leaked the sampler's whole // ForkJoinPool (close() is the only thing that shuts it down). MultiBurst burst = new MultiBurst("Region Sampler"); @@ -803,9 +803,7 @@ public final class ModdedStudioCommands { burst.close(); } server.execute(() -> counts.forEach((String key, AtomicInteger count) -> { - IrisRegion region = engine.getData().getRegionLoader().load(key); - String rarity = region == null ? "?" : String.valueOf(region.getRarity()); - IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_RARITY, MessageArgument.untrusted("key", key), MessageArgument.untrusted("rarity", rarity), MessageArgument.untrusted("value", Form.f((double) count.get() / totalTasks * 100, 2)))); + IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_RARITY, MessageArgument.untrusted("key", key), MessageArgument.untrusted("rarity", engine.getDimension().getRegionWeight(key)),MessageArgument.untrusted("value", Form.f((double) count.get() / totalTasks * 100, 2)))); })); } catch (Throwable e) { ModdedIrisLog.error("Iris region sampling failed", e); diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index dd83d6881..f3d719707 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -36,7 +36,7 @@ types that carry them and lists what the Iris adapter still owes. | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | | Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | -| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion`, `PackExpression`, `PackImageMap` | +| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion` (their children and biome lists are `Weighted` entries; `Weighted.pick` walks them the way the host does), `PackExpression`, `PackImageMap` | | Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | diff --git a/api/api/src/main/java/com/volmit/world/PackBiome.java b/api/api/src/main/java/com/volmit/world/PackBiome.java index 4299cf8dd..51603bfd2 100644 --- a/api/api/src/main/java/com/volmit/world/PackBiome.java +++ b/api/api/src/main/java/com/volmit/world/PackBiome.java @@ -7,21 +7,21 @@ import java.util.Objects; /** A biome of the loaded pack, found through {@code PackResources} by the ids a {@link BiomeSample} gives. * platformBiome is the platform biome the host writes for it. vanillaBiome is the biome vanilla's own rules see it as, * such as which structures may start in it: the platform biome unless the pack says otherwise. children are the pack - * biomes that can generate inside it. Rarity is relative to the biome's siblings: higher is rarer. + * biomes that can generate inside it, in the order the child noise walks them; the biome itself is listed among them + * where it stays itself. */ -public record PackBiome(ResourceId id, String name, ResourceId platformBiome, ResourceId vanillaBiome, int rarity, - List children) { +public record PackBiome(ResourceId id, String name, ResourceId platformBiome, ResourceId vanillaBiome, + List> children) { public PackBiome { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); Objects.requireNonNull(platformBiome, "platformBiome"); Objects.requireNonNull(vanillaBiome, "vanillaBiome"); - if (rarity < 1) throw new IllegalArgumentException("Biome rarity must be at least 1: " + rarity); children = List.copyOf(children); } /** A biome that vanilla's rules see as its platform biome. */ - public PackBiome(ResourceId id, String name, ResourceId platformBiome, int rarity, List children) { - this(id, name, platformBiome, platformBiome, rarity, children); + public PackBiome(ResourceId id, String name, ResourceId platformBiome, List> children) { + this(id, name, platformBiome, platformBiome, children); } } diff --git a/api/api/src/main/java/com/volmit/world/PackRegion.java b/api/api/src/main/java/com/volmit/world/PackRegion.java index 2473e20a2..3677439be 100644 --- a/api/api/src/main/java/com/volmit/world/PackRegion.java +++ b/api/api/src/main/java/com/volmit/world/PackRegion.java @@ -5,15 +5,15 @@ import java.util.List; import java.util.Objects; /** A region of the loaded pack, found through {@code PackResources} by the id a {@link BiomeSample} gives. - * The biome lists name the pack biomes the region generates on land, at sea, on shores and in caves. - * Rarity is relative to the other regions: higher is rarer. + * The biome lists name the pack biomes the region generates on land, at sea, on shores and in caves, in the order + * the biome noise walks them. */ -public record PackRegion(ResourceId id, String name, int rarity, List landBiomes, - List seaBiomes, List shoreBiomes, List caveBiomes) { +public record PackRegion(ResourceId id, String name, List> landBiomes, + List> seaBiomes, List> shoreBiomes, + List> caveBiomes) { public PackRegion { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); - if (rarity < 1) throw new IllegalArgumentException("Region rarity must be at least 1: " + rarity); landBiomes = List.copyOf(landBiomes); seaBiomes = List.copyOf(seaBiomes); shoreBiomes = List.copyOf(shoreBiomes); diff --git a/api/api/src/main/java/com/volmit/world/Weighted.java b/api/api/src/main/java/com/volmit/world/Weighted.java new file mode 100644 index 000000000..ce0d70234 --- /dev/null +++ b/api/api/src/main/java/com/volmit/world/Weighted.java @@ -0,0 +1,59 @@ +package com.volmit.world; + +import java.util.List; +import java.util.Objects; + +/** A list entry that counts as {@code weight} copies of itself in a row, as biome, region and child lists write it. + * {@link #pick} walks such a list with a noise from 0 to 1, so a module that picks among a pack's weighted lists + * (a region's biomes, a biome's children) lands on the same entry the host does. + */ +public record Weighted(T value, int weight) { + public static final int MIN_WEIGHT = 1; + public static final int MAX_WEIGHT = 1000; + + /** Which entry gets noise lying exactly on the edge between two. Cellular noise sits on such edges over whole cells, + * so this decides real patches of terrain. A region's biome list gives edges to the earlier entry and children to the + * later one. + */ + public enum Edge { + EARLIER, + LATER + } + + public Weighted { + Objects.requireNonNull(value, "value"); + if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) { + throw new IllegalArgumentException("Weight must be from " + MIN_WEIGHT + " to " + MAX_WEIGHT + ": " + weight); + } + } + + /** Picks along the list as if every entry were written out {@code weight} times: the noise from 0 to 1 is split into + * equal slots, one per copy, in list order. Noise below 0 picks the first entry, noise above 1 the last; an empty list + * picks nothing. + */ + public static T pick(List> entries, double noise, Edge edge) { + if (entries.isEmpty()) { + return null; + } + + double slotPosition = noise * totalWeight(entries); + int slotsUpToHere = 0; + for (Weighted entry : entries) { + slotsUpToHere += entry.weight(); + boolean inThisEntry = edge == Edge.EARLIER ? slotPosition <= slotsUpToHere : slotPosition < slotsUpToHere; + if (inThisEntry) { + return entry.value(); + } + } + + return entries.getLast().value(); + } + + public static int totalWeight(List> entries) { + int total = 0; + for (Weighted entry : entries) { + total += entry.weight(); + } + return total; + } +} diff --git a/api/host/src/test/java/com/volmit/ApiValuesTest.java b/api/host/src/test/java/com/volmit/ApiValuesTest.java index dd56100b0..e9c471676 100644 --- a/api/host/src/test/java/com/volmit/ApiValuesTest.java +++ b/api/host/src/test/java/com/volmit/ApiValuesTest.java @@ -160,24 +160,20 @@ class ApiValuesTest { @Test void packBiomesAndRegionsAreImmutableValues() { - var children = new ArrayList<>(List.of(ResourceId.parse("pack:dunes"))); - var desert = new PackBiome(ResourceId.parse("pack:desert"), "Desert", ResourceId.parse("minecraft:desert"), 2, children); + var children = new ArrayList<>(List.of(new Weighted<>(ResourceId.parse("pack:dunes"), 2))); + var desert = new PackBiome(ResourceId.parse("pack:desert"), "Desert", ResourceId.parse("minecraft:desert"), children); children.clear(); - assertEquals(List.of(ResourceId.parse("pack:dunes")), desert.children()); + assertEquals(List.of(new Weighted<>(ResourceId.parse("pack:dunes"), 2)), desert.children()); assertThrows(UnsupportedOperationException.class, () -> desert.children().clear()); - assertThrows(IllegalArgumentException.class, - () -> new PackBiome(desert.id(), "Desert", desert.platformBiome(), 0, List.of())); assertEquals(desert.platformBiome(), desert.vanillaBiome(), "vanilla sees the platform biome unless a pack says otherwise"); var mesa = new PackBiome(ResourceId.parse("pack:mesa"), "Mesa", ResourceId.parse("minecraft:desert"), - ResourceId.parse("minecraft:badlands"), 1, List.of()); + ResourceId.parse("minecraft:badlands"), List.of()); assertEquals(ResourceId.parse("minecraft:badlands"), mesa.vanillaBiome()); - var land = List.of(desert.id()); - var arid = new PackRegion(ResourceId.parse("pack:arid"), "Arid", 1, land, List.of(), List.of(), List.of()); + var land = List.of(new Weighted<>(desert.id(), 1)); + var arid = new PackRegion(ResourceId.parse("pack:arid"), "Arid", land, List.of(), List.of(), List.of()); assertEquals(land, arid.landBiomes()); - assertThrows(UnsupportedOperationException.class, () -> arid.caveBiomes().add(desert.id())); - assertThrows(IllegalArgumentException.class, - () -> new PackRegion(arid.id(), "Arid", 0, land, List.of(), List.of(), List.of())); + assertThrows(UnsupportedOperationException.class, () -> arid.caveBiomes().add(new Weighted<>(desert.id(), 1))); } static final class Keep {} diff --git a/api/host/src/test/java/com/volmit/WeightedTest.java b/api/host/src/test/java/com/volmit/WeightedTest.java new file mode 100644 index 000000000..a6f26b172 --- /dev/null +++ b/api/host/src/test/java/com/volmit/WeightedTest.java @@ -0,0 +1,45 @@ +package com.volmit; + +import com.volmit.world.Weighted; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class WeightedTest { + @Test + void weightedEntriesCountAsCopiesOfThemselvesInARow() { + assertThrows(IllegalArgumentException.class, () -> new Weighted<>("plains", 0)); + assertThrows(IllegalArgumentException.class, () -> new Weighted<>("plains", Weighted.MAX_WEIGHT + 1)); + assertThrows(NullPointerException.class, () -> new Weighted(null, 1)); + + var entries = List.of(new Weighted<>("barren", 3), new Weighted<>("forest", 1)); + assertEquals("barren", Weighted.pick(entries, 0.74, Weighted.Edge.EARLIER)); + assertEquals("forest", Weighted.pick(entries, 0.76, Weighted.Edge.EARLIER)); + assertEquals("barren", Weighted.pick(entries, -0.5, Weighted.Edge.EARLIER)); + assertEquals("forest", Weighted.pick(entries, 1.5, Weighted.Edge.LATER)); + assertNull(Weighted.pick(List.>of(), 0.5, Weighted.Edge.EARLIER)); + } + + @Test + void anEdgeGoesWhereTheRuleSays() { + var entries = List.of(new Weighted<>("first", 1), new Weighted<>("second", 1)); + assertEquals("first", Weighted.pick(entries, 0.5, Weighted.Edge.EARLIER)); + assertEquals("second", Weighted.pick(entries, 0.5, Weighted.Edge.LATER)); + assertEquals("second", Weighted.pick(entries, Math.nextUp(0.5), Weighted.Edge.EARLIER)); + } + + @Test + void halfSlotWeightsMatchTheOldRoundedChildPick() { + var oldSlots = List.of("barren", "barren", "barren", "forest", "barren", "barren"); + var converted = List.of(new Weighted<>("barren", 5), new Weighted<>("forest", 2), new Weighted<>("barren", 3)); + for (int step = 0; step <= 1000; step++) { + double noise = step / 1000D; + String oldPick = oldSlots.get((int) Math.round(noise * (oldSlots.size() - 1))); + assertEquals(oldPick, Weighted.pick(converted, noise, Weighted.Edge.LATER), "noise " + noise); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index 74d40820f..e58251356 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -26,6 +26,7 @@ import art.arcane.iris.engine.object.image.IrisImageMap; import art.arcane.iris.engine.object.noise.expression.IrisExpression; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeEntry; import art.arcane.iris.engine.object.world.region.IrisRegion; import com.volmit.block.BlockRegistry; import com.volmit.host.ResourceKindRegistration; @@ -39,6 +40,7 @@ import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.world.PackBiome; import com.volmit.world.PackRegion; +import com.volmit.world.Weighted; import java.util.Arrays; import java.util.Collection; @@ -247,16 +249,16 @@ public final class IrisPackResources implements PackResources { private PackBiome biomeOf(ResourceId id, IrisBiome biome) { return new PackBiome(id, biome.getName(), ResourceId.parse(biome.getDerivativeKey()), ResourceId.parse(biome.getVanillaDerivativeKey()), - biome.getRarity(), idsOf(biome.getChildren())); + weightedIdsOf(biome.getChildren())); } private PackRegion regionOf(ResourceId id, IrisRegion region) { - return new PackRegion(id, region.getName(), region.getRarity(), idsOf(region.getLandBiomes()), idsOf(region.getSeaBiomes()), - idsOf(region.getShoreBiomes()), idsOf(region.getCaveBiomes())); + return new PackRegion(id, region.getName(), weightedIdsOf(region.getLandBiomes()), weightedIdsOf(region.getSeaBiomes()), + weightedIdsOf(region.getShoreBiomes()), weightedIdsOf(region.getCaveBiomes())); } - private List idsOf(Collection keys) { - return keys.stream().map(ids::of).toList(); + private List> weightedIdsOf(Collection entries) { + return entries.stream().map(entry -> new Weighted<>(ids.of(entry.getBiome()), entry.getWeight())).toList(); } /** One kind of pack resource: the keys the pack has, how a key's resource is read, an index from ids to keys and what was read so far. */ diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java index 58d98e712..27cad20b3 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackDimensionValidator.java @@ -24,6 +24,7 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimensionType; import art.arcane.iris.engine.object.world.IrisWorldBoundary; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.world.Weighted; import java.io.File; import java.nio.charset.StandardCharsets; @@ -59,7 +60,8 @@ final class PackDimensionValidator { int resolvedRegions = 0; for (int i = 0; i < regionsArray.length(); i++) { - String regionKey = regionsArray.optString(i, null); + String regionKey = PackValidationIo.entryKey(regionsArray, i, "region"); + validateWeight(regionsArray.optJSONObject(i), "Dimension '" + dimensionKey + "' regions[" + i + "]", blockingErrors); if (regionKey == null || regionKey.isBlank()) { warnings.add("Dimension '" + dimensionKey + "' has a blank region entry at index " + i + "."); continue; @@ -78,10 +80,10 @@ final class PackDimensionValidator { continue; } - int anyBiome = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, warnings) - + countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, warnings) - + countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, warnings) - + countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, warnings); + int anyBiome = countBiomeRefs(regionJson, "landBiomes", biomesFolder, regionKey, blockingErrors, warnings) + + countBiomeRefs(regionJson, "seaBiomes", biomesFolder, regionKey, blockingErrors, warnings) + + countBiomeRefs(regionJson, "shoreBiomes", biomesFolder, regionKey, blockingErrors, warnings) + + countBiomeRefs(regionJson, "caveBiomes", biomesFolder, regionKey, blockingErrors, warnings); if (anyBiome == 0) { blockingErrors.add("Region '" + regionKey + "' has no resolvable biomes."); } @@ -94,14 +96,25 @@ final class PackDimensionValidator { } } - private static int countBiomeRefs(JSONObject regionJson, String field, File biomesFolder, String regionKey, List warnings) { + private static void validateWeight(JSONObject entry, String path, List blockingErrors) { + if (entry == null) { + return; + } + Integer weight = PackIntegerChecks.integerField(entry, "weight", Weighted.MIN_WEIGHT, path, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".weight", weight, Weighted.MIN_WEIGHT, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".weight", weight, Weighted.MAX_WEIGHT, blockingErrors); + } + + private static int countBiomeRefs(JSONObject regionJson, String field, File biomesFolder, String regionKey, + List blockingErrors, List warnings) { JSONArray arr = regionJson.optJSONArray(field); if (arr == null) { return 0; } int resolved = 0; for (int i = 0; i < arr.length(); i++) { - String biomeKey = arr.optString(i, null); + String biomeKey = PackValidationIo.entryKey(arr, i, "biome"); + validateWeight(arr.optJSONObject(i), "Region '" + regionKey + "' " + field + "[" + i + "]", blockingErrors); if (biomeKey == null || biomeKey.isBlank()) { continue; } diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java index 4332a1c8d..f133e2e8c 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackImageMapValidator.java @@ -519,7 +519,7 @@ final class PackImageMapValidator { return; } for (int index = 0; index < values.length(); index++) { - if (biomeKey.equals(values.optString(index, null))) { + if (biomeKey.equals(PackValidationIo.entryKey(values, index, "biome"))) { roles.add(role); return; } @@ -532,7 +532,7 @@ final class PackImageMapValidator { ) { Set regionKeys = new TreeSet<>(); if (dimension.getRegions() != null) { - for (String regionKey : dimension.getRegions()) { + for (String regionKey : dimension.getRegionKeys()) { String normalized = normalized(regionKey); if (normalized != null) { regionKeys.add(normalized); diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java b/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java new file mode 100644 index 000000000..ee4d57af5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java @@ -0,0 +1,224 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.pack; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Positions in the text of a JSON file as Iris reads it, with comments and trailing commas, so a file can be edited + * in place without rewriting the formatting around the edit. + */ +final class PackJsonText { + private PackJsonText() { + } + + /** A member of an object: the key and where its value starts and ends in the text. */ + record Member(String key, int keyStart, int valueStart, int valueEnd) { + } + + /** A value inside an array: where it starts and ends in the text. */ + record Item(int start, int end) { + } + + /** A replacement of the text from {@code start} up to {@code end}. */ + record Edit(int start, int end, String replacement) { + } + + static List members(String text, int objectStart) { + if (text.charAt(objectStart) != '{') { + throw new IllegalArgumentException("An object was expected at " + objectStart); + } + + List members = new ArrayList<>(); + int index = skipBlank(text, objectStart + 1); + while (index < text.length() && text.charAt(index) != '}') { + if (text.charAt(index) == ',') { + index = skipBlank(text, index + 1); + continue; + } + + if (text.charAt(index) != '"') { + throw new IllegalArgumentException("A key was expected at " + index); + } + + int keyEnd = stringEnd(text, index); + int colon = skipBlank(text, keyEnd + 1); + int valueStart = skipBlank(text, colon + 1); + int valueEnd = valueEnd(text, valueStart); + members.add(new Member(text.substring(index + 1, keyEnd), index, valueStart, valueEnd)); + index = skipBlank(text, valueEnd); + } + return members; + } + + static Member member(List members, String key) { + return members.stream().filter(member -> member.key().equals(key)).findFirst().orElse(null); + } + + static List items(String text, int arrayStart) { + if (text.charAt(arrayStart) != '[') { + throw new IllegalArgumentException("An array was expected at " + arrayStart); + } + + List items = new ArrayList<>(); + int index = skipBlank(text, arrayStart + 1); + while (index < text.length() && text.charAt(index) != ']') { + if (text.charAt(index) == ',') { + index = skipBlank(text, index + 1); + continue; + } + + int end = valueEnd(text, index); + items.add(new Item(index, end)); + index = skipBlank(text, end); + } + return items; + } + + /** The text of the file with every edit applied; the edits must not overlap. */ + static String apply(String text, List edits) { + StringBuilder edited = new StringBuilder(text); + edits.stream().sorted(Comparator.comparingInt(Edit::start).reversed()) + .forEach(edit -> edited.replace(edit.start(), edit.end(), edit.replacement())); + return edited.toString(); + } + + /** The edit that takes the member out, together with its comma and, when it stands alone there, its lines. */ + static Edit removal(String text, Member member) { + int start = member.keyStart(); + int end = member.valueEnd(); + int after = skipBlank(text, end); + if (after < text.length() && text.charAt(after) == ',') { + end = after + 1; + } else { + int before = start - 1; + while (before >= 0 && Character.isWhitespace(text.charAt(before))) { + before--; + } + if (before >= 0 && text.charAt(before) == ',') { + start = before; + } + } + + int lineStart = text.lastIndexOf('\n', start - 1) + 1; + int lineEnd = text.indexOf('\n', end); + if (lineEnd < 0) { + lineEnd = text.length(); + } + + boolean alone = text.substring(lineStart, start).isBlank() && text.substring(end, lineEnd).isBlank(); + if (!alone) { + return new Edit(start, end, ""); + } + return new Edit(lineStart, Math.min(lineEnd + 1, text.length()), ""); + } + + /** The whitespace the line holding {@code position} starts with. */ + static String indentAt(String text, int position) { + int lineStart = text.lastIndexOf('\n', position - 1) + 1; + int index = lineStart; + while (index < position && (text.charAt(index) == ' ' || text.charAt(index) == '\t')) { + index++; + } + return text.substring(lineStart, index); + } + + static int skipBlank(String text, int index) { + int position = index; + while (position < text.length()) { + if (Character.isWhitespace(text.charAt(position))) { + position++; + } else if (isComment(text, position)) { + position = commentEnd(text, position); + } else { + break; + } + } + return position; + } + + static int valueEnd(String text, int start) { + char first = text.charAt(start); + if (first == '"') { + return stringEnd(text, start) + 1; + } + + if (first != '[' && first != '{') { + return literalEnd(text, start); + } + + int depth = 0; + int index = start; + while (index < text.length()) { + char current = text.charAt(index); + if (current == '"') { + index = stringEnd(text, index); + } else if (isComment(text, index)) { + index = commentEnd(text, index) - 1; + } else if (current == '[' || current == '{') { + depth++; + } else if (current == ']' || current == '}') { + depth--; + if (depth == 0) { + return index + 1; + } + } + index++; + } + throw new IllegalArgumentException("The value at " + start + " is not closed"); + } + + private static int literalEnd(String text, int start) { + int index = start; + while (index < text.length() && ",]} \t\r\n".indexOf(text.charAt(index)) < 0 && !isComment(text, index)) { + index++; + } + return index; + } + + private static int stringEnd(String text, int quote) { + int index = quote + 1; + while (index < text.length() && text.charAt(index) != '"') { + index += text.charAt(index) == '\\' ? 2 : 1; + } + if (index >= text.length()) { + throw new IllegalArgumentException("The string at " + quote + " is not closed"); + } + return index; + } + + private static boolean isComment(String text, int index) { + return text.startsWith("//", index) || text.startsWith("/*", index); + } + + private static int commentEnd(String text, int start) { + if (text.startsWith("//", start)) { + int lineEnd = text.indexOf('\n', start); + return lineEnd < 0 ? text.length() : lineEnd; + } + + int close = text.indexOf("*/", start + 2); + if (close < 0) { + throw new IllegalArgumentException("The comment at " + start + " is not closed"); + } + return close + 2; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java b/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java index 215b878fe..3008da4a0 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackValidationIo.java @@ -57,6 +57,12 @@ public final class PackValidationIo { } } + /** The key the entry at {@code index} of a weighted list names in {@code field}; null when the entry is not an object with one. */ + static String entryKey(JSONArray entries, int index, String field) { + JSONObject entry = entries.optJSONObject(index); + return entry == null ? null : entry.optString(field, null); + } + static boolean isScannableJsonPath(Path path) { String name = path.getFileName().toString(); if (!name.endsWith(".json")) { diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java b/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java new file mode 100644 index 000000000..fe6c0719f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java @@ -0,0 +1,514 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.pack; + +import art.arcane.iris.core.pack.PackJsonText.Edit; +import art.arcane.iris.core.pack.PackJsonText.Item; +import art.arcane.iris.core.pack.PackJsonText.Member; +import com.google.gson.JsonParser; +import com.volmit.world.Weighted; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.stream.Stream; + +/** + * Converts a pack from rarity to weighted list entries, keeping the share every list entry had in its pick: + *
+ * "landBiomes": [{"biome": "plains", "weight": 3}, ...]        (also seaBiomes, shoreBiomes, caveBiomes)
+ * "regions":    [{"region": "temperate", "weight": 2}, ...]     (in the dimension)
+ * "children":   [{"biome": "forest", "weight": 2}, {"biome": "plains", "weight": 5}, ...]
+ * "carving":    [{"id": "deep", "children": [{"id": "lush", "weight": 2}, {"id": "deep", "weight": 5}]}]
+ * 
+ * Region, biome and dimension lists were picked with a share of 1 / rarity per entry, so an entry's weight is the least + * common multiple of the list's rarities divided by its rarity, reduced by the greatest common divisor. Children were + * picked from rounded slots, the rarer a biome the fewer, alternating from both ends, with the parent among them; the + * parent is listed among its children wherever it kept the spot, in half slots, since the first and last slot only + * held half a slot of noise. A carving entry's children pick the same way by the rarity of the entries' biomes. The + * top-level {@code rarity} of biomes and regions is removed; nested rarities (loot, spawns, objects) stay. + *

+ * Files are edited as text, so formatting elsewhere stays; a rewritten list gets one entry per line. A list that would need + * a weight above {@link Weighted#MAX_WEIGHT} stops the conversion. A pack with lists already converted and lists not yet + * converted cannot be told apart from rarity 1 and is refused. + *

+ * Usage: {@code PackWeightConverter [--dry-run] ...} + */ +public final class PackWeightConverter { + private static final String INDENT_STEP = " "; + private static final String JSON_EXTENSION = ".json"; + private static final int DEFAULT_RARITY = 1; + private static final List BIOME_LISTS = List.of("landBiomes", "seaBiomes", "shoreBiomes", "caveBiomes"); + + /** The files a conversion changed (relative to the pack) and what it could not carry over exactly. */ + public record Result(List changedFiles, List warnings) { + } + + /** A pack the converter cannot convert while keeping every pick. */ + public static final class ConversionException extends RuntimeException { + ConversionException(String message) { + super(message); + } + } + + private record Entry(String key, int weight) { + } + + private record Option(String key, int rarity) { + } + + private record CarvingBand(String biome, boolean enabled) { + } + + private final Path pack; + private final Map biomeRarities; + private final Map regionRarities; + private final TreeSet warnings = new TreeSet<>(); + private String currentFile = ""; + + private PackWeightConverter(Path pack) throws IOException { + this.pack = pack; + this.biomeRarities = rarities("biomes"); + this.regionRarities = rarities("regions"); + } + + public static Result convert(Path pack, boolean dryRun) throws IOException { + PackWeightConverter converter = new PackWeightConverter(pack); + converter.refusePartlyConverted(); + Map converted = new LinkedHashMap<>(); + for (String folder : List.of("biomes", "regions", "dimensions")) { + for (Path file : converter.files(folder)) { + String text = converter.convertFile(folder, file); + if (text != null) { + converted.put(file, text); + } + } + } + + List changed = new ArrayList<>(); + for (Map.Entry file : converted.entrySet()) { + changed.add(relative(pack, file.getKey())); + if (!dryRun) { + Files.writeString(file.getKey(), file.getValue(), StandardCharsets.UTF_8); + } + } + return new Result(changed, List.copyOf(converter.warnings)); + } + + public static void main(String[] arguments) throws IOException { + boolean dryRun = false; + List packs = new ArrayList<>(); + for (String argument : arguments) { + if (argument.equals("--dry-run")) { + dryRun = true; + } else { + packs.add(Path.of(argument)); + } + } + + if (packs.isEmpty()) { + System.err.println("Usage: PackWeightConverter [--dry-run] ..."); + System.exit(2); + } + + for (Path folder : packs) { + try { + Result result = convert(folder, dryRun); + result.changedFiles().forEach(System.out::println); + result.warnings().forEach(warning -> System.out.println("warning: " + warning)); + System.out.println(folder + ": " + result.changedFiles().size() + " files " + (dryRun ? "would change" : "changed")); + } catch (ConversionException refusal) { + System.err.println(folder + ": " + refusal.getMessage()); + System.exit(1); + } + } + } + + /** The converted text of the file; null when nothing in it changes. */ + private String convertFile(String folder, Path file) throws IOException { + currentFile = relative(pack, file); + String text = Files.readString(file, StandardCharsets.UTF_8); + String converted = switch (folder) { + case "biomes" -> convertBiome(keyOf(pack.resolve(folder), file), text); + case "regions" -> convertRegion(text); + default -> convertDimension(text); + }; + if (converted.equals(text)) { + return null; + } + + verifyParses(converted); + return converted; + } + + private static String relative(Path pack, Path file) { + return pack.relativize(file).toString().replace('\\', '/'); + } + + private String convertBiome(String key, String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + Member children = PackJsonText.member(members, "children"); + List childKeys = stringItems(text, children); + if (childKeys != null) { + edits.add(replaceList(text, children, "biome", childEntries(key, childKeys))); + } + addRarityRemoval(text, members, edits); + return PackJsonText.apply(text, edits); + } + + private String convertRegion(String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + for (String list : BIOME_LISTS) { + Member member = PackJsonText.member(members, list); + List keys = stringItems(text, member); + if (keys != null) { + edits.add(replaceList(text, member, "biome", listEntries(keys, biomeRarities))); + } + } + addRarityRemoval(text, members, edits); + return PackJsonText.apply(text, edits); + } + + private String convertDimension(String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + Member regions = PackJsonText.member(members, "regions"); + List regionKeys = stringItems(text, regions); + if (regionKeys != null) { + edits.add(replaceList(text, regions, "region", listEntries(regionKeys, regionRarities))); + } + + Member carving = PackJsonText.member(members, "carving"); + if (carving != null && text.charAt(carving.valueStart()) == '[') { + edits.addAll(convertCarving(text, carving)); + } + return PackJsonText.apply(text, edits); + } + + private List convertCarving(String text, Member carving) { + List> bands = new ArrayList<>(); + for (Item item : PackJsonText.items(text, carving.valueStart())) { + bands.add(text.charAt(item.start()) == '{' ? PackJsonText.members(text, item.start()) : List.of()); + } + + Map bandsById = new HashMap<>(); + for (List members : bands) { + String id = stringValue(text, PackJsonText.member(members, "id")).trim(); + if (!id.isEmpty()) { + bandsById.put(id, carvingBand(text, members)); + } + } + + List edits = new ArrayList<>(); + for (List members : bands) { + Member children = PackJsonText.member(members, "children"); + List childIds = stringItems(text, children); + if (childIds != null) { + edits.add(replaceList(text, children, "id", carvingChildEntries(text, members, childIds, bandsById))); + } + } + return edits; + } + + private CarvingBand carvingBand(String text, List members) { + Member enabled = PackJsonText.member(members, "enabled"); + boolean isEnabled = enabled == null || !text.startsWith("false", enabled.valueStart()); + return new CarvingBand(stringValue(text, PackJsonText.member(members, "biome")).trim(), isEnabled); + } + + private List carvingChildEntries(String text, List members, List childIds, Map bandsById) { + String parentId = stringValue(text, PackJsonText.member(members, "id")).trim(); + if (parentId.isEmpty()) { + throw new ConversionException(currentFile + ": a carving entry with children needs an id, so that it can list itself among them"); + } + + List