From 1dd1ee44da203fa37a1bd69e7e1902c58ab372e6 Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:12:46 -0700 Subject: [PATCH] Heal explosion holes gradually and keep the Magic plugin's blocks D224: explosion holes in natural land heal on their own over about a week, layer by layer, with saplings growing back into trees, pausing near players. Everything else still needs an admin's approved run. Rewild now reads the Magic plugin's blocks, automata and pending spell undos and keeps them; in magic.worlds nothing resets or heals unless Magic is running and answers. Tested with unit tests only (103 pass). No test servers tonight, so the server side of a step and the Magic hook against a running Magic are untested; they're listed in docs/test-audit.md for the bot run before 0.4.0 is tagged. Task: K675 Co-Authored-By: Claude Opus 5.5 --- README.md | 27 +- build.gradle.kts | 2 +- docs/decisions.md | 6 + docs/releases/v0.4.0.md | 15 + docs/test-audit.md | 21 ++ .../com/extantape/rewild/RewildPlugin.java | 8 + .../extantape/rewild/cmd/RewildCommand.java | 41 ++- .../extantape/rewild/config/RegenConfig.java | 14 + .../com/extantape/rewild/heal/HealCheck.java | 47 ++++ .../com/extantape/rewild/heal/HealJob.java | 95 +++++++ .../com/extantape/rewild/heal/HealPlan.java | 182 ++++++++++++ .../extantape/rewild/heal/HealService.java | 266 ++++++++++++++++++ .../com/extantape/rewild/keep/Keepers.java | 10 + .../com/extantape/rewild/keep/MagicKeeps.java | 97 +++++++ .../com/extantape/rewild/track/Tracking.java | 2 +- src/main/resources/config.yml | 26 +- .../com/extantape/rewild/HealPlanTest.java | 135 +++++++++ .../rewild/config/RegenConfigTest.java | 22 ++ .../rewild/heal/HealCheckAndJobTest.java | 104 +++++++ .../extantape/rewild/keep/MagicKeepsTest.java | 40 +++ 20 files changed, 1153 insertions(+), 7 deletions(-) create mode 100644 docs/releases/v0.4.0.md create mode 100644 src/main/java/com/extantape/rewild/heal/HealCheck.java create mode 100644 src/main/java/com/extantape/rewild/heal/HealJob.java create mode 100644 src/main/java/com/extantape/rewild/heal/HealPlan.java create mode 100644 src/main/java/com/extantape/rewild/heal/HealService.java create mode 100644 src/main/java/com/extantape/rewild/keep/MagicKeeps.java create mode 100644 src/test/java/com/extantape/rewild/HealPlanTest.java create mode 100644 src/test/java/com/extantape/rewild/heal/HealCheckAndJobTest.java create mode 100644 src/test/java/com/extantape/rewild/keep/MagicKeepsTest.java diff --git a/README.md b/README.md index 77d8a0d..f714302 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ A Paper plugin that rewilds abandoned, mined-out land back to fresh terrain from the world's seed, and keeps every block players placed exactly where it is. Paths, builds, chests and protected places stay; the holes, quarries and craters around them fill back in. -**Status:** pre-release. 0.3.0 is a redesign and has passed its tests on throwaway Paper 26.3 servers with a bot as the player (see [Testing](#testing)). It hasn't run on a real server, and nobody has looked at a rewilded area in a real game client yet. +**Status:** pre-release. 0.4.0 adds gradual healing of explosion holes and a hook for the Magic plugin; those have passed unit tests only, and haven't run on a server yet. 0.3.0 is a redesign and has passed its tests on throwaway Paper 26.3 servers with a bot as the player (see [Testing](#testing)). It hasn't run on a real server, and nobody has looked at a rewilded area in a real game client yet. - Paper 26.1 and newer, Java 25. Not Spigot, and not 1.21.x. -- Off in every world until you turn it on. Dry run by default. Worlds in `never-reset-worlds`, such as kids' worlds, can never be turned on by mistake. +- Off in every world until you turn it on. Dry run by default. Worlds in `never-reset-worlds`, such as creative and lobby worlds, can never be turned on by mistake. - Nothing resets until an admin has said which plugins to respect, an admin approves a run, and every run can be undone. ## How it works @@ -61,6 +61,25 @@ Sometimes the chunk is kept whole, by a pet or a respawn point, or someone still Before either kind of change, the plugin checks the bedrock pattern of the fresh copy against the real chunk, and refuses if they differ. A repair doesn't happen if anything that keeps the chunk whole reaches below the cut, if players changed or visited anything down there recently, or if the chunk is in a claim, at spawn or in an admin-protected area. It only runs in overworld-type worlds. +### Explosion holes heal gradually + +From 0.4.0, a hole a creeper or TNT blows in natural land heals on its own, a step at a time, with no admin approval. Rewild writes down the blocks the blast destroyed and puts them back about once a day: + +1. The ground fills from the bottom up, a few layers a step. Grass, podzol and moss go back as plain dirt first. +2. The next step the grass comes back on that dirt, and each tree the blast felled gets a sapling of its own wood. +3. Then a young tree: the lower half of the trunk and the leaves near it. +4. Last, the rest of the trees, loose leaves, flowers, grass and snow. + +A typical crater, 3 or 4 layers deep, takes about a week. A deeper hole fills more layers a step, so it still takes about a week. + +A hole only heals on its own when all of this holds: the world is enabled, the land was generated after Rewild started tracking it, the blast destroyed nothing a player placed and no container, and no player's block or filled container, claim, kept area, admin-protected area, respawn point or Magic block is within 8 blocks. Any other hole waits for an admin's approved run, as before. + +Healing waits while a player is within 24 blocks, while the hole's chunks aren't loaded, and while anything that would stop a reset is wrong (the claim plugin is down, say). Each step only fills air, water and blocks anything may replace, such as short grass and snow, plus the dirt or sapling an earlier step laid. It never fills a block something is in, and never replaces a block a player put there since. While `dry-run` is true, each step is only reported in the log. `/rewild healing` lists the holes healing now. + +### Magic + +Wherever the Magic plugin is running, Rewild keeps its blocks and automata in place, with 8 blocks around each for its structure (`magic.keep-radius`), and the areas its spells changed that Magic will put back itself. A blast that's part of a spell is left to Magic. List the worlds where Magic is played in `magic.worlds`: nothing in those worlds resets or heals unless Magic is running and answers. + ## Safety - **Dry run by default.** With `dry-run: true`, an approved run is checked at the next restart and reported in the log, and no world file changes. @@ -108,6 +127,7 @@ All commands need `rewild.admin`, which ops have. Players get no commands. | `/rewild keep list [world] [--json]` | Lists kept areas, with who kept them and whether they count. | | `/rewild unkeep ` | Removes a kept area. `/rewild unkeep [] [plugin:]` removes one by its exact corners. | | `/rewild plugins [--json]` | Lists installed plugins and which Rewild respects. `respect ...`, `ignore ...` and `ignore-rest` answer. | +| `/rewild healing` | Lists explosion holes healing on their own, with where they are and the next step. `step ` runs the next step now (it still waits for nearby players), and `cancel ` stops one, leaving what's back. | | `/rewild reload` | Reloads config.yml, keep-plugins.yml and the kept areas. | With `bluemap.enabled: true`, the last scan also appears as a BlueMap layer. It's off by default, because kept chunks show where people build and sleep. Only turn it on for a map that only admins can open. @@ -143,6 +163,9 @@ If a respected provider throws, nothing in that world resets. If LanternGraves i - A below-ground repair drops mobs and items under the cut, and doesn't bring back mineshaft minecarts. - GriefPrevention is the only claim plugin supported. Animated Architecture has no hook, but its builds are made of player-placed blocks, which the tracker sees. - Undo restores a chunk as it was before the run, so anything built in it since is lost. +- Healing has passed unit tests only (0.4.0). It hasn't run on a server yet, with a bot or a player. +- If a healing sapling grows into a tree on its own before the young-tree step, that step leaves the trunk alone and adds the young tree's leaves and logs around it where there's air. +- A healed hole gets back the blocks the blast destroyed. Water or lava that flowed in and set into stone or obsidian is left as it is, because it isn't air. ## Testing diff --git a/build.gradle.kts b/build.gradle.kts index e41dc72..ebe6636 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,7 +3,7 @@ plugins { } group = "com.extantape" -version = "0.3.2" +version = "0.4.0" java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) diff --git a/docs/decisions.md b/docs/decisions.md index 3285e40..7020b47 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -26,3 +26,9 @@ Decisions in the design brief that weren't reopened: off by default in every wor ## 2026-11-14 - **No old names (owner, D196):** "Make sure none of the plugins retain old references or commands". The folder move from the plugin's earlier name and its tests are removed. Released as 0.3.2. + +## 2026-11-22 + +- **Every survival world, and gradual healing (owner, D224, 2026-11-16):** "If it's survival, even magic, it should be on that. It should probably plug into the magic plugin so it doesn't delete things from that realm, but it still should rewild." Pace: "About a week (Recommended)". Explosions: "Explosion holes heal on their own". Kids' worlds get the same rules as any other survival world, so the docs no longer suggest listing them in `never-reset-worlds`. +- **How 0.4.0 heals (the lead's design, for the owner's say):** a qualifying explosion hole is recorded as it happens and put back in daily steps: ground bottom up over `days - 3` steps (grass as dirt first), then grass and a sapling per felled tree, then the young tree (lower half of the trunk and leaves within 2 blocks), then the rest of the tree and small plants. A hole qualifies only in known land, with nothing player-placed or filled destroyed, and no build, filled container, claim, kept area, protected area, respawn point or Magic block within `healing.build-radius` (8). Healing pauses within `healing.pause-radius` (24) of a player, while chunks are unloaded, and while any reset safety check fails. A step fills only air, liquids and replaceable blocks, or the dirt or sapling an earlier step laid, and skips blocks an entity is in. Dry run logs steps instead of placing them, and completes the job. +- **Magic hook (the lead's design):** read by reflection from Magic's public API (tested against the Magic 11.3 jar's interfaces, not a running server). Magic blocks and automata are kept with `magic.keep-radius` (8) around each, and spell changes Magic will undo are kept too; a blast inside a pending undo is left to Magic. In `magic.worlds`, nothing resets or heals unless Magic is running and answers (fail closed). Magic worlds go in config only after a bot run with Magic installed. diff --git a/docs/releases/v0.4.0.md b/docs/releases/v0.4.0.md new file mode 100644 index 0000000..3ff34ff --- /dev/null +++ b/docs/releases/v0.4.0.md @@ -0,0 +1,15 @@ +Explosion holes heal on their own, gradually (D224), and Rewild keeps the Magic plugin's blocks. + +## What's new + +- A hole a creeper or TNT blows in natural land heals over about a week with no approval: the ground fills bottom up, about a step a day, then grass, then saplings, young trees and full trees, then flowers. It only heals when nothing a player placed is in it or within 8 blocks, and it waits while a player is within 24 blocks. Other holes wait for an admin's approved run as before. +- `/rewild healing` lists holes healing now. `step ` runs the next step, and `cancel ` stops one. +- The Magic plugin's blocks, automata and pending spell changes are kept in place. In worlds listed in `magic.worlds`, nothing resets or heals unless Magic is running. + +## Upgrading + +Replace the jar. New settings (`healing`, `magic`) get their defaults; add them to config.yml to change them. Healing is on by default, and while `dry-run` is true it only reports in the log. + +## Tested + +Unit tests pass (103). Healing and the Magic hook haven't run on a server yet. diff --git a/docs/test-audit.md b/docs/test-audit.md index 2a8ffbc..941bf05 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -2,6 +2,27 @@ Kept by this repo's owning session (Minecraft: Plugins Lead), per `~/Code/CLAUDE.md`, "Test self-audits". Newest first. +## 2026-11-22: 0.4.0 gradual healing and the Magic hook (K675) + +Offline, unit tests only: no test servers tonight (owner). 103 unit tests pass. + +| Promise | Covered by | +| --- | --- | +| A typical crater heals in about a week, bottom up, one band of layers a step | `HealPlanTest.aTypicalCraterTakesAboutAWeekAndFillsBottomUp`, `aDeepHoleTakesMoreLayersPerStepNotMoreDays` | +| Grass comes back as dirt first, and the grass step may replace only that dirt | `grassComesBackAsDirtFirstThenGrassReplacingIt` | +| Felled trees: sapling, then young tree replacing only its sapling, then whole | `aFelledTreeComesBackAsASaplingThenAYoungTreeThenWhole`, `touchingLogsAreOneTreeAndSeparateOnesAreTwo`, `saplingsMatchTheWoodAndStrippedOrUnknownLogsGetNone` | +| Small plants last; air never placed; each block once | `smallPlantsComeBackLast`, `airIsNeverPlacedAndEveryRecordedBlockComesBackOnce`, `nothingToHealMeansNoSteps` | +| **Only natural, known land heals without approval** (fails closed) | `HealCheckAndJobTest.unknownLandNeverHealsOnItsOwn`, `aBlastThroughPlayerBlocksWaitsForAnAdmin`, `aBuildNearbyStopsIt_evenInTheNextChunk`, `aFilledContainerNearbyStopsIt`, `aHoleInKnownNaturalLandHeals` | +| Healing survives a restart; a damaged file is refused, not guessed | `aJobSurvivesARestartExactly`, `aDamagedJobFileIsRefusedNotGuessed` | +| **A Magic world without Magic running never resets or heals**; Magic that can't answer stops resets | `MagicKeepsTest` (5 tests) | +| Settings default to a week and bad values stop resets | `RegenConfigTest.healingIsOnWithAWeekAndMagicWorldsAreRead` | + +Gaps, for the bot run before release (not possible tonight): +- The server side of a step: pausing near a player, waiting for unloaded chunks, not overwriting a block placed since, skipping blocks an entity is in, dry run placing nothing, claims and kept areas refusing a hole, and a blast through a chest refusing it. These need a Paper server; add them to `test/` as `heal.mjs`, with `healing.step-hours` forced through `/rewild healing step`. +- The Magic hook against a running Magic 11.3: it was written against the jar's interfaces only. + +Skipped: none of the pure rules; the reflection calls themselves are left to the bot run, since a mock would only test the mock. + ## 2026-11-12: the 0.3.0 redesign The redesign changes what a reset does, so every keep and safety promise was mapped again. "Acceptance" is `test/acceptance.mjs` and `test/keep.mjs` on a throwaway Paper 26.3 (build 249) server; "unit" is `src/test`. diff --git a/src/main/java/com/extantape/rewild/RewildPlugin.java b/src/main/java/com/extantape/rewild/RewildPlugin.java index 588a698..8cbd3d3 100644 --- a/src/main/java/com/extantape/rewild/RewildPlugin.java +++ b/src/main/java/com/extantape/rewild/RewildPlugin.java @@ -28,6 +28,7 @@ public final class RewildPlugin extends JavaPlugin { private TrackerListener listener; private ScanService scans; private RunService runs; + private com.extantape.rewild.heal.HealService healing; private Preview preview; private MapLayer mapLayer = MapLayer.NONE; /** Runs before any world loads: apply or undo approved runs while no chunk is open. */ @@ -80,6 +81,8 @@ public void onEnable() { scans = new ScanService(this, tracking); runs = new RunService(this, tracking); preview = new Preview(this, scans); + healing = new com.extantape.rewild.heal.HealService(this, tracking); + healing.start(); if (config.blueMap && Bukkit.getPluginManager().getPlugin("BlueMap") != null) { try { mapLayer = new BlueMapLayer(getLogger()); @@ -115,6 +118,7 @@ public String pluginsProblem() { @Override public void onDisable() { if (preview != null) preview.stopAll(); + if (healing != null) healing.stop(); mapLayer.close(); if (tracking == null) return; var snaps = runs.shutdownSnapshots(); @@ -158,6 +162,10 @@ public RunService runs() { return runs; } + public com.extantape.rewild.heal.HealService healing() { + return healing; + } + public Preview preview() { return preview; } diff --git a/src/main/java/com/extantape/rewild/cmd/RewildCommand.java b/src/main/java/com/extantape/rewild/cmd/RewildCommand.java index e910de8..4b55d13 100644 --- a/src/main/java/com/extantape/rewild/cmd/RewildCommand.java +++ b/src/main/java/com/extantape/rewild/cmd/RewildCommand.java @@ -28,7 +28,7 @@ /** /rewild: admin-only, registered through Paper's command API. Players get no commands. */ public final class RewildCommand implements BasicCommand { public static final String PERMISSION = "rewild.admin"; - private static final List SUBS = List.of("status", "why", "preview", "scan", "approve", "undo", "protect", "keep", "unkeep", "plugins", "reload"); + private static final List SUBS = List.of("status", "why", "preview", "scan", "approve", "undo", "protect", "keep", "unkeep", "plugins", "healing", "reload"); private final RewildPlugin plugin; public RewildCommand(RewildPlugin plugin) { @@ -79,12 +79,13 @@ void run(CommandSender sender, String[] args) { case "keep" -> keep(sender, args); case "unkeep" -> unkeep(sender, args); case "plugins" -> plugins(sender, args); + case "healing" -> healing(sender, args); case "reload" -> { List errors = plugin.reload(); if (errors.isEmpty()) say(sender, NamedTextColor.GREEN, "Config reloaded. New thresholds apply to the next scan."); else say(sender, NamedTextColor.RED, "Config reloaded with problems, so nothing will reset: " + String.join("; ", errors)); } - default -> say(sender, NamedTextColor.GRAY, "/rewild status | why [world] [x z] | preview [radius] | scan [world] | approve | approve generator | undo | protect [radius] [note] | protect remove | protect list | keep [] [plugin:] [note] | keep list [world] [--json] | unkeep | plugins [respect|ignore ...] [ignore-rest] [--json] | reload"); + default -> say(sender, NamedTextColor.GRAY, "/rewild status | why [world] [x z] | preview [radius] | scan [world] | approve | approve generator | undo | protect [radius] [note] | protect remove | protect list | keep [] [plugin:] [note] | keep list [world] [--json] | unkeep | plugins [respect|ignore ...] [ignore-rest] [--json] | healing [step|cancel ] | reload"); } } catch (IOException e) { say(sender, NamedTextColor.RED, "That failed: " + e.getMessage()); @@ -525,6 +526,39 @@ private void protect(CommandSender sender, String[] args) throws IOException { say(sender, NamedTextColor.GREEN, "Protected " + (2 * radius + 1) * (2 * radius + 1) + " chunk(s) around you. They'll never reset."); } + /** /rewild healing: list holes healing on their own; step one now (still waits for nearby players); cancel one. */ + private void healing(CommandSender sender, String[] args) throws IOException { + var h = plugin.healing(); + if (args.length >= 3 && args[1].equalsIgnoreCase("cancel")) { + if (h.cancel(args[2])) say(sender, NamedTextColor.GREEN, "Healing " + args[2] + " canceled. What's already back stays."); + else say(sender, NamedTextColor.RED, "No healing called " + args[2] + ". /rewild healing lists them."); + return; + } + if (args.length >= 3 && args[1].equalsIgnoreCase("step")) { + var j = h.all().stream().filter(x -> x.id.equals(args[2])).findFirst().orElse(null); + World w = j == null ? null : Bukkit.getWorld(j.world); + if (j == null || w == null) { + say(sender, NamedTextColor.RED, "No healing called " + args[2] + " in a loaded world. /rewild healing lists them."); + return; + } + say(sender, NamedTextColor.GREEN, h.step(j, w, System.currentTimeMillis(), true)); + return; + } + var all = h.all(); + if (all.isEmpty()) { + say(sender, NamedTextColor.GRAY, plugin.tracking().config().healExplosions + ? "No explosion holes are healing right now." : "Explosion holes don't heal on their own here (healing.explosions is false)."); + return; + } + say(sender, NamedTextColor.GREEN, all.size() + " hole(s) healing, about one step every " + plugin.tracking().config().healStepHours + " hours:"); + for (var j : all) { + World w = Bukkit.getWorld(j.world); + int[] c = j.center(); + say(sender, NamedTextColor.GRAY, j.id + " " + (w == null ? "unloaded world" : w.getName()) + " " + c[0] + " " + c[1] + " " + c[2] + + " " + j.cells.size() + " blocks, " + j.done + " step(s) done, next " + date(j.next)); + } + } + @Override public java.util.Collection suggest(CommandSourceStack source, String[] args) { CommandSender sender = source.getSender(); @@ -547,6 +581,9 @@ public java.util.Collection suggest(CommandSourceStack source, String[] if (args.length == 3 && sub.equals("approve") && args[1].equalsIgnoreCase("generator")) { return plugin.tracking().states().stream().map(s -> s.name).filter(n -> n.startsWith(args[2])).toList(); } + if (args.length == 2 && sub.equals("healing")) return List.of("step", "cancel").stream().filter(s -> s.startsWith(args[1])).toList(); + if (args.length == 3 && sub.equals("healing") && (args[1].equalsIgnoreCase("step") || args[1].equalsIgnoreCase("cancel"))) + return plugin.healing().all().stream().map(j -> j.id).filter(s -> s.startsWith(args[2])).toList(); if (args.length == 2 && sub.equals("protect")) return List.of("remove", "list", "0", "1", "2"); if (args.length == 2 && sub.equals("plugins")) return List.of("respect", "ignore", "ignore-rest", "--json").stream().filter(s -> s.startsWith(args[1])).toList(); if (args.length == 3 && sub.equals("plugins") && (args[1].equalsIgnoreCase("respect") || args[1].equalsIgnoreCase("ignore"))) { diff --git a/src/main/java/com/extantape/rewild/config/RegenConfig.java b/src/main/java/com/extantape/rewild/config/RegenConfig.java index 579ddae..f34e0c9 100644 --- a/src/main/java/com/extantape/rewild/config/RegenConfig.java +++ b/src/main/java/com/extantape/rewild/config/RegenConfig.java @@ -33,6 +33,12 @@ public record WorldSettings( public final String warnMessage; public final int trashKeepDays; public final boolean blueMap; + /** Gradual healing (0.4.0, D224): explosion holes in natural land heal on their own, a step at a time. */ + public final boolean healExplosions; + public final int healDays, healStepHours, healPauseRadius, healBuildRadius; + /** Worlds where Magic is played: nothing there resets or heals unless Magic is running and answers (D224). */ + public final java.util.Set magicWorlds = new java.util.HashSet<>(); + public final int magicRadius; /** Worlds that never reset, overriding enabled. Kids' worlds belong here. */ public final java.util.Set neverReset = new java.util.HashSet<>(); /** Block types kept wherever they are when a chunk rewilds, with what holds them up. Dirt paths by default. */ @@ -53,6 +59,14 @@ public RegenConfig(FileConfiguration c) { warnMessage = string(c, "run.warn-message", "Some untouched wild land in this world will refresh at the next restart."); trashKeepDays = positive(c, "trash.keep-days", 30); blueMap = bool(c, "bluemap.enabled", false); + healExplosions = bool(c, "healing.explosions", true); + healDays = positive(c, "healing.days", 7); + healStepHours = positive(c, "healing.step-hours", 24); + healPauseRadius = positive(c, "healing.pause-radius", 24); + healBuildRadius = positive(c, "healing.build-radius", 8); + if (c.contains("magic.worlds") && !c.isList("magic.worlds")) errors.add("magic.worlds must be a list of world names"); + magicWorlds.addAll(c.getStringList("magic.worlds")); + magicRadius = positive(c, "magic.keep-radius", 8); if (c.contains("never-reset-worlds") && !c.isList("never-reset-worlds")) errors.add("never-reset-worlds must be a list of world names"); neverReset.addAll(c.getStringList("never-reset-worlds")); keepBlocks = c.contains("keep-blocks") ? patterns(c, "keep-blocks") : List.of("DIRT_PATH"); diff --git a/src/main/java/com/extantape/rewild/heal/HealCheck.java b/src/main/java/com/extantape/rewild/heal/HealCheck.java new file mode 100644 index 0000000..8882d48 --- /dev/null +++ b/src/main/java/com/extantape/rewild/heal/HealCheck.java @@ -0,0 +1,47 @@ +package com.extantape.rewild.heal; + +import com.extantape.rewild.store.ChunkRecord; +import java.util.List; +import java.util.function.BiFunction; + +/** + * Whether an explosion hole may heal on its own (D224: "Explosion holes (creepers, TNT) in natural land with no builds + * nearby heal on their own without approval; everything else still needs an admin's approval"). Fails closed: any doubt + * is a reason, and the hole waits for an admin like any other damage. + */ +public final class HealCheck { + private HealCheck() {} + + /** + * Null when the hole may heal on its own, otherwise why not. + * + * @param record the tracker's record of a chunk (null when it has none) + */ + public static String why(List cells, int buildRadius, BiFunction record) { + if (cells.isEmpty()) return "nothing natural was destroyed"; + int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE; + for (HealPlan.Cell c : cells) { + ChunkRecord r = record.apply(c.x() >> 4, c.z() >> 4); + if (r == null || !r.known) return "it reached land generated before Rewild was tracking it, so Rewild can't tell what's natural"; + if (r.placed.containsKey(ChunkRecord.pos(c.x() & 15, c.y(), c.z() & 15))) return "it destroyed blocks a player placed"; + minX = Math.min(minX, c.x()); minY = Math.min(minY, c.y()); minZ = Math.min(minZ, c.z()); + maxX = Math.max(maxX, c.x()); maxY = Math.max(maxY, c.y()); maxZ = Math.max(maxZ, c.z()); + } + minX -= buildRadius; minY -= buildRadius; minZ -= buildRadius; + maxX += buildRadius; maxY += buildRadius; maxZ += buildRadius; + for (int cx = minX >> 4; cx <= maxX >> 4; cx++) + for (int cz = minZ >> 4; cz <= maxZ >> 4; cz++) { + ChunkRecord r = record.apply(cx, cz); + if (r == null) continue; + for (long p : r.placed.keySet()) if (inside(r, p, minX, minY, minZ, maxX, maxY, maxZ)) return "a player's build is within " + buildRadius + " blocks"; + for (long p : r.filledContainers) if (inside(r, p, minX, minY, minZ, maxX, maxY, maxZ)) return "a container a player uses is within " + buildRadius + " blocks"; + } + return null; + } + + private static boolean inside(ChunkRecord r, long p, int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + int x = (r.x << 4) + ChunkRecord.posX(p), y = ChunkRecord.posY(p), z = (r.z << 4) + ChunkRecord.posZ(p); + return x >= minX && x <= maxX && y >= minY && y <= maxY && z >= minZ && z <= maxZ; + } +} diff --git a/src/main/java/com/extantape/rewild/heal/HealJob.java b/src/main/java/com/extantape/rewild/heal/HealJob.java new file mode 100644 index 0000000..87184b3 --- /dev/null +++ b/src/main/java/com/extantape/rewild/heal/HealJob.java @@ -0,0 +1,95 @@ +package com.extantape.rewild.heal; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * One hole healing a step at a time: the blocks to put back and how far along it is. Saved as a plain text file: + *
+ * rewild-heal 1
+ * world 6f1c...
+ * created 1763800000000
+ * next 1763886400000
+ * done 2
+ * cell 10 63 -4 minecraft:grass_block[snowy=false]
+ * 
+ * Written to a temporary file and moved into place, so a crash leaves the old file or the new one. + */ +public final class HealJob { + public final String id; + public final UUID world; + public final long created; + public long next; + public int done; + public final List cells; + + public HealJob(String id, UUID world, long created, long next, int done, List cells) { + this.id = id; + this.world = world; + this.created = created; + this.next = next; + this.done = done; + this.cells = List.copyOf(cells); + } + + /** The middle of the hole, for messages and the pause check: x, y, z. */ + public int[] center() { + long x = 0, y = 0, z = 0; + for (HealPlan.Cell c : cells) { x += c.x(); y += c.y(); z += c.z(); } + int n = Math.max(1, cells.size()); + return new int[] {(int) (x / n), (int) (y / n), (int) (z / n)}; + } + + /** min x, min z, max x, max z. */ + public int[] bounds() { + int a = Integer.MAX_VALUE, b = Integer.MAX_VALUE, c = Integer.MIN_VALUE, d = Integer.MIN_VALUE; + for (HealPlan.Cell cell : cells) { a = Math.min(a, cell.x()); b = Math.min(b, cell.z()); c = Math.max(c, cell.x()); d = Math.max(d, cell.z()); } + return new int[] {a, b, c, d}; + } + + public void save(Path file) throws IOException { + StringBuilder sb = new StringBuilder("rewild-heal 1\n"); + sb.append("world ").append(world).append('\n').append("created ").append(created).append('\n') + .append("next ").append(next).append('\n').append("done ").append(done).append('\n'); + for (HealPlan.Cell c : cells) sb.append("cell ").append(c.x()).append(' ').append(c.y()).append(' ').append(c.z()).append(' ').append(c.data()).append('\n'); + Files.createDirectories(file.getParent()); + Path tmp = file.resolveSibling(file.getFileName() + ".tmp"); + Files.writeString(tmp, sb, StandardCharsets.UTF_8); + Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } + + /** Reads a job, or throws if the file isn't one; a bad cell line is an error too, never guessed. */ + public static HealJob load(Path file) throws IOException { + List lines = Files.readAllLines(file, StandardCharsets.UTF_8); + if (lines.isEmpty() || !lines.getFirst().equals("rewild-heal 1")) throw new IOException(file.getFileName() + " isn't a Rewild healing file"); + UUID world = null; + long created = -1, next = -1; + int done = -1; + List cells = new ArrayList<>(); + try { + for (String l : lines.subList(1, lines.size())) { + if (l.isBlank()) continue; + String[] p = l.split(" ", 5); + switch (p[0]) { + case "world" -> world = UUID.fromString(p[1]); + case "created" -> created = Long.parseLong(p[1]); + case "next" -> next = Long.parseLong(p[1]); + case "done" -> done = Integer.parseInt(p[1]); + case "cell" -> cells.add(new HealPlan.Cell(Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]), p[4])); + default -> throw new IOException("unknown line: " + l); + } + } + } catch (RuntimeException e) { + throw new IOException(file.getFileName() + " has a bad line: " + e.getMessage()); + } + if (world == null || created < 0 || next < 0 || done < 0) throw new IOException(file.getFileName() + " is missing its header"); + String name = file.getFileName().toString(); + return new HealJob(name.endsWith(".txt") ? name.substring(0, name.length() - 4) : name, world, created, next, done, cells); + } +} diff --git a/src/main/java/com/extantape/rewild/heal/HealPlan.java b/src/main/java/com/extantape/rewild/heal/HealPlan.java new file mode 100644 index 0000000..fe7deed --- /dev/null +++ b/src/main/java/com/extantape/rewild/heal/HealPlan.java @@ -0,0 +1,182 @@ +package com.extantape.rewild.heal; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Predicate; + +/** + * How a hole heals, step by step (D224: "if a creeper blows a hole in the ground, the next day one layer is filled, then + * a couple days later another is ... so stuff doesn't just snap back but truly rewilds. Same with trees"). Pure: no + * server, so every rule here is unit tested. + * + *
    + *
  1. Ground fills from the bottom up, a few layers per step, sized so the ground takes {@code days - 3} steps. + * Grass-type surface blocks go in as plain dirt.
  2. + *
  3. The next step, the grass comes back on that dirt, and each felled tree gets a sapling where its trunk stood.
  4. + *
  5. The step after, each tree is a young tree: the lower half of its trunk and the leaves close to it.
  6. + *
  7. The last step puts the rest of the trees, loose leaves and the small plants (flowers, grass, snow) back.
  8. + *
+ * With the default 7 days, a typical creeper crater (3 or 4 layers deep) takes about a week. + */ +public final class HealPlan { + /** A block to put back, at world coordinates, as Minecraft block data ("minecraft:stone"). */ + public record Cell(int x, int y, int z, String data) { + public String material() { + String d = data.toLowerCase(Locale.ROOT); + int b = d.indexOf('['); + String m = b < 0 ? d : d.substring(0, b); + return m.startsWith("minecraft:") ? m.substring(10) : m; + } + } + + /** + * What one step places. {@code over} is a block this placement may replace besides air, water and the like: the + * dirt an earlier step laid where grass now goes, or the sapling where the trunk now goes. Null for none. + */ + public record Placement(int x, int y, int z, String data, String over) {} + + private static final Set GRASSY = Set.of("grass_block", "podzol", "mycelium", "moss_block"); + private static final Map SAPLINGS = Map.ofEntries( + Map.entry("oak", "oak_sapling"), Map.entry("spruce", "spruce_sapling"), Map.entry("birch", "birch_sapling"), + Map.entry("jungle", "jungle_sapling"), Map.entry("acacia", "acacia_sapling"), Map.entry("dark_oak", "dark_oak_sapling"), + Map.entry("cherry", "cherry_sapling"), Map.entry("pale_oak", "pale_oak_sapling"), Map.entry("mangrove", "mangrove_propagule"), + Map.entry("crimson", "crimson_fungus"), Map.entry("warped", "warped_fungus")); + + private HealPlan() {} + + static boolean isLog(String m) { + return m.endsWith("_log") || m.endsWith("_wood") || m.endsWith("_stem") || m.endsWith("_hyphae"); + } + + static boolean isLeaves(String m) { + return m.endsWith("_leaves") || m.equals("nether_wart_block") || m.equals("warped_wart_block") || m.equals("shroomlight"); + } + + /** The sapling for a log ("oak_log" to "minecraft:oak_sapling"), or null when there's none (stripped logs too). */ + static String saplingFor(String logMaterial) { + if (logMaterial.startsWith("stripped_")) return null; + String wood = logMaterial.replaceFirst("_(log|wood|stem|hyphae)$", ""); + String s = SAPLINGS.get(wood); + return s == null ? null : "minecraft:" + s; + } + + /** + * The steps, in order. Step 0 runs a step after the damage, and each later one a step after that. + * + * @param plant true for small plants that come back last (flowers, grass, snow layers); the caller decides, from + * the same list that says what doesn't count as damage. + */ + public static List> steps(List cells, int days, Predicate plant) { + List ground = new ArrayList<>(), logs = new ArrayList<>(), leaves = new ArrayList<>(), plants = new ArrayList<>(); + for (Cell c : cells) { + String m = c.material(); + if (m.equals("air") || m.equals("cave_air") || m.equals("void_air")) continue; + if (isLog(m)) logs.add(c); + else if (isLeaves(m)) leaves.add(c); + else if (plant.test(m)) plants.add(c); + else ground.add(c); + } + List> steps = new ArrayList<>(); + + // 1. Ground, bottom up. + TreeSet layers = new TreeSet<>(); + for (Cell c : ground) layers.add(c.y); + int groundSteps = Math.max(1, days - 3); + int perStep = Math.max(1, (int) Math.ceil(layers.size() / (double) groundSteps)); + List ys = new ArrayList<>(layers); + for (int i = 0; i < ys.size(); i += perStep) { + Set band = new HashSet<>(ys.subList(i, Math.min(ys.size(), i + perStep))); + List step = new ArrayList<>(); + for (Cell c : ground) + if (band.contains(c.y)) step.add(new Placement(c.x, c.y, c.z, GRASSY.contains(c.material()) ? "minecraft:dirt" : c.data, null)); + sort(step); + steps.add(step); + } + + // 2. Grass on the dirt, saplings where trunks stood. + List> trees = trees(logs); + List grass = new ArrayList<>(); + for (Cell c : ground) if (GRASSY.contains(c.material())) grass.add(new Placement(c.x, c.y, c.z, c.data, "minecraft:dirt")); + Map, Cell> bases = new HashMap<>(); + for (List t : trees) { + Cell base = t.stream().min(Comparator.comparingInt(Cell::y).thenComparingInt(Cell::x).thenComparingInt(Cell::z)).orElseThrow(); + bases.put(t, base); + String sapling = saplingFor(base.material()); + if (sapling != null) grass.add(new Placement(base.x, base.y, base.z, sapling, null)); + } + if (!grass.isEmpty() || !trees.isEmpty()) steps.add(sorted(grass)); + + // 3. Young trees: the lower half of each trunk and the leaves within 2 blocks of it. + Set placedLeaves = new HashSet<>(), placedLogs = new HashSet<>(); + if (!trees.isEmpty()) { + List young = new ArrayList<>(); + for (List t : trees) { + Cell base = bases.get(t); + int top = t.stream().mapToInt(Cell::y).max().orElse(base.y); + int half = base.y + (top - base.y + 1) / 2; + List lower = t.stream().filter(c -> c.y < Math.max(half, base.y + 1)).toList(); + String sapling = saplingFor(base.material()); + for (Cell c : lower) { young.add(new Placement(c.x, c.y, c.z, c.data, c == base ? sapling : null)); placedLogs.add(c); } + for (Cell l : leaves) + for (Cell c : lower) + if (Math.abs(l.x - c.x) <= 2 && Math.abs(l.y - c.y) <= 2 && Math.abs(l.z - c.z) <= 2) { + if (placedLeaves.add(l)) young.add(new Placement(l.x, l.y, l.z, l.data, null)); + break; + } + } + steps.add(sorted(young)); + } + + // 4. Everything else: the rest of the trees, loose leaves and small plants. + List last = new ArrayList<>(); + for (Cell c : logs) if (!placedLogs.contains(c)) last.add(new Placement(c.x, c.y, c.z, c.data, null)); + for (Cell c : leaves) if (!placedLeaves.contains(c)) last.add(new Placement(c.x, c.y, c.z, c.data, null)); + for (Cell c : plants) last.add(new Placement(c.x, c.y, c.z, c.data, null)); + if (!last.isEmpty()) steps.add(sorted(last)); + return steps; + } + + /** Logs that touch (including diagonally) are one tree. */ + static List> trees(List logs) { + Map at = new HashMap<>(); + for (Cell c : logs) at.put(key(c.x, c.y, c.z), c); + Set seen = new HashSet<>(); + List> out = new ArrayList<>(); + for (Cell start : logs) { + if (!seen.add(start)) continue; + List tree = new ArrayList<>(); + List todo = new ArrayList<>(List.of(start)); + while (!todo.isEmpty()) { + Cell c = todo.removeLast(); + tree.add(c); + for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) for (int dz = -1; dz <= 1; dz++) { + Cell n = at.get(key(c.x + dx, c.y + dy, c.z + dz)); + if (n != null && seen.add(n)) todo.add(n); + } + } + out.add(tree); + } + return out; + } + + private static long key(int x, int y, int z) { + return ((long) (x & 0x3FFFFFF) << 38) | ((long) (z & 0x3FFFFFF) << 12) | (y & 0xFFF); + } + + private static List sorted(List l) { + sort(l); + return l; + } + + /** Bottom up, so nothing is placed floating on a gap the same step fills. */ + private static void sort(List l) { + l.sort(Comparator.comparingInt(Placement::y).thenComparingInt(Placement::x).thenComparingInt(Placement::z)); + } +} diff --git a/src/main/java/com/extantape/rewild/heal/HealService.java b/src/main/java/com/extantape/rewild/heal/HealService.java new file mode 100644 index 0000000..f93b1d8 --- /dev/null +++ b/src/main/java/com/extantape/rewild/heal/HealService.java @@ -0,0 +1,266 @@ +package com.extantape.rewild.heal; + +import com.extantape.rewild.config.RegenConfig; +import com.extantape.rewild.keep.KeepPlan; +import com.extantape.rewild.keep.Keepers; +import com.extantape.rewild.store.ChunkRecord; +import com.extantape.rewild.store.WorldState; +import com.extantape.rewild.store.WorldStore; +import com.extantape.rewild.track.Tracking; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; +import java.util.logging.Level; +import java.util.stream.Stream; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.Container; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitTask; + +/** + * Gradual healing (0.4.0, D224). Records the natural blocks an explosion destroys, when the hole qualifies to heal on + * its own ({@link HealCheck}, plus claims, admin-protected areas, kept areas and respawn points), and puts them back a + * step at a time ({@link HealPlan}): about one step a day, bottom up, waiting while a player is near and while the + * chunks aren't loaded. A step only fills air, water and other blocks that anything may replace, plus the dirt or + * sapling an earlier step of the same hole laid, so it never overwrites what a player built since. Dry run logs each + * step instead of placing it. + */ +public final class HealService implements org.bukkit.event.Listener { + private static final long CHECK_TICKS = 20L * 60; + private static final long KEEPERS_TTL_MS = 5 * 60 * 1000; + + private final Plugin plugin; + private final Tracking tracking; + private final Path dir; + private final Map jobs = new ConcurrentHashMap<>(); + private final Map keepersCache = new ConcurrentHashMap<>(); + private final Map keepersAt = new ConcurrentHashMap<>(); + private BukkitTask task; + + public HealService(Plugin plugin, Tracking tracking) { + this.plugin = plugin; + this.tracking = tracking; + this.dir = plugin.getDataFolder().toPath().resolve("healing"); + } + + public void start() { + load(); + Bukkit.getPluginManager().registerEvents(this, plugin); + task = Bukkit.getScheduler().runTaskTimer(plugin, this::tick, CHECK_TICKS, CHECK_TICKS); + } + + public void stop() { + if (task != null) task.cancel(); + } + + public Collection all() { + return List.copyOf(jobs.values()); + } + + private void load() { + jobs.clear(); + if (!Files.isDirectory(dir)) return; + try (Stream files = Files.walk(dir, 2)) { + for (Path f : files.filter(p -> p.toString().endsWith(".txt")).toList()) { + try { + HealJob j = HealJob.load(f); + jobs.put(j.id, j); + } catch (IOException e) { + plugin.getLogger().warning("Healing file skipped, left in place for a look: " + e.getMessage()); + } + } + } catch (IOException e) { + plugin.getLogger().log(Level.WARNING, "Couldn't read the healing folder", e); + } + } + + private Path file(HealJob j) { + return dir.resolve(j.world.toString()).resolve(j.id + ".txt"); + } + + // ----- Recording. + + @org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityExplode(org.bukkit.event.entity.EntityExplodeEvent e) { + explosion(e.getLocation().getWorld(), e.blockList()); + } + + @org.bukkit.event.EventHandler(priority = org.bukkit.event.EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockExplode(org.bukkit.event.block.BlockExplodeEvent e) { + explosion(e.getBlock().getWorld(), e.blockList()); + } + + /** Called while an explosion's blocks are still in place (the event, at MONITOR). */ + public void explosion(World w, List blocks) { + RegenConfig cfg = tracking.config(); + if (!cfg.healExplosions || blocks.isEmpty()) return; + WorldState s = tracking.state(w); + if (s == null || !s.healthy()) return; // only enabled, healthy worlds + List cells = new ArrayList<>(); + for (Block b : blocks) { + if (b.getType().isAir()) continue; + if (b.getState(false) instanceof Container) return; // a chest, barrel or furnace: not plain nature + cells.add(new HealPlan.Cell(b.getX(), b.getY(), b.getZ(), b.getBlockData().getAsString())); + } + if (cells.isEmpty()) return; + if (com.extantape.rewild.keep.MagicKeeps.spellChanged(blocks)) return; // Magic puts its own spells back + WorldStore store = s.store; + String why = HealCheck.why(cells, cfg.healBuildRadius, store::get); + if (why == null) why = kept(w, s, cells); + int[] c = center(cells); + if (why != null) { + plugin.getLogger().fine("Explosion hole at " + c[0] + " " + c[1] + " " + c[2] + " in " + w.getName() + " won't heal on its own: " + why + "."); + return; + } + long now = System.currentTimeMillis(); + String id = "h" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(now)) + "-" + Integer.toHexString(ThreadLocalRandom.current().nextInt(0x1000, 0x10000)); + HealJob j = new HealJob(id, w.getUID(), now, now + cfg.healStepHours * 3_600_000L, 0, cells); + try { + j.save(file(j)); + jobs.put(j.id, j); + plugin.getLogger().info("Explosion hole at " + c[0] + " " + c[1] + " " + c[2] + " in " + w.getName() + " (" + cells.size() + + " blocks) will heal over about " + cfg.healDays + " days, starting in " + cfg.healStepHours + " hours. Healing " + id + "."); + } catch (IOException e) { + plugin.getLogger().log(Level.WARNING, "Couldn't save healing for the explosion at " + c[0] + " " + c[1] + " " + c[2], e); + } + } + + /** Claims, kept areas, admin-protected areas and respawn points keep a hole from healing on its own. */ + private String kept(World w, WorldState s, List cells) { + Keepers.Result k = keepers(w); + if (k.claimsProblem != null) return "claims can't be checked (" + k.claimsProblem + ")"; + if (k.externalProblem != null) return "another plugin's keeps can't be checked (" + k.externalProblem + ")"; + for (HealPlan.Cell c : cells) { + int cx = c.x() >> 4, cz = c.z() >> 4; + for (int[] b : k.claims) if (cx >= b[0] - 1 && cx <= b[2] + 1 && cz >= b[1] - 1 && cz <= b[3] + 1) return "it's in or next to a claim"; + if (k.external.containsKey(ChunkRecord.key(cx, cz))) return "another plugin keeps that land"; + if (k.respawnChunks.contains(ChunkRecord.key(cx, cz))) return "it's next to a player's respawn point"; + for (WorldStore.ProtectedArea a : s.store.protectedAreas()) if (a.contains(cx, cz)) return "an admin protected that land"; + for (KeepPlan.Area a : k.areas) + if (a.world().equals(w.getName()) && c.x() >= a.minX() && c.x() <= a.maxX() && c.y() >= a.minY() && c.y() <= a.maxY() && c.z() >= a.minZ() && c.z() <= a.maxZ()) + return "it's in a kept area (" + a.reason() + ")"; + } + return null; + } + + private Keepers.Result keepers(World w) { + long now = System.currentTimeMillis(); + Long at = keepersAt.get(w.getUID()); + if (at == null || now - at > KEEPERS_TTL_MS) { + keepersCache.put(w.getUID(), tracking.keepers(w)); + keepersAt.put(w.getUID(), now); + } + return keepersCache.get(w.getUID()); + } + + // ----- Healing. + + void tick() { + long now = System.currentTimeMillis(); + for (HealJob j : List.copyOf(jobs.values())) { + if (now < j.next) continue; + World w = Bukkit.getWorld(j.world); + if (w == null || tracking.state(w) == null) continue; // world gone or no longer enabled: wait + step(j, w, now, false); + } + } + + /** Runs the job's next step if it can. force skips the wait for the day (for tests and admins); never the player check. */ + public String step(HealJob j, World w, long now, boolean force) { + RegenConfig cfg = tracking.config(); + List> steps = HealPlan.steps(j.cells, cfg.healDays, m -> RegenConfig.matchesAny(cfg.world(w.getName()).damageIgnore(), m.toUpperCase(Locale.ROOT))); + if (j.done >= steps.size()) return finish(j, w); + if (!force && now < j.next) return "not due yet"; + int[] b = j.bounds(); + for (int cx = b[0] >> 4; cx <= b[2] >> 4; cx++) + for (int cz = b[1] >> 4; cz <= b[3] >> 4; cz++) + if (!w.isChunkLoaded(cx, cz)) return "waiting for its chunks to load"; + WorldState s = tracking.state(w); + if (s == null || !s.healthy()) return "waiting: " + (s == null ? "the world isn't enabled" : s.problem); + Keepers.Result k = keepers(w); + if (k.claimsProblem != null || k.externalProblem != null) return "waiting: " + (k.claimsProblem != null ? k.claimsProblem : k.externalProblem); + int r = cfg.healPauseRadius; + for (Player p : w.getPlayers()) { + var l = p.getLocation(); + if (l.getX() >= b[0] - r && l.getX() <= b[2] + r && l.getZ() >= b[1] - r && l.getZ() <= b[3] + r) return "paused: a player is nearby"; + } + int placed = 0, blocked = 0; + // Never fill a block a mob, pet or dropped item is in (players are already kept well away). + var box = new org.bukkit.util.BoundingBox(b[0], w.getMinHeight(), b[1], b[2] + 1, w.getMaxHeight(), b[3] + 1); + List occupied = w.getNearbyEntities(box).stream().map(org.bukkit.entity.Entity::getBoundingBox).toList(); + for (HealPlan.Placement p : steps.get(j.done)) { + Block at = w.getBlockAt(p.x(), p.y(), p.z()); + if (!replaceable(at, p.over())) { blocked++; continue; } + var cell = org.bukkit.util.BoundingBox.of(at); + if (occupied.stream().anyMatch(cell::overlaps)) { blocked++; continue; } + BlockData data; + try { + data = Bukkit.createBlockData(p.data()); + } catch (IllegalArgumentException e) { + blocked++; + continue; + } + if (!cfg.dryRun) at.setBlockData(data, false); + placed++; + } + j.done++; + j.next = now + cfg.healStepHours * 3_600_000L; + int[] c = j.center(); + String what = (cfg.dryRun ? "Dry run: would heal " : "Healed ") + "step " + j.done + " of " + steps.size() + " at " + c[0] + " " + c[1] + " " + c[2] + + " in " + w.getName() + ": " + placed + " blocks" + (blocked > 0 ? ", " + blocked + " left alone because something is there now" : "") + ". Healing " + j.id + "."; + plugin.getLogger().info(what); + if (j.done >= steps.size()) return finish(j, w) + " " + what; + try { + j.save(file(j)); + } catch (IOException e) { + plugin.getLogger().log(Level.WARNING, "Couldn't save healing " + j.id, e); + } + return what; + } + + /** Air, water and lava, and what anything may replace (short grass, snow layers, fire), or the block this step expects. */ + static boolean replaceable(Block at, String over) { + Material m = at.getType(); + if (m.isAir() || at.isLiquid() || at.isReplaceable()) return true; + if (over == null) return false; + String here = at.getBlockData().getAsString(); + int bracket = here.indexOf('['); + return (bracket < 0 ? here : here.substring(0, bracket)).equals(over); + } + + private String finish(HealJob j, World w) { + jobs.remove(j.id); + try { + Files.deleteIfExists(file(j)); + } catch (IOException e) { + plugin.getLogger().log(Level.WARNING, "Couldn't remove the finished healing file " + j.id, e); + } + return "Healing " + j.id + " in " + w.getName() + " is finished."; + } + + public boolean cancel(String id) throws IOException { + HealJob j = jobs.remove(id); + if (j == null) return false; + Files.deleteIfExists(file(j)); + return true; + } + + private static int[] center(List cells) { + return new HealJob("x", new UUID(0, 0), 0, 0, 0, cells).center(); + } +} diff --git a/src/main/java/com/extantape/rewild/keep/Keepers.java b/src/main/java/com/extantape/rewild/keep/Keepers.java index a1b8a08..97cef1f 100644 --- a/src/main/java/com/extantape/rewild/keep/Keepers.java +++ b/src/main/java/com/extantape/rewild/keep/Keepers.java @@ -45,10 +45,19 @@ public static final class Result { private final Respect respect; private final CommandKeeps commandKeeps; + private final Set magicWorlds; + private final int magicRadius; + public Keepers(String claimPlugin, Respect respect, CommandKeeps commandKeeps) { + this(claimPlugin, respect, commandKeeps, Set.of(), 8); + } + + public Keepers(String claimPlugin, Respect respect, CommandKeeps commandKeeps, Set magicWorlds, int magicRadius) { this.claimPlugin = claimPlugin; this.respect = respect; this.commandKeeps = commandKeeps; + this.magicWorlds = magicWorlds; + this.magicRadius = magicRadius; } public Result read(World w) { @@ -58,6 +67,7 @@ public Result read(World w) { readProviders(w, r); readCommandKeeps(w, r); readMultiversePortals(w, r); + MagicKeeps.read(w, magicWorlds, magicRadius, r); return r; } diff --git a/src/main/java/com/extantape/rewild/keep/MagicKeeps.java b/src/main/java/com/extantape/rewild/keep/MagicKeeps.java new file mode 100644 index 0000000..fe20778 --- /dev/null +++ b/src/main/java/com/extantape/rewild/keep/MagicKeeps.java @@ -0,0 +1,97 @@ +package com.extantape.rewild.keep; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.plugin.Plugin; + +/** + * Keeps the Magic plugin's blocks and spell changes (D224: "It should probably plug into the magic plugin so it doesn't + * delete things from that realm, but it still should rewild"). Read through Magic's public API by reflection, so Rewild + * runs without Magic installed. Kept, block by block, while the land around them rewilds or heals: + *
    + *
  • every Magic block and automaton, with {@code magic.keep-radius} blocks around it for its structure;
  • + *
  • every area a spell changed that Magic will put back itself (its pending undo lists).
  • + *
+ * Fails closed: in a world listed in {@code magic.worlds}, nothing resets or heals unless Magic is running and answers. + */ +public final class MagicKeeps { + private MagicKeeps() {} + + /** Why a world can't reset or heal because of Magic, or null. Pure, for tests. */ + static String problem(String world, Set magicWorlds, boolean running, String readError) { + boolean needed = magicWorlds.contains(world); + if (!running) return needed ? "Magic isn't running, and " + world + " is a Magic world" : null; + if (readError != null) return "Magic's blocks couldn't be read (" + readError + ")"; + return null; + } + + /** A Magic block at x y z becomes a kept box radius blocks around it. Pure, for tests. */ + static KeepPlan.Area around(String world, int x, int y, int z, int radius, String what) { + return new KeepPlan.Area(world, x - radius, y - radius, z - radius, x + radius, y + radius, z + radius, what); + } + + private static Object controller() throws ReflectiveOperationException { + Plugin magic = Bukkit.getPluginManager().getPlugin("Magic"); + if (magic == null || !magic.isEnabled()) return null; + return magic.getClass().getMethod("getController").invoke(magic); + } + + static void read(World w, Set magicWorlds, int radius, Keepers.Result r) { + Plugin magic = Bukkit.getPluginManager().getPlugin("Magic"); + boolean running = magic != null && magic.isEnabled(); + String error = null; + List areas = new ArrayList<>(); + if (running) { + try { + Object c = controller(); + if (c == null) throw new IllegalStateException("no controller"); + for (Object block : (Collection) c.getClass().getMethod("getMagicBlocks").invoke(c)) { + Location l = (Location) block.getClass().getMethod("getLocation").invoke(block); + if (l == null || l.getWorld() == null || !l.getWorld().getUID().equals(w.getUID())) continue; + String key = String.valueOf(block.getClass().getMethod("getTemplateKey").invoke(block)); + areas.add(around(w.getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ(), radius, "a Magic block (" + key + ")")); + } + for (Object undo : (Collection) c.getClass().getMethod("getPendingUndo").invoke(c)) { + Method affects = undo.getClass().getMethod("affectsWorld", World.class); + if (!(Boolean) affects.invoke(undo, w)) continue; + Object box = undo.getClass().getMethod("getArea").invoke(undo); + if (box == null) continue; + org.bukkit.util.Vector min = (org.bukkit.util.Vector) box.getClass().getMethod("getMin").invoke(box); + org.bukkit.util.Vector max = (org.bukkit.util.Vector) box.getClass().getMethod("getMax").invoke(box); + areas.add(new KeepPlan.Area(w.getName(), min.getBlockX(), min.getBlockY(), min.getBlockZ(), max.getBlockX(), max.getBlockY(), max.getBlockZ(), + "a spell's change that Magic will undo")); + } + } catch (ReflectiveOperationException | RuntimeException | LinkageError e) { + error = e.toString(); + } + } + String p = problem(w.getName(), magicWorlds, running, error); + if (p != null) r.externalProblem = p; + else r.areas.addAll(areas); + } + + /** + * True when any of these blocks is part of a spell's change Magic will put back, or when Magic can't say. Checked + * live as an explosion happens, so a spell's blast is left to Magic's own undo. False when Magic isn't running. + */ + public static boolean spellChanged(List blocks) { + try { + Object c = controller(); + if (c == null) return false; + for (Object undo : (Collection) c.getClass().getMethod("getPendingUndo").invoke(c)) { + Method contains = undo.getClass().getMethod("contains", Block.class); + for (Block b : blocks) if ((Boolean) contains.invoke(undo, b)) return true; + } + return false; + } catch (ReflectiveOperationException | RuntimeException | LinkageError e) { + return true; + } + } +} diff --git a/src/main/java/com/extantape/rewild/track/Tracking.java b/src/main/java/com/extantape/rewild/track/Tracking.java index 64394e2..51bda3b 100644 --- a/src/main/java/com/extantape/rewild/track/Tracking.java +++ b/src/main/java/com/extantape/rewild/track/Tracking.java @@ -69,7 +69,7 @@ public synchronized com.extantape.rewild.keep.CommandKeeps commandKeeps() { /** Reads everything outside the tracker that can keep a chunk or a block, for one world. Main thread only. */ public com.extantape.rewild.keep.Keepers.Result keepers(World w) { - return new com.extantape.rewild.keep.Keepers(config.claimPlugin, respect(), commandKeeps()).read(w); + return new com.extantape.rewild.keep.Keepers(config.claimPlugin, respect(), commandKeeps(), config.magicWorlds, config.magicRadius).read(w); } public void setConfig(RegenConfig config) { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 282ab57..9cdb078 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -9,7 +9,7 @@ # reported in the log, and no world file changes. dry-run: true -# Worlds that must never reset, whatever else this file says. Put every kids' world here. A world listed here is +# Worlds that must never reset, whatever else this file says, such as creative, flatland and lobby worlds. A world listed here is # never tracked, scanned or reset, even if it's also enabled below. never-reset-worlds: [] @@ -23,6 +23,30 @@ worlds: # idle: # days-without-changes: 60 +# Gradual healing. An explosion hole (a creeper, TNT) heals on its own, a step at a time, when it's in land Rewild knows +# is natural, it destroyed nothing a player placed, and no build, filled container, claim, kept area, admin-protected +# area, respawn point or Magic block is near it. Any other hole waits for an admin's approved run, as before. +# The ground fills bottom up, about one step a day: dirt first, then grass, then saplings, young trees and full trees, +# then flowers and grass. A typical crater takes about a week. Healing waits while a player is nearby, and while +# dry-run is true it only says in the log what it would put back. +healing: + explosions: true + # About how many days a typical crater takes from the first step to the last. + days: 7 + # Hours between steps. + step-hours: 24 + # Healing waits while a player is within this many blocks of the hole. + pause-radius: 24 + # A player's block or filled container within this many blocks keeps a hole from healing on its own. + build-radius: 8 + +# Worlds where the Magic plugin is played. In these, nothing resets or heals unless Magic is running and answers. +# Wherever Magic is running, its blocks (with keep-radius blocks around each, for its structure) and the changes its +# spells will undo are kept in place. +magic: + worlds: [] + keep-radius: 8 + # The claim plugin that must be running before anything resets. If it's missing or broken, nothing resets. # Set to "none" only for a server with no claim plugin at all. claims: diff --git a/src/test/java/com/extantape/rewild/HealPlanTest.java b/src/test/java/com/extantape/rewild/HealPlanTest.java new file mode 100644 index 0000000..6d7c565 --- /dev/null +++ b/src/test/java/com/extantape/rewild/HealPlanTest.java @@ -0,0 +1,135 @@ +package com.extantape.rewild; + +import static org.junit.jupiter.api.Assertions.*; + +import com.extantape.rewild.heal.HealPlan; +import com.extantape.rewild.heal.HealPlan.Cell; +import com.extantape.rewild.heal.HealPlan.Placement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import org.junit.jupiter.api.Test; + +class HealPlanTest { + static final Predicate PLANTS = m -> Set.of("short_grass", "poppy", "snow", "fern").contains(m); + + /** A crater: a 5 by 5 bowl, 4 layers deep, grass on top, stone below. */ + static List crater() { + List cells = new ArrayList<>(); + for (int x = 0; x < 5; x++) for (int z = 0; z < 5; z++) { + cells.add(new Cell(x, 63, z, "minecraft:grass_block[snowy=false]")); + cells.add(new Cell(x, 62, z, "minecraft:dirt")); + cells.add(new Cell(x, 61, z, "minecraft:stone")); + if (x > 0 && x < 4 && z > 0 && z < 4) cells.add(new Cell(x, 60, z, "minecraft:stone")); + } + cells.add(new Cell(2, 64, 2, "minecraft:poppy")); + return cells; + } + + static int stepOf(List> steps, int x, int y, int z, String data) { + for (int i = 0; i < steps.size(); i++) + for (Placement p : steps.get(i)) if (p.x() == x && p.y() == y && p.z() == z && p.data().equals(data)) return i; + return -1; + } + + @Test + void aTypicalCraterTakesAboutAWeekAndFillsBottomUp() { + List> steps = HealPlan.steps(crater(), 7, PLANTS); + assertTrue(steps.size() >= 5 && steps.size() <= 7, "about a week of daily steps: " + steps.size()); + assertEquals(0, stepOf(steps, 2, 60, 2, "minecraft:stone"), "the bottom layer first, the day after"); + assertTrue(stepOf(steps, 2, 61, 2, "minecraft:stone") > 0, "the next layer later"); + assertTrue(stepOf(steps, 2, 62, 2, "minecraft:dirt") > stepOf(steps, 2, 61, 2, "minecraft:stone")); + for (List s : steps) + for (int i = 1; i < s.size(); i++) assertTrue(s.get(i).y() >= s.get(i - 1).y(), "each step places bottom up"); + } + + @Test + void grassComesBackAsDirtFirstThenGrassReplacingIt() { + List> steps = HealPlan.steps(crater(), 7, PLANTS); + int dirt = stepOf(steps, 0, 63, 0, "minecraft:dirt"); + int grass = stepOf(steps, 0, 63, 0, "minecraft:grass_block[snowy=false]"); + assertTrue(dirt >= 0 && grass > dirt, "dirt at step " + dirt + ", grass at " + grass); + Placement g = steps.get(grass).stream().filter(p -> p.x() == 0 && p.y() == 63 && p.z() == 0).findFirst().orElseThrow(); + assertEquals("minecraft:dirt", g.over(), "the grass may replace the dirt laid before it, and nothing else solid"); + } + + @Test + void smallPlantsComeBackLast() { + List> steps = HealPlan.steps(crater(), 7, PLANTS); + assertEquals(steps.size() - 1, stepOf(steps, 2, 64, 2, "minecraft:poppy")); + } + + @Test + void aFelledTreeComesBackAsASaplingThenAYoungTreeThenWhole() { + List cells = new ArrayList<>(); + cells.add(new Cell(0, 63, 0, "minecraft:grass_block")); + for (int y = 64; y <= 69; y++) cells.add(new Cell(0, y, 0, "minecraft:oak_log[axis=y]")); + cells.add(new Cell(1, 66, 0, "minecraft:oak_leaves[distance=1,persistent=false]")); // near the lower trunk + cells.add(new Cell(1, 70, 0, "minecraft:oak_leaves[distance=1,persistent=false]")); // up top + List> steps = HealPlan.steps(cells, 7, PLANTS); + int sapling = stepOf(steps, 0, 64, 0, "minecraft:oak_sapling"); + int youngBase = stepOf(steps, 0, 64, 0, "minecraft:oak_log[axis=y]"); + int top = stepOf(steps, 0, 69, 0, "minecraft:oak_log[axis=y]"); + assertTrue(sapling > stepOf(steps, 0, 63, 0, "minecraft:dirt"), "the sapling goes in after the ground"); + assertTrue(youngBase > sapling, "then the young trunk replaces it"); + assertEquals("minecraft:oak_sapling", steps.get(youngBase).stream().filter(p -> p.y() == 64).findFirst().orElseThrow().over()); + assertEquals(youngBase, stepOf(steps, 0, 66, 0, "minecraft:oak_log[axis=y]"), "the lower half comes with the young tree"); + assertEquals(youngBase, stepOf(steps, 1, 66, 0, "minecraft:oak_leaves[distance=1,persistent=false]"), "with the leaves near it"); + assertTrue(top > youngBase, "the top of the trunk comes last"); + assertEquals(top, stepOf(steps, 1, 70, 0, "minecraft:oak_leaves[distance=1,persistent=false]")); + } + + @Test + void touchingLogsAreOneTreeAndSeparateOnesAreTwo() { + List cells = new ArrayList<>(); + for (int y = 64; y <= 66; y++) cells.add(new Cell(0, y, 0, "minecraft:birch_log")); + cells.add(new Cell(1, 67, 1, "minecraft:birch_log")); // diagonal branch: same tree + for (int y = 64; y <= 66; y++) cells.add(new Cell(5, y, 5, "minecraft:spruce_log")); + List> steps = HealPlan.steps(cells, 7, PLANTS); + long saplings = steps.stream().flatMap(List::stream).filter(p -> p.data().endsWith("_sapling")).count(); + assertEquals(2, saplings, "one sapling per tree"); + assertTrue(stepOf(steps, 0, 64, 0, "minecraft:birch_sapling") >= 0); + assertTrue(stepOf(steps, 5, 64, 5, "minecraft:spruce_sapling") >= 0); + } + + @Test + void saplingsMatchTheWoodAndStrippedOrUnknownLogsGetNone() { + List cells = List.of(new Cell(0, 64, 0, "minecraft:mangrove_log"), new Cell(9, 64, 9, "minecraft:stripped_oak_log"), + new Cell(20, 64, 20, "minecraft:crimson_stem")); + List> steps = HealPlan.steps(cells, 7, PLANTS); + Set placedSaplings = new HashSet<>(); + steps.stream().flatMap(List::stream).filter(p -> p.y() == 64 && !p.data().contains("log") && !p.data().contains("stem")).forEach(p -> placedSaplings.add(p.data())); + assertEquals(Set.of("minecraft:mangrove_propagule", "minecraft:crimson_fungus"), placedSaplings); + assertEquals(1, steps.stream().flatMap(List::stream).filter(p -> p.data().equals("minecraft:stripped_oak_log")).count(), "it still comes back, just without a sapling"); + } + + @Test + void aDeepHoleTakesMoreLayersPerStepNotMoreDays() { + List cells = new ArrayList<>(); + for (int y = 30; y < 60; y++) cells.add(new Cell(0, y, 0, "minecraft:stone")); + List> steps = HealPlan.steps(cells, 7, PLANTS); + assertEquals(4, steps.size(), "30 layers spread over the 4 ground steps of a week"); + assertEquals(30, steps.stream().mapToInt(List::size).sum(), "every block is placed exactly once"); + } + + @Test + void airIsNeverPlacedAndEveryRecordedBlockComesBackOnce() { + List cells = new ArrayList<>(crater()); + cells.add(new Cell(9, 70, 9, "minecraft:air")); + cells.add(new Cell(9, 71, 9, "minecraft:cave_air")); + List> steps = HealPlan.steps(cells, 7, PLANTS); + long finals = steps.stream().flatMap(List::stream).filter(p -> !p.data().equals("minecraft:dirt") || p.over() != null).count(); + assertTrue(steps.stream().flatMap(List::stream).noneMatch(p -> p.data().contains("air"))); + long grass = crater().stream().filter(c -> c.data().startsWith("minecraft:grass_block")).count(); + assertEquals(crater().size() + grass, steps.stream().mapToInt(List::size).sum(), "each block once, plus dirt before each grass"); + assertTrue(finals > 0); + } + + @Test + void nothingToHealMeansNoSteps() { + assertTrue(HealPlan.steps(List.of(), 7, PLANTS).isEmpty()); + assertTrue(HealPlan.steps(List.of(new Cell(0, 64, 0, "minecraft:air")), 7, PLANTS).isEmpty()); + } +} diff --git a/src/test/java/com/extantape/rewild/config/RegenConfigTest.java b/src/test/java/com/extantape/rewild/config/RegenConfigTest.java index 72149f3..809c46a 100644 --- a/src/test/java/com/extantape/rewild/config/RegenConfigTest.java +++ b/src/test/java/com/extantape/rewild/config/RegenConfigTest.java @@ -80,4 +80,26 @@ void wildcardPatterns() { assertTrue(RegenConfig.matches("CHEST", "CHEST")); assertFalse(RegenConfig.matches("CHEST", "TRAPPED_CHEST")); } + + @Test + void healingIsOnWithAWeekAndMagicWorldsAreRead() { + RegenConfig c = new RegenConfig(shipped()); + assertTrue(c.healExplosions); + assertEquals(7, c.healDays); + assertEquals(24, c.healStepHours); + assertEquals(24, c.healPauseRadius); + assertEquals(8, c.healBuildRadius); + assertTrue(c.magicWorlds.isEmpty()); + assertTrue(c.healthy(), String.join("; ", c.errors())); + YamlConfiguration y = shipped(); + y.set("magic.worlds", java.util.List.of("magic", "second_magic")); + y.set("healing.days", 0); + RegenConfig d = new RegenConfig(y); + assertEquals(java.util.Set.of("magic", "second_magic"), d.magicWorlds); + assertEquals(7, d.healDays, "a bad value falls back"); + assertFalse(d.healthy(), "and is reported, so nothing resets"); + y.set("healing.days", 7); + y.set("magic.worlds", "magic"); + assertFalse(new RegenConfig(y).healthy(), "magic.worlds must be a list"); + } } diff --git a/src/test/java/com/extantape/rewild/heal/HealCheckAndJobTest.java b/src/test/java/com/extantape/rewild/heal/HealCheckAndJobTest.java new file mode 100644 index 0000000..07ab67a --- /dev/null +++ b/src/test/java/com/extantape/rewild/heal/HealCheckAndJobTest.java @@ -0,0 +1,104 @@ +package com.extantape.rewild.heal; + +import static org.junit.jupiter.api.Assertions.*; + +import com.extantape.rewild.store.ChunkRecord; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiFunction; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class HealCheckAndJobTest { + final Map chunks = new HashMap<>(); + final BiFunction lookup = (x, z) -> chunks.get(ChunkRecord.key(x, z)); + + ChunkRecord known(int cx, int cz) { + ChunkRecord r = new ChunkRecord(cx, cz); + r.known = true; + chunks.put(r.key(), r); + return r; + } + + static List hole() { + return List.of(new HealPlan.Cell(5, 63, 5, "minecraft:grass_block"), new HealPlan.Cell(5, 62, 5, "minecraft:dirt")); + } + + @Test + void aHoleInKnownNaturalLandHeals() { + known(0, 0); + assertNull(HealCheck.why(hole(), 8, lookup)); + } + + @Test + void unknownLandNeverHealsOnItsOwn() { + assertNotNull(HealCheck.why(hole(), 8, lookup), "no record at all"); + known(0, 0).known = false; + assertTrue(HealCheck.why(hole(), 8, lookup).contains("before Rewild was tracking")); + } + + @Test + void aBlastThroughPlayerBlocksWaitsForAnAdmin() { + known(0, 0).placed.put(ChunkRecord.pos(5, 63, 5), "OAK_PLANKS"); + assertTrue(HealCheck.why(hole(), 8, lookup).contains("a player placed")); + } + + @Test + void aBuildNearbyStopsIt_evenInTheNextChunk() { + known(0, 0); + known(1, 0).placed.put(ChunkRecord.pos(0, 63, 5), "TORCH"); // x 16: 11 blocks away + assertNull(HealCheck.why(hole(), 8, lookup), "11 blocks is outside an 8-block radius"); + assertTrue(HealCheck.why(hole(), 12, lookup).contains("build is within 12")); + } + + @Test + void aFilledContainerNearbyStopsIt() { + known(0, 0).filledContainers.add(ChunkRecord.pos(8, 62, 5)); + assertTrue(HealCheck.why(hole(), 8, lookup).contains("container")); + } + + @Test + void nothingDestroyedIsNotAHole() { + assertNotNull(HealCheck.why(List.of(), 8, lookup)); + } + + @Test + void aJobSurvivesARestartExactly(@TempDir Path dir) throws IOException { + UUID w = UUID.randomUUID(); + HealJob j = new HealJob("h1", w, 100, 200, 2, List.of(new HealPlan.Cell(-3, -60, 7, "minecraft:oak_log[axis=y]"), + new HealPlan.Cell(1, 2, 3, "minecraft:snow[layers=2]"))); + Path f = dir.resolve(w.toString()).resolve("h1.txt"); + j.save(f); + HealJob back = HealJob.load(f); + assertEquals("h1", back.id); + assertEquals(w, back.world); + assertEquals(100, back.created); + assertEquals(200, back.next); + assertEquals(2, back.done); + assertEquals(j.cells, back.cells); + assertFalse(Files.exists(f.resolveSibling("h1.txt.tmp")), "no temporary file left behind"); + } + + @Test + void aDamagedJobFileIsRefusedNotGuessed(@TempDir Path dir) throws IOException { + Path f = dir.resolve("bad.txt"); + Files.writeString(f, "rewild-heal 1\nworld " + UUID.randomUUID() + "\ncreated 1\nnext 2\ndone 0\ncell 1 two 3 minecraft:stone\n"); + assertThrows(IOException.class, () -> HealJob.load(f)); + Files.writeString(f, "something else\n"); + assertThrows(IOException.class, () -> HealJob.load(f)); + Files.writeString(f, "rewild-heal 1\ncell 1 2 3 minecraft:stone\n"); + assertThrows(IOException.class, () -> HealJob.load(f), "no header"); + } + + @Test + void centerAndBoundsCoverTheHole() { + HealJob j = new HealJob("h", UUID.randomUUID(), 0, 0, 0, List.of(new HealPlan.Cell(0, 60, 0, "minecraft:stone"), new HealPlan.Cell(4, 64, -2, "minecraft:stone"))); + assertArrayEquals(new int[] {2, 62, -1}, j.center()); + assertArrayEquals(new int[] {0, -2, 4, 0}, j.bounds()); + } +} diff --git a/src/test/java/com/extantape/rewild/keep/MagicKeepsTest.java b/src/test/java/com/extantape/rewild/keep/MagicKeepsTest.java new file mode 100644 index 0000000..4953205 --- /dev/null +++ b/src/test/java/com/extantape/rewild/keep/MagicKeepsTest.java @@ -0,0 +1,40 @@ +package com.extantape.rewild.keep; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Set; +import org.junit.jupiter.api.Test; + +class MagicKeepsTest { + @Test + void aMagicWorldWithoutMagicRunningFailsClosed() { + assertNotNull(MagicKeeps.problem("magic", Set.of("magic"), false, null)); + } + + @Test + void otherWorldsDontNeedMagic() { + assertNull(MagicKeeps.problem("survival", Set.of("magic"), false, null)); + } + + @Test + void magicThatCantAnswerStopsResetsEverywhere() { + assertNotNull(MagicKeeps.problem("survival", Set.of("magic"), true, "NoSuchMethodException")); + assertNotNull(MagicKeeps.problem("magic", Set.of("magic"), true, "NoSuchMethodException")); + } + + @Test + void magicThatAnswersIsFine() { + assertNull(MagicKeeps.problem("magic", Set.of("magic"), true, null)); + } + + @Test + void aMagicBlockKeepsItsStructureAroundIt() { + KeepPlan.Area a = MagicKeeps.around("magic", 10, 64, -5, 8, "a Magic block"); + assertEquals(2, a.minX()); + assertEquals(18, a.maxX()); + assertEquals(56, a.minY()); + assertEquals(72, a.maxY()); + assertEquals(-13, a.minZ()); + assertEquals(3, a.maxZ()); + } +}