From b54c277568c08b6ddadce34f39676d7e362376eb Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:08:09 +0100 Subject: [PATCH] Use vanilla height profiles for existing planet ores --- .forgejo/workflows/planet-ore-profiles.yml | 52 ++++ .../worldgen/biome/frozen_desert.json | 44 ++-- .../com/example/duneterrain/DuneTerrain.java | 30 +-- .../com/example/duneterrain/OreHeights.java | 144 +++++++++++ .../example/duneterrain/OreHeightsTest.java | 40 +++ tools/PlanetOreTransition.java | 65 +++++ tools/planet_ore_release.py | 113 +++++++++ tools/reset-planet-ores.py | 227 ++++++++++++++++++ tools/test_planet_ore_release.py | 64 +++++ 9 files changed, 723 insertions(+), 56 deletions(-) create mode 100644 .forgejo/workflows/planet-ore-profiles.yml create mode 100644 DuneTerrain/src/main/java/com/example/duneterrain/OreHeights.java create mode 100644 DuneTerrain/src/test/java/com/example/duneterrain/OreHeightsTest.java create mode 100644 tools/PlanetOreTransition.java create mode 100644 tools/planet_ore_release.py create mode 100644 tools/reset-planet-ores.py create mode 100644 tools/test_planet_ore_release.py diff --git a/.forgejo/workflows/planet-ore-profiles.yml b/.forgejo/workflows/planet-ore-profiles.yml new file mode 100644 index 00000000..ade31f41 --- /dev/null +++ b/.forgejo/workflows/planet-ore-profiles.yml @@ -0,0 +1,52 @@ +name: Planet Ore Profiles Build +on: + workflow_dispatch: + push: + branches: ['feat/planet-ore-profiles-*'] + +jobs: + planet-ore-profiles: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Build and verify ore sampler + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + python3 tools/test_planet_ore_release.py + mkdir planet-ore-artifacts + python3 tools/planet_ore_release.py extract DuneTerrain/build/libs/DuneRealms-Terrain.jar planet-ore-artifacts/ore-heights.zip + cp tools/{PlanetOreTransition.java,planet_ore_release.py,reset-planet-ores.py} planet-ore-artifacts/ + cp DuneTerrain/planet-datapacks/sigma_draconis_iv/data/dunerealms/worldgen/biome/frozen_desert.json planet-ore-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > planet-ore-artifacts/SOURCE_COMMIT + (cd planet-ore-artifacts && sha256sum -- *.java *.json *.py *.zip SOURCE_COMMIT > SHA256SUMS) + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + - name: Verify the class transition builder + shell: bash + run: | + set -euo pipefail + javac -d "$(mktemp -d)" tools/PlanetOreTransition.java + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Planet-Ore-Profiles + path: planet-ore-artifacts/ + if-no-files-found: error diff --git a/DuneTerrain/planet-datapacks/sigma_draconis_iv/data/dunerealms/worldgen/biome/frozen_desert.json b/DuneTerrain/planet-datapacks/sigma_draconis_iv/data/dunerealms/worldgen/biome/frozen_desert.json index 28f43799..503d1cca 100644 --- a/DuneTerrain/planet-datapacks/sigma_draconis_iv/data/dunerealms/worldgen/biome/frozen_desert.json +++ b/DuneTerrain/planet-datapacks/sigma_draconis_iv/data/dunerealms/worldgen/biome/frozen_desert.json @@ -7,17 +7,7 @@ "creature_spawn_probability": 0.07, "downfall": 0.5, "effects": { - "fog_color": 12638463, - "mood_sound": { - "block_search_extent": 8, - "offset": 2, - "sound": "minecraft:ambient.cave", - "tick_delay": 6000 - }, - "music_volume": 1, - "sky_color": 8364543, - "water_color": 4159204, - "water_fog_color": 329011 + "water_color": "#3f76e4" }, "features": [ [], @@ -44,22 +34,6 @@ "minecraft:ore_andesite_upper", "minecraft:ore_andesite_lower", "minecraft:ore_tuff", - "minecraft:ore_coal_upper", - "minecraft:ore_coal_lower", - "minecraft:ore_iron_upper", - "minecraft:ore_iron_middle", - "minecraft:ore_iron_small", - "minecraft:ore_gold", - "minecraft:ore_gold_lower", - "minecraft:ore_redstone", - "minecraft:ore_redstone_lower", - "minecraft:ore_diamond", - "minecraft:ore_diamond_medium", - "minecraft:ore_diamond_large", - "minecraft:ore_diamond_buried", - "minecraft:ore_lapis", - "minecraft:ore_lapis_buried", - "minecraft:ore_copper", "minecraft:underwater_magma", "minecraft:disk_sand", "minecraft:disk_clay", @@ -108,5 +82,19 @@ "water_ambient": [], "water_creature": [] }, - "temperature": -0.7 + "temperature": -0.7, + "attributes": { + "minecraft:visual/fog_color": "#c0d8ff", + "minecraft:visual/sky_color": "#7fa1ff", + "minecraft:visual/water_fog_color": "#050533", + "minecraft:audio/ambient_sounds": { + "mood": { + "block_search_extent": 8, + "offset": 2, + "sound": "minecraft:ambient.cave", + "tick_delay": 6000 + } + }, + "minecraft:audio/music_volume": 1 + } } diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java index aa80a1ae..68431548 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java @@ -633,34 +633,8 @@ public final class DuneTerrain extends JavaPlugin implements Listener { } } } - // Arrakis now permits only its explicitly configured coal and emerald deposits. - org.bukkit.configuration.ConfigurationSection ores = plugin.getConfig().getConfigurationSection(path + "ores"); - if (ores == null) return; - int minY = Math.max(minWorldY + 1, plugin.getConfig().getInt(path + "ores.min-y", -48)); - int maxY = Math.min(maxWorldY - 4, plugin.getConfig().getInt(path + "ores.max-y", 48)); - int veinSize = Math.max(1, Math.min(16, plugin.getConfig().getInt(path + "ores.vein-size", 5))); - if (maxY < minY) return; - for (String key : ores.getKeys(false)) { - Material ore = Material.matchMaterial(key); - if (ore == null || (!key.endsWith("_ORE") && !(planet.equals("giedi_prime") && ore == Material.ANCIENT_DEBRIS))) continue; - if(planet.equals("arrakis")&&ore!=Material.COAL_ORE&&ore!=Material.EMERALD_ORE)continue; - int attempts = Math.max(0, Math.min(64, ores.getInt(key, 0))); - int effectiveVeinSize = ore == Material.ANCIENT_DEBRIS - ? Math.max(1, Math.min(16, plugin.getConfig().getInt(path + "ancient-debris.vein-size", 5))) : veinSize; - int oreMinY = ore == Material.ANCIENT_DEBRIS ? Math.max(minWorldY + 1, plugin.getConfig().getInt(path + "ancient-debris.min-y", -59)) : minY; - int oreMaxY = ore == Material.ANCIENT_DEBRIS ? Math.min(maxWorldY - 4, plugin.getConfig().getInt(path + "ancient-debris.max-y", 16)) : maxY; - if (oreMaxY < oreMinY) continue; - for (int attempt = 0; attempt < attempts; attempt++) { - int x = random.nextInt(16), z = random.nextInt(16), y = oreMinY + random.nextInt(oreMaxY - oreMinY + 1); - for (int n = 0; n < effectiveVeinSize; n++) { - int vx = Math.max(0, Math.min(15, x + random.nextInt(3) - 1)); - int vz = Math.max(0, Math.min(15, z + random.nextInt(3) - 1)); - int vy = Math.max(oreMinY, Math.min(oreMaxY, y + random.nextInt(3) - 1)); - Material existing = data.getType(vx, vy, vz); - if (existing == Material.STONE || existing == Material.DEEPSLATE || existing == Material.TUFF) data.setBlock(vx, vy, vz, ore); - } - } - } + OreHeights.place(plugin.getConfig().getConfigurationSection(path + "ores"), + data, random, path, planet, minWorldY, maxWorldY); } private void placeJungleTree(ChunkData data, int x, int y, int z, Random random, int maxY) { int height = 4 + random.nextInt(4); diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/OreHeights.java b/DuneTerrain/src/main/java/com/example/duneterrain/OreHeights.java new file mode 100644 index 00000000..79e96a1d --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/OreHeights.java @@ -0,0 +1,144 @@ +package com.example.duneterrain; + +import java.util.Map; +import java.util.Random; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.generator.ChunkGenerator.ChunkData; + +/** Ordinary 26.2 placed-feature height densities, with the planet's own vein counts. */ +final class OreHeights { + private static final int BELOW_BOTTOM = -64; + private static final int TOP = 319; + private static final int MAX_ANCHOR = 480; + + private record Band(int min, int max, double weight, boolean triangle) { + double density(int y) { + if (y < min || y > max) return 0; + if (!triangle) return weight / (max - min + 1); + int lowSide = (max - min) / 2; + int highSide = max - min - lowSide; + int outcomes = 1 + Math.min(Math.min(y - min, max - y), lowSide); + return weight * outcomes / ((lowSide + 1) * (highSide + 1)); + } + } + + private static Band uniform(int min, int max, double weight) { return new Band(min, max, weight, false); } + private static Band triangle(int min, int max, double weight) { return new Band(min, max, weight, true); } + + private static double[] curve(Band... bands) { + double[] cumulative = new double[MAX_ANCHOR - BELOW_BOTTOM + 2]; + for (int y = BELOW_BOTTOM; y <= MAX_ANCHOR; y++) { + int index = y - BELOW_BOTTOM; + double density = 0; + for (Band band : bands) density += band.density(y); + cumulative[index + 1] = cumulative[index] + density; + } + return cumulative; + } + + // Data in Minecraft 26.2 data/minecraft/worldgen/placed_feature/ore_*.json. + // The base biome weights exclude badlands bonus gold and larger dripstone copper veins. + private static final Map HEIGHTS = Map.of( + Material.COAL_ORE, curve(triangle(0, 192, 20), uniform(136, TOP, 30)), + Material.COPPER_ORE, curve(triangle(-16, 112, 16)), + Material.IRON_ORE, curve(triangle(-24, 56, 10), uniform(-64, 72, 10), triangle(80, 384, 90)), + Material.GOLD_ORE, curve(triangle(-64, 32, 4), uniform(-64, -48, .5)), + Material.LAPIS_ORE, curve(triangle(-32, 32, 2), uniform(-64, 64, 4)), + Material.REDSTONE_ORE, curve(uniform(-64, 15, 4), triangle(-96, -32, 8)), + Material.DIAMOND_ORE, curve(triangle(-144, 16, 11 + 1.0 / 9), uniform(-64, -4, 2)), + Material.EMERALD_ORE, curve(triangle(-16, 480, 100)), + Material.ANCIENT_DEBRIS, curve(triangle(8, 24, 1), uniform(8, 119, 1)) + ); + + private static final Map DEEPSLATE = Map.of( + Material.COAL_ORE, Material.DEEPSLATE_COAL_ORE, + Material.COPPER_ORE, Material.DEEPSLATE_COPPER_ORE, + Material.IRON_ORE, Material.DEEPSLATE_IRON_ORE, + Material.GOLD_ORE, Material.DEEPSLATE_GOLD_ORE, + Material.LAPIS_ORE, Material.DEEPSLATE_LAPIS_ORE, + Material.REDSTONE_ORE, Material.DEEPSLATE_REDSTONE_ORE, + Material.DIAMOND_ORE, Material.DEEPSLATE_DIAMOND_ORE, + Material.EMERALD_ORE, Material.DEEPSLATE_EMERALD_ORE + ); + + private OreHeights() {} + + static int choose(Material ore, int minY, int maxY, double quantile) { + if (minY > maxY) return Integer.MIN_VALUE; + double[] curve = HEIGHTS.get(ore); + if (curve == null) return minY + (int)(quantile * (maxY - minY + 1)); + int low = Math.max(minY, BELOW_BOTTOM) - BELOW_BOTTOM; + int high = Math.min(maxY, MAX_ANCHOR) - BELOW_BOTTOM; + if (low > high || curve[low] == curve[high + 1]) return Integer.MIN_VALUE; + double threshold = curve[low] + quantile * (curve[high + 1] - curve[low]); + while (low < high) { + int mid = (low + high) >>> 1; + if (curve[mid + 1] <= threshold) low = mid + 1; + else high = mid; + } + return low + BELOW_BOTTOM; + } + + static Material variant(Material ore, Material host) { + return host == Material.DEEPSLATE || host == Material.TUFF ? DEEPSLATE.getOrDefault(ore, ore) : ore; + } + + static void place(ConfigurationSection ores, ChunkData data, Random random, String path, + String planet, int minWorldY, int maxWorldY) { + if (ores == null) return; + ConfigurationSection config = ores.getRoot(); + int legacyMin = Math.max(minWorldY + 1, ores.getInt("min-y", -48)); + int legacyMax = Math.min(maxWorldY - 4, ores.getInt("max-y", 48)); + if (legacyMax < legacyMin) return; + int defaultSize = Math.clamp(ores.getInt("vein-size", 5), 1, 16); + int[] ceilingByColumn = new int[256]; + java.util.Arrays.fill(ceilingByColumn, Integer.MIN_VALUE); + for (String key : ores.getKeys(false)) { + Material ore = Material.matchMaterial(key); + boolean debris = ore == Material.ANCIENT_DEBRIS; + if (ore == null || (!key.endsWith("_ORE") && !(debris && planet.equals("giedi_prime")))) continue; + if (planet.equals("arrakis") && ore != Material.COAL_ORE && ore != Material.EMERALD_ORE) continue; + int attempts = Math.clamp(ores.getInt(key, 0), 0, 64); + int size = debris ? Math.clamp(config.getInt(path + "ancient-debris.vein-size", 5), 1, 16) : defaultSize; + int oldMin = debris ? Math.max(minWorldY + 1, config.getInt(path + "ancient-debris.min-y", -59)) : legacyMin; + int oldMax = debris ? Math.min(maxWorldY - 4, config.getInt(path + "ancient-debris.max-y", 16)) : legacyMax; + if (oldMax < oldMin) continue; + int lower = HEIGHTS.containsKey(ore) ? minWorldY + 1 : oldMin; + int upper = HEIGHTS.containsKey(ore) ? maxWorldY - 4 : oldMax; + for (int attempt = 0; attempt < attempts; attempt++) { + int x = random.nextInt(16), z = random.nextInt(16); + int priorDraw = random.nextInt(oldMax - oldMin + 1); + int column = x * 16 + z; + if (ceilingByColumn[column] == Integer.MIN_VALUE) { + int ceiling = maxWorldY - 4; + while (ceiling > minWorldY && !host(data.getType(x, ceiling, z))) ceiling--; + ceilingByColumn[column] = ceiling; + } + double quantile = quantile(priorDraw, column, attempt); + int height = choose(ore, lower, Math.min(upper, ceilingByColumn[column]), quantile); + for (int n = 0; n < size; n++) { + int vx = Math.clamp(x + random.nextInt(3) - 1, 0, 15); + int vz = Math.clamp(z + random.nextInt(3) - 1, 0, 15); + int dy = random.nextInt(3) - 1; + if (height == Integer.MIN_VALUE) continue; + int vy = Math.clamp(height + dy, lower, upper); + Material existing = data.getType(vx, vy, vz); + if (host(existing)) data.setBlock(vx, vy, vz, variant(ore, existing)); + } + } + } + } + + private static boolean host(Material material) { + return material == Material.STONE || material == Material.DEEPSLATE || material == Material.TUFF; + } + + // Keep the generator's original random draws and derive the height entropy from their values. + private static double quantile(int draw, int column, int attempt) { + long mixed = (draw * 256L + column + 1) * 0x9e3779b97f4a7c15L + attempt; + mixed = (mixed ^ (mixed >>> 30)) * 0xbf58476d1ce4e5b9L; + mixed = (mixed ^ (mixed >>> 27)) * 0x94d049bb133111ebL; + return ((mixed ^ (mixed >>> 31)) >>> 11) * 0x1.0p-53; + } +} diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/OreHeightsTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/OreHeightsTest.java new file mode 100644 index 00000000..f7dc4f1b --- /dev/null +++ b/DuneTerrain/src/test/java/com/example/duneterrain/OreHeightsTest.java @@ -0,0 +1,40 @@ +package com.example.duneterrain; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.stream.IntStream; +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +class OreHeightsTest { + @Test void vanillaDepthTrendsSurviveClippingToPlanetBedrockAndSurface() { + assertTrue(mean(Material.DIAMOND_ORE, -63, 70) < -30); + assertTrue(mean(Material.REDSTONE_ORE, -63, 70) < -32); + assertTrue(mean(Material.GOLD_ORE, -63, 70) < -12); + assertTrue(mean(Material.COAL_ORE, -63, 70) > 40); + assertTrue(mean(Material.EMERALD_ORE, -63, 70) > 35); + assertTrue(mean(Material.COPPER_ORE, -63, 100) > 35); + assertTrue(mean(Material.IRON_ORE, -63, 70) > -10); + assertTrue(Math.abs(mean(Material.LAPIS_ORE, -63, 70)) < 3); + assertEquals(Integer.MIN_VALUE, OreHeights.choose(Material.COAL_ORE, -63, -1, .5)); + assertEquals(Integer.MIN_VALUE, OreHeights.choose(Material.DIAMOND_ORE, 17, 100, .5)); + assertEquals(42, OreHeights.choose(Material.COPPER_ORE, 42, 42, .5)); + } + + @Test void highPeaksKeepVanillaUpperIronAndCoalBands() { + assertTrue(OreHeights.choose(Material.IRON_ORE, -63, 250, .85) > 170); + assertTrue(OreHeights.choose(Material.COAL_ORE, -63, 250, .85) > 175); + } + + @Test void deepslateHostChangesTheBlockVariantOnly() { + assertEquals(Material.DIAMOND_ORE, OreHeights.variant(Material.DIAMOND_ORE, Material.STONE)); + assertEquals(Material.DEEPSLATE_DIAMOND_ORE, OreHeights.variant(Material.DIAMOND_ORE, Material.DEEPSLATE)); + assertEquals(Material.DEEPSLATE_LAPIS_ORE, OreHeights.variant(Material.LAPIS_ORE, Material.TUFF)); + assertEquals(Material.ANCIENT_DEBRIS, OreHeights.variant(Material.ANCIENT_DEBRIS, Material.DEEPSLATE)); + } + + private static double mean(Material ore, int minY, int maxY) { + return IntStream.range(0, 1000).map(i -> OreHeights.choose(ore, minY, maxY, (i + .5) / 1000)) + .average().orElseThrow(); + } +} diff --git a/tools/PlanetOreTransition.java b/tools/PlanetOreTransition.java new file mode 100644 index 00000000..815dde9e --- /dev/null +++ b/tools/PlanetOreTransition.java @@ -0,0 +1,65 @@ +import java.lang.classfile.ClassFile; +import java.lang.classfile.ClassTransform; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.CodeElement; +import java.lang.classfile.CodeTransform; +import java.lang.classfile.instruction.CharacterRange; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.classfile.instruction.LocalVariable; +import java.lang.classfile.instruction.LocalVariableType; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.nio.file.Files; +import java.nio.file.Path; + +/** Preserve the five retained generators, replacing the private ore-placement tail only. */ +class PlanetOreTransition { + private static final String PACKAGE = "com.example.duneterrain."; + private static final String GENERATOR = PACKAGE + "DuneTerrain$PlanetChunkGenerator"; + private static final String CHUNK = "Lorg/bukkit/generator/ChunkGenerator$ChunkData;"; + private static final String PARAMETERS = CHUNK + "Ljava/util/Random;Ljava/lang/String;"; + private static final String DESCRIPTOR = "(" + PARAMETERS + "II)V"; + private static final String SECTION = "Lorg/bukkit/configuration/ConfigurationSection;"; + + static byte[] patch(byte[] bytes) { + var format = ClassFile.of(); + var original = format.parse(bytes); + if (!original.thisClass().asInternalName().equals(GENERATOR.replace('.', '/'))) + throw new IllegalArgumentException("Expected retained planet generator"); + var splice = new OreTail(); + var updated = format.transformClass(original, ClassTransform.transformingMethodBodies( + method -> method.methodName().equalsString("placeOres") && method.methodType().equalsString(DESCRIPTOR), + splice)); + if (splice.configLookups != 1) throw new IllegalArgumentException("Unexpected retained ore routine"); + return updated; + } + + private static final class OreTail implements CodeTransform { + private int configLookups; + + @Override public void accept(CodeBuilder out, CodeElement element) { + if (element instanceof InvokeInstruction call + && call.owner().asInternalName().equals("org/bukkit/configuration/file/FileConfiguration") + && call.name().equalsString("getConfigurationSection") + && call.type().equalsString("(Ljava/lang/String;)" + SECTION)) { + if (++configLookups != 1) throw new IllegalArgumentException("Multiple ore configuration lookups"); + out.with(element); + out.aload(1).aload(2).aload(3).aload(0) + .getfield(ClassDesc.of(GENERATOR), "planet", ClassDesc.of("java.lang.String")) + .iload(4).iload(5) + .invokestatic(ClassDesc.of(PACKAGE + "OreHeights"), "place", + MethodTypeDesc.ofDescriptor("(" + SECTION + PARAMETERS + "Ljava/lang/String;II)V")) + .return_(); + } else if (configLookups == 0 && !(element instanceof LocalVariable + || element instanceof LocalVariableType || element instanceof CharacterRange)) { + out.with(element); + } + } + } + + public static void main(String[] args) throws Exception { + if (args.length != 2) throw new IllegalArgumentException("Expected input and output class paths"); + Files.write(Path.of(args[1]), patch(Files.readAllBytes(Path.of(args[0]))), + java.nio.file.StandardOpenOption.CREATE_NEW); + } +} diff --git a/tools/planet_ore_release.py b/tools/planet_ore_release.py new file mode 100644 index 00000000..a8d70073 --- /dev/null +++ b/tools/planet_ore_release.py @@ -0,0 +1,113 @@ +"""Assemble canonical ore code with each hash-pinned retained planet archive.""" + +import argparse +import hashlib +import json +from pathlib import Path +import subprocess +import tempfile +from zipfile import ZIP_DEFLATED, ZipFile + + +PLANETS = { + 'arrakis': '8ae685ebe3272f9a6be2928ecf2421b1892b9c4d3a40ed8efe1c22a57d1bd7b8', + 'caladan': 'de18104b28bd5aadeec139484b8627b961325a095d512e96561a87f9c9c54619', + 'giedi_prime': 'e853921b730a45edd32899fa614d0b60e09b41e478d7610520473b5b402e72f9', + 'kaitain': '263b9a704245dc810b239264315c3d90813f4fd5daac2437052580916021b1ac', + 'sigma_draconis_iv': '73424945f1206a7bfee4308ef1a91deff0fa8356166ded6f32dd6ce49179ec16', +} +PACKAGE = 'com/example/duneterrain/' +GENERATOR = PACKAGE + 'DuneTerrain$PlanetChunkGenerator.class' +SAMPLER = {PACKAGE + suffix for suffix in ('OreHeights.class', 'OreHeights$Band.class')} +SIGMA_PACK = '37544b795b053b3388f5335ad18db39a54fad0f484a8a4a76bbc850c689a7bfa' +SIGMA_BIOME = 'data/dunerealms/worldgen/biome/frozen_desert.json' +NATIVE_ORES = { + 'coal_upper', 'coal_lower', 'iron_upper', 'iron_middle', 'iron_small', 'gold', 'gold_lower', + 'redstone', 'redstone_lower', 'diamond', 'diamond_medium', 'diamond_large', 'diamond_buried', + 'lapis', 'lapis_buried', 'copper', +} + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def archive_names(archive): + entries = archive.namelist() + if len(set(entries)) != len(entries): + raise ValueError('Duplicate ZIP entry') + return set(entries) + + +def extract(compiled, output): + with ZipFile(compiled) as jar, ZipFile(output, 'x', ZIP_DEFLATED) as patch: + archive_names(jar) + for name in sorted(SAMPLER): + patch.writestr(name, jar.read(name)) + + +def assemble(planet, baseline, bundle, output, java): + if sha(baseline) != PLANETS[planet]: + raise ValueError('Unexpected retained terrain archive for ' + planet) + with ZipFile(baseline) as original, ZipFile(bundle / 'ore-heights.zip') as patch: + if SAMPLER & archive_names(original) or archive_names(patch) != SAMPLER: + raise ValueError('Unexpected ore sampler entries') + with tempfile.TemporaryDirectory() as tmp: + previous, candidate = Path(tmp) / 'previous.class', Path(tmp) / 'candidate.class' + previous.write_bytes(original.read(GENERATOR)) + subprocess.run([java, str(bundle / 'PlanetOreTransition.java'), str(previous), str(candidate)], check=True) + generator = candidate.read_bytes() + with ZipFile(output, 'x', ZIP_DEFLATED) as result: + for entry in original.infolist(): + result.writestr(entry, generator if entry.filename == GENERATOR else original.read(entry)) + for name in sorted(SAMPLER): + result.writestr(name, patch.read(name)) + + +def verify_terrain(baseline, candidate, bundle): + with ZipFile(baseline) as original, ZipFile(candidate) as incoming, ZipFile(bundle / 'ore-heights.zip') as patch: + names = archive_names(original) + if archive_names(patch) != SAMPLER or archive_names(incoming) != names | SAMPLER: + raise ValueError('Unexpected assembled Terrain archive entries') + if incoming.read(GENERATOR) == original.read(GENERATOR): + raise ValueError('Planet ore method was not updated') + for name in names - {GENERATOR}: + if incoming.read(name) != original.read(name): + raise ValueError(f'Unrelated Terrain entry changed: {name}') + for name in SAMPLER: + if incoming.read(name) != patch.read(name): + raise ValueError(f'Ore class differs from the canonical build: {name}') + + +def sigma_pack(baseline, reviewed, output): + if sha(baseline) != SIGMA_PACK: + raise ValueError('Unexpected retained Sigma biome pack') + with ZipFile(baseline) as original: + archive_names(original) + expected = json.loads(original.read(SIGMA_BIOME)) + features = {f'minecraft:ore_{name}' for name in NATIVE_ORES} + removed = set() + for layer in expected['features']: + removed.update(features.intersection(layer)) + layer[:] = [name for name in layer if name not in features] + if removed != features or expected != json.loads(reviewed.read_bytes()): + raise ValueError('Sigma biome patch changes more than the duplicated ore list') + with ZipFile(output, 'x', ZIP_DEFLATED) as result: + for entry in original.infolist(): + result.writestr(entry, reviewed.read_bytes() if entry.filename == SIGMA_BIOME else original.read(entry)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('mode', choices=['extract', 'sigma-pack', *PLANETS]) + parser.add_argument('input', type=Path) + parser.add_argument('output', type=Path) + parser.add_argument('--bundle', type=Path) + parser.add_argument('--java', default='java') + args = parser.parse_args() + if args.mode == 'extract': + extract(args.input, args.output) + elif args.mode == 'sigma-pack': + sigma_pack(args.input, args.bundle / 'frozen_desert.json', args.output) + else: + assemble(args.mode, args.input, args.bundle, args.output, args.java) diff --git a/tools/reset-planet-ores.py b/tools/reset-planet-ores.py new file mode 100644 index 00000000..1d642c0a --- /dev/null +++ b/tools/reset-planet-ores.py @@ -0,0 +1,227 @@ +"""Install the exact ore build and clear only one reviewed primary overworld.""" + +import argparse +from contextlib import ExitStack +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import tempfile + +from planet_ore_release import PLANETS, SIGMA_PACK, sha, sigma_pack, verify_terrain + + +ROOT = Path('/opt/dunerealms/servers') +DIMENSION = Path('dimensions/minecraft/overworld') +CHUNKS = ('region', 'entities', 'poi') +IDENTITY = ('data/minecraft/world_gen_settings.dat', 'data/paper/metadata.dat') +CONFIG = 'plugins/DuneTerrain/config.yml' +PACK = Path('datapacks/dunerealms-biomes.zip') +ASSETS = {'ore-heights.zip', 'PlanetOreTransition.java', 'planet_ore_release.py', + 'reset-planet-ores.py', 'frozen_desert.json', 'SOURCE_COMMIT'} + + +def checked(path): + if path.resolve(strict=True) != path.absolute(): + raise ValueError(f'Unexpected symlink or path: {path}') + return path + + +def fingerprint(path): + checked(path) + st = path.stat() + if not stat.S_ISREG(st.st_mode): + raise ValueError(f'Expected a regular file: {path}') + with path.open('rb') as stream: + digest = hashlib.file_digest(stream, 'sha256').hexdigest() + return (digest, st.st_uid, st.st_gid, stat.S_IMODE(st.st_mode)) + + +def world_snapshot(world, exclusions): + result = {} + for folder, dirs, files in os.walk(checked(world)): + path = Path(folder) + for name in dirs: + checked(path / name) + if path == world / DIMENSION: + dirs[:] = [name for name in dirs if name not in CHUNKS] + for name in files: + entry = path / name + if entry not in exclusions: + result[entry.relative_to(world).as_posix()] = fingerprint(entry) + return result + + +def chunk_files(dimension): + result = [] + for directory in CHUNKS: + folder = dimension / directory + if folder.is_symlink(): + raise ValueError(f'Symlinked chunk directory: {folder}') + if not folder.exists(): + if directory == 'region': + raise ValueError('Primary region directory is missing') + continue + for entry in sorted(checked(folder).iterdir()): + if not re.fullmatch(r'[rc]\.-?\d+\.-?\d+\.(mca|mcc)', entry.name) or not checked(entry).is_file(): + raise ValueError(f'Unexpected chunk storage entry: {entry}') + result.append(entry) + return result + + +def service(*args): + return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=True).stdout.strip() + + +def state(unit): + return service('show', unit, '--property=ActiveState', '--value') + + +def verify_bundle(bundle, source): + rows = (bundle / 'SHA256SUMS').read_text().splitlines() + sums = dict(row.split(' ', 1)[::-1] for row in rows) + if not re.fullmatch(r'[0-9a-f]{40}', source) or len(rows) != len(ASSETS) or sums.keys() != ASSETS: + raise ValueError('Unexpected canonical artifact manifest') + if any(fingerprint(bundle / name)[0] != digest for name, digest in sums.items()): + raise ValueError('Canonical artifact checksum mismatch') + if (bundle / 'SOURCE_COMMIT').read_text().strip() != source: + raise ValueError('Canonical artifact source mismatch') + + +def snapshot_server(root): + properties = root / 'server.properties' + settings = dict(line.split('=', 1) for line in properties.read_text().splitlines() if '=' in line and not line.startswith('#')) + return { + 'settings': settings, + 'configs': {name: fingerprint(root / name) for name in ( + CONFIG, 'bukkit.yml', 'plugins/MCGUI/config.yml', 'plugins/DunerealmsGUI/menu-pack.yml')}, + 'jars': {p.name: fingerprint(p) for p in (root / 'plugins').glob('*.jar')}, + } + + +def stage(target, payload, expected, stack): + fd, filename = tempfile.mkstemp(prefix='.planet-ore-', dir=target.parent) + candidate = Path(filename) + stack.callback(candidate.unlink, missing_ok=True) + with os.fdopen(fd, 'wb') as stream: + stream.write(payload) + os.fchown(stream.fileno(), expected[1], expected[2]) + os.fchmod(stream.fileno(), expected[3]) + stream.flush() + os.fsync(stream.fileno()) + return candidate + + +def run(planet, bundle, source, candidate, expected_candidate, apply, receipt): + verify_bundle(checked(bundle), source) + root = checked(ROOT / planet) + unit = f'dune-{planet}.service' + if state(unit) != 'active' or service('show', unit, '--property=WorkingDirectory', '--value') != str(root): + raise ValueError('Unexpected planet service or working directory') + before = snapshot_server(root) + if before['settings'].get('level-name') != planet: + raise ValueError('Unexpected primary world name') + bukkit = (root / 'bukkit.yml').read_text() + if not re.search(rf'^\s+generator:\s*[\'\"]?DuneTerrain:{planet}[\'\"]?\s*$', bukkit, re.M): + raise ValueError('Expected the current DuneTerrain generator') + world = checked(root / planet) + dimension = checked(world / DIMENSION) + identity = {name: fingerprint(dimension / name) for name in IDENTITY} + existing = [name for name, pin in before['jars'].items() if pin[0] == PLANETS[planet]] + if len(existing) != 1: + raise ValueError('Expected exactly one pinned Terrain variant') + jar = root / 'plugins' / existing[0] + if not re.fullmatch(r'[0-9a-f]{64}', expected_candidate) or fingerprint(candidate)[0] != expected_candidate: + raise ValueError('Assembled Terrain differs from the independently reviewed candidate hash') + verify_terrain(jar, candidate, bundle) + pack = world / PACK if planet == 'sigma_draconis_iv' else None + previous = {jar: fingerprint(jar)} + if pack: + previous[pack] = fingerprint(pack) + if previous[pack][0] != SIGMA_PACK: + raise ValueError('Sigma biome pack differs from the reviewed baseline') + with tempfile.TemporaryDirectory() as temp: + targets = {jar: candidate} + if pack: + targets[pack] = Path(temp) / 'sigma.zip' + sigma_pack(pack, bundle / 'frozen_desert.json', targets[pack]) + report = {'source': source, 'planet': planet, 'unit': unit, 'world': str(world), 'identity': identity, + 'incoming': {str(target): sha(candidate) for target, candidate in targets.items()}, + 'chunkFileCount': len(chunk_files(dimension)), 'status': 'planned'} + if not apply: + return report + with receipt.open('x') as stream, ExitStack() as stack: + os.fchmod(stream.fileno(), 0o600) + originals = {target: stage(target, target.read_bytes(), previous[target], stack) for target in targets} + staged = {target: stage(target, candidate.read_bytes(), previous[target], stack) + for target, candidate in targets.items()} + if any(fingerprint(path) != previous[target] for target, path in originals.items()): + raise ValueError('Previous bytes changed during staging') + if any(fingerprint(path)[0] != report['incoming'][str(target)] for target, path in staged.items()): + raise ValueError('Incoming bytes changed during staging') + replaced, deleting = [], False + try: + service('stop', unit) + if state(unit) not in {'inactive', 'failed'} or service('show', unit, '--property=MainPID', '--value') != '0': + raise ValueError('Planet service failed to stop') + if snapshot_server(root) != before or any(fingerprint(target) != value for target, value in previous.items()): + raise ValueError('Protected server files changed during shutdown') + if any(fingerprint(dimension / name) != value for name, value in identity.items()): + raise ValueError('Primary seed or Paper identity changed during shutdown') + exclusions = {pack, *originals.values(), *staged.values()} + protected = world_snapshot(world, exclusions) + chunks = chunk_files(dimension) + for target, candidate in staged.items(): + os.replace(candidate, target) + replaced.append(target) + for file in chunks: + file.unlink() + deleting = True + if world_snapshot(world, exclusions) != protected: + raise ValueError('Protected world files changed before restart') + expected_server = before + expected_server['jars'][jar.name] = (report['incoming'][str(jar)], *previous[jar][1:]) + if snapshot_server(root) != expected_server or any( + fingerprint(target) != (report['incoming'][str(target)], *previous[target][1:]) for target in targets): + raise ValueError('Installed or retained bytes changed before restart') + report['chunkFileCount'] = len(chunks) + report['protectedWorldFileCount'] = len(protected) + service('start', unit) + report['status'] = 'start-accepted' + except BaseException: + report['status'] = 'needs-review' if deleting else 'aborted-before-world-reset' + if not deleting: + for target in reversed(replaced): + os.replace(originals[target], target) + if state(unit) in {'inactive', 'failed'}: + service('start', unit) + raise + finally: + json.dump(report, stream, indent=2) + stream.write('\n') + return report + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('planet', choices=PLANETS) + parser.add_argument('--bundle', required=True, type=Path) + parser.add_argument('--expected-source', required=True) + parser.add_argument('--candidate', required=True, type=Path) + parser.add_argument('--candidate-sha256', required=True) + parser.add_argument('--apply-reset-no-backup', action='store_true') + parser.add_argument('--receipt', type=Path) + args = parser.parse_args() + if args.apply_reset_no_backup != (args.receipt is not None): + parser.error('An apply requires a new private receipt path') + if args.apply_reset_no_backup: + import fcntl + with Path('/run/lock/dunerealms-planet-ore-reset.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + result = run(args.planet, args.bundle, args.expected_source, args.candidate, args.candidate_sha256, True, args.receipt) + else: + result = run(args.planet, args.bundle, args.expected_source, args.candidate, args.candidate_sha256, False, None) + print(json.dumps(result, indent=2)) diff --git a/tools/test_planet_ore_release.py b/tools/test_planet_ore_release.py new file mode 100644 index 00000000..453a6983 --- /dev/null +++ b/tools/test_planet_ore_release.py @@ -0,0 +1,64 @@ +import importlib.util +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from zipfile import ZipFile + +from planet_ore_release import GENERATOR, PLANETS, SAMPLER, verify_terrain + + +spec = importlib.util.spec_from_file_location('reset_planet_ores', Path(__file__).with_name('reset-planet-ores.py')) +reset = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reset) + + +class PlanetOreReleaseTest(unittest.TestCase): + def test_world_scope_preserves_other_dimensions_and_all_player_files(self): + with TemporaryDirectory() as temp: + world = Path(temp).resolve() + overworld = world / reset.DIMENSION + names = [ + overworld / 'region/r.0.0.mca', overworld / 'entities/r.0.0.mca', + overworld / 'data/paper/metadata.dat', world / 'players/data/test.dat', + world / 'dimensions/minecraft/the_nether/region/r.0.0.mca', + ] + for name in names: + name.parent.mkdir(parents=True, exist_ok=True) + name.write_text('retained fixture') + self.assertEqual(set(reset.chunk_files(overworld)), set(names[:2])) + self.assertEqual(set(reset.world_snapshot(world, set())), + {p.relative_to(world).as_posix() for p in names[2:]}) + unexpected = overworld / 'region/unreviewed.txt' + unexpected.touch() + with self.assertRaises(ValueError): + reset.chunk_files(overworld) + + def test_candidate_cannot_change_other_terrain_entries(self): + with TemporaryDirectory() as temp: + folder = Path(temp) + with ZipFile(folder / 'baseline.jar', 'w') as archive: + archive.writestr(GENERATOR, b'previous') + archive.writestr('config.yml', b'unchanged') + with ZipFile(folder / 'ore-heights.zip', 'w') as archive: + for name in SAMPLER: + archive.writestr(name, b'canonical') + for title, config in [('valid', b'unchanged'), ('modified', b'changed')]: + path = folder / f'{title}.jar' + with ZipFile(path, 'w') as archive: + archive.writestr(GENERATOR, b'reviewed transformation') + archive.writestr('config.yml', config) + for name in SAMPLER: + archive.writestr(name, b'canonical') + if title == 'valid': + verify_terrain(folder / 'baseline.jar', path, folder) + else: + with self.assertRaises(ValueError): + verify_terrain(folder / 'baseline.jar', path, folder) + + def test_five_world_scope_excludes_lobby(self): + self.assertEqual(set(PLANETS), {'arrakis', 'caladan', 'giedi_prime', 'kaitain', 'sigma_draconis_iv'}) + self.assertTrue(all(len(pin) == 64 for pin in PLANETS.values())) + + +if __name__ == '__main__': + unittest.main() -- 2.53.0