From 78dea2fb774f1fa2924ea9c6e17c894a150fd870 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:09:19 +0100 Subject: [PATCH] Rebuild Arrakis strata and bloom attempts with guarded world reset --- .forgejo/workflows/arrakis-terrain.yml | 43 ++ DuneTerrain/build.gradle.kts | 6 +- DuneTerrain/docs/ARRAKIS-RESET-20261129.md | 43 ++ .../example/duneterrain/ArrakisBlooms.java | 15 + .../example/duneterrain/ArrakisEcology.java | 2 +- .../example/duneterrain/ArrakisStrata.java | 7 + .../com/example/duneterrain/DuneTerrain.java | 40 +- DuneTerrain/src/main/resources/config.yml | 5 +- DuneTerrain/src/main/resources/plugin.yml | 2 +- .../duneterrain/ArrakisEcologyTest.java | 2 +- .../duneterrain/ArrakisGenerationTest.java | 47 ++ .../resources/retained-arrakis-terrain.json | 612 ++++++++++++++++++ tools/reset-arrakis-terrain.py | 284 ++++++++ tools/test_arrakis_terrain_reset.py | 112 ++++ tools/verify-arrakis-terrain.py | 28 + 15 files changed, 1220 insertions(+), 28 deletions(-) create mode 100644 .forgejo/workflows/arrakis-terrain.yml create mode 100644 DuneTerrain/docs/ARRAKIS-RESET-20261129.md create mode 100644 DuneTerrain/src/main/java/com/example/duneterrain/ArrakisBlooms.java create mode 100644 DuneTerrain/src/main/java/com/example/duneterrain/ArrakisStrata.java create mode 100644 DuneTerrain/src/test/java/com/example/duneterrain/ArrakisGenerationTest.java create mode 100644 DuneTerrain/src/test/resources/retained-arrakis-terrain.json create mode 100644 tools/reset-arrakis-terrain.py create mode 100644 tools/test_arrakis_terrain_reset.py create mode 100644 tools/verify-arrakis-terrain.py diff --git a/.forgejo/workflows/arrakis-terrain.yml b/.forgejo/workflows/arrakis-terrain.yml new file mode 100644 index 00000000..18cace7b --- /dev/null +++ b/.forgejo/workflows/arrakis-terrain.yml @@ -0,0 +1,43 @@ +name: Arrakis Terrain Build +on: + workflow_dispatch: + +jobs: + terrain: + 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: Test and package the bounded Terrain release + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneTerrain test jar + python3 tools/test_arrakis_terrain_reset.py -v + python3 tools/verify-arrakis-terrain.py DuneTerrain/build/libs/DuneRealms-Terrain.jar DuneTerrain/src/test/resources/retained-arrakis-terrain.json + mkdir terrain-artifacts + cp DuneTerrain/build/libs/DuneRealms-Terrain.jar terrain-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > terrain-artifacts/SOURCE_COMMIT + python3 tools/write-plugin-manifest.py terrain-artifacts "$GITHUB_SHA" + cp tools/reset-arrakis-terrain.py tools/verify-arrakis-terrain.py tools/plugin_backend_abi.py terrain-artifacts/ + cp DuneTerrain/src/test/resources/retained-arrakis-terrain.json DuneTerrain/docs/ARRAKIS-RESET-20261129.md terrain-artifacts/ + (cd terrain-artifacts && sha256sum -- *.jar *.json *.py *.md SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Arrakis-Terrain + path: terrain-artifacts/ + if-no-files-found: error diff --git a/DuneTerrain/build.gradle.kts b/DuneTerrain/build.gradle.kts index 22016d0f..ed47cc83 100644 --- a/DuneTerrain/build.gradle.kts +++ b/DuneTerrain/build.gradle.kts @@ -1,7 +1,7 @@ plugins { java } group = "com.example" -version = "1.0.13-worlds1" +version = "1.0.14-arrakis2" repositories { mavenCentral() @@ -33,5 +33,5 @@ tasks.assemble { dependsOn(highlandsDatapack) } val mockitoAgent by configurations.creating dependencies { mockitoAgent("org.mockito:mockito-core:5.15.2") { isTransitive = false } } tasks.test { jvmArgs("-javaagent:${mockitoAgent.singleFile.absolutePath}") } - -sourceSets.main { java.srcDir("../citizens-common/src/main/java") } + +sourceSets.main { java.srcDir("../citizens-common/src/main/java") } diff --git a/DuneTerrain/docs/ARRAKIS-RESET-20261129.md b/DuneTerrain/docs/ARRAKIS-RESET-20261129.md new file mode 100644 index 00000000..fc12908a --- /dev/null +++ b/DuneTerrain/docs/ARRAKIS-RESET-20261129.md @@ -0,0 +1,43 @@ +# Arrakis terrain: bounded generation and reset + +## Owner scope and verified target + +The owner explicitly requested a full Arrakis world reset after specifying four regular sand blocks above three sandstone blocks, no red-sand filler, generation-only spice blooms as rare as vanilla desert wells, and fewer new camels. The reset targets only `/opt/dunerealms/servers/arrakis`, `dune-arrakis.service`, level name `arrakis`. Lobby and the other planet servers are excluded. Preserve player identity, inventories, statistics, advancements, central keys, claims, economy and earned progression. The owner's later world-reset instruction supersedes preserving the old Arrakis terrain/builds/containers; the old world remains privately recoverable. + +The actual installed filename was `DuneTerrain-1.0.7.jar`, but its descriptor is **1.0.12-arrakeen1-fauna4-trails1-surface1-fauna606**, SHA-256 `012f9b0055020a94de955ec277cc46ca82a5efc8149e748ff30a333b6bc026dc`. Do not infer versions from filenames. Actual Bukkit mapping is `worlds.arrakis.generator: DuneTerrain:arrakis` with the matching biome provider. Actual Paper is 26.2 build 135; no Paper upgrade is included. + +## Source changes + +- Ordinary dune columns are SAND at surface depths 0–3, SANDSTONE at depths 4–6, then STONE/bedrock below. Heights, seed and formation settings are unchanged. Existing retained `filler: RED_SAND` configuration cannot silently override these Arrakis layers. Other planet generation keeps its existing path. +- Authentic DRIED_KELP_BLOCK spice disks previously depended on red sand below the surface. Their predicate now recognizes the new layer profile and places them below the four sand layers. Existing harvesting/identity/value rules are retained. +- New bloom anchors use a deterministic seed/chunk-bound algorithm with one-in-1000 chunk attempts and the existing sand/height checks. The target runtime's actual `data/minecraft/worldgen/placed_feature/desert_well.json` uses `rarity_filter` chance 1000, in-square placement, MOTION_BLOCKING heightmap and biome checks. This matches attempt rarity, not a guarantee of one successful bloom per 1000 chunks. +- Keep `spice-blow.spacing=2000` for historical anchor proof. Add `spice-blow.rarity=1000` for the new algorithm. Both old and new valid anchors remain accepted by the existing discovery proof. Reuse magma markers, detonation, authenticated spice drops and announcement/proof callbacks. No timed regeneration or reward change. +- New unprotected natural/chunk-generation camel allowance changes from the verified 50% to 10% on Arrakis: 80% fewer accepted attempts. This spawn policy does not kill existing or protected/tamed/named/NPC/custom/bred camels and does not affect other worlds. The separately authorised world reset archives old entities along with the old terrain. + +## Retained runtime compatibility + +The candidate retains all 28 old Terrain classes and their public fields/methods, verified without invoking gameplay. Pin the unchanged starter-repair resource. Read-only local comparison found StarterRepairDrops, FaunaProof and ChukkaMobs byte-identical to the actual retained runtime; normalized FaunaModels bytecode is identical, and JerboaMobs differs only in synthetic lambda numbering. Existing four starter repair parts, 5% player-kill drops, spice crafting and fauna/proof tests remain part of the build. No Core, Essentials or JARVIS JAR is shipped or replaced. + +Candidate descriptor: **DuneTerrain 1.0.14-arrakis2**. The dedicated `arrakis-terrain.yml` workflow tests/packages Terrain only. The general GUI installer deliberately refuses Terrain replacement and must not be repurposed for this operation. + +## Exact Paper 26.2 reset boundary + +Verified layout is `arrakis/{data,dimensions,players,datapacks,level.dat,level.dat_old,session.lock}`. Player storage is `players/{data,stats,advancements}`. There is no root `uid.dat` or old root `region` folder. The only actual dimension is `dimensions/minecraft/overworld`, containing `data`, `region`, `entities`, `poi` and its `paper-world.yml`. + +The built helper makes a complete private, hash-verified world snapshot while the exact service is stopped. It then archives **only** the overworld `region`, `entities` and `poi` directories and installs the single source-pinned Terrain JAR into the original installed filename. It leaves all other world files byte-for-byte untouched before restart, including player files, root/dimension persistent data, `level.dat` seed/identity, datapacks and dimension settings. It never runs SQL or changes central identities/claims/economy. Retaining identity also preserves coordinate-based historical proof and personal-loot keys. Paper may normally rewrite metadata after restart; do not claim whole-world byte equality after the game resumes. + +Original JAR mode/owner are preserved. All other JAR hashes/owners/modes and configurations are checked. Paper's generated `server.properties` comment timestamp is ignored when checking its actual settings. No recursive delete occurs. Old chunk directories and a complete snapshot remain in a root-private backup. Receipt rollback restores old chunk directories/Terrain while retaining **current** player/world metadata, and archives any newly generated chunk directories rather than deleting them. + +## Operator commands and acceptance + +Run only through the coordinating operator on the verified host, using the exact reviewed CI artifact and full source SHA. Existing reset authority does not authorise another root or world. + +```sh +python3 reset-arrakis-terrain.py --root /opt/dunerealms/servers/arrakis --artifacts /exact/verified/artifact --expected-source FULL_SOURCE_SHA +# After reviewing that exact plan: +python3 reset-arrakis-terrain.py --root /opt/dunerealms/servers/arrakis --artifacts /exact/verified/artifact --expected-source FULL_SOURCE_SHA --apply-reset +# If runtime acceptance fails, use the actual emitted private receipt: +python3 reset-arrakis-terrain.py --root /opt/dunerealms/servers/arrakis --expected-source FULL_SOURCE_SHA --rollback-receipt /actual/private/receipt.json +``` + +Apply requires the Linux administrator and an exclusive operation lock. Source/hash/identity, unit working directory, level name, generator mapping, reviewed old Terrain hash and retained data guards fail closed. Automatic restoration covers an installation/service-start failure. A successful systemd start is reported as **awaiting Paper readiness and generator acceptance**, not a working-world claim. The operator must verify Done, expected plugin version/hash, registered repair/fauna consumers, actual column layers, rarity/proof fixtures and retained players/identity after startup. No real payments or gameplay rewards are needed as tests. diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisBlooms.java b/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisBlooms.java new file mode 100644 index 00000000..9c8af29d --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisBlooms.java @@ -0,0 +1,15 @@ +package com.example.duneterrain; +/** Version 2 generation-only anchors. Legacy cell anchors are validated separately. */ +final class ArrakisBlooms { + static final int DESERT_WELL_RARITY=1000; + private static final long SALT=0x5350494345424c32L; + record Anchor(int x,int z){} + static long mix(long value){value=(value^(value>>>30))*0xBF58476D1CE4E5B9L;value=(value^(value>>>27))*0x94D049BB133111EBL;return value^(value>>>31);} + static Anchor anchor(long seed,int chunkX,int chunkZ,int rarity){ + if(rarity<1)throw new IllegalArgumentException("Positive attempt rarity required"); + long roll=mix(seed^((long)chunkX*0x9E3779B97F4A7C15L)^((long)chunkZ*0xC2B2AE3D27D4EB4FL)^SALT); + if(Math.floorMod(roll,rarity)!=0)return null; + return new Anchor(Math.toIntExact((long)chunkX*16+Math.floorMod(mix(roll+SALT),16)),Math.toIntExact((long)chunkZ*16+Math.floorMod(mix(roll-SALT),16))); + } + static boolean matches(long seed,int x,int z,int rarity){var point=anchor(seed,Math.floorDiv(x,16),Math.floorDiv(z,16),rarity);return point!=null&&point.x()==x&&point.z()==z;} +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisEcology.java b/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisEcology.java index 0e78aae8..702d0944 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisEcology.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisEcology.java @@ -61,7 +61,7 @@ public final class ArrakisEcology implements Listener { if(natural(reason)&&!naturalAllowance(e.getWorld(),true)){event.setCancelled(true);return;} if(ChukkaMobs.isChukka(chicken)||natural(reason)||reason==CreatureSpawnEvent.SpawnReason.BREEDING||reason==CreatureSpawnEvent.SpawnReason.EGG){ChukkaMobs.prepare(chicken);return;} } - if(e instanceof Camel){var reason=event.getSpawnReason();if((reason==CreatureSpawnEvent.SpawnReason.NATURAL||reason.name().equals("CHUNK_GEN"))&&!protectedMob(e)&&random.getAsDouble()>=.5)event.setCancelled(true);return;} + if(e instanceof Camel){var reason=event.getSpawnReason();if((reason==CreatureSpawnEvent.SpawnReason.NATURAL||reason.name().equals("CHUNK_GEN"))&&!protectedMob(e)&&random.getAsDouble()>=.1)event.setCancelled(true);return;} if(event.getSpawnReason()!=CreatureSpawnEvent.SpawnReason.CUSTOM&&!protectedMob(e))event.setCancelled(true); } @EventHandler(priority=EventPriority.MONITOR) public void loaded(com.destroystokyo.paper.event.entity.EntityAddToWorldEvent event){ diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisStrata.java b/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisStrata.java new file mode 100644 index 00000000..4fe8a637 --- /dev/null +++ b/DuneTerrain/src/main/java/com/example/duneterrain/ArrakisStrata.java @@ -0,0 +1,7 @@ +package com.example.duneterrain; +import org.bukkit.Material; +/** Ordinary dune columns; deposits/structures remain separate generation features. */ +final class ArrakisStrata { + static Material material(int depth){if(depth<0)throw new IllegalArgumentException("Negative surface depth");return depth<4?Material.SAND:depth<7?Material.SANDSTONE:Material.STONE;} + static boolean air(Material material){return material==Material.AIR||material==Material.CAVE_AIR||material==Material.VOID_AIR;} +} diff --git a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java index 851639d4..3f7b51e3 100644 --- a/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java +++ b/DuneTerrain/src/main/java/com/example/duneterrain/DuneTerrain.java @@ -98,7 +98,7 @@ public final class DuneTerrain extends JavaPlugin implements Listener { Block center = findSpiceBlowCenter(block); if (center != null) { detonateSpiceBlow(center); - if(actor!=null&&generatedSpiceBlow(center.getX(),center.getZ(),Math.max(256,getConfig().getInt("spice-blow.spacing",2000)))&¢er.getType()==Material.GLOWSTONE){ + if(actor!=null&&(generatedSpiceBlow(center.getX(),center.getZ(),Math.max(256,getConfig().getInt("spice-blow.spacing",2000)))||ArrakisBlooms.matches(center.getWorld().getSeed(),center.getX(),center.getZ(),Math.max(1,getConfig().getInt("spice-blow.rarity",ArrakisBlooms.DESERT_WELL_RARITY))))&¢er.getType()==Material.GLOWSTONE){ UUID reference=UUID.nameUUIDFromBytes((center.getWorld().getUID()+":"+center.getX()+":"+center.getZ()).getBytes(java.nio.charset.StandardCharsets.UTF_8)); FaunaProof.milestone(actor,"husbandry_spice_blow",reference); } @@ -393,9 +393,13 @@ public final class DuneTerrain extends JavaPlugin implements Listener { int h = Math.max(minY + 8, Math.min(maxY - 8, baseHeight + (int) Math.round(n * variation))); heights[x][z] = h; data.setBlock(x, minY, z, Material.BEDROCK); - for (int y = minY + 1; y < h - 3; y++) data.setBlock(x, y, z, core); - for (int y = h - 3; y < h; y++) data.setBlock(x, y, z, filler); - data.setBlock(x, h, z, surface); + if(planet.equals("arrakis")){ + for(int y=minY+1;y<=h;y++)data.setBlock(x,y,z,ArrakisStrata.material(h-y)); + }else{ + for (int y = minY + 1; y < h - 3; y++) data.setBlock(x, y, z, core); + for (int y = h - 3; y < h; y++) data.setBlock(x, y, z, filler); + data.setBlock(x, h, z, surface); + } if (plugin.getConfig().getBoolean(path + "water.swamp-pools", false) && h < waterLevel) { double poolNoise = Math.sin(gx * 0.035) * Math.cos(gz * 0.031); @@ -591,20 +595,20 @@ public final class DuneTerrain extends JavaPlugin implements Listener { // Dunes stay visibly ordinary sand, including dense-spice areas. // Preserve suspicious-sand deposits and exposed rock formations. for(int x=0;x<16;x++)for(int z=0;z<16;z++)for(int y=maxWorldY;y>minWorldY;y--){ - var top=data.getType(x,y,z);if(top.isAir())continue; + var top=data.getType(x,y,z);if(ArrakisStrata.air(top))continue; if(top==Material.RED_SAND||top==Material.ORANGE_TERRACOTTA)data.setBlock(x,y,z,Material.SAND); break; } - // Native clay disk profile: one candidate per chunk, radius 2–3, - // half-height 1. Here red sand replaces clay's wet-floor filter. + // Native clay disk geometry: one candidate per chunk, radius 2–3, + // half-height 1, inside sandstone below the four sand layers. int cx=3+random.nextInt(10),cz=3+random.nextInt(10),radius=2+random.nextInt(2),surface=-1; - for(int y=maxWorldY;y>minWorldY+5;y--)if(!data.getType(cx,y,cz).isAir()){surface=y;break;} - if(surface>minWorldY+5&&data.getType(cx,surface,cz)==Material.SAND&&data.getType(cx,surface-1,cz)==Material.RED_SAND){ - int center=surface-3; + for(int y=maxWorldY;y>minWorldY+5;y--)if(!ArrakisStrata.air(data.getType(cx,y,cz))){surface=y;break;} + if(surface>minWorldY+7&&data.getType(cx,surface,cz)==Material.SAND&&data.getType(cx,surface-3,cz)==Material.SAND&&data.getType(cx,surface-4,cz)==Material.SANDSTONE){ + int center=surface-5; for(int dx=-radius;dx<=radius;dx++)for(int dz=-radius;dz<=radius;dz++)if(dx*dx+dz*dz<=radius*radius)for(int dy=-1;dy<=1;dy++){ int x=cx+dx,z=cz+dz,y=center+dy,columnSurface=surface+radius; - while(columnSurface>minWorldY+5&&data.getType(x,columnSurface,z).isAir())columnSurface--; - if(y>columnSurface-2||data.getType(x,columnSurface,z)!=Material.SAND||data.getType(x,columnSurface-1,z)!=Material.RED_SAND)continue; + while(columnSurface>minWorldY+5&&ArrakisStrata.air(data.getType(x,columnSurface,z)))columnSurface--; + if(y>columnSurface-4||data.getType(x,columnSurface,z)!=Material.SAND||data.getType(x,columnSurface-3,z)!=Material.SAND||data.getType(x,columnSurface-4,z)!=Material.SANDSTONE)continue; var material=data.getType(x,y,z); if(material==Material.RED_SAND||material==Material.SAND||material==Material.SANDSTONE||material==Material.STONE)data.setBlock(x,y,z,Material.DRIED_KELP_BLOCK); } @@ -935,15 +939,9 @@ public final class DuneTerrain extends JavaPlugin implements Listener { @Override public void populate(WorldInfo world, Random random, int chunkX, int chunkZ, LimitedRegion region) { if (!world.getName().equalsIgnoreCase("arrakis") || !plugin.getConfig().getBoolean("spice-blow.enabled", true)) return; - int spacing = Math.max(256, plugin.getConfig().getInt("spice-blow.spacing", 2000)); - long centerX = chunkX * 16L + 8, centerZ = chunkZ * 16L + 8; - long cellX = Math.floorDiv(centerX, spacing), cellZ = Math.floorDiv(centerZ, spacing); - long h1 = mix64(cellX * 0x9E3779B97F4A7C15L ^ cellZ * 0xC2B2AE3D27D4EB4FL ^ SALT); - long h2 = mix64(cellZ * 0x165667B19E3779F9L ^ cellX * 0x85EBCA77C2B2AE63L ^ ~SALT); - long anchorX = cellX * spacing + 8 + Math.floorMod(h1, spacing - 16); - long anchorZ = cellZ * spacing + 8 + Math.floorMod(h2, spacing - 16); - if (Math.floorDiv(anchorX, 16) != chunkX || Math.floorDiv(anchorZ, 16) != chunkZ) return; - int x = (int)anchorX, z = (int)anchorZ, y = region.getHighestBlockYAt(x, z); + var anchor=ArrakisBlooms.anchor(world.getSeed(),chunkX,chunkZ,Math.max(1,plugin.getConfig().getInt("spice-blow.rarity",ArrakisBlooms.DESERT_WELL_RARITY))); + if(anchor==null)return; + int x=anchor.x(),z=anchor.z(),y=region.getHighestBlockYAt(x,z); if (y < world.getMinHeight() + 2 || y + 2 >= world.getMaxHeight()) return; if (!region.isInRegion(x, y, z) || region.getType(x, y, z) != Material.SAND) return; for (int dx = -1; dx <= 1; dx++) for (int dz = -1; dz <= 1; dz++) diff --git a/DuneTerrain/src/main/resources/config.yml b/DuneTerrain/src/main/resources/config.yml index a20fdd89..4592e73d 100644 --- a/DuneTerrain/src/main/resources/config.yml +++ b/DuneTerrain/src/main/resources/config.yml @@ -17,6 +17,9 @@ sietches: spice-blow: enabled: true + # New-generation attempt rate, matching the target runtime's desert-well rarity. + rarity: 1000 + # Retained for validating historical bloom anchors; do not remove/change during migration. spacing: 2000 radius: 24 target-value: 15000 @@ -39,7 +42,7 @@ planets: terrain: {base-height: 70, height-variation: 11, noise-scale: 0.02} biome: DESERT surface: SAND - filler: RED_SAND + filler: SANDSTONE water: {level: 63, swamp-pools: false, coverage: 0.18} vegetation: {trees: false, tree-chance: 0.0, flowers-per-chunk: 0} oasis-trees: {enabled: true, spacing: 300, trunk-height: 7} diff --git a/DuneTerrain/src/main/resources/plugin.yml b/DuneTerrain/src/main/resources/plugin.yml index 827ddc0a..01bfdbd5 100644 --- a/DuneTerrain/src/main/resources/plugin.yml +++ b/DuneTerrain/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: DuneTerrain -version: 1.0.13-worlds1 +version: 1.0.14-arrakis2 main: com.example.duneterrain.DuneTerrain api-version: '1.21' load: STARTUP diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisEcologyTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisEcologyTest.java index 19e0e4c2..51c0453e 100644 --- a/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisEcologyTest.java +++ b/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisEcologyTest.java @@ -37,7 +37,7 @@ class ArrakisEcologyTest { @Test void taggedQuestNpcExemptFromEcology(){var npc=entity(Villager.class,"arrakis");when(npc.getPersistentDataContainer().has(new NamespacedKey("dunerealms","quest_character"),PersistentDataType.STRING)).thenReturn(true);var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var spawn=new CreatureSpawnEvent(npc,CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(spawn);assertFalse(spawn.isCancelled());} @Test void ordinaryNaturalMobsAreBlockedOnlyOnArrakis(){var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var desert=new CreatureSpawnEvent(entity(Zombie.class,"arrakis"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(desert);assertTrue(desert.isCancelled());var other=new CreatureSpawnEvent(entity(Zombie.class,"caladan"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(other);assertFalse(other.isCancelled());} @Test void customSpawnedRaidersAndTaggedCreaturesSurvive(){var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var custom=new CreatureSpawnEvent(entity(Zombie.class,"arrakis"),CreatureSpawnEvent.SpawnReason.CUSTOM);feature.spawning(custom);assertFalse(custom.isCancelled());var tagged=entity(Zombie.class,"arrakis");when(tagged.getPersistentDataContainer().getKeys()).thenReturn(Set.of(new NamespacedKey("dunerealms","raider")));var event=new CreatureSpawnEvent(tagged,CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(event);assertFalse(event.isCancelled());} - @Test void camelRateIsHalvedOnlyForNewNaturalArrakisWildlife(){for(double roll:new double[]{.49,.5,.99}){var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->roll);var desert=new CreatureSpawnEvent(entity(Camel.class,"arrakis"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(desert);assertEquals(roll>=.5,desert.isCancelled());var other=new CreatureSpawnEvent(entity(Camel.class,"caladan"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(other);assertFalse(other.isCancelled());var custom=new CreatureSpawnEvent(entity(Camel.class,"arrakis"),CreatureSpawnEvent.SpawnReason.CUSTOM);feature.spawning(custom);assertFalse(custom.isCancelled());var tame=entity(Camel.class,"arrakis");when(tame.isTamed()).thenReturn(true);var protectedEvent=new CreatureSpawnEvent(tame,CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(protectedEvent);assertFalse(protectedEvent.isCancelled());}} + @Test void camelRateReducedEightyPercentOnlyForNewNaturalArrakisWildlife(){for(double roll:new double[]{.099,.1,.49,.99}){var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->roll);var desert=new CreatureSpawnEvent(entity(Camel.class,"arrakis"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(desert);assertEquals(roll>=.1,desert.isCancelled());var other=new CreatureSpawnEvent(entity(Camel.class,"caladan"),CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(other);assertFalse(other.isCancelled());var custom=new CreatureSpawnEvent(entity(Camel.class,"arrakis"),CreatureSpawnEvent.SpawnReason.CUSTOM);feature.spawning(custom);assertFalse(custom.isCancelled());var tame=entity(Camel.class,"arrakis");when(tame.isTamed()).thenReturn(true);var protectedEvent=new CreatureSpawnEvent(tame,CreatureSpawnEvent.SpawnReason.NATURAL);feature.spawning(protectedEvent);assertFalse(protectedEvent.isCancelled());}} @Test void fireDeathsUseCookedDefinitionAndBloodAndRareWaterRolls(){for(boolean burning:new boolean[]{false,true})for(double roll:new double[]{.01999,.02,.19999,.2}){var animal=entity(Rabbit.class,"arrakis");when(animal.getFireTicks()).thenReturn(burning?20:0);var meat=mock(ItemStack.class);var hide=mock(ItemStack.class);var vial=mock(ItemStack.class);var blood=mock(ItemStack.class);var requested=new ArrayList();var feature=new ArrakisEcology(mock(Plugin.class),id->{requested.add(id);return id.equals("jerboa_hide")?hide:id.equals("jerboa_water_vial")?vial:id.equals("blood_vial")?blood:meat;},()->roll);var event=new EntityDeathEvent(animal,mock(org.bukkit.damage.DamageSource.class),new ArrayList<>());feature.death(event);assertEquals(burning?"jerboa_cooked_meat":"jerboa_raw_meat",requested.getFirst());var expected=new ArrayList<>(List.of(meat,hide));if(roll<.2)expected.add(blood);if(roll<.02)expected.add(vial);assertEquals(expected,event.getDrops());}} @Test void suffocationImmunityDoesNotDependOnWater(){var wolf=entity(Wolf.class,"arrakis");when(wolf.getPersistentDataContainer().has(new NamespacedKey("dunerealms","tiny_worm_pet"),PersistentDataType.BYTE)).thenReturn(true);var feature=new ArrakisEcology(mock(Plugin.class),id->{throw new AssertionError();},()->0);var event=mock(EntityDamageEvent.class);when(event.getEntity()).thenReturn(wolf);when(event.getCause()).thenReturn(EntityDamageEvent.DamageCause.SUFFOCATION);feature.suffocation(event);verify(event).setCancelled(true);var attack=mock(EntityDamageEvent.class);when(attack.getEntity()).thenReturn(wolf);when(attack.getCause()).thenReturn(EntityDamageEvent.DamageCause.ENTITY_ATTACK);feature.suffocation(attack);verify(attack,never()).setCancelled(anyBoolean());} } diff --git a/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisGenerationTest.java b/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisGenerationTest.java new file mode 100644 index 00000000..f6f5a107 --- /dev/null +++ b/DuneTerrain/src/test/java/com/example/duneterrain/ArrakisGenerationTest.java @@ -0,0 +1,47 @@ +package com.example.duneterrain; +import java.util.*; +import org.bukkit.Material; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.generator.WorldInfo; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +class ArrakisGenerationTest { + @Test void regularDunesKeepFourSandLayersAndSpiceDepositsStillGenerate()throws Exception{ + var config=new YamlConfiguration(); + config.set("planets.arrakis.terrain.base-height",8);config.set("planets.arrakis.terrain.height-variation",0); + config.set("planets.arrakis.surface","SAND");config.set("planets.arrakis.filler","RED_SAND"); // Actual retained config must migrate without silently retaining red sand. + for(String flag:List.of("planets.arrakis.oasis-trees.enabled","planets.arrakis.darkstone-islands.enabled","planets.arrakis.highlands.enabled","spice-deposits.patches.enabled","dense-spice.enabled"))config.set(flag,false); + config.set("spice-deposits.per-chunk",0); + var plugin=mock(DuneTerrain.class);when(plugin.getConfig()).thenReturn(config); + var type=Class.forName(DuneTerrain.class.getName()+"$PlanetChunkGenerator");var constructor=type.getDeclaredConstructor(DuneTerrain.class,String.class);constructor.setAccessible(true); + var generator=(ChunkGenerator)constructor.newInstance(plugin,"arrakis"); + var world=mock(WorldInfo.class);when(world.getName()).thenReturn("arrakis");when(world.getMinHeight()).thenReturn(0);when(world.getMaxHeight()).thenReturn(32);when(world.getSeed()).thenReturn(42L); + var blocks=new HashMap,Material>();var data=mock(ChunkGenerator.ChunkData.class); + doAnswer(c->{blocks.put(List.of(c.getArgument(0),c.getArgument(1),c.getArgument(2)),c.getArgument(3));return null;}).when(data).setBlock(anyInt(),anyInt(),anyInt(),any(Material.class)); + when(data.getType(anyInt(),anyInt(),anyInt())).thenAnswer(c->blocks.getOrDefault(List.of(c.getArgument(0),c.getArgument(1),c.getArgument(2)),Material.AIR)); + var random=mock(Random.class);when(random.nextInt(anyInt())).thenReturn(0); + generator.generateNoise(world,random,0,0,data); + for(int x=0;x<16;x++)for(int z=0;z<16;z++)for(int depth=0;depth<4;depth++)assertEquals(Material.SAND,data.getType(x,8-depth,z)); + for(int depth=4;depth<7;depth++)assertEquals(Material.SANDSTONE,data.getType(15,8-depth,15)); + assertEquals(Material.STONE,data.getType(15,1,15));assertEquals(Material.BEDROCK,data.getType(15,0,15)); + assertFalse(blocks.containsValue(Material.RED_SAND));assertEquals(Material.DRIED_KELP_BLOCK,data.getType(3,3,3)); + } + @Test void newBloomAnchorsAreDeterministicWithinTheirChunkAndSeedBound(){ + for(int cx:new int[]{-100,-1,0,1,100})for(int cz:new int[]{-100,-1,0,1,100}){ + var anchor=ArrakisBlooms.anchor(42,cx,cz,1);assertEquals(cx,Math.floorDiv(anchor.x(),16));assertEquals(cz,Math.floorDiv(anchor.z(),16)); + assertEquals(anchor,ArrakisBlooms.anchor(42,cx,cz,1));assertTrue(ArrakisBlooms.matches(42,anchor.x(),anchor.z(),1)); + } + assertThrows(IllegalArgumentException.class,()->ArrakisBlooms.anchor(0,0,0,0)); + } + @Test void attemptDensityMatchesDesertWellRarityWithoutClaimingTerrainSuccess(){ + int candidates=0;for(int x=0;x<1000;x++)for(int z=0;z<1000;z++)if(ArrakisBlooms.anchor(42,x,z,1000)!=null)candidates++; + assertTrue(candidates>=850&&candidates<=1150,"candidate attempts: "+candidates); + } + @Test void historicalCellAnchorProofStillRecognizesPreviouslyGeneratedBlooms(){ + int spacing=2000;long salt=0x5350494345424c4fL; + int x=(int)(8+Math.floorMod(ArrakisBlooms.mix(salt),spacing-16));int z=(int)(8+Math.floorMod(ArrakisBlooms.mix(~salt),spacing-16)); + assertTrue(DuneTerrain.generatedSpiceBlow(x,z,spacing));assertFalse(DuneTerrain.generatedSpiceBlow(x+1,z,spacing)); + } +} diff --git a/DuneTerrain/src/test/resources/retained-arrakis-terrain.json b/DuneTerrain/src/test/resources/retained-arrakis-terrain.json new file mode 100644 index 00000000..4b1dd39f --- /dev/null +++ b/DuneTerrain/src/test/resources/retained-arrakis-terrain.json @@ -0,0 +1,612 @@ +{ + "runtimeSha256": "012f9b0055020a94de955ec277cc46ca82a5efc8149e748ff30a333b6bc026dc", + "runtimeVersion": "1.0.12-arrakeen1-fauna4-trails1-surface1-fauna606", + "classes": { + "com/example/duneterrain/DenseSpice": { + "methods": [ + [ + "initialize", + "(Lorg/bukkit/event/world/ChunkLoadEvent;)V" + ], + [ + "harvest", + "(Lorg/bukkit/event/block/BlockBreakEvent;)V" + ], + [ + "place", + "(Lorg/bukkit/event/block/BlockPlaceEvent;)V" + ], + [ + "push", + "(Lorg/bukkit/event/block/BlockPistonExtendEvent;)V" + ], + [ + "pull", + "(Lorg/bukkit/event/block/BlockPistonRetractEvent;)V" + ], + [ + "explode", + "(Lorg/bukkit/event/entity/EntityExplodeEvent;)V" + ], + [ + "explode", + "(Lorg/bukkit/event/block/BlockExplodeEvent;)V" + ], + [ + "reward", + "(Lorg/bukkit/event/block/BlockBreakEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DesertVillages": { + "methods": [ + [ + "populate", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/LimitedRegion;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain$PersonalLoot": { + "methods": [ + [ + "toString", + "()Ljava/lang/String;" + ], + [ + "hashCode", + "()I" + ], + [ + "equals", + "(Ljava/lang/Object;)Z" + ], + [ + "inventory", + "()Lorg/bukkit/inventory/Inventory;" + ], + [ + "id", + "()Ljava/lang/String;" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain$PlanetBiomeProvider": { + "methods": [ + [ + "getBiome", + "(Lorg/bukkit/generator/WorldInfo;III)Lorg/bukkit/block/Biome;" + ], + [ + "getBiomes", + "(Lorg/bukkit/generator/WorldInfo;)Ljava/util/List;" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain$PlanetChunkGenerator$GroundKey": { + "methods": [ + [ + "toString", + "()Ljava/lang/String;" + ], + [ + "hashCode", + "()I" + ], + [ + "equals", + "(Ljava/lang/Object;)Z" + ], + [ + "shape", + "()Lcom/example/duneterrain/RockPlateaus$Shape;" + ], + [ + "baseHeight", + "()I" + ], + [ + "variation", + "()D" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain$PlanetChunkGenerator": { + "methods": [ + [ + "getDefaultPopulators", + "(Lorg/bukkit/World;)Ljava/util/List;" + ], + [ + "generateNoise", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/ChunkGenerator$ChunkData;)V" + ], + [ + "getDefaultBiomeProvider", + "(Lorg/bukkit/generator/WorldInfo;)Lorg/bukkit/generator/BiomeProvider;" + ], + [ + "shouldGenerateStructures", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;II)Z" + ], + [ + "shouldGenerateMobs", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;II)Z" + ], + [ + "shouldGenerateDecorations", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;II)Z" + ], + [ + "shouldGenerateCaves", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;II)Z" + ], + [ + "getBaseHeight", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/HeightMap;)I" + ], + [ + "generateCaves", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/ChunkGenerator$ChunkData;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain$SietchPopulator": { + "methods": [ + [ + "populate", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/LimitedRegion;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain$SpiceBlowPopulator": { + "methods": [ + [ + "populate", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/LimitedRegion;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/DuneTerrain": { + "methods": [ + [ + "", + "()V" + ], + [ + "announceSpiceBloom", + "(Lorg/bukkit/Location;)V" + ], + [ + "onBloomChunkLoad", + "(Lorg/bukkit/event/world/ChunkLoadEvent;)V" + ], + [ + "onSietchChestOpen", + "(Lorg/bukkit/event/player/PlayerInteractEvent;)V" + ], + [ + "onSietchLootClick", + "(Lorg/bukkit/event/inventory/InventoryClickEvent;)V" + ], + [ + "onSietchLootDrag", + "(Lorg/bukkit/event/inventory/InventoryDragEvent;)V" + ], + [ + "onSietchLootClose", + "(Lorg/bukkit/event/inventory/InventoryCloseEvent;)V" + ], + [ + "getDefaultWorldGenerator", + "(Ljava/lang/String;Ljava/lang/String;)Lorg/bukkit/generator/ChunkGenerator;" + ], + [ + "getDefaultBiomeProvider", + "(Ljava/lang/String;Ljava/lang/String;)Lorg/bukkit/generator/BiomeProvider;" + ], + [ + "onEnable", + "()V" + ], + [ + "onServerLoad", + "(Lorg/bukkit/event/server/ServerLoadEvent;)V" + ], + [ + "onSpiceBlowEntityMove", + "(Lio/papermc/paper/event/entity/EntityMoveEvent;)V" + ], + [ + "onSpiceBlowPlayerMove", + "(Lorg/bukkit/event/player/PlayerMoveEvent;)V" + ], + [ + "onSpiceBlowProjectile", + "(Lorg/bukkit/event/entity/ProjectileHitEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/HarkonnenFortress": { + "methods": [ + [ + "populate", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/LimitedRegion;)V" + ], + [ + "loot", + "(Lorg/bukkit/event/world/LootGenerateEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/HighlandSietches$Site": { + "methods": [ + [ + "toString", + "()Ljava/lang/String;" + ], + [ + "hashCode", + "()I" + ], + [ + "equals", + "(Ljava/lang/Object;)Z" + ], + [ + "x", + "()I" + ], + [ + "z", + "()I" + ], + [ + "cacheId", + "()J" + ] + ], + "fields": [] + }, + "com/example/duneterrain/HighlandSietches": { + "methods": [], + "fields": [] + }, + "com/example/duneterrain/RockPlateaus$Shape": { + "methods": [ + [ + "toString", + "()Ljava/lang/String;" + ], + [ + "hashCode", + "()I" + ], + [ + "equals", + "(Ljava/lang/Object;)Z" + ], + [ + "seed", + "()J" + ], + [ + "centerX", + "()J" + ], + [ + "centerZ", + "()J" + ], + [ + "radius", + "()D" + ], + [ + "scale", + "()D" + ], + [ + "cosine", + "()D" + ], + [ + "sine", + "()D" + ] + ], + "fields": [] + }, + "com/example/duneterrain/RockPlateaus": { + "methods": [], + "fields": [] + }, + "com/example/duneterrain/ArrakisEcology$Items": { + "methods": [ + [ + "build", + "(Ljava/lang/String;)Lorg/bukkit/inventory/ItemStack;" + ] + ], + "fields": [] + }, + "com/example/duneterrain/ArrakisEcology": { + "methods": [ + [ + "start", + "(Lorg/bukkit/plugin/Plugin;)V" + ], + [ + "spawning", + "(Lorg/bukkit/event/entity/CreatureSpawnEvent;)V" + ], + [ + "loaded", + "(Lcom/destroystokyo/paper/event/entity/EntityAddToWorldEvent;)V" + ], + [ + "bloom", + "(Lorg/bukkit/plugin/Plugin;Lorg/bukkit/Location;)V" + ], + [ + "feed", + "(Lorg/bukkit/event/player/PlayerInteractEntityEvent;)V" + ], + [ + "breed", + "(Lorg/bukkit/event/entity/EntityBreedEvent;)V" + ], + [ + "suffocation", + "(Lorg/bukkit/event/entity/EntityDamageEvent;)V" + ], + [ + "death", + "(Lorg/bukkit/event/entity/EntityDeathEvent;)V" + ], + [ + "cook", + "(Lorg/bukkit/event/block/BlockCookEvent;)V" + ], + [ + "disable", + "(Lorg/bukkit/event/server/PluginDisableEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/NativePlants": { + "methods": [ + [ + "", + "()V" + ], + [ + "allowed", + "(Ljava/lang/String;Ljava/lang/String;)Z" + ], + [ + "place", + "(Lorg/bukkit/event/block/BlockPlaceEvent;)V" + ], + [ + "crop", + "(Lorg/bukkit/event/block/BlockGrowEvent;)V" + ], + [ + "grow", + "(Lorg/bukkit/event/world/StructureGrowEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/OceanAquifers": { + "methods": [ + [ + "", + "()V" + ], + [ + "flood", + "(Lorg/bukkit/generator/WorldInfo;IILorg/bukkit/generator/ChunkGenerator$ChunkData;Ljava/lang/String;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/SietchReservoirs": { + "methods": [], + "fields": [] + }, + "com/example/duneterrain/TemperateLandscape$1": { + "methods": [], + "fields": [] + }, + "com/example/duneterrain/TemperateLandscape": { + "methods": [ + [ + "", + "()V" + ], + [ + "enabled", + "(Ljava/lang/String;)Z" + ], + [ + "height", + "(JIILjava/lang/String;)I" + ], + [ + "lavaSurface", + "(JII)Z" + ], + [ + "islandDistance", + "(JII)D" + ], + [ + "biome", + "(Lorg/bukkit/generator/WorldInfo;IIILjava/lang/String;)Lorg/bukkit/block/Biome;" + ], + [ + "biomes", + "(Ljava/lang/String;)Ljava/util/List;" + ], + [ + "generate", + "(Lorg/bukkit/generator/WorldInfo;Ljava/util/Random;IILorg/bukkit/generator/ChunkGenerator$ChunkData;Ljava/lang/String;)V" + ] + ], + "fields": [ + [ + "SEA", + "I" + ] + ] + }, + "com/example/duneterrain/StarterRepairDrops": { + "methods": [ + [ + "start", + "(Lorg/bukkit/plugin/Plugin;)V" + ], + [ + "killed", + "(Lorg/bukkit/event/entity/EntityDeathEvent;)V" + ], + [ + "loaded", + "(Lorg/bukkit/event/server/ServerLoadEvent;)V" + ], + [ + "preview", + "(Lorg/bukkit/event/inventory/PrepareItemCraftEvent;)V" + ], + [ + "craft", + "(Lorg/bukkit/event/inventory/CraftItemEvent;)V" + ], + [ + "automated", + "(Lorg/bukkit/event/block/CrafterCraftEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/TrailsBridge": { + "methods": [ + [ + "start", + "(Lorg/bukkit/plugin/Plugin;)V" + ], + [ + "step", + "(Lorg/bukkit/event/player/PlayerMoveEvent;)V" + ], + [ + "brush", + "(Lorg/bukkit/event/player/PlayerInteractEvent;)V" + ], + [ + "placed", + "(Lorg/bukkit/event/block/BlockPlaceEvent;)V" + ], + [ + "broken", + "(Lorg/bukkit/event/block/BlockBreakEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/FaunaModels": { + "methods": [ + [ + "close", + "()V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/JerboaMobs": { + "methods": [ + [ + "feed", + "(Lorg/bukkit/event/player/PlayerInteractEntityEvent;)V" + ], + [ + "breed", + "(Lorg/bukkit/event/entity/EntityBreedEvent;)V" + ], + [ + "target", + "(Lorg/bukkit/event/entity/EntityTargetLivingEntityEvent;)V" + ], + [ + "attacked", + "(Lorg/bukkit/event/entity/EntityDamageByEntityEvent;)V" + ], + [ + "shed", + "(Lorg/bukkit/event/entity/EntityDropItemEvent;)V" + ], + [ + "death", + "(Lorg/bukkit/event/entity/EntityDeathEvent;)V" + ], + [ + "unload", + "(Lorg/bukkit/event/world/EntitiesUnloadEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/PlanetSoil": { + "methods": [ + [ + "start", + "(Lorg/bukkit/plugin/Plugin;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/ChukkaMobs": { + "methods": [ + [ + "laid", + "(Lorg/bukkit/event/entity/EntityDropItemEvent;)V" + ], + [ + "hatch", + "(Lorg/bukkit/event/player/PlayerEggThrowEvent;)V" + ], + [ + "breed", + "(Lorg/bukkit/event/entity/EntityBreedEvent;)V" + ], + [ + "death", + "(Lorg/bukkit/event/entity/EntityDeathEvent;)V" + ] + ], + "fields": [] + }, + "com/example/duneterrain/FaunaProof": { + "methods": [], + "fields": [] + } + }, + "resources": { + "starter-repair-parts.json": { + "rawSha256": "79db6acf155526e379b8b26ea6b6f69785a1d345b23cf39e563ab0299cf3d2a6", + "canonicalSha256": "29707d610bc7960bf94fd62d5b4fc69d0218a7f6b4bb2e526d1f1ae6062c75c1" + } + } +} diff --git a/tools/reset-arrakis-terrain.py b/tools/reset-arrakis-terrain.py new file mode 100644 index 00000000..e5ebb82b --- /dev/null +++ b/tools/reset-arrakis-terrain.py @@ -0,0 +1,284 @@ +"""Pinned Arrakis-only Terrain install/reset. No database access and no recursive deletion.""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import zipfile + +APPROVED_ROOT = Path('/opt/dunerealms/servers/arrakis') +UNIT = 'dune-arrakis.service' +CHUNKS = ('region', 'entities', 'poi') +OLD_TERRAIN_SHA = '012f9b0055020a94de955ec277cc46ca82a5efc8149e748ff30a333b6bc026dc' + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): h.update(block) + return h.hexdigest() + + +def checked(path): + path = Path(path).absolute() + if path.is_symlink() or path.resolve(strict=True) != path: raise ValueError('Symlinked or noncanonical path') + return path + + +def tree(path): + result = {} + for file in sorted(checked(path).rglob('*')): + if file.is_symlink(): raise ValueError('Symlink in world data') + if file.is_file(): result[file.relative_to(path).as_posix()] = digest(file) + return result + + +def identity(path): + with zipfile.ZipFile(path) as jar: text = jar.read('plugin.yml').decode() + return {key: re.search(r'^' + key + r':\s*(.+?)\s*$', text, re.M).group(1).strip('"\'') for key in ('name', 'version', 'main')} + + +def metadata(path): + value = path.stat() + return {'mode': stat.S_IMODE(value.st_mode), 'uid': value.st_uid, 'gid': value.st_gid} + + +def set_metadata(path, value): + os.chmod(path, value['mode']) + if hasattr(os, 'chown'): os.chown(path, value['uid'], value['gid']) + + +def plugin_snapshot(folder, exclude=None): + return {p.name: {'sha256': digest(p), **metadata(p)} for p in sorted(folder.glob('*.jar')) if p != exclude} + + +def yaml_value(text, expected): + stack = [] + for line in text.splitlines(): + match = re.match(r'^( *)([A-Za-z0-9_-]+):[ \t]*(.*)$', line) + if not match: continue + indent, key, value = len(match[1]), match[2], match[3].strip() + stack = [entry for entry in stack if entry[0] < indent] + [(indent, key)] + if tuple(entry[1] for entry in stack) == expected: return value.strip('"\'') + return None + + +def protected(world): + prefixes = tuple('dimensions/minecraft/overworld/' + name + '/' for name in CHUNKS) + return {name: value for name, value in tree(world).items() if not name.startswith(prefixes)} + + +def config_pin(path): + if path.name != 'server.properties': return digest(path) + # Paper rewrites its generated comment timestamp on startup; compare actual settings. + settings = {} + for line in path.read_text().splitlines(): + if line.strip() and not line.lstrip().startswith(('#', '!')): + key, separator, value = line.partition('=') + if not separator: raise ValueError('Unsupported server property syntax') + settings[key.strip()] = value.strip() + return hashlib.sha256(json.dumps(settings, sort_keys=True).encode()).hexdigest() + + +def plan(root, artifacts, expected_source, expected_old=OLD_TERRAIN_SHA): + root, artifacts = checked(root), checked(artifacts) + if root != APPROVED_ROOT.absolute(): raise ValueError('Only the verified Arrakis server root is permitted') + if not re.fullmatch('[a-f0-9]{40}', expected_source): raise ValueError('Exact source commit required') + manifest = json.loads((artifacts / 'release-manifest.json').read_text()) + if manifest['sourceCommit'] != expected_source or (artifacts / 'SOURCE_COMMIT').read_text().strip() != expected_source: raise ValueError('Artifact source mismatch') + entries = manifest['plugins'] + if len(entries) != 1 or entries[0]['name'] != 'DuneTerrain': raise ValueError('Terrain-only artifact required') + item = entries[0] + if Path(item['filename']).name != item['filename']: raise ValueError('Invalid artifact filename') + incoming = checked(artifacts / item['filename']) + if digest(incoming) != item['sha256'] or identity(incoming) != {k: item[k] for k in ('name', 'version', 'main')}: raise ValueError('Incoming Terrain identity/hash mismatch') + if item['main'] != 'com.example.duneterrain.DuneTerrain': raise ValueError('Unexpected Terrain entry point') + world = checked(root / 'arrakis') + dimension = checked(world / 'dimensions/minecraft/overworld') + if not (world / 'level.dat').is_file() or not (world / 'players').is_dir(): raise ValueError('Expected Paper 26.2 world/player layout missing') + for name in CHUNKS: checked(dimension / name) + props = (root / 'server.properties').read_text() + if not re.search(r'^\s*level-name\s*=\s*arrakis\s*$', props, re.M): raise ValueError('Server level-name is not Arrakis') + bukkit = (root / 'bukkit.yml').read_text() + if yaml_value(bukkit, ('worlds', 'arrakis', 'generator')) != 'DuneTerrain:arrakis': raise ValueError('Verified generator mapping missing') + plugins = checked(root / 'plugins') + installed = [p for p in plugins.glob('*.jar') if identity(p)['name'] == 'DuneTerrain'] + if len(installed) != 1: raise ValueError('Expected one installed Terrain identity') + target = checked(installed[0]) + if digest(target) != expected_old: raise ValueError('Installed Terrain differs from reviewed runtime') + configs = [root / 'server.properties', root / 'bukkit.yml', plugins / 'DuneTerrain/config.yml'] + for file in configs: checked(file) + if yaml_value(configs[2].read_text(), ('server', 'planet')) != 'arrakis': raise ValueError('Terrain planet setting mismatch') + # Traversal also rejects symlinks before any service or world mutation. + tree(world) + return {'root': str(root), 'world': str(world), 'dimension': str(dimension), 'unit': UNIT, + 'source': expected_source, 'incoming': str(incoming), 'incomingSha256': item['sha256'], + 'target': str(target), 'previousSha256': expected_old, 'previousMetadata': metadata(target), + 'retainedJars': plugin_snapshot(plugins, target), 'configs': {str(p.relative_to(root)): config_pin(p) for p in configs}, + 'resetDirectories': list(CHUNKS), 'preserved': 'All other world bytes, including players, data, level.dat, datapacks and dimension settings'} + + +def save(path, value): + temporary = path.with_suffix('.new') + temporary.write_text(json.dumps(value, indent=2) + '\n') + os.chmod(temporary, 0o600) + os.replace(temporary, path) + + +class Service: + def __init__(self, root): + directory = subprocess.check_output(['systemctl', 'show', UNIT, '--property=WorkingDirectory', '--value'], text=True).strip() + if Path(directory) != root: raise ValueError('Unit working directory mismatch') + def active(self): return subprocess.run(['systemctl', 'is-active', '--quiet', UNIT]).returncode == 0 + def stop(self): subprocess.run(['systemctl', 'stop', UNIT], check=True) + def start(self): subprocess.run(['systemctl', 'start', UNIT], check=True) + + +def verify_retained(value): + root, target = Path(value['root']), Path(value['target']) + if plugin_snapshot(root / 'plugins', target) != value['retainedJars']: raise ValueError('A retained plugin changed') + for name, expected in value['configs'].items(): + if config_pin(checked(root / name)) != expected: raise ValueError('A retained configuration changed') + + +def rollback(receipt, controller, internal=False): + receipt = checked(receipt) + value = json.loads(receipt.read_text()) + root = checked(value['root']) + if root != APPROVED_ROOT.absolute() or value['unit'] != UNIT: raise ValueError('Rollback target mismatch') + if not receipt.is_relative_to(root / 'backups'): raise ValueError('Receipt is outside the private backup root') + dimension, target = checked(value['dimension']), checked(value['target']) + if dimension != root / 'arrakis/dimensions/minecraft/overworld' or target.parent != root / 'plugins': raise ValueError('Invalid receipt scope') + backup = receipt.parent + previous = checked(backup / 'previous-terrain.jar') + if digest(previous) != value['previousSha256']: raise ValueError('Original Terrain backup hash changed') + if identity(previous)['name'] != 'DuneTerrain' or identity(target)['name'] != 'DuneTerrain': raise ValueError('Rollback plugin identity mismatch') + for field in ('moved', 'restored'): + names = value.get(field, []) + if len(names) != len(set(names)) or not set(names).issubset(CHUNKS): raise ValueError('Invalid rollback directory list') + if value['state'].startswith('rolled-back'): + if digest(target) != value['previousSha256']: raise ValueError('Rolled-back Terrain changed') + if value['wasActive'] and not controller.active(): controller.start() + return value + if not internal and digest(target) not in {value['incomingSha256'], value['previousSha256'] if value['state'] == 'rolling-back' else value['incomingSha256']}: raise ValueError('Installed Terrain changed after this rollout') + verify_retained(value) + for name in value.get('moved', []): + original = backup / 'retired' / name + if name in value.get('restored', []): continue + source = original if original.exists() else dimension / name + if tree(checked(source)) != value['originalChunks'][name]: raise ValueError('Original chunk backup changed') + controller.stop() + if controller.active(): raise RuntimeError('Arrakis service did not stop') + failed = backup / 'replaced-after-rollback' + failed.mkdir(mode=0o700, exist_ok=True) + value['state'] = 'rolling-back' + save(receipt, value) + for name in value.get('moved', []): + if name in value.get('restored', []): continue + original = backup / 'retired' / name + current = dimension / name + if original.exists(): + if current.exists(): checked(current).rename(failed / name) + checked(original).rename(current) + value.setdefault('restored', []).append(name) + save(receipt, value) + shutil.copy2(previous, target) + set_metadata(target, value['previousMetadata']) + verify_retained(value) + value['state'] = 'rolled-back; current player/world metadata retained' + save(receipt, value) + if value['wasActive']: controller.start() + return value + + +def apply(value, controller, stamp=None): + root, world, dimension, target = map(Path, (value['root'], value['world'], value['dimension'], value['target'])) + stamp = stamp or datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ') + base = root / 'backups' + base.mkdir(exist_ok=True) + if base.resolve() != base: raise ValueError('Symlinked backup root') + backup = base / ('arrakis-reset-' + value['source'][:7] + '-' + stamp) + backup.mkdir(mode=0o700) + receipt = backup / 'receipt.json' + value = {**value, 'wasActive': controller.active(), 'moved': [], 'state': 'preparing'} + save(receipt, value) + if value['wasActive']: controller.stop() + if controller.active(): raise RuntimeError('Arrakis service did not stop') + try: + if digest(target) != value['previousSha256'] or digest(value['incoming']) != value['incomingSha256']: raise ValueError('Terrain changed after planning') + verify_retained(value) + before, profiles = tree(world), protected(world) + shutil.copytree(world, backup / 'world-snapshot', copy_function=shutil.copy2) + if tree(backup / 'world-snapshot') != before: raise ValueError('Full world backup verification failed') + shutil.copy2(target, backup / 'previous-terrain.jar') + value['protectedBefore'] = profiles + value['originalChunks'] = {name: tree(dimension / name) for name in CHUNKS} + (backup / 'retired').mkdir(mode=0o700) + save(receipt, value) + for name in CHUNKS: + folder = dimension / name + attrs = metadata(folder) + value['moved'].append(name) + save(receipt, value) + folder.rename(backup / 'retired' / name) + folder.mkdir() + set_metadata(folder, attrs) + temporary = target.with_suffix('.incoming') + shutil.copy2(value['incoming'], temporary) + set_metadata(temporary, value['previousMetadata']) + os.replace(temporary, target) + if digest(target) != value['incomingSha256']: raise ValueError('Installed Terrain hash mismatch') + if protected(world) != profiles: raise ValueError('Protected world/player data changed') + verify_retained(value) + value['state'] = 'installed; awaiting runtime verification' + save(receipt, value) + if value['wasActive']: controller.start() + value['state'] = 'started; awaiting Paper readiness and generator acceptance' if value['wasActive'] else 'installed; service left stopped' + save(receipt, value) + return receipt + except Exception: + if value['moved']: + rollback(receipt, controller, internal=True) + elif value['wasActive']: + controller.start() + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--root', required=True) + parser.add_argument('--artifacts') + parser.add_argument('--expected-source', required=True) + parser.add_argument('--expected-terrain-sha', default=OLD_TERRAIN_SHA) + parser.add_argument('--apply-reset', action='store_true') + parser.add_argument('--rollback-receipt') + args = parser.parse_args() + value = None + if args.rollback_receipt: + value = json.loads(Path(args.rollback_receipt).read_text()) + if value['source'] != args.expected_source or value['root'] != str(checked(args.root)): raise ValueError('Rollback source/root mismatch') + else: + if not args.artifacts: parser.error('--artifacts is required') + value = plan(args.root, args.artifacts, args.expected_source, args.expected_terrain_sha) + if not args.apply_reset: + print(json.dumps({k: value[k] for k in ('root', 'unit', 'source', 'resetDirectories', 'preserved')}, indent=2)) + return + if os.name != 'posix' or os.geteuid() != 0: raise ValueError('Apply requires the verified Linux server administrator') + import fcntl + lock = checked(args.root) / '.arrakis-terrain-reset.lock' + if lock.is_symlink(): raise ValueError('Symlinked operation lock') + with lock.open('a') as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + if args.rollback_receipt: + rollback(args.rollback_receipt, Service(checked(args.root))) + print('Receipt-backed Arrakis rollback completed; player metadata retained.') + else: + print('Receipt:', apply(value, Service(checked(args.root)))) + + +if __name__ == '__main__': main() diff --git a/tools/test_arrakis_terrain_reset.py b/tools/test_arrakis_terrain_reset.py new file mode 100644 index 00000000..089341ec --- /dev/null +++ b/tools/test_arrakis_terrain_reset.py @@ -0,0 +1,112 @@ +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +import zipfile + +spec = importlib.util.spec_from_file_location('reset', Path(__file__).with_name('reset-arrakis-terrain.py')) +reset = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reset) + + +class FakeService: + def __init__(self): self.running = True; self.fail_start = False + def active(self): return self.running + def stop(self): self.running = False + def start(self): + if self.fail_start: + self.fail_start = False + raise RuntimeError('simulated startup failure') + self.running = True + + +class ResetTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() / 'arrakis-server' + self.root.mkdir() + self.original_root = reset.APPROVED_ROOT + reset.APPROVED_ROOT = self.root + self.addCleanup(setattr, reset, 'APPROVED_ROOT', self.original_root) + self.world = self.root / 'arrakis' + self.dimension = self.world / 'dimensions/minecraft/overworld' + for name in reset.CHUNKS: + path = self.dimension / name + path.mkdir(parents=True) + (path / 'test.dat').write_bytes(('original ' + name).encode()) + for name in ['players/data', 'players/stats', 'players/advancements', 'data/minecraft', 'datapacks', 'dimensions/minecraft/overworld/data']: + path = self.world / name + path.mkdir(parents=True, exist_ok=True) + (path / 'preserved.dat').write_bytes(('earned ' + name).encode()) + (self.world / 'level.dat').write_bytes(b'opaque original seed and world identity') + (self.dimension / 'paper-world.yml').write_text('preserved world settings') + (self.root / 'server.properties').write_text('# old timestamp\nlevel-name=arrakis\nserver-port=25565\n') + (self.root / 'bukkit.yml').write_text('worlds:\n arrakis:\n generator: DuneTerrain:arrakis\n') + plugins = self.root / 'plugins' + (plugins / 'DuneTerrain').mkdir(parents=True) + (plugins / 'DuneTerrain/config.yml').write_text('server:\n planet: arrakis\n') + self.target = plugins / 'legacy-terrain.jar' + self.jar(self.target, 'DuneTerrain', 'old') + self.jar(plugins / 'retained.jar', 'JarvisTranslator', 'working') + self.artifacts = self.root.parent / 'artifacts' + self.artifacts.mkdir() + self.incoming = self.artifacts / 'DuneRealms-Terrain.jar' + self.jar(self.incoming, 'DuneTerrain', 'new') + self.source = 'a' * 40 + (self.artifacts / 'SOURCE_COMMIT').write_text(self.source) + (self.artifacts / 'release-manifest.json').write_text(json.dumps({'sourceCommit': self.source, 'plugins': [{**reset.identity(self.incoming), 'filename': self.incoming.name, 'sha256': reset.digest(self.incoming)}]})) + self.service = FakeService() + + def jar(self, path, name, version): + with zipfile.ZipFile(path, 'w') as jar: + jar.writestr('plugin.yml', f'name: {name}\nversion: {version}\nmain: com.example.duneterrain.DuneTerrain\n') + + def plan(self): return reset.plan(self.root, self.artifacts, self.source, reset.digest(self.target)) + + def test_only_chunk_directories_reset_and_rollback_keeps_current_player_progress(self): + protected = reset.protected(self.world) + receipt = reset.apply(self.plan(), self.service, 'test') + self.assertEqual(protected, reset.protected(self.world)) + self.assertTrue(self.service.active()) + self.assertEqual(reset.digest(self.incoming), reset.digest(self.target)) + for name in reset.CHUNKS: self.assertEqual([], list((self.dimension / name).iterdir())) + player = self.world / 'players/data/preserved.dat' + player.write_bytes(b'new earned progress since canary') + (self.root / 'server.properties').write_text('# Paper new timestamp\nlevel-name=arrakis\nserver-port=25565\n') + reset.rollback(receipt, self.service) + self.assertEqual(b'new earned progress since canary', player.read_bytes()) + for name in reset.CHUNKS: self.assertEqual(('original ' + name).encode(), (self.dimension / name / 'test.dat').read_bytes()) + reset.rollback(receipt, self.service) # Receipt rollback is idempotent. + + def test_start_failure_restores_original_chunks_and_plugin(self): + before = reset.tree(self.world) + old = reset.digest(self.target) + self.service.fail_start = True + with self.assertRaises(RuntimeError): reset.apply(self.plan(), self.service, 'failure') + self.assertEqual(old, reset.digest(self.target)) + self.assertEqual(before, reset.tree(self.world)) + self.assertTrue(self.service.active()) + + def test_mismatched_source_or_jar_cannot_stop_service(self): + with self.assertRaises(ValueError): reset.plan(self.root, self.artifacts, 'b' * 40, reset.digest(self.target)) + self.incoming.write_bytes(b'changed artifact') + with self.assertRaises(ValueError): self.plan() + self.assertTrue(self.service.active()) + + def test_another_server_root_is_never_allowed(self): + other = self.root.parent / 'lobby' + other.mkdir() + with self.assertRaises(ValueError): reset.plan(other, self.artifacts, self.source) + + def test_config_change_after_plan_refused_without_world_mutation(self): + value = self.plan() + before = reset.tree(self.world) + (self.root / 'bukkit.yml').write_text('changed generator') + with self.assertRaises(ValueError): reset.apply(value, self.service, 'config') + self.assertEqual(before, reset.tree(self.world)) + self.assertTrue(self.service.active()) + + +if __name__ == '__main__': unittest.main() diff --git a/tools/verify-arrakis-terrain.py b/tools/verify-arrakis-terrain.py new file mode 100644 index 00000000..baa550ed --- /dev/null +++ b/tools/verify-arrakis-terrain.py @@ -0,0 +1,28 @@ +"""Read-only ABI/resource verification against the reviewed active Arrakis Terrain contract.""" +import hashlib +import json +from pathlib import Path +import sys +import zipfile +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from plugin_backend_abi import jar_classes + + +def verify(jar, contract): + classes = jar_classes(jar) + for name, old in contract['classes'].items(): + if name not in classes: raise ValueError('Missing retained Terrain class: ' + name) + for kind in ('methods', 'fields'): + for member in old[kind]: + if member not in classes[name][kind]: raise ValueError('Missing retained Terrain API: ' + name + ':' + str(member)) + with zipfile.ZipFile(jar) as archive: + for name, expected in contract['resources'].items(): + payload = archive.read(name) + if isinstance(expected, dict): + payload = json.dumps(json.loads(payload), sort_keys=True, separators=(',', ':')).encode() + expected = expected['canonicalSha256'] + if hashlib.sha256(payload).hexdigest() != expected: raise ValueError('Retained gameplay resource changed: ' + name) + return {'retainedClasses': len(contract['classes']), 'retainedResources': len(contract['resources'])} + + +if __name__ == '__main__': print(json.dumps(verify(sys.argv[1], json.loads(Path(sys.argv[2]).read_text())))) -- 2.53.0