From 7b6228f412697e1b665e5edecfd8af7009bea69a Mon Sep 17 00:00:00 2001 From: tastybento Date: Tue, 24 Nov 2026 17:40:38 -0800 Subject: [PATCH 1/3] Boxed II: world templates, areas and box cleanup World creation - The seed world is captured once into a template file per area and dimension, then unloaded. Later boots only open the file. Blocks are read from disk on demand and only biomes are kept in memory, so the first boot takes about half a minute and the server no longer needs 12 GB. - Biome providers list only the biomes they can produce, and the generator gives a fixed spawn, so the server does not search before generating. Areas - areas.yml defines areas, each with its own seed, biomes and structures. An area owns one row of the box grid and its blueprint bundle picks it. - A player has one box per area. An area can require another, unlocked at a box size set per area. Locked areas show in the picker but cannot be chosen, and closed or unbuilt ones are hidden. - A new box is put at the height that lands the starter blueprint's spawn sign on the area's ground. - /boxadmin areas lists, visits, creates, rebuilds and cleans areas. - /boxadmin place works anywhere in a box position and accepts ground and surface for y. Boxes - A deleted box's position is restored from the template and used again. - Advancements count towards the box the player is in. Those handed back when a player moves between boxes are ignored, and a player with several boxes is brought in line with the box on arrival. - Unnamed boxes are listed by their area. Needs BentoBox 3.25.0 for the game mode hooks this uses. Worlds made by earlier versions are not compatible. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HBXcjZkd22rGNW5ZyL1git --- CLAUDE.md | 19 +- README.md | 88 +++- pom.xml | 2 +- .../bentobox/boxed/AdvancementsManager.java | 19 +- src/main/java/world/bentobox/boxed/Boxed.java | 424 ++++++++++++++---- .../java/world/bentobox/boxed/areas/Area.java | 41 ++ .../boxed/areas/AreaLocationStrategy.java | 74 +++ .../bentobox/boxed/areas/AreaManager.java | 242 ++++++++++ .../world/bentobox/boxed/areas/AreaRules.java | 139 ++++++ .../world/bentobox/boxed/areas/BoxHeight.java | 106 +++++ .../boxed/commands/AdminAreasCommand.java | 346 ++++++++++++++ .../commands/AdminPlaceStructureCommand.java | 102 ++++- .../biomes/AbstractCopyBiomeProvider.java | 19 +- .../biomes/AbstractSeedBiomeProvider.java | 41 +- .../biomes/NetherSeedBiomeGenerator.java | 9 +- .../generators/biomes/SeedBiomeGenerator.java | 10 +- .../chunks/AbstractBoxedChunkGenerator.java | 63 +-- .../chunks/BoxedBlockPopulator.java | 11 +- .../chunks/BoxedChunkGenerator.java | 210 +-------- .../chunks/BoxedSeedChunkGenerator.java | 15 - .../boxed/generators/template/RawBiomes.java | 47 ++ .../boxed/generators/template/RawChunk.java | 163 +++++++ .../boxed/generators/template/Template.java | 207 +++++++++ .../generators/template/TemplateBuilder.java | 371 +++++++++++++++ .../generators/template/TemplateChunk.java | 148 ++++++ .../generators/template/TemplateFile.java | 259 +++++++++++ .../boxed/listeners/AdvancementListener.java | 69 ++- .../bentobox/boxed/listeners/BoxCleaner.java | 305 +++++++++++++ .../boxed/listeners/EnderPearlListener.java | 2 + .../boxed/listeners/NewAreaListener.java | 6 +- src/main/resources/addon.yml | 2 +- src/main/resources/areas.yml | 45 ++ src/main/resources/locales/en-US.yml | 402 +++-------------- .../boxed/AdvancementsManagerTest.java | 33 ++ .../boxed/areas/AreaLocationStrategyTest.java | 123 +++++ .../bentobox/boxed/areas/AreaManagerTest.java | 195 ++++++++ .../bentobox/boxed/areas/AreaRulesTest.java | 196 ++++++++ .../bentobox/boxed/areas/BoxHeightTest.java | 166 +++++++ .../AdminPlaceStructureCommandTest.java | 45 ++ .../biomes/CopyBiomeProviderTest.java | 49 +- .../template/TemplateChunkTest.java | 142 ++++++ .../generators/template/TemplateFileTest.java | 109 +++++ .../listeners/AdvancementListenerTest.java | 35 +- .../boxed/listeners/BoxCleanerTest.java | 141 ++++++ .../listeners/EnderPearlListenerTest.java | 13 + .../boxed/listeners/NewAreaListenerTest.java | 1 + 46 files changed, 4456 insertions(+), 798 deletions(-) create mode 100644 src/main/java/world/bentobox/boxed/areas/Area.java create mode 100644 src/main/java/world/bentobox/boxed/areas/AreaLocationStrategy.java create mode 100644 src/main/java/world/bentobox/boxed/areas/AreaManager.java create mode 100644 src/main/java/world/bentobox/boxed/areas/AreaRules.java create mode 100644 src/main/java/world/bentobox/boxed/areas/BoxHeight.java create mode 100644 src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java create mode 100644 src/main/java/world/bentobox/boxed/generators/template/RawBiomes.java create mode 100644 src/main/java/world/bentobox/boxed/generators/template/RawChunk.java create mode 100644 src/main/java/world/bentobox/boxed/generators/template/Template.java create mode 100644 src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java create mode 100644 src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java create mode 100644 src/main/java/world/bentobox/boxed/generators/template/TemplateFile.java create mode 100644 src/main/java/world/bentobox/boxed/listeners/BoxCleaner.java create mode 100644 src/main/resources/areas.yml create mode 100644 src/test/java/world/bentobox/boxed/areas/AreaLocationStrategyTest.java create mode 100644 src/test/java/world/bentobox/boxed/areas/AreaManagerTest.java create mode 100644 src/test/java/world/bentobox/boxed/areas/AreaRulesTest.java create mode 100644 src/test/java/world/bentobox/boxed/areas/BoxHeightTest.java create mode 100644 src/test/java/world/bentobox/boxed/generators/template/TemplateChunkTest.java create mode 100644 src/test/java/world/bentobox/boxed/generators/template/TemplateFileTest.java create mode 100644 src/test/java/world/bentobox/boxed/listeners/BoxCleanerTest.java diff --git a/CLAUDE.md b/CLAUDE.md index 1fdaba4..6c1cf58 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -Boxed is a BentoBox GameModeAddon for Minecraft (Paper) where each player is confined to a small expandable box. Completing Minecraft advancements grows the box. Built against `bentobox` 3.23.7, Paper API 26.3, Java 25. +Boxed is a BentoBox GameModeAddon for Minecraft (Paper) where each player is confined to a small expandable box. Completing Minecraft advancements grows the box. Built against `bentobox` 3.25.0-SNAPSHOT, Paper API 26.3, Java 25. ## Build / Test @@ -22,14 +22,23 @@ Surefire is configured with a long list of `--add-opens` JVM args required by Mo Boxed is a BentoBox addon, not a standalone plugin. `Boxed` extends `GameModeAddon` and is loaded by BentoBox at runtime. `BoxedPladdon` is the Paper plugin-loader shim so Paper recognises the jar. -### The two-world "seed + game" generator model +### The "seed world -> template -> game world" generator model This is the core concept and touches almost everything: -1. **Seed world** (`/seed`, and `/seed_nether`): a real vanilla-ish world generated once using `BoxedSeedChunkGenerator` + `SeedBiomeGenerator` / `NetherSeedBiomeGenerator`. It's where Minecraft's normal terrain + structures (villages, shipwrecks, fortresses, etc.) actually get generated by the server. -2. **Game world** (``, `_nether`): the world players actually play in. It uses `BoxedChunkGenerator` (a subclass of `AbstractBoxedChunkGenerator`) which does **not** generate terrain from scratch — instead, `Boxed.copyChunks(...)` pre-reads every chunk inside `islandDistance` from the seed world during `createWorlds()` and stores them in the chunk generator. When the game world asks for a chunk, the generator serves back the pre-captured copy. +1. **Seed world** (`/seed`, and `/seed_nether`): a real vanilla-ish world generated using `BoxedSeedChunkGenerator` + `SeedBiomeGenerator` / `NetherSeedBiomeGenerator`. It's where Minecraft's normal terrain + structures actually get generated by the server. It is only loaded when a template has to be built. +2. **Template** (`generators/template`): `TemplateBuilder` captures every chunk inside `islandDistance` of the seed world into a `.bxt` file (`/areas//normal.bxt`, `nether.bxt`) and `Boxed.loadTemplate()` then unloads the seed world. This happens once; later boots only open the file. `Template` reads block data from disk on demand (LRU of decoded `TemplateChunk`s) and keeps all biomes in memory. Deleting the `.bxt` files forces a rebuild. +3. **Game world** (``, `_nether`): the world players actually play in. `BoxedChunkGenerator` does **not** generate terrain; it copies the template chunk at `repeatCalc(chunkX), repeatCalc(chunkZ)`, so every box is identical. `AbstractCopyBiomeProvider` and `BoxedBlockPopulator` read the same template. -This is why first boot is extremely slow and RAM-hungry (see `README.md` warnings): the entire seed region is force-loaded up front. Any change to world generation, structure handling, or world naming must respect both worlds and the copy step in `Boxed.copyChunks()` / `createOverWorld()` / `createNether()`. The `generatorMaps` / `generatorMap` fields in `Boxed.java` route world names → generators for `getDefaultWorldGenerator` (used by Multiverse and similar world-management plugins) and for the hook in `allLoaded()` that calls `WorldManagementHook.registerWorld`. +Never hold the whole region in memory or load the seed world on a normal boot — that is what made old versions need 12 GB and 10 minutes. Biome providers must return an accurate `getBiomes()` list: if a Nether provider claims overworld biomes are possible, the server searches for stronghold biomes before generating any chunk, which takes minutes. Any change to world generation, structure handling, or world naming must respect the seed world, the template format (`TemplateFile` magic/version) and the game world. The `generatorMaps` / `generatorMap` fields in `Boxed.java` route world names → generators for `getDefaultWorldGenerator` (used by Multiverse and similar world-management plugins) and for the hook in `allLoaded()` that calls `WorldManagementHook.registerWorld`. + +### Areas + +`areas/AreaManager` loads `areas.yml`. Each `Area` (seed, biomes file, structures file) has its own seed worlds (`/seed_`), its own templates (`areas//*.bxt`) and owns one east-west **row** of the box grid, persisted in `areas/grid.yml` and never reassigned. The generator, biome provider and populator pick the template from the chunk's z alone (`AbstractBoxedChunkGenerator.rowCalc` -> `Boxed.getTemplate(env, chunkZ)`), so anything that generates chunks must pass real game-world chunk coordinates, not folded ones. Boxes are placed by `AreaLocationStrategy`, returned from `Boxed.getNewIslandLocationStrategy(user, bundle)` (a BentoBox 3.25.0 hook): the blueprint bundle's unique id names the area, unknown bundles use `default`. The y of a box's centre comes from `areas/BoxHeight`: BentoBox pastes the starter blueprint with its bedrock at the centre, so the centre is set to land the blueprint's `[spawn_here]` sign on the area's ground (read from the template; falls back to the island-height setting). The nether blueprint is pasted at the same y, so it only lines up where the nether ground happens to match. Structure lists are per area via `Boxed.getStructuresFile(location)`. `AreaRules` refuses a box (by throwing from the hook, before anything is created) when the area is closed (`enabled: false`), is waiting for a restart, or is chained (`requires` + the required area's `unlocks-next-at` box size) and not yet unlocked, or the player already has a box in that area (one per area; the box being reset does not count). `/boxadmin areas` (`AdminAreasCommand`) lists, visits, creates and requests rebuilds of areas; creating and rebuilding only take effect at the next start because templates are built in `createWorlds()`. + +### Deleted boxes + +`listeners/BoxCleaner` restores a deleted (soft-deleted, `isDeletable()`) box's whole position from the template — generated chunks only, both dimensions, within a 10 ms per tick budget — then removes the island record so `AreaLocationStrategy` can hand the position out again (it always takes the first position in the row with no record). Do not rely on BentoBox's region-file purge for Boxed: it only deletes a region when every position overlapping it is deletable, and 640-block positions always share 512-block regions with neighbours. Deleted boxes are re-queued from the island cache on `BentoBoxReadyEvent`, so no extra persistence is needed. ### Advancements drive box size diff --git a/README.md b/README.md index 5eeeb41..18f406f 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,12 @@ A game mode where you are boxed into a tiny space that only expands by completin ## BentoBox Requirements -* Requires BentoBox 3.17.0 or later (Snapshots can be downloaded here: [https://ci.bentobox.world](https://ci.bentobox.world)). BentoBox 3.16.1+ is needed for native region-file cleanup of deleted boxes — see [Reclaiming Disk Space](#reclaiming-disk-space-deleted-island-chunks). +* Requires BentoBox 3.25.0 or later (Snapshots can be downloaded here: [https://ci.bentobox.world](https://ci.bentobox.world)). BentoBox 3.16.1+ is needed for native region-file cleanup of deleted boxes — see [Reclaiming Disk Space](#reclaiming-disk-space-deleted-island-chunks). * InvSwitcher - keeps advancements, inventory, etc. separate between worlds on a server. * Border - shows the box -### Warning!! -Boxed requires **a lot of RAM** and can take up to **10 minutes** to boot up for the first time as it pre-generates the worlds. After the initial start, it will start up much quicker. With 12GB of RAM running on a fast ARM-based system, it takes ~ 8 minutes for the first boot. If you do not have enough RAM then weird things will happen to your server including strange errors about chunks and things like that. To dedicate enough RAM to your JVM, use the correct flags during startup. Here is my `start.sh` for running on Paper 1.19.4: -``` -#!/bin/sh -java -Xms12G -Xmx12G -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1 -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:InitiatingHeapOccupancyPercent=15 -Dusing.aikars.flags=https://mcflags.emc.gs -Daikars.new.flags=true -jar paper-1.19.4.jar nogui -``` +### First start +The first time Boxed starts it builds its worlds from a hidden seed world and saves the result as template files in `plugins/BentoBox/addons/Boxed/areas/`. This takes around 30 seconds on a modern machine and happens only once. After that the seed world is not loaded at all and Boxed starts in a few seconds. No special amount of RAM is needed. ## How to install @@ -24,7 +20,7 @@ java -Xms12G -Xmx12G -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMill 1. Place Boxed addon into the BentoBox addons folder along with InvSwitcher and Border (use the latest versions!). 2. (Optional) Install the Datapack for custom advancements - https://github.com/BentoBoxWorld/BoxedDataPack/ -3. Restart the server - new worlds will be created. This will take a while! +3. Restart the server - new worlds will be created. The first start takes a little longer. 4. Login. 5. Type `/boxed` to start. 6. Turn off advancement announcements with `/gamerule announceAdvancements false` to avoid spam, or set `boxed.broadcast-advancements: true` in `config.yml` to have Boxed broadcast them instead. @@ -66,6 +62,52 @@ Want to use your own terrain or a custom-built map instead? See [Using a Custom | `boxed.deny-visitor-advancements` | `true` | If `true`, visitors cannot earn advancements. Note: visitors will still receive other rewards such as experience. | | `world.allow-structures` | `false` | Allow vanilla structures to generate in the seed world. | +### Areas (areas.yml) + +An *area* is a kind of land that a box can be made in. Every box in the same area has exactly the same land; boxes in different areas have different land, biomes and structures. Out of the box there is one area called `default`. + +To add an area, run `/boxadmin areas create [seed]` and restart the server. The command adds the area to `areas.yml`, gives it a biomes file (a copy of `biomes.yml` to edit) and an empty structures file, and makes a blueprint bundle with the same name. Players who pick that bundle get a box in that area; bundles that do not match an area use the default area. The land of the new area is built once at the restart (about 20 seconds) and saved in `areas//`. + +You can also do the same by hand: add the area to `areas.yml` and make a blueprint bundle whose unique id is the area's name. + +| Command | What it does | +|---------|--------------| +| `/boxadmin areas` | Lists the areas with their row, seed and number of boxes. | +| `/boxadmin areas tp ` | Takes you to the land where the area's next box will be, so you can look at it and place structures before any player has a box there. | +| `/boxadmin areas create [seed]` | Makes a new area and its blueprint bundle. Needs a restart. | +| `/boxadmin areas rebuild [regenerate]` | Builds the area's land again at the next restart. With `regenerate` the seed worlds are thrown away first, which is needed after changing the area's seed or biomes. Without it, the land is rebuilt from the seed worlds as they are, which keeps changes made to them by hand. | +| `/boxadmin areas clean [x z]` | Puts the land of the box position you are in (or the one at x, z) back the way it was. Use it after trying out structures in a position nobody has a box in. Positions with a box in use are refused. | + +Areas can be chained so that a player's box in one area has to reach a certain size before the next area is unlocked, and can be closed to new boxes: + +| Setting | Description | +|---------|-------------| +| `requires` | The area that unlocks this one. Leave out for an area anyone can start in. | +| `unlocks-next-at` | The size a player's box in this area must reach to unlock the areas that require it. Set it per area to make some harder than others. 0 (the default) means having a box there is enough. | +| `enabled` | Set to `false` to stop new boxes being made in the area. Existing boxes are not affected. | + +A player can have one box in each area. They need to be allowed more than one box (`world.concurrent-area` in `config.yml`) to have boxes in more than one area at a time. With InvSwitcher, turn on `options.islands.advancements` so each box has its own advancements. + +```yaml +areas: + default: + biomes: biomes.yml + structures: structures.yml + unlocks-next-at: 100 + icelands: + seed: 1234567890 + biomes: biomes-icelands.yml + structures: structures-icelands.yml + requires: default +``` + +Each area owns one east-west row of the world, recorded in `areas/grid.yml`, and its boxes are placed along that row. `/boxadmin place` saves structures to the structures file of the area you are standing in. Requires BentoBox 3.25.0 or later. + +Notes: +* Do not remove an area that has boxes in it, and do not edit `areas/grid.yml`. +* Changing an area's seed or biomes after it is built does nothing until you run `/boxadmin areas rebuild regenerate` and restart. +* A row that no area owns has the default area's land. If players have already seen the edge of such a row, those chunks keep the default land after a new area is given that row. + ### Blueprint There is one blueprint "island" that is used to generate the tree, chest and blocks below down to y = 5. The default height of the surface is about y = 65, so the blueprint has to be about 60 blocks tall. If you make any good blueprints, please share them! @@ -122,14 +164,14 @@ Admins can place structures in-game using the `/boxadmin place` command: | Argument | Description | |----------|-------------| | `` | Minecraft structure name (tab-complete to see available structures) | -| `[x y z]` | Coordinates where the structure should be placed. Use `~` for the current position. | +| `[x y z]` | Coordinates where the structure should be placed. Use `~` for the current position. For `y` you can also use `ground` to sit the structure on the highest solid block, ignoring water and trees (the sea bed at sea), or `surface` for the top of whatever is there (the water surface at sea). Add an offset to sink or raise it, for example `ground-1` or `surface+3`. | | `[ROTATION]` | Optional rotation: `NONE`, `CLOCKWISE_90`, `CLOCKWISE_180`, `COUNTERCLOCKWISE_90` | | `[MIRROR]` | Optional mirror: `NONE`, `LEFT_RIGHT`, `FRONT_BACK` | | `[NO_MOBS]` | Optional flag to suppress mob spawning from this structure | To undo the last placed structure: `/boxadmin place undo` -When a structure is placed via this command while standing in a player box, it is automatically saved to `structures.yml` and will be placed in all future boxes. +The structure is saved to the structures file of the area you are in and will be placed in all future boxes of that area. You do not need to be in a box: use `/boxadmin areas tp ` to go to an area's land before anyone has a box there. Operators, and players with the Border addon's `boxed.border.bypass` permission, can walk around outside a box; other admins are put in spectator mode. ## Using a Custom Map as the Seed @@ -143,12 +185,14 @@ Boxed uses two worlds: 1. A hidden **seed world** — `/seed` (overworld) and `/seed_nether` (nether). This is a normal world generated from the numeric world seed. 2. The **game world** — `` and `_nether` — that players actually play in. -On **every server start**, Boxed reads the chunks around the centre of the seed world and copies them into the game world's generator. Each player's box is then served a copy of that captured terrain. +The **first time** the server starts, Boxed reads the chunks around the centre of the seed world and saves them, with their biomes, as template files: `plugins/BentoBox/addons/Boxed/areas/default/normal.bxt` and `nether.bxt`. Each player's box is then served a copy of that terrain from the template. The seed world is unloaded once the templates are built and is not loaded again. Two facts make custom maps possible: -* The copy reads the seed world **from disk**, live, on every boot — so anything you change in the seed world flows into newly generated boxes. -* The game world **copies the seed world's biomes as-is**. There is no biome remapping when a chunk is copied, so whatever biomes are in the seed world are what players get. +* The templates are built from the seed world **on disk**, so anything you change in the seed world can be turned into new templates. +* The templates **copy the seed world's biomes as-is**. There is no biome remapping, so whatever biomes are in the seed world are what players get. + +**To rebuild the templates** after changing the seed world, run `/boxadmin areas rebuild default` and restart the server (or stop the server, delete the `.bxt` files and start it again). The seed world's saved chunks are read again and anything not yet generated is generated. Two limits to keep in mind: @@ -178,9 +222,9 @@ Notes: this reproduces vanilla terrain for that seed. Boxed still applies its ow You can go into the seed world and build, paste, or remove whatever you like. -1. Use a world-management plugin (e.g. Multiverse) to teleport into `/seed`. +1. Use a world-management plugin (e.g. Multiverse) to load and teleport into `/seed`. It is not loaded by default. 2. Build or WorldEdit/paste your changes **around 0,0**, within the island-distance radius. -3. Restart the server. On boot, Boxed re-copies the seed world, so your edits appear in any box that is generated **after** the restart. +3. Stop the server, delete the `.bxt` template files (see above) and start it again. Boxed rebuilds the templates from the seed world, so your edits appear in any box that is generated **after** the restart. To apply your edits to boxes/areas that already exist, you must regenerate those game-world chunks while leaving the seed world untouched — for example by deleting the relevant region files in `` / `_nether`, or by resetting/deleting the affected islands so BentoBox reaps their region files (see [Reclaiming Disk Space](#reclaiming-disk-space-deleted-island-chunks)). When the chunks regenerate they are re-copied from the seed world, which is the source of truth. @@ -193,8 +237,9 @@ This replaces the generated seed world with a world you built or downloaded. 3. Copy your world's region files into Boxed's seed world folders, replacing what's there: * Overworld: your `region/` → `/seed/region/` * Nether: your `DIM-1/region/` → `/seed_nether/region/` -4. Delete the game-world folders so they regenerate from your new seed world on next boot: +4. Delete the game-world folders and the `.bxt` template files so they are rebuilt from your new seed world on next boot: * `` and `_nether` + * `plugins/BentoBox/addons/Boxed/areas/default/*.bxt` * Leave the seed worlds (`/seed`, `/seed_nether`) in place. 5. Start the server. Boxed copies your imported chunks — terrain **and biomes** — into the freshly generated game world. @@ -204,7 +249,6 @@ Biomes: because the game world copies the seed world's biomes unchanged, your im * The copy radius is `world.island-distance`. If you increase it, your custom content must cover the larger area. * BentoBox's native region cleanup never touches the seed worlds, so your custom terrain is safe. If you run a third-party chunk-cleaner like Regionerator, exempt the seed worlds (see [Reclaiming Disk Space](#reclaiming-disk-space-deleted-island-chunks)) or your custom seed terrain may be deleted and boxes will stop matching. -* The first boot after importing is slow and RAM-hungry, just like a normal first start (see the warning near the top of this file). * All boxes share the same captured terrain, so every player gets the same custom map layout. @@ -248,7 +292,13 @@ Download the official [Boxed DataPack](https://github.com/BentoBoxWorld/BoxedDat **As of BentoBox 3.16.1, BentoBox reclaims disk space natively — you no longer need a third-party plugin for this.** (The region-file housekeeping sweep was added in 3.15.0; admin deletes were routed through it in 3.16.1.) -### How it works now +### Boxed cleans up its own boxes + +When a box is deleted or reset, Boxed puts its land back the way it was: every chunk of the box's position that has been generated, in the overworld and the Nether, is compared with the area's template and anything different is restored. Structures, mobs and dropped items are removed too. This is done a little each tick and takes around a minute for a well-explored box. When it finishes, the console says so and the position is free for a new box, which gets its structures placed afresh. Boxes waiting to be cleaned when the server stops are picked up when it starts again. + +This does not depend on the region-file housekeeping described below, which Boxed worlds rarely benefit from: neighbouring box positions share region files, so a region can almost never be deleted while any neighbour is in use. The housekeeping is still safe to leave on. + +### How BentoBox housekeeping works When an island is deleted or reset, BentoBox does **not** wipe blocks immediately. Instead it *soft-deletes* the island: the owner is cleared, the box is locked, and the island is flagged `deletable` in the database. The actual world data is reclaimed later by deleting the `.mca` region files from disk — far cheaper than regenerating chunks block-by-block. @@ -275,7 +325,7 @@ The sweep only scans gamemode island worlds and only the region files belonging ### Regionerator (legacy / optional) -You can still run [Regionerator](https://github.com/Jikoo/Regionerator) if you prefer, but it is no longer necessary for Boxed. If you do use it, exempt the seed worlds so it doesn't delete the terrain Boxed copies from (which would make startup very slow). Add these entries to the `worlds` section of the Regionerator config: +You can still run [Regionerator](https://github.com/Jikoo/Regionerator) if you prefer, but it is no longer necessary for Boxed. If you do use it, exempt the seed worlds so it doesn't delete the terrain the templates are built from. Add these entries to the `worlds` section of the Regionerator config: ```yaml worlds: diff --git a/pom.xml b/pom.xml index ac3221d..202618e 100644 --- a/pom.xml +++ b/pom.xml @@ -57,7 +57,7 @@ 4.119.0 26.3.build.231-stable - 3.23.7 + 3.25.0-SNAPSHOT ${build.version}-SNAPSHOT diff --git a/src/main/java/world/bentobox/boxed/AdvancementsManager.java b/src/main/java/world/bentobox/boxed/AdvancementsManager.java index 1b0644f..42ea846 100644 --- a/src/main/java/world/bentobox/boxed/AdvancementsManager.java +++ b/src/main/java/world/bentobox/boxed/AdvancementsManager.java @@ -178,8 +178,8 @@ public int addAdvancement(Player p, Advancement advancement) { if (score == 0) { return 0; } - // Get island - Island island = addon.getIslands().getIsland(addon.getOverWorld(), p.getUniqueId()); + // Get the box this counts towards + Island island = getBox(p); if (island != null && island.getRank(p.getUniqueId()) >= RanksManager.MEMBER_RANK // Only island members expand island && addAdvancement(island, advancement.getKey().toString())) { @@ -192,6 +192,21 @@ && addAdvancement(island, advancement.getKey().toString())) { } + /** + * Gets the box that a player's advancements count towards. A player can have a box in + * more than one area, so this is the box they are in, if they are a member of it. If they + * are somewhere else, it is their main box. + * @param p player + * @return the box, or null if the player has none + */ + @Nullable + public Island getBox(Player p) { + Island here = p.getLocation() == null ? null + : addon.getIslands().getIslandAt(p.getLocation()) + .filter(i -> i.getRank(p.getUniqueId()) >= RanksManager.MEMBER_RANK).orElse(null); + return here != null ? here : addon.getIslands().getIsland(addon.getOverWorld(), p.getUniqueId()); + } + /** * Sets the island protection size and fires an event for it * @param island - island diff --git a/src/main/java/world/bentobox/boxed/Boxed.java b/src/main/java/world/bentobox/boxed/Boxed.java index 80c1cca..9e6bf75 100644 --- a/src/main/java/world/bentobox/boxed/Boxed.java +++ b/src/main/java/world/bentobox/boxed/Boxed.java @@ -1,22 +1,34 @@ package world.bentobox.boxed; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; import java.util.Collections; import java.util.HashMap; +import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import java.util.stream.Stream; import org.bukkit.Bukkit; -import org.bukkit.Difficulty; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.WorldCreator; +import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.SpawnCategory; import org.bukkit.generator.BiomeProvider; import org.bukkit.generator.ChunkGenerator; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + import world.bentobox.bentobox.api.addons.GameModeAddon; import world.bentobox.bentobox.api.commands.admin.DefaultAdminCommand; import world.bentobox.bentobox.api.commands.island.DefaultPlayerCommand; @@ -26,8 +38,19 @@ import world.bentobox.bentobox.api.flags.Flag.Mode; import world.bentobox.bentobox.api.flags.Flag.Type; import world.bentobox.bentobox.api.hooks.Hook; +import world.bentobox.bentobox.database.json.BentoboxTypeAdapterFactory; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.blueprints.BundleAvailability; +import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle; +import world.bentobox.bentobox.database.objects.Island; import world.bentobox.bentobox.hooks.WorldManagementHook; +import world.bentobox.bentobox.managers.island.NewIslandLocationStrategy; +import world.bentobox.boxed.areas.Area; +import world.bentobox.boxed.areas.AreaLocationStrategy; +import world.bentobox.boxed.areas.AreaManager; +import world.bentobox.boxed.areas.AreaRules; import world.bentobox.bentobox.managers.RanksManager; +import world.bentobox.boxed.commands.AdminAreasCommand; import world.bentobox.boxed.commands.AdminPlaceStructureCommand; import world.bentobox.boxed.generators.biomes.BoxedBiomeGenerator; import world.bentobox.boxed.generators.biomes.NetherSeedBiomeGenerator; @@ -35,7 +58,11 @@ import world.bentobox.boxed.generators.chunks.AbstractBoxedChunkGenerator; import world.bentobox.boxed.generators.chunks.BoxedChunkGenerator; import world.bentobox.boxed.generators.chunks.BoxedSeedChunkGenerator; +import world.bentobox.boxed.generators.template.Template; +import world.bentobox.boxed.generators.template.TemplateBuilder; +import world.bentobox.boxed.generators.template.TemplateChunk; import world.bentobox.boxed.listeners.AdvancementListener; +import world.bentobox.boxed.listeners.BoxCleaner; import world.bentobox.boxed.listeners.EnderPearlListener; import world.bentobox.boxed.listeners.NewAreaListener; @@ -55,22 +82,23 @@ public class Boxed extends GameModeAddon { .type(Type.WORLD_SETTING) .defaultSetting(true) .build(); - private static final String SEED = "seed"; private static final String NETHER = "_nether"; + private static final String AREAS_FOLDER = "areas"; + private static final String REBUILD_MARKER = "rebuild"; + private static final String REGENERATE = "regenerate"; private static final String THE_END = "_the_end"; // Settings private Settings settings; private AbstractBoxedChunkGenerator worldGen; - private BoxedSeedChunkGenerator seedGen; private NewAreaListener newAreaListener; + private BoxCleaner boxCleaner; private AbstractBoxedChunkGenerator netherGen; - private BoxedSeedChunkGenerator netherSeedGen; + private AreaManager areas; private final Config configObject = new Config<>(this, Settings.class); private AdvancementsManager advManager; - private World seedWorld; private final Map generatorMap = new HashMap<>(); private final Map generatorMaps = new HashMap<>(); private BiomeProvider boxedBiomeProvider; @@ -91,6 +119,7 @@ public void setup() { super.setup(); new AdminPlaceStructureCommand(this); + new AdminAreasCommand(this); } }; } @@ -108,17 +137,25 @@ private boolean loadSettings() { this.worldGen = new BoxedChunkGenerator(this); generatorMaps.put(settings.getWorldName(), worldGen); - seedGen = new BoxedSeedChunkGenerator(this, Environment.NORMAL, - new SeedBiomeGenerator(this)); - generatorMaps.put(settings.getWorldName() + "/" + SEED, seedGen); - - // Nether generators + // Nether generator this.netherGen = new BoxedChunkGenerator(this); generatorMaps.put(settings.getWorldName() + NETHER, netherGen); - netherSeedGen = new BoxedSeedChunkGenerator(this, Environment.NETHER, - new NetherSeedBiomeGenerator(this)); - generatorMaps.put(settings.getWorldName() + "/" + SEED + NETHER, netherSeedGen); + // Areas and the generators of their seed worlds. Areas are only loaded once because + // they hold the open templates. + if (areas == null) { + saveResource("areas.yml", false); + areas = new AreaManager(YamlConfiguration.loadConfiguration(new File(getDataFolder(), "areas.yml")), + new File(getDataFolder(), AREAS_FOLDER + File.separator + "grid.yml"), settings.getSeed(), + this::logError); + } + String worldName = settings.getWorldName().toLowerCase(Locale.ENGLISH); + for (Area area : areas.getAreas()) { + generatorMaps.put(area.seedWorldName(worldName, false), new BoxedSeedChunkGenerator(this, + Environment.NORMAL, new SeedBiomeGenerator(this, area.biomes()))); + generatorMaps.put(area.seedWorldName(worldName, true), new BoxedSeedChunkGenerator(this, + Environment.NETHER, new NetherSeedBiomeGenerator(this, area.biomes()))); + } return true; } @@ -150,6 +187,8 @@ public void onEnable() { this.registerListener(new EnderPearlListener(this)); newAreaListener = new NewAreaListener(this); this.registerListener(newAreaListener); + boxCleaner = new BoxCleaner(this); + this.registerListener(boxCleaner); // Register placeholders PlaceholdersManager phManager = new PlaceholdersManager(this); @@ -166,6 +205,9 @@ public void onDisable() { if (newAreaListener != null) { newAreaListener.saveNow(); } + if (areas != null) { + areas.removeTemplates().forEach(this::close); + } } @Override @@ -184,65 +226,305 @@ public Settings getSettings() { @Override public void createWorlds() { - String worldName = settings.getWorldName().toLowerCase(); + String worldName = settings.getWorldName().toLowerCase(Locale.ENGLISH); + // Get the land of every area ready before the game worlds ask for it + for (Area area : areas.getAreas()) { + boolean regenerate = checkRebuildRequest(area); + loadTemplate(area, worldName, Environment.NORMAL, settings.getSeedX(), settings.getSeedZ(), regenerate); + if (settings.isNetherGenerate()) { + loadTemplate(area, worldName, Environment.NETHER, settings.getNetherSeedX(), + settings.getNetherSeedZ(), regenerate); + } + } // Create overworld - createOverWorld(worldName); + if (getServer().getWorld(worldName) == null) { + log("Creating Boxed world ..."); + } + islandWorld = getWorld(worldName, World.Environment.NORMAL); // Make the nether if it does not exist if (settings.isNetherGenerate()) { - createNether(worldName); + if (getServer().getWorld(worldName + NETHER) == null) { + log("Creating Boxed's Nether..."); + } + netherWorld = getWorld(worldName, World.Environment.NETHER); } // The End is not supported yet } - private void createNether(String worldName) { - // Create vanilla seed nether world - log("Creating Boxed Seed Nether world ..."); - World seedWorldNether = WorldCreator - .name(worldName + "/" + SEED + NETHER) - .generator(netherSeedGen) - .environment(Environment.NETHER) - .seed(getSettings().getSeed()) - .createWorld(); - seedWorldNether.setDifficulty(Difficulty.EASY); + /** + * @param area area + * @param env environment + * @return the template file for the area and environment + */ + File getTemplateFile(Area area, Environment env) { + return new File(getAreaFolder(area), env.name().toLowerCase(Locale.ENGLISH) + ".bxt"); + } - seedWorldNether.setSpawnLocation(settings.getNetherSeedX(), 64, settings.getNetherSeedZ()); - generatorMap.put(seedWorldNether, netherSeedGen); - getPlugin().getIWM().addWorld(seedWorldNether, this); - copyChunks(seedWorldNether, netherGen); + /** + * Opens the template of an area for an environment. If there is no usable template file, + * the area's seed world is loaded, the template is built from it and the seed world is + * unloaded again. This only happens once; after that the seed world is not needed to run + * the server. + * @param area area + * @param worldName name of the game overworld + * @param env environment + * @param seedX block x of the centre of the area in the seed world + * @param seedZ block z of the centre of the area in the seed world + * @param regenerate true to throw away the seed world and generate it again + */ + private void loadTemplate(Area area, String worldName, Environment env, int seedX, int seedZ, + boolean regenerate) { + String what = "the " + env + " land of the " + area.id() + " area"; + String seedWorldName = area.seedWorldName(worldName, env == Environment.NETHER); + File file = getTemplateFile(area, env); + int size = worldGen.getSize(); + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization() + .disableHtmlEscaping().registerTypeAdapterFactory(new BentoboxTypeAdapterFactory(getPlugin())) + .create(); + Template template = openTemplate(file, gson, size, area.seed()); + if (template == null) { + log("Building " + what + " from its seed world. This only happens once..."); + long start = System.currentTimeMillis(); + WorldCreator creator = WorldCreator + .name(seedWorldName) + .generator(generatorMaps.get(seedWorldName)) + .environment(env) + .seed(area.seed()); + World seedWorld = creator.createWorld(); + if (seedWorld != null && regenerate) { + seedWorld = regenerateSeedWorld(seedWorld, creator); + } + if (seedWorld == null) { + logError("Could not create seed world " + seedWorldName); + return; + } + try { + new TemplateBuilder(seedWorld, seedX >> 4, seedZ >> 4, size, gson, this::log).build(file, + area.seed()); + } catch (IOException e) { + logError("Could not build " + what + ": " + e); + getPlugin().logStacktrace(e); + } + // The seed world is saved so the template can be rebuilt from it later + if (!Bukkit.unloadWorld(seedWorld, true)) { + logWarning("Could not unload seed world " + seedWorldName); + } + log("Built " + what + " in " + (System.currentTimeMillis() - start) / 1000 + " seconds"); + template = openTemplate(file, gson, size, area.seed()); + } + if (template == null) { + logError("There is no template for " + what + ". Boxes there will be empty!"); + } else { + close(areas.setTemplate(area, env, template)); + } + } - if (getServer().getWorld(worldName + NETHER) == null) { - log("Creating Boxed's Nether..."); + /** + * Opens a template file if it exists and matches the current settings. + * @return the template, or null if it has to be built + */ + private Template openTemplate(File file, Gson gson, int size, long seed) { + if (!file.exists()) { + return null; } - netherWorld = getWorld(worldName, World.Environment.NETHER); + try { + Template template = new Template(file, gson, this::logError); + if (template.getSize() == size && template.getSeed() == seed) { + return template; + } + log(file + " was built with a different seed or area radius, so it will be rebuilt"); + template.close(); + } catch (IOException e) { + logError("Could not read " + file + ", so it will be rebuilt: " + e.getMessage()); + } + return null; } - private void createOverWorld(String worldName) { - // Create vanilla seed world - log("Creating Boxed Seed world ..."); - seedWorld = WorldCreator - .name(worldName + "/" + SEED) - .generator(seedGen) - .environment(Environment.NORMAL) - .seed(getSettings().getSeed()) - .createWorld(); - seedWorld.setDifficulty(Difficulty.EASY); + private void close(@Nullable Template template) { + if (template != null) { + try { + template.close(); + } catch (IOException e) { + logError("Could not close a template: " + e.getMessage()); + } + } + } - seedWorld.setSpawnLocation(settings.getSeedX(), 64, settings.getSeedZ()); + /** + * @return the cleaner that puts the land of deleted boxes back + */ + public BoxCleaner getBoxCleaner() { + return boxCleaner; + } - generatorMap.put(seedWorld, seedGen); - getPlugin().getIWM().addWorld(seedWorld, this); - copyChunks(seedWorld, worldGen); + /** + * @return the areas that boxes can be made in + */ + public AreaManager getAreas() { + return areas; + } - if (getServer().getWorld(worldName) == null) { - log("Creating Boxed world ..."); + /** + * Gets the area that a chunk of the game world is in. + * @param chunkZ chunk z in the game world + * @return the area + */ + public Area getAreaAt(int chunkZ) { + return areas.getAreaAtRow(AbstractBoxedChunkGenerator.rowCalc(chunkZ, worldGen.getSize())); + } + + /** + * Gets the land that the boxes at a chunk of the game world are made from. + * @param env environment + * @param chunkZ chunk z in the game world + * @return the template, or null if there is none + */ + @Nullable + public Template getTemplate(Environment env, int chunkZ) { + return areas.getTemplate(getAreaAt(chunkZ), env); + } + + /** + * Gets the land for a chunk of the game world. + * @param env environment + * @param chunkX chunk x in the game world + * @param chunkZ chunk z in the game world + * @return the chunk, or null if there is none + */ + @Nullable + public TemplateChunk getTemplateChunk(Environment env, int chunkX, int chunkZ) { + Template template = getTemplate(env, chunkZ); + return template == null ? null : template.getChunk(worldGen.repeatCalc(chunkX), worldGen.repeatCalc(chunkZ)); + } + + /** + * Gets the middle of the box position that a location is in. Box positions are a fixed + * grid, so this works whether or not anyone has a box there. + * @param location a location in the game world + * @return the middle of the box position, at the same height as the location + */ + public Location getBoxCentre(Location location) { + int pitch = worldGen.getSize() * 2 * 16; + int x = Math.floorDiv(location.getBlockX() + pitch / 2, pitch) * pitch; + int z = Math.floorDiv(location.getBlockZ() + pitch / 2, pitch) * pitch; + return new Location(location.getWorld(), x, location.getBlockY(), z); + } + + /** + * Gets the file that lists the structures placed in new boxes of the area at a location. + * @param location a location in the game world + * @return the area's structures file, which may not exist yet + */ + public File getStructuresFile(Location location) { + return new File(getDataFolder(), getAreaAt(location.getBlockZ() >> 4).structures()); + } + + /** + * Boxes are placed in the area that matches the blueprint bundle the player picked. The + * box is refused if the area is closed or the player has not unlocked it. + */ + @Override + public NewIslandLocationStrategy getNewIslandLocationStrategy(User user, String blueprintBundle, + Island oldIsland) throws IOException { + return new AreaLocationStrategy(this, new AreaRules(this).check(user, blueprintBundle, oldIsland)); + } + + /** + * Areas that are closed or not built yet are not offered to players. Areas a player has + * not unlocked, or already has a box in, are shown but cannot be picked. + */ + @Override + public BundleAvailability getBundleAvailability(User user, BlueprintBundle bundle, Island oldIsland) { + return new AreaRules(this).availability(user, bundle.getUniqueId(), oldIsland); + } + + /** + * A player has at most one box in an area, so a box with no name is listed by its area: + * the display name of the area's blueprint bundle, or the area's name if it has none. + */ + @Override + public String getIslandLabel(User user, Island island) { + if (island.getCenter() == null) { + return null; } + Area area = getAreaAt(island.getCenter().getBlockZ() >> 4); + BlueprintBundle bundle = getPlugin().getBlueprintsManager().getBlueprintBundles(this).get(area.id()); + return bundle == null || bundle.getDisplayName() == null || bundle.getDisplayName().isBlank() ? area.id() + : bundle.getDisplayName(); + } - // Create the world if it does not exist - islandWorld = getWorld(worldName, World.Environment.NORMAL); + /** + * @param area area + * @return the folder that holds the area's templates + */ + public File getAreaFolder(Area area) { + return new File(getDataFolder(), AREAS_FOLDER + File.separator + area.id()); + } + + /** + * Asks for the land of an area to be built again the next time the server starts. + * @param area area + * @param regenerate true to also throw away the area's seed worlds, so that changes to + * its seed or biomes take effect. False rebuilds from the seed worlds + * as they are, which keeps any changes made to them by hand. + * @return true if the request was saved + */ + public boolean requestRebuild(Area area, boolean regenerate) { + File marker = new File(getAreaFolder(area), REBUILD_MARKER); + try { + Files.createDirectories(marker.getParentFile().toPath()); + Files.writeString(marker.toPath(), regenerate ? REGENERATE : ""); + return true; + } catch (IOException e) { + logError("Could not save rebuild request for area " + area.id() + ": " + e.getMessage()); + return false; + } + } + /** + * Acts on a rebuild request left by {@link #requestRebuild(Area, boolean)}: removes the + * area's templates so that they are built again. + * @return true if the seed worlds must be thrown away too + */ + private boolean checkRebuildRequest(Area area) { + File marker = new File(getAreaFolder(area), REBUILD_MARKER); + if (!marker.exists()) { + return false; + } + boolean regenerate = false; + try { + regenerate = REGENERATE.equals(Files.readString(marker.toPath()).strip()); + for (Environment env : Environment.values()) { + Files.deleteIfExists(getTemplateFile(area, env).toPath()); + } + Files.delete(marker.toPath()); + log("The land of the " + area.id() + " area will be rebuilt as requested."); + } catch (IOException e) { + logError("Could not act on the rebuild request for area " + area.id() + ": " + e.getMessage()); + } + return regenerate; } - + + /** + * Throws away a seed world and makes it again from nothing. + * @return the new seed world, or null if it could not be made + */ + private World regenerateSeedWorld(World seedWorld, WorldCreator creator) { + File folder = seedWorld.getWorldFolder(); + // Be very sure this is a seed world before deleting anything + if (!folder.getName().startsWith("seed") || !Bukkit.unloadWorld(seedWorld, false)) { + logError("Could not regenerate seed world " + seedWorld.getName() + ". Using it as it is."); + return seedWorld; + } + try (Stream files = Files.walk(folder.toPath())) { + files.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete()); + } catch (IOException e) { + logError("Could not delete seed world " + folder + ": " + e.getMessage()); + } + return creator.createWorld(); + } + /** * Registers a world with world management plugins * @@ -262,42 +544,6 @@ private void registerToWorldManagementPlugins(@NonNull World world) { } } - /** - * Copies chunks from the seed world, so they can be pasted in the game world - * @param world - source world - * @param gen - generator to store the chunks - */ - private void copyChunks(World world, AbstractBoxedChunkGenerator gen) { - int startX = 0; - int startZ = 0; - if (world.getEnvironment().equals(Environment.NORMAL)) { - startX = this.settings.getSeedX() >> 4; - startZ = this.settings.getSeedZ() >> 4; - } else { - startX = this.settings.getNetherSeedX() >> 4; - startZ = this.settings.getNetherSeedZ() >> 4; - } - - // Convert to chunks - int size = (int)(this.getSettings().getIslandDistance() / 16D); - double percent = size * 4D * size; - int count = 0; - int last = 0; - for (int x = -size; x <= size; x ++) { - for (int z = -size; z <= size; z++) { - gen.setChunk(x, z, world.getChunkAt(startX + x, startZ + z)); - count++; - int p = (int) (count / percent * 100); - if (p % 10 == 0 && p != last) { - last = p; - this.log("Pregenerating seed chunks for " + world.getName() + "'s " + world.getEnvironment() + " " - + p + "% done"); - } - - } - } - } - /** * Get the chunk generator for a Boxed world * @param env - nether, normal, or end @@ -322,7 +568,7 @@ private World getWorld(String worldName2, Environment env) { .name(worldName2) .generator(getChunkGenerator(env)) .environment(env) - .seed(seedWorld.getSeed()) // For development + .seed(settings.getSeed()) .createWorld(); // Set spawn rates if (w != null) { diff --git a/src/main/java/world/bentobox/boxed/areas/Area.java b/src/main/java/world/bentobox/boxed/areas/Area.java new file mode 100644 index 0000000..f47f801 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/areas/Area.java @@ -0,0 +1,41 @@ +package world.bentobox.boxed.areas; + +/** + * A kind of land that boxes can be made in. Every box in an area has the same land. + * + * @param id unique name of the area. It matches the unique id of a blueprint bundle. + * @param seed world seed the land is generated from + * @param biomes name of the file that defines the biomes around the middle of the area + * @param structures name of the file that lists the structures placed in each new box + * @param row row of the box grid that this area's boxes are placed in + * @param enabled false if new boxes can no longer be made in this area. Existing boxes stay. + * @param requires name of the area that unlocks this one, or null if anyone can start here + * @param unlockSize the size a player's box in this area must reach to unlock the areas that + * require it. Each area sets its own, so some can be harder than others. + * 0 means that just having a box in the area is enough. + * @author tastybento + */ +public record Area(String id, long seed, String biomes, String structures, int row, boolean enabled, + String requires, int unlockSize) { + + /** + * Name of the area that always exists + */ + public static final String DEFAULT = "default"; + + /** + * @return true if this is the default area + */ + public boolean isDefault() { + return DEFAULT.equals(id); + } + + /** + * @param worldName name of the game overworld + * @param nether true for the Nether seed world + * @return name of the seed world this area's land is generated in + */ + public String seedWorldName(String worldName, boolean nether) { + return worldName + "/seed" + (isDefault() ? "" : "_" + id) + (nether ? "_nether" : ""); + } +} diff --git a/src/main/java/world/bentobox/boxed/areas/AreaLocationStrategy.java b/src/main/java/world/bentobox/boxed/areas/AreaLocationStrategy.java new file mode 100644 index 0000000..cd2f3fb --- /dev/null +++ b/src/main/java/world/bentobox/boxed/areas/AreaLocationStrategy.java @@ -0,0 +1,74 @@ +package world.bentobox.boxed.areas; + +import org.bukkit.Location; +import org.bukkit.World; + +import world.bentobox.bentobox.managers.island.DefaultNewIslandLocationStrategy; +import world.bentobox.boxed.Boxed; + +/** + * Finds the place for a new box in an area. Boxes of an area go along the area's row of the + * box grid, spreading out east and west from the middle. + * + * @author tastybento + */ +public class AreaLocationStrategy extends DefaultNewIslandLocationStrategy { + + /** + * How many taken positions in a row to pass before giving up + */ + static final int MAX_TRIES = 10000; + + private final Boxed addon; + private final Area area; + private final int height; + + /** + * @param addon Boxed + * @param area the area the box will be in + */ + public AreaLocationStrategy(Boxed addon, Area area) { + this.addon = addon; + this.area = area; + this.height = new BoxHeight(addon).get(area); + } + + @Override + public Location getNextLocation(World world) { + return find(world); + } + + /** + * Finds where the next box of the area will go. + * @param world the game overworld + * @return location of the next box, or the middle of the area's row if the row is full + */ + public Location peekNextLocation(World world) { + Location loc = find(world); + return loc == null ? location(world, 0) : loc; + } + + private Location location(World world, int position) { + // Distance between box centres. The generator repeats the land on whole chunks. + int pitch = addon.getChunkGenerator(World.Environment.NORMAL).getSize() * 2 * 16; + return new Location(world, (double) AreaManager.column(position) * pitch, height, + (double) area.row() * pitch); + } + + /** + * Finds the first position in the area's row that nothing is at. Positions are searched + * from the middle every time, so a position is used again once the box that was there + * has been deleted and its data cleaned up. Until then the old box is still on record, + * which keeps the position taken, so a new box never gets another player's leftovers. + */ + private Location find(World world) { + for (int position = 0; position < MAX_TRIES; position++) { + Location loc = location(world, position); + if (isIsland(loc) == Result.FREE) { + return loc; + } + } + addon.logError("Could not find a free spot for a box in area " + area.id()); + return null; + } +} diff --git a/src/main/java/world/bentobox/boxed/areas/AreaManager.java b/src/main/java/world/bentobox/boxed/areas/AreaManager.java new file mode 100644 index 0000000..f326160 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/areas/AreaManager.java @@ -0,0 +1,242 @@ +package world.bentobox.boxed.areas; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +import org.bukkit.World.Environment; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.eclipse.jdt.annotation.NonNull; +import org.eclipse.jdt.annotation.Nullable; + +import world.bentobox.boxed.generators.template.Template; + +/** + * Knows the areas, where each one is in the world and what land it has. + *

+ * Boxes are placed on a grid. Each area owns one row of that grid, which runs east-west + * without end, so the area a chunk belongs to can be worked out from its z coordinate alone. + * That is what lets the chunk generator pick the right land for any chunk. Which row an area + * owns is saved in {@code areas/grid.yml} the first time the area is seen and never changes. + * A row that no area owns has the default area's land. + * + * @author tastybento + */ +public class AreaManager { + + private static final Pattern VALID_ID = Pattern.compile("[a-z0-9_]+"); + private static final String ROWS = "rows"; + + private final File gridFile; + private final YamlConfiguration grid; + private final Map areas = new LinkedHashMap<>(); + private final Map rows = new ConcurrentHashMap<>(); + private final Map> templates = new ConcurrentHashMap<>(); + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Area defaultArea; + + /** + * @param config the contents of areas.yml + * @param gridFile file that records which row each area owns + * @param defaultSeed seed of the default area if it does not set one + * @param errorLog where to report problems with the config + */ + public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed, + java.util.function.Consumer errorLog) { + this.gridFile = gridFile; + this.grid = YamlConfiguration.loadConfiguration(gridFile); + ConfigurationSection section = config.getConfigurationSection("areas"); + List ids = new ArrayList<>(); + // The default area always exists and always comes first + ids.add(Area.DEFAULT); + if (section != null) { + for (String id : section.getKeys(false)) { + if (!VALID_ID.matcher(id).matches()) { + errorLog.accept("Area name '" + id + + "' is not valid. Use lower case letters, numbers and underscores only. Ignoring it."); + } else if (!ids.contains(id)) { + ids.add(id); + } + } + } + boolean changed = false; + for (String id : ids) { + String path = ROWS + "." + id; + if (!grid.contains(path)) { + grid.set(path, nextFreeRow()); + changed = true; + } + ConfigurationSection s = section == null ? null : section.getConfigurationSection(id); + if (s == null) { + s = new YamlConfiguration(); + } + String requires = s.getString("requires"); + if (requires != null && (!ids.contains(requires) || requires.equals(id))) { + errorLog.accept("Area '" + id + "' requires area '" + requires + + "', which is not a different, known area. Ignoring the requirement."); + requires = null; + } + Area area = new Area(id, s.getLong("seed", defaultSeed), s.getString("biomes", "biomes.yml"), + s.getString("structures", "structures.yml"), grid.getInt(path), s.getBoolean("enabled", true), + requires, Math.max(0, s.getInt("unlocks-next-at", 0))); + areas.put(id, area); + rows.put(area.row(), area); + } + defaultArea = areas.get(Area.DEFAULT); + if (changed) { + save(errorLog); + } + } + + /** + * Rows are handed out in the order 0, 1, 2... Rows of areas that have since been removed + * from the config stay taken, because their boxes are still in the world. + */ + private int nextFreeRow() { + ConfigurationSection s = grid.getConfigurationSection(ROWS); + int row = 0; + if (s != null) { + for (String id : s.getKeys(false)) { + row = Math.max(row, s.getInt(id) + 1); + } + } + return row; + } + + private void save(java.util.function.Consumer errorLog) { + try { + File parent = gridFile.getParentFile(); + if (parent != null) { + parent.mkdirs(); + } + grid.save(gridFile); + } catch (IOException e) { + errorLog.accept("Could not save " + gridFile + ": " + e.getMessage()); + } + } + + /** + * @return all the areas, default first + */ + public Collection getAreas() { + return areas.values(); + } + + /** + * @param id name of an area + * @return the area, or null if there is no area with that name + */ + @Nullable + public Area getArea(@Nullable String id) { + return id == null ? null : areas.get(id); + } + + /** + * Notes an area that has been added to the config but will not exist until the server + * restarts. Boxes cannot be made in it until then. + * @param id name of the new area + */ + public void addPending(String id) { + pending.add(id); + } + + /** + * @param id name of an area or blueprint bundle, may be null + * @return true if this is a new area that is waiting for a restart + */ + public boolean isPending(@Nullable String id) { + return id != null && pending.contains(id); + } + + /** + * @param id name to check + * @return true if the name can be used for an area + */ + public static boolean isValidName(String id) { + return VALID_ID.matcher(id).matches(); + } + + /** + * @return the default area + */ + @NonNull + public Area getDefaultArea() { + return defaultArea; + } + + /** + * Gets the area that boxes made with a blueprint bundle go in. + * @param bundle unique id of the blueprint bundle, may be null + * @return the area with the same name as the bundle, otherwise the default area + */ + @NonNull + public Area getAreaForBundle(@Nullable String bundle) { + Area area = bundle == null ? null : areas.get(bundle); + return area == null ? defaultArea : area; + } + + /** + * Gets the area that owns a row of the box grid. Safe to call from any thread. + * @param row grid row + * @return the area, which is the default area if no area owns the row + */ + @NonNull + public Area getAreaAtRow(int row) { + Area area = rows.get(row); + return area == null ? defaultArea : area; + } + + /** + * Sets the land of an area. + * @param area area + * @param env environment + * @param template the land + * @return the land the area had before, or null + */ + @Nullable + public Template setTemplate(Area area, Environment env, Template template) { + return templates.computeIfAbsent(area.row(), k -> new ConcurrentHashMap<>()).put(env, template); + } + + /** + * Gets the land of an area. Safe to call from any thread. + * @param area area + * @param env environment + * @return the land, or null if the area has none in this environment + */ + @Nullable + public Template getTemplate(Area area, Environment env) { + Map map = templates.get(area.row()); + return map == null ? null : map.get(env); + } + + /** + * Removes and returns the land of every area so that it can be closed. + * @return all templates + */ + public List