diff --git a/CLAUDE.md b/CLAUDE.md index e0f63ed..22087e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,6 +46,12 @@ Never hold the whole region in memory or load the seed world on a normal boot `listeners/FortressMobsListener` makes a copied fortress work: natural spawns on nether bricks in the game Nether are swapped for wither skeletons, blazes and skeletons at vanilla fortress weights (`world.nether.fortress-mobs`). `LandSurvey` records spawners as the mob they make, and `requirements.yml` treats nether bricks as the fortress. +### Biome styles and the area workshop + +`generators/biomes/BiomeLayout` reads one dimension of a biomes file and answers "which chosen biome is at dx,dz from the middle" (null = the seed's own). It supports per-quarter lists, `rings`, random `patches`, and `blend` (noise that bends the edges). `AbstractSeedBiomeProvider` only adds the centres and the vanilla fallback. `biomes.yml` is the "original" style; `biomes/*.yml` are the others (`workshop/BiomeStyles` maps names to files). With `blend: 0` the original layout must stay exactly as it was, because existing areas depend on it. + +`workshop/WorkshopManager` runs the one workshop: temporary worlds `/workshop` and `/workshop_nether` (folders inside the game world's folder, like seed worlds) made with the seed generator, peaceful, spawn limits 0. Its state (`workshop/Workshop`: seed, biomes file, source area, centres, the players inside and the game mode each had outside) is saved to `areas/workshop.yml` on every change and reloaded, with the worlds, in `onEnable`. `listeners/WorkshopListener` forces creative on entry, restores the game mode on exit, respawns in place, and sends players home if the workshop was discarded while they were offline (`areas/displaced.yml`). `/boxadmin areas edit` (`AdminAreasEditCommand`) holds the logic and can be typed; `WorkshopDialogs` is only the Paper dialog UI on top, and cannot be unit tested under MockBukkit. Still to build: spot scanning in the workshop, choosing the centre, structure logging and turning the workshop into an area without a restart. + ### 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. diff --git a/README.md b/README.md index 6d17544..55eafd7 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ You can also do the same by hand: add the area to `areas.yml` and make a bluepri | `/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. | | `/boxadmin areas check ` | Plays out how a box grows in the area and reports where players get stuck. See [Checking that an area can be played](#checking-that-an-area-can-be-played). | | `/boxadmin areas find [seed\|random] [radius]` | Looks through a seed for good places to start a box. See [Finding a good place to start](#finding-a-good-place-to-start). | +| `/boxadmin areas edit` | Opens the area workshop, where a new area is tried out in a temporary world. See [The area workshop](#the-area-workshop). | 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: @@ -199,15 +200,60 @@ The Nether of a box is a copy, so the game does not know the fortress is there a A good start does not mean the area can be finished. Run `/boxadmin areas check ` after the restart to see how far a box there can grow. -### biomes.yml -The player's land has biomes and they are defined here. It's not possible to define where the biomes are right now, only what affect they have on the terrain. +### The area workshop -* height: the default height is 8. Lower numbers will produce lower land, higher higher land. -* scale: this is how smooth the land will be. Smaller numbers are more jagged, larger numbers are flatter. +The workshop is a set of temporary worlds for trying out a seed and a biome style before they become an area. **It is not finished yet:** today it makes the worlds and lets you look around and build in them. Picking the middle of the box, placing structures and turning the result into an area are still to come. -Setting ocean biomes to higher height numbers will result in the ocean floor being above the sea level and creating land. +Run `/boxadmin areas edit`. A dialog box asks for: -A lot of these numbers are rough guesses right now and if you come up with better values, please share them! +* **Area** - a new area, or an existing one to start from. +* **Seed** - leave it empty for a random seed, or to keep the seed of the area you picked. `-1` is always a random seed. +* **Biome style** - see [Biome styles](#biome-styles). + +You are then taken to the temporary world. While you are there: + +* Everyone who comes in is put in creative mode and gets their old game mode back when they leave. If you switch to survival and die, you come back where you died, in creative mode. +* The world is peaceful and nothing spawns, so nothing changes the land except you. +* You can leave and come back. The workshop, and everything built in it, stays until you discard it, including over a server restart. There is one workshop at a time, and other admins can join it. +* If you start from an existing area without changing its seed or biome style, the workshop starts as a copy of the land that area was built from, so changes made to it by hand are kept. + +Run `/boxadmin areas edit` again to go back to it, go to its Nether, or discard it. Discarding sends everyone inside to their box (or to spawn if they have none) and deletes the temporary worlds. Players who were inside but offline are sent to their box when they next join. + +Everything can also be typed, which is the only way from the console: + +| Command | Description | +|---------|-------------| +| `/boxadmin areas edit start [biome style\|same] [area]` | Starts work on an area. `same` keeps the seed or biome style of the area named. | +| `/boxadmin areas edit go [nether]` | Goes to the area being worked on. From the console it just makes the world. | +| `/boxadmin areas edit discard confirm` | Throws away the area being worked on. | + +The permission is `boxed.admin.areas.edit`. + +### Biome styles + +A box is small, so Boxed lays chosen biomes out around the middle of it to give players variety: snow, ice, desert, jungle and their plants and animals, all within reach. A biome style is a file that says how. The styles that come with Boxed are: + +| Style | File | What it does | +|-------|------|--------------| +| `original` | `biomes.yml` | Each quarter of the box (north-east, south-east, north-west, south-west) has its own list of biomes by distance from the middle. The edges between biomes are straight. | +| `natural` | `biomes/natural.yml` | The same biomes as `original`, with the edges blended so that there are no straight lines. | +| `rings` | `biomes/rings.yml` | Biomes in rings around the middle, the same all the way round. | +| `random` | `biomes/random.yml` | Patches of biomes picked at random from a list. | +| `none` | `biomes/none.yml` | No chosen biomes. Every box has the biomes the seed has at that place. | + +To make your own style, copy one of the files in the `biomes` folder, give it a new name and change it. It then appears in the workshop under that name. An area uses a style through its `biomes` setting in `areas.yml`, for example `biomes: biomes/natural.yml`. + +A style file has a `distribution` section with a part for the `overworld` and a part for the `nether`. Each part uses one of: + +* `north-east`, `south-east`, `north-west` and `south-west` - a list for each quarter of the box. +* `rings` - one list used all the way round. +* `patches` - a `size` in blocks and a list of `biomes`. Each patch gets one of the biomes at random. The patch in the middle always gets the first in the list. List a biome twice to make it twice as common. + +The lists for quarters and rings are entries of `distance:BIOME`. The distance is a fraction of the area's radius (`world.area-radius` in `config.yml`), so `1.0` is the edge of the biggest possible box, and biomes can be set as far as `2.0`. `CUSTOM` means "leave the biome the seed has". + +`blend` at the top of the file is how many blocks the edges between biomes wander. `0`, or leaving it out, gives straight edges. + +Biomes are fixed when the land is generated. Changing a style does nothing to an area that is already built until you run `/boxadmin areas rebuild regenerate` and restart. ### structures.yml This file records which Minecraft structures should be placed in each new player's box when their area is first created. Structures are stored relative to the island center and are placed in overworld (`normal`) and nether sections. diff --git a/src/main/java/world/bentobox/boxed/Boxed.java b/src/main/java/world/bentobox/boxed/Boxed.java index b1ba63f..b7473b5 100644 --- a/src/main/java/world/bentobox/boxed/Boxed.java +++ b/src/main/java/world/bentobox/boxed/Boxed.java @@ -7,6 +7,7 @@ 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; @@ -65,6 +66,9 @@ import world.bentobox.boxed.listeners.EnderPearlListener; import world.bentobox.boxed.listeners.FortressMobsListener; import world.bentobox.boxed.listeners.NewAreaListener; +import world.bentobox.boxed.listeners.WorkshopListener; +import world.bentobox.boxed.workshop.BiomeStyles; +import world.bentobox.boxed.workshop.WorkshopManager; /** * Main Boxed class - provides a survival game inside a box @@ -95,6 +99,7 @@ public class Boxed extends GameModeAddon { private BoxCleaner boxCleaner; private AbstractBoxedChunkGenerator netherGen; private AreaManager areas; + private WorkshopManager workshop; private final Config configObject = new Config<>(this, Settings.class); @@ -109,6 +114,10 @@ public void onLoad() { saveDefaultConfig(); // Load settings from config.yml. This will check if there are any issues with it too. loadSettings(); + // The biome styles that come with Boxed. Admins add their own to the same folder. + for (String style : List.of("natural", "rings", "random", "none")) { + saveResource(BiomeStyles.FOLDER + "/" + style + ".yml", false); + } // Register commands playerCommand = new DefaultPlayerCommand(this) {}; @@ -191,6 +200,10 @@ public void onEnable() { this.registerListener(newAreaListener); boxCleaner = new BoxCleaner(this); this.registerListener(boxCleaner); + // An area that was being worked on when the server stopped is still there + workshop = new WorkshopManager(this); + workshop.load(); + this.registerListener(new WorkshopListener(this, workshop)); // Register placeholders PlaceholdersManager phManager = new PlaceholdersManager(this); @@ -367,6 +380,13 @@ public AreaManager getAreas() { return areas; } + /** + * @return the workshop, where admins make new areas + */ + public WorkshopManager getWorkshop() { + return workshop; + } + /** * Gets the area that a chunk of the game world is in. * @param chunkZ chunk z in the game world diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java index 4c1669a..3dc9709 100644 --- a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java @@ -71,6 +71,7 @@ public void setup() { new Clean(this); new Check(this); new AdminAreasFindCommand(this); + new AdminAreasEditCommand(this); } @Override diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java new file mode 100644 index 0000000..9dfe5c2 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasEditCommand.java @@ -0,0 +1,260 @@ +package world.bentobox.boxed.commands; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +import org.bukkit.World.Environment; + +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.localization.TextVariables; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.bentobox.util.Util; +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.areas.Area; +import world.bentobox.boxed.workshop.BiomeStyles; +import world.bentobox.boxed.workshop.Workshop; +import world.bentobox.boxed.workshop.WorkshopManager; + +/** + * Opens the area workshop: temporary worlds where an admin tries out a seed and a biome + * style and shapes the land before it becomes an area. Players get dialog boxes; everything + * can also be typed, which is what the console has to do. + * + * @author tastybento + */ +public class AdminAreasEditCommand extends CompositeCommand { + + private static final String PREFIX = "boxed.commands.boxadmin.areas.edit."; + private static final String NONE = PREFIX + "none"; + private static final String FAILED = PREFIX + "failed"; + private static final String START = "start"; + private static final String GO = "go"; + private static final String DISCARD = "discard"; + private static final String CONFIRM = "confirm"; + private static final String RANDOM = "random"; + private static final String NETHER = "nether"; + private static final String SEED_VAR = "[seed]"; + /** + * Stands for "the same as the area that is being edited" + */ + static final String SAME = "same"; + /** + * Stands for "not an existing area" + */ + static final String NEW = "new"; + + private final WorkshopDialogs dialogs = new WorkshopDialogs(this); + + /** + * @param parent the areas command + */ + public AdminAreasEditCommand(CompositeCommand parent) { + super(parent, "edit"); + } + + @Override + public void setup() { + this.setPermission("admin.areas.edit"); + this.setOnlyPlayer(false); + this.setParametersHelp(PREFIX + "parameters"); + this.setDescription(PREFIX + "description"); + } + + @Override + public boolean execute(User user, String label, List args) { + WorkshopManager manager = this.getAddon().getWorkshop(); + if (args.isEmpty()) { + return open(user, manager); + } + return switch (args.get(0).toLowerCase(Locale.ENGLISH)) { + case START -> startTyped(user, args); + case GO -> goTyped(user, args); + case DISCARD -> { + if (args.size() == 2 && CONFIRM.equalsIgnoreCase(args.get(1))) { + yield discard(user); + } + user.sendMessage(PREFIX + "discard-confirm"); + yield false; + } + default -> help(user); + }; + } + + private boolean startTyped(User user, List args) { + if (args.size() < 2 || args.size() > 4) { + return help(user); + } + return start(user, args.get(1), args.size() > 2 ? args.get(2) : SAME, args.size() > 3 ? args.get(3) : NEW); + } + + private boolean goTyped(User user, List args) { + if (args.size() == 1) { + return go(user, Environment.NORMAL); + } + return args.size() == 2 && NETHER.equalsIgnoreCase(args.get(1)) ? go(user, Environment.NETHER) : help(user); + } + + private boolean help(User user) { + this.showHelp(this, user); + return false; + } + + /** + * Shows where things stand: the dialog boxes for a player, a line of text for the console. + */ + private boolean open(User user, WorkshopManager manager) { + Optional workshop = manager.get(); + if (user.isPlayer()) { + workshop.ifPresentOrElse(w -> dialogs.showStatus(user, w), () -> dialogs.showStart(user)); + } else if (workshop.isPresent()) { + Workshop w = workshop.get(); + user.sendMessage(PREFIX + "status", SEED_VAR, String.valueOf(w.getSeed()), "[style]", + BiomeStyles.name(w.getBiomes()), "[area]", w.getArea() == null ? "-" : w.getArea()); + } else { + user.sendMessage(NONE, TextVariables.LABEL, getTopLabel()); + } + return true; + } + + /** + * Starts work on an area and takes the admin there. + * @param user who asked + * @param seedText a seed, "random" or -1 for a random one, or blank or "same" for the seed + * of the area being edited (random for a new area) + * @param style name of a biome style, or "same" for the style of the area being edited + * (the original style for a new area) + * @param areaId name of an existing area to start from, or "new" + * @return true if work started + */ + boolean start(User user, String seedText, String style, String areaId) { + Boxed addon = getAddon(); + WorkshopManager manager = addon.getWorkshop(); + if (manager.get().isPresent()) { + user.sendMessage(PREFIX + "exists"); + return false; + } + Area area = null; + if (areaId != null && !NEW.equalsIgnoreCase(areaId)) { + area = addon.getAreas().getArea(areaId.toLowerCase(Locale.ENGLISH)); + if (area == null) { + user.sendMessage("boxed.commands.boxadmin.areas.unknown-area"); + return false; + } + } + Long seed = parseSeed(seedText, area); + if (seed == null) { + user.sendMessage("boxed.commands.boxadmin.areas.create.invalid-seed"); + return false; + } + String biomes; + if (style == null || SAME.equalsIgnoreCase(style)) { + biomes = area == null ? BiomeStyles.file(addon.getDataFolder(), BiomeStyles.ORIGINAL) : area.biomes(); + } else { + biomes = BiomeStyles.file(addon.getDataFolder(), style); + } + if (biomes == null) { + user.sendMessage(PREFIX + "unknown-style", "[styles]", + String.join(", ", BiomeStyles.list(addon.getDataFolder()))); + return false; + } + try { + manager.start(seed, biomes, area); + } catch (IOException e) { + addon.logError("Could not start work on an area: " + e.getMessage()); + user.sendMessage(FAILED); + return false; + } + user.sendMessage(PREFIX + "started", SEED_VAR, String.valueOf(seed), "[style]", BiomeStyles.name(biomes)); + return go(user, Environment.NORMAL); + } + + private static Long parseSeed(String text, Area area) { + String seed = text == null ? "" : text.trim(); + if (seed.isEmpty() || SAME.equalsIgnoreCase(seed)) { + return area == null ? ThreadLocalRandom.current().nextLong() : area.seed(); + } + if (RANDOM.equalsIgnoreCase(seed) || seed.equals("-1")) { + return ThreadLocalRandom.current().nextLong(); + } + try { + return Long.parseLong(seed); + } catch (NumberFormatException _) { + return null; + } + } + + /** + * Takes the admin to the area being worked on. The world is made if it does not exist + * yet, so the console can use this to make it too. + * @param user who asked + * @param env dimension to go to + * @return true if there is somewhere to go + */ + boolean go(User user, Environment env) { + Boxed addon = getAddon(); + WorkshopManager manager = addon.getWorkshop(); + if (manager.get().isEmpty()) { + user.sendMessage(NONE, TextVariables.LABEL, getTopLabel()); + return false; + } + if (!manager.hasDimension(env) || manager.getWorld(env) == null) { + user.sendMessage(FAILED); + return false; + } + if (!user.isPlayer()) { + user.sendMessage(PREFIX + "ready"); + return true; + } + manager.enter(user.getPlayer(), env).whenComplete((ok, error) -> { + if (error != null || !Boolean.TRUE.equals(ok)) { + user.sendMessage(FAILED); + } else { + user.sendMessage(PREFIX + "welcome"); + } + }); + return true; + } + + /** + * Throws away the area being worked on. + * @param user who asked + * @return true if there was one + */ + boolean discard(User user) { + WorkshopManager manager = this.getAddon().getWorkshop(); + if (manager.get().isEmpty()) { + user.sendMessage(NONE, TextVariables.LABEL, getTopLabel()); + return false; + } + manager.discard().thenAccept(clean -> user.sendMessage(PREFIX + (Boolean.TRUE.equals(clean) ? "discarded" : "discard-failed"))); + return true; + } + + @Override + public Optional> tabComplete(User user, String alias, List args) { + Boxed addon = getAddon(); + String last = args.isEmpty() ? "" : args.get(args.size() - 1); + // The first argument is this command's own label + List options = new ArrayList<>(); + String sub = args.size() > 2 ? args.get(1).toLowerCase(Locale.ENGLISH) : ""; + if (args.size() <= 2) { + options.addAll(List.of(START, GO, DISCARD)); + } else if (sub.equals(START) && args.size() == 3) { + options.addAll(List.of(RANDOM, SAME)); + } else if (sub.equals(START) && args.size() == 4) { + options.add(SAME); + options.addAll(BiomeStyles.list(addon.getDataFolder())); + } else if (sub.equals(START) && args.size() == 5) { + addon.getAreas().getAreas().forEach(a -> options.add(a.id())); + } else if (sub.equals(GO) && args.size() == 3) { + options.add(NETHER); + } else if (sub.equals(DISCARD) && args.size() == 3) { + options.add(CONFIRM); + } + return Optional.of(Util.tabLimit(options, last)); + } +} diff --git a/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java b/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java new file mode 100644 index 0000000..db38a75 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/commands/WorkshopDialogs.java @@ -0,0 +1,117 @@ +package world.bentobox.boxed.commands; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import org.bukkit.Bukkit; +import org.bukkit.World.Environment; + +import io.papermc.paper.dialog.Dialog; +import io.papermc.paper.dialog.DialogResponseView; +import io.papermc.paper.registry.data.dialog.ActionButton; +import io.papermc.paper.registry.data.dialog.DialogBase; +import io.papermc.paper.registry.data.dialog.action.DialogAction; +import io.papermc.paper.registry.data.dialog.body.DialogBody; +import io.papermc.paper.registry.data.dialog.input.DialogInput; +import io.papermc.paper.registry.data.dialog.input.SingleOptionDialogInput.OptionEntry; +import io.papermc.paper.registry.data.dialog.type.DialogType; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickCallback; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.areas.Area; +import world.bentobox.boxed.workshop.BiomeStyles; +import world.bentobox.boxed.workshop.Workshop; + +/** + * The dialog boxes of the area workshop. They only collect what the admin wants; the work is + * done by {@link AdminAreasEditCommand}, which can also be driven by typing. + * + * @author tastybento + */ +final class WorkshopDialogs { + + private static final String PREFIX = "boxed.commands.boxadmin.areas.edit.dialog."; + private static final String SEED = "seed"; + private static final String STYLE = "style"; + private static final String AREA = "area"; + private static final ClickCallback.Options ONCE = ClickCallback.Options.builder().uses(1) + .lifetime(Duration.ofMinutes(30)).build(); + + private final AdminAreasEditCommand command; + + WorkshopDialogs(AdminAreasEditCommand command) { + this.command = command; + } + + private static Component text(User user, String key, String... variables) { + return user.getTranslationAsComponent(PREFIX + key, variables); + } + + private ActionButton button(User user, String key, Consumer action) { + // What a button does is run on the main thread, whichever thread the click arrives on + return ActionButton.builder(text(user, key)).action(DialogAction.customClick( + (view, audience) -> Bukkit.getScheduler().runTask(command.getPlugin(), () -> action.accept(view)), + ONCE)).build(); + } + + private static ActionButton close(User user, String key) { + return ActionButton.builder(text(user, key)).build(); + } + + /** + * Asks what to start work on: a new area or an existing one, the seed and the biome style. + */ + void showStart(User user) { + Boxed addon = command.getAddon(); + List areas = new ArrayList<>(); + areas.add(OptionEntry.create(AdminAreasEditCommand.NEW, text(user, "new-area"), true)); + for (Area area : addon.getAreas().getAreas()) { + areas.add(OptionEntry.create(area.id(), Component.text(area.id()), false)); + } + List styles = new ArrayList<>(); + styles.add(OptionEntry.create(AdminAreasEditCommand.SAME, text(user, "same-style"), true)); + for (String style : BiomeStyles.list(addon.getDataFolder())) { + styles.add(OptionEntry.create(style, Component.text(style), false)); + } + DialogBase base = DialogBase.builder(text(user, "start-title")).canCloseWithEscape(true) + .body(List.of(DialogBody.plainMessage(text(user, "start-body")))) + .inputs(List.of(DialogInput.singleOption(AREA, text(user, AREA), areas).build(), + DialogInput.text(SEED, text(user, SEED)).initial("").maxLength(24).build(), + DialogInput.singleOption(STYLE, text(user, STYLE), styles).build())) + .build(); + user.getPlayer().showDialog(Dialog.create(b -> b.empty().base(base).type(DialogType.confirmation( + button(user, "go", view -> command.start(user, view.getText(SEED), view.getText(STYLE), + view.getText(AREA))), + close(user, "cancel"))))); + } + + /** + * Shows the area being worked on, with buttons to go to it or throw it away. + */ + void showStatus(User user, Workshop workshop) { + Boxed addon = command.getAddon(); + List buttons = new ArrayList<>(); + buttons.add(button(user, "go-overworld", view -> command.go(user, Environment.NORMAL))); + if (addon.getWorkshop().hasDimension(Environment.NETHER)) { + buttons.add(button(user, "go-nether", view -> command.go(user, Environment.NETHER))); + } + buttons.add(button(user, "discard", view -> showDiscard(user))); + DialogBase base = DialogBase.builder(text(user, "status-title")).canCloseWithEscape(true) + .body(List.of(DialogBody.plainMessage(text(user, "status-body", "[seed]", + String.valueOf(workshop.getSeed()), "[style]", BiomeStyles.name(workshop.getBiomes()), + "[area]", workshop.getArea() == null ? "-" : workshop.getArea())))) + .build(); + user.getPlayer().showDialog(Dialog.create(b -> b.empty().base(base) + .type(DialogType.multiAction(buttons).exitAction(close(user, "save-for-later")).columns(1).build()))); + } + + private void showDiscard(User user) { + DialogBase base = DialogBase.builder(text(user, "discard-title")).canCloseWithEscape(true) + .body(List.of(DialogBody.plainMessage(text(user, "discard-body")))).build(); + user.getPlayer().showDialog(Dialog.create(b -> b.empty().base(base).type(DialogType.confirmation( + button(user, "discard", view -> command.discard(user)), close(user, "cancel"))))); + } +} diff --git a/src/main/java/world/bentobox/boxed/generators/biomes/AbstractSeedBiomeProvider.java b/src/main/java/world/bentobox/boxed/generators/biomes/AbstractSeedBiomeProvider.java index 81a3436..f75e6e5 100644 --- a/src/main/java/world/bentobox/boxed/generators/biomes/AbstractSeedBiomeProvider.java +++ b/src/main/java/world/bentobox/boxed/generators/biomes/AbstractSeedBiomeProvider.java @@ -7,23 +7,17 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; import java.util.concurrent.atomic.AtomicReference; import org.bukkit.NamespacedKey; import org.bukkit.World.Environment; import org.bukkit.block.Biome; -import org.bukkit.block.BlockFace; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.generator.BiomeParameterPoint; import org.bukkit.generator.BiomeProvider; import org.bukkit.generator.WorldInfo; -import org.bukkit.util.Vector; import org.eclipse.jdt.annotation.NonNull; import io.papermc.paper.registry.RegistryAccess; @@ -38,11 +32,6 @@ */ public abstract class AbstractSeedBiomeProvider extends BiomeProvider { - /** - * Config marker for "no custom biome here, use the vanilla one" - */ - private static final String CUSTOM_BIOME = "CUSTOM"; - private static final String DEFAULT_BIOMES = "biomes.yml"; private static final Map ENV_MAP; @@ -308,7 +297,7 @@ static ContLoc getCont(double continentalness) { * one. The spot finder tries out several in one world. */ private final AtomicReference centres = new AtomicReference<>(); - protected final Map> quadrants; + private final BiomeLayout layout; protected AbstractSeedBiomeProvider(Boxed boxed, Environment env) { this(boxed, env, DEFAULT_BIOMES); @@ -346,16 +335,8 @@ protected AbstractSeedBiomeProvider(Boxed boxed, Environment env, String biomesF } } YamlConfiguration config = YamlConfiguration.loadConfiguration(biomeFile); - SortedMap northEast = loadQuad(config, ENV_MAP.get(env) + ".north-east"); - SortedMap southEast = loadQuad(config, ENV_MAP.get(env) + ".south-east"); - SortedMap northWest = loadQuad(config, ENV_MAP.get(env) + ".north-west"); - SortedMap southWest = loadQuad(config, ENV_MAP.get(env) + ".south-west"); - - quadrants = new EnumMap<>(BlockFace.class); - quadrants.put(BlockFace.NORTH_EAST, northEast); - quadrants.put(BlockFace.NORTH_WEST, northWest); - quadrants.put(BlockFace.SOUTH_EAST, southEast); - quadrants.put(BlockFace.SOUTH_WEST, southWest); + layout = new BiomeLayout(config.getConfigurationSection(ENV_MAP.get(env)), config.getDouble("blend", 0), dist, + this::parseBiome, addon::logError); } /** @@ -389,11 +370,6 @@ private int[] nearestCentre(int x, int z) { return nearest; } - private Biome getQuadrantBiome(BlockFace dir, double d) { - Entry en = ((TreeMap) quadrants.get(dir)).ceilingEntry(d); - return en == null ? null : en.getValue(); - } - @Override public Biome getBiome(WorldInfo worldInfo, int x, int y, int z, BiomeParameterPoint biomeParameterPoint) { return this.getMappedBiome(worldInfo, x, y, z, biomeParameterPoint); @@ -917,30 +893,11 @@ private Biome getMappedBiome(WorldInfo worldInfo, int x, int y, int z, BiomePara * */ - Vector s = new Vector(x, 0, z); int[] centre = nearestCentre(x, z); - Vector l = new Vector(centre[0], 0, centre[1]); - double dis = l.distance(s); - if (dis > dist * 2) { - // Only customize biomes around the spawn location - return getVanillaBiome(worldInfo, x, y, z, biomeParameterPoint, null); - } - // Provide custom biomes - Biome result; - double d = dis / dist; // Normalize - Vector direction = s.subtract(l); - if (direction.getBlockX() <= 0 && direction.getBlockZ() <= 0) { - result = getQuadrantBiome(BlockFace.NORTH_WEST, d); - } else if (direction.getBlockX() > 0 && direction.getBlockZ() <= 0) { - result = getQuadrantBiome(BlockFace.NORTH_EAST, d); - } else if (direction.getBlockX() <= 0 && direction.getBlockZ() > 0) { - result = getQuadrantBiome(BlockFace.SOUTH_WEST, d); - } else { - result = getQuadrantBiome(BlockFace.SOUTH_EAST, d); - } - + Biome result = layout.get(x - centre[0], z - centre[1]); if (result == null) { - result = getVanillaBiome(worldInfo, x, y, z, biomeParameterPoint, null); + // Only some of the land around the middle has chosen biomes + return getVanillaBiome(worldInfo, x, y, z, biomeParameterPoint, null); } // Caves @@ -965,48 +922,16 @@ public List getBiomes(WorldInfo worldInfo) { } Set biomes = new LinkedHashSet<>(List.of(Biome.NETHER_WASTES, Biome.CRIMSON_FOREST, Biome.WARPED_FOREST, Biome.SOUL_SAND_VALLEY, Biome.BASALT_DELTAS)); - quadrants.values().forEach(q -> q.values().stream().filter(Objects::nonNull).forEach(biomes::add)); + biomes.addAll(layout.biomes()); return List.copyOf(biomes); } - /** - * Loads the custom biomes from the config file - * @param config - Yaml configuration object - * @param sector - the direction section to load - * @return sorted map of the biomes and their probabilities as keys - */ - private SortedMap loadQuad(YamlConfiguration config, String sector) { - SortedMap result = new TreeMap<>(); - if (!config.contains(sector)) { - return result; - } - for (String ring : config.getStringList(sector)) { - String[] split = ring.split(":"); - if (split.length != 2) { - addon.logError(ring + " must be in the format ratio:biome where ratio is a double."); - continue; - } - try { - double d = Double.parseDouble(split[0]); - // A biome of null means that no alternative biome should be applied - result.put(d, parseBiome(split[1])); - } catch (NumberFormatException e) { - addon.logError(sector + ": " + split[0] - + " does not seem to be a double. For integers add a .0 to the end"); - } - } - return result; - } - /** * Looks up a biome by config name. - * @param name biome name from the config, e.g. PLAINS or minecraft:plains. CUSTOM means "no biome". - * @return the biome, or null if the name is CUSTOM or the biome is unknown on this server + * @param name biome name from the config, e.g. PLAINS or minecraft:plains + * @return the biome, or null if the biome is unknown on this server */ private Biome parseBiome(String name) { - if (CUSTOM_BIOME.equalsIgnoreCase(name)) { - return null; - } NamespacedKey key = NamespacedKey.fromString(name.toLowerCase(Locale.ENGLISH)); Biome biome = key == null ? null : RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME).get(key); if (biome == null) { diff --git a/src/main/java/world/bentobox/boxed/generators/biomes/BiomeLayout.java b/src/main/java/world/bentobox/boxed/generators/biomes/BiomeLayout.java new file mode 100644 index 0000000..1ef7171 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/generators/biomes/BiomeLayout.java @@ -0,0 +1,177 @@ +package world.bentobox.boxed.generators.biomes; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; +import java.util.function.Consumer; +import java.util.function.Function; + +import org.bukkit.block.Biome; +import org.bukkit.block.BlockFace; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.util.noise.SimplexNoiseGenerator; +import org.eclipse.jdt.annotation.Nullable; + +/** + * How the chosen biomes are laid out around the middle of an area. A biomes file describes + * one layout per dimension, in one of three ways: + *
    + *
  • {@code north-east}, {@code south-east}, {@code north-west} and {@code south-west}: + * each quarter has its own list of biomes by distance from the middle.
  • + *
  • {@code rings}: one list of biomes by distance, the same all the way round.
  • + *
  • {@code patches}: square patches of a given {@code size}, each given one of a list of + * {@code biomes} at random. The patch in the middle always gets the first in the list.
  • + *
+ * Distances are a fraction of the area's radius. {@code blend} is how many blocks the edges + * between biomes wander, so that they are not straight lines. + *

+ * Instances are immutable and can be used from any thread. + * + * @author tastybento + */ +public class BiomeLayout { + + /** + * Config marker for "no chosen biome here, use the one the seed has" + */ + public static final String CUSTOM_BIOME = "CUSTOM"; + /** + * How far apart the bends in a blended edge are, in blocks + */ + private static final double WAVELENGTH = 80; + /** + * Moves the second noise sample well away from the first so the two are unrelated + */ + private static final double NOISE_OFFSET = 1000; + + private static final Map QUARTERS = Map.of(BlockFace.NORTH_EAST, "north-east", + BlockFace.SOUTH_EAST, "south-east", BlockFace.NORTH_WEST, "north-west", BlockFace.SOUTH_WEST, "south-west"); + + private final int dist; + private final double blend; + private final Map> quadrants = new EnumMap<>(BlockFace.class); + private final int patchSize; + private final List patches = new ArrayList<>(); + private final SimplexNoiseGenerator noise = new SimplexNoiseGenerator(20261125L); + + /** + * @param section the part of a biomes file for one dimension, or null for no chosen biomes + * @param blend how many blocks the edges between biomes wander. 0 for straight edges. + * @param dist the radius of an area in blocks + * @param parser turns a biome name into a biome, or null if there is no such biome + * @param errorLog where to report mistakes in the file + */ + public BiomeLayout(@Nullable ConfigurationSection section, double blend, int dist, + Function parser, Consumer errorLog) { + this.dist = dist; + this.blend = Math.max(0, blend); + if (section != null && section.contains("rings")) { + TreeMap rings = loadRings(section, "rings", parser, errorLog); + for (BlockFace quarter : QUARTERS.keySet()) { + quadrants.put(quarter, rings); + } + } else { + QUARTERS.forEach((quarter, key) -> quadrants.put(quarter, loadRings(section, key, parser, errorLog))); + } + ConfigurationSection p = section == null ? null : section.getConfigurationSection("patches"); + this.patchSize = p == null ? 0 : Math.max(16, p.getInt("size", 96)); + if (p != null) { + p.getStringList("biomes").forEach(name -> patches.add(parse(name, parser))); + } + } + + private static Biome parse(String name, Function parser) { + return CUSTOM_BIOME.equalsIgnoreCase(name.trim()) ? null : parser.apply(name.trim()); + } + + /** + * Reads a list of "distance:biome" entries. + */ + private static TreeMap loadRings(@Nullable ConfigurationSection section, String key, + Function parser, Consumer errorLog) { + TreeMap result = new TreeMap<>(); + if (section == null) { + return result; + } + for (String ring : section.getStringList(key)) { + String[] split = ring.split(":", 2); + if (split.length != 2) { + errorLog.accept(ring + " must be in the format ratio:biome where ratio is a double."); + continue; + } + try { + // A biome of null means that no alternative biome should be applied + result.put(Double.parseDouble(split[0]), parse(split[1], parser)); + } catch (NumberFormatException _) { + errorLog.accept(key + ": " + split[0] + " does not seem to be a double. For integers add a .0 to the end"); + } + } + return result; + } + + /** + * Gets the chosen biome for a block. + * @param dx block x relative to the middle of the area + * @param dz block z relative to the middle of the area + * @return the biome, or null if the seed's own biome should be used there + */ + @Nullable + public Biome get(int dx, int dz) { + double x = dx; + double z = dz; + // Chosen biomes only go as far as twice the radius, measured before any blending + if (Math.sqrt(x * x + z * z) > dist * 2D) { + return null; + } + if (blend > 0) { + x += blend * noise.noise(dx / WAVELENGTH, dz / WAVELENGTH); + z += blend * noise.noise(dx / WAVELENGTH + NOISE_OFFSET, dz / WAVELENGTH + NOISE_OFFSET); + } + if (!patches.isEmpty()) { + return patch(Math.floorDiv((int) Math.floor(x) + patchSize / 2, patchSize), + Math.floorDiv((int) Math.floor(z) + patchSize / 2, patchSize)); + } + BlockFace quarter; + if (x <= 0 && z <= 0) { + quarter = BlockFace.NORTH_WEST; + } else if (x > 0 && z <= 0) { + quarter = BlockFace.NORTH_EAST; + } else if (x <= 0) { + quarter = BlockFace.SOUTH_WEST; + } else { + quarter = BlockFace.SOUTH_EAST; + } + Map.Entry en = quadrants.get(quarter).ceilingEntry(Math.sqrt(x * x + z * z) / dist); + return en == null ? null : en.getValue(); + } + + /** + * Picks the biome of a patch. It only depends on which patch it is, so every box of every + * area that uses the same file gets the same pattern. + */ + private Biome patch(int px, int pz) { + if (px == 0 && pz == 0) { + return patches.get(0); + } + long h = px * 341873128712L + pz * 132897987541L; + h ^= h >>> 29; + h *= 0x9E3779B97F4A7C15L; + h ^= h >>> 32; + return patches.get((int) Math.floorMod(h, (long) patches.size())); + } + + /** + * @return every biome this layout can choose + */ + public Set biomes() { + Set all = new LinkedHashSet<>(); + quadrants.values().forEach(q -> q.values().stream().filter(Objects::nonNull).forEach(all::add)); + patches.stream().filter(Objects::nonNull).forEach(all::add); + return all; + } +} diff --git a/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java b/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java new file mode 100644 index 0000000..1f4201f --- /dev/null +++ b/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java @@ -0,0 +1,94 @@ +package world.bentobox.boxed.listeners; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerRespawnEvent; + +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.workshop.WorkshopManager; + +/** + * The rules for players in the workshop worlds. Everyone who comes in is put in creative + * mode and gets their old game mode back when they leave. Anyone who dies there comes back + * where they died. Players who were in a workshop that was removed while they were away + * are sent to their box when they return. + * + * @author tastybento + */ +public class WorkshopListener implements Listener { + + private final Boxed addon; + private final WorkshopManager manager; + private final Map deaths = new HashMap<>(); + + /** + * @param addon Boxed + * @param manager the workshop + */ + public WorkshopListener(Boxed addon, WorkshopManager manager) { + this.addon = addon; + this.manager = manager; + } + + // Other plugins may set the game mode when a player changes world, so this goes last + @EventHandler(priority = EventPriority.MONITOR) + public void onChangedWorld(PlayerChangedWorldEvent e) { + Player player = e.getPlayer(); + boolean was = manager.isWorkshopWorld(e.getFrom()); + boolean is = manager.isWorkshopWorld(player.getWorld()); + if (is && !was) { + manager.playerEntered(player, player.getGameMode()); + player.setGameMode(GameMode.CREATIVE); + } else if (was && !is) { + GameMode mode = manager.playerLeft(player); + player.setGameMode(mode == null ? Bukkit.getDefaultGameMode() : mode); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(PlayerJoinEvent e) { + Player player = e.getPlayer(); + if (manager.isWorkshopWorld(player.getWorld())) { + // They were here when they left, or the server was stopped + manager.playerEntered(player, Bukkit.getDefaultGameMode()); + player.setGameMode(GameMode.CREATIVE); + return; + } + GameMode mode = manager.takeDisplaced(player.getUniqueId()); + if (mode != null) { + // The workshop they were in has gone + player.setGameMode(mode); + Bukkit.getScheduler().runTask(addon.getPlugin(), () -> manager.sendOut(player)); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onDeath(PlayerDeathEvent e) { + Player player = e.getEntity(); + if (manager.isWorkshopWorld(player.getWorld())) { + deaths.put(player.getUniqueId(), player.getLocation()); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onRespawn(PlayerRespawnEvent e) { + Location death = deaths.remove(e.getPlayer().getUniqueId()); + if (death != null && manager.isWorkshopWorld(death.getWorld())) { + e.setRespawnLocation(death); + // The game mode cannot be changed until the player is back in the world + Bukkit.getScheduler().runTask(addon.getPlugin(), () -> e.getPlayer().setGameMode(GameMode.CREATIVE)); + } + } +} diff --git a/src/main/java/world/bentobox/boxed/workshop/BiomeStyles.java b/src/main/java/world/bentobox/boxed/workshop/BiomeStyles.java new file mode 100644 index 0000000..e82b2f4 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/workshop/BiomeStyles.java @@ -0,0 +1,85 @@ +package world.bentobox.boxed.workshop; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import org.eclipse.jdt.annotation.Nullable; + +/** + * The biome layouts an admin can pick from. A style is a biomes file: {@code biomes.yml} is + * the style called "original" and every file in the {@code biomes} folder is a style named + * after the file. Admins make their own by copying one of those files. + * + * @author tastybento + */ +public final class BiomeStyles { + + /** + * Name of the style that Boxed has always had + */ + public static final String ORIGINAL = "original"; + /** + * Folder that holds the other styles + */ + public static final String FOLDER = "biomes"; + private static final String ORIGINAL_FILE = "biomes.yml"; + private static final String YML = ".yml"; + + private BiomeStyles() { + } + + /** + * @param dataFolder the addon's folder + * @return the names of the styles, the original first + */ + public static List list(File dataFolder) { + List names = new ArrayList<>(); + names.add(ORIGINAL); + String[] files = new File(dataFolder, FOLDER).list((dir, name) -> name.endsWith(YML)); + if (files != null) { + Arrays.sort(files); + for (String file : files) { + names.add(file.substring(0, file.length() - YML.length())); + } + } + return names; + } + + /** + * @param dataFolder the addon's folder + * @param style name of a style, or the name of a biomes file in the addon's folder + * @return the biomes file relative to the addon's folder, or null if there is no such style + */ + @Nullable + public static String file(File dataFolder, String style) { + if (ORIGINAL.equalsIgnoreCase(style)) { + return ORIGINAL_FILE; + } + // Names come from commands, so they must not be able to point outside the folder + if (!style.matches("[A-Za-z0-9_.-]+") || style.contains("..")) { + return null; + } + String inFolder = FOLDER + "/" + style.toLowerCase(Locale.ENGLISH) + YML; + if (new File(dataFolder, inFolder).isFile()) { + return inFolder; + } + return style.endsWith(YML) && new File(dataFolder, style).isFile() ? style : null; + } + + /** + * @param file a biomes file relative to the addon's folder + * @return the name of the style it is + */ + public static String name(String file) { + if (ORIGINAL_FILE.equals(file)) { + return ORIGINAL; + } + String prefix = FOLDER + "/"; + return file.startsWith(prefix) && file.endsWith(YML) + ? file.substring(prefix.length(), file.length() - YML.length()) + : file; + } +} diff --git a/src/main/java/world/bentobox/boxed/workshop/Workshop.java b/src/main/java/world/bentobox/boxed/workshop/Workshop.java new file mode 100644 index 0000000..0310f08 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/workshop/Workshop.java @@ -0,0 +1,166 @@ +package world.bentobox.boxed.workshop; + +import java.io.File; +import java.io.IOException; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; + +import org.bukkit.GameMode; +import org.bukkit.World.Environment; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.eclipse.jdt.annotation.Nullable; + +/** + * An area that an admin is working on. It is saved every time it changes, so it is still + * there after a restart. + * + * @author tastybento + */ +public class Workshop { + + private static final String PLAYERS_KEY = "players"; + private static final String BIOMES_KEY = "biomes"; + private static final String CENTRES_KEY = "centres"; + + private final long seed; + private final String biomes; + private final String area; + private final Map centres = new EnumMap<>(Environment.class); + private final Map players = new HashMap<>(); + + /** + * @param seed world seed of the land + * @param biomes name of the biomes file, relative to the addon's folder + * @param area name of the existing area this started from, or null if it is a new one + */ + public Workshop(long seed, String biomes, @Nullable String area) { + this.seed = seed; + this.biomes = biomes; + this.area = area; + } + + /** + * @return world seed of the land + */ + public long getSeed() { + return seed; + } + + /** + * @return name of the biomes file, relative to the addon's folder + */ + public String getBiomes() { + return biomes; + } + + /** + * @return name of the existing area this started from, or null if it is a new one + */ + @Nullable + public String getArea() { + return area; + } + + /** + * @param env dimension + * @return block x and z of the place that will be the middle of every box + */ + public int[] getCentre(Environment env) { + return centres.getOrDefault(env, new int[] { 0, 0 }).clone(); + } + + /** + * @param env dimension + * @param x block x of the place that will be the middle of every box + * @param z block z + */ + public void setCentre(Environment env, int x, int z) { + centres.put(env, new int[] { x, z }); + } + + /** + * Notes a player who has come in, and the game mode to give back when they leave. + * @param uuid player + * @param mode the game mode they had outside + */ + public void addPlayer(UUID uuid, GameMode mode) { + players.putIfAbsent(uuid, mode); + } + + /** + * @param uuid player who has left + * @return the game mode they had outside, or null if they were not known to be inside + */ + @Nullable + public GameMode removePlayer(UUID uuid) { + return players.remove(uuid); + } + + /** + * @return the players who are inside, online or not, and the game mode each had outside + */ + public Map getPlayers() { + return Map.copyOf(players); + } + + /** + * @param file file to save to + * @throws IOException if the file cannot be written + */ + public void save(File file) throws IOException { + YamlConfiguration config = new YamlConfiguration(); + config.set("seed", seed); + config.set(BIOMES_KEY, biomes); + config.set("area", area); + centres.forEach((env, c) -> config.set(CENTRES_KEY + "." + env.name().toLowerCase(Locale.ENGLISH), c[0] + "," + c[1])); + players.forEach((uuid, mode) -> config.set(PLAYERS_KEY + "." + uuid, mode.name())); + File parent = file.getParentFile(); + if (parent != null) { + parent.mkdirs(); + } + config.save(file); + } + + /** + * @param file file written by {@link #save(File)} + * @return the workshop, or null if the file does not exist or does not hold one + */ + @Nullable + public static Workshop load(File file) { + if (!file.exists()) { + return null; + } + YamlConfiguration config = YamlConfiguration.loadConfiguration(file); + if (!config.contains("seed") || config.getString(BIOMES_KEY) == null) { + return null; + } + Workshop workshop = new Workshop(config.getLong("seed"), config.getString(BIOMES_KEY), config.getString("area")); + ConfigurationSection c = config.getConfigurationSection(CENTRES_KEY); + if (c != null) { + for (String key : c.getKeys(false)) { + String[] xz = c.getString(key, "").split(","); + try { + workshop.setCentre(Environment.valueOf(key.toUpperCase(Locale.ENGLISH)), + Integer.parseInt(xz[0].trim()), Integer.parseInt(xz[1].trim())); + } catch (IllegalArgumentException | ArrayIndexOutOfBoundsException _) { + // A centre that cannot be read is left at 0,0 + } + } + } + ConfigurationSection p = config.getConfigurationSection(PLAYERS_KEY); + if (p != null) { + for (String key : p.getKeys(false)) { + try { + workshop.addPlayer(UUID.fromString(key), GameMode.valueOf(p.getString(key, ""))); + } catch (IllegalArgumentException _) { + // Not a player entry + } + } + } + return workshop; + } +} diff --git a/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java b/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java new file mode 100644 index 0000000..0bfeb38 --- /dev/null +++ b/src/main/java/world/bentobox/boxed/workshop/WorkshopManager.java @@ -0,0 +1,414 @@ +package world.bentobox.boxed.workshop; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; + +import org.bukkit.Bukkit; +import org.bukkit.Difficulty; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.WorldCreator; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.entity.SpawnCategory; +import org.eclipse.jdt.annotation.Nullable; + +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.areas.Area; +import world.bentobox.boxed.generators.biomes.AbstractSeedBiomeProvider; +import world.bentobox.boxed.generators.biomes.NetherSeedBiomeGenerator; +import world.bentobox.boxed.generators.biomes.SeedBiomeGenerator; +import world.bentobox.boxed.generators.chunks.BoxedSeedChunkGenerator; + +/** + * Runs the workshop: the worlds where an admin tries out a seed and a biome style, picks + * the place that will be the middle of every box and shapes the land before it becomes an + * area. There is one workshop at a time. It stays, with its worlds, until it is thrown away + * or made into an area, including over restarts. + * + * @author tastybento + */ +public class WorkshopManager { + + /** + * Name of the workshop's overworld inside the game world's folder + */ + public static final String WORLD = "workshop"; + private static final String NETHER = "_nether"; + private static final int NETHER_FLOOR = 32; + private static final int NETHER_ROOF = 110; + + private final Boxed addon; + private final File areasFolder; + private final File file; + private final File displacedFile; + private final Map worlds = new EnumMap<>(Environment.class); + private final Map biomes = new EnumMap<>(Environment.class); + private final Map displaced = new HashMap<>(); + private Workshop workshop; + private boolean closing; + + /** + * @param addon Boxed + */ + public WorkshopManager(Boxed addon) { + this.addon = addon; + this.areasFolder = new File(addon.getDataFolder(), "areas"); + this.file = new File(areasFolder, "workshop.yml"); + this.displacedFile = new File(areasFolder, "displaced.yml"); + } + + /** + * Brings back the workshop that was in progress when the server stopped, with its worlds. + * Call once the game worlds exist. + */ + public void load() { + YamlConfiguration config = YamlConfiguration.loadConfiguration(displacedFile); + for (String key : config.getKeys(false)) { + try { + displaced.put(UUID.fromString(key), GameMode.valueOf(config.getString(key, ""))); + } catch (IllegalArgumentException _) { + // Not a player entry + } + } + workshop = Workshop.load(file); + if (workshop == null) { + return; + } + addon.log("An area is being worked on (seed " + workshop.getSeed() + "). Loading its worlds..."); + for (Environment env : List.of(Environment.NORMAL, Environment.NETHER)) { + File folder = worldFolder(env); + if (folder != null && folder.isDirectory()) { + getWorld(env); + } + } + } + + /** + * @return the area being worked on, if there is one + */ + public Optional get() { + return closing ? Optional.empty() : Optional.ofNullable(workshop); + } + + /** + * @param world a world + * @return true if it is one of the workshop's worlds + */ + public boolean isWorkshopWorld(@Nullable World world) { + return world != null && worlds.containsValue(world); + } + + /** + * @param env dimension + * @return true if the workshop can have this dimension + */ + public boolean hasDimension(Environment env) { + return env == Environment.NORMAL || (env == Environment.NETHER && addon.getSettings().isNetherGenerate()); + } + + private static String suffix(Environment env) { + return env == Environment.NETHER ? NETHER : ""; + } + + private String worldName(Environment env) { + return addon.getSettings().getWorldName().toLowerCase(Locale.ENGLISH) + "/" + WORLD + suffix(env); + } + + /** + * Worlds made by Boxed are kept in folders inside the game world's own folder. + * @return where a workshop world is kept, or null if the game world is not loaded + */ + @Nullable + private File worldFolder(Environment env) { + World overWorld = addon.getOverWorld(); + return overWorld == null ? null : new File(overWorld.getWorldFolder(), WORLD + suffix(env)); + } + + /** + * Starts work on an area. + * @param seed world seed of the land + * @param biomesFile the biomes file to use, relative to the addon's folder + * @param area an existing area to start from, or null for a new one. If the seed and + * biomes are the area's own, the workshop starts as a copy of the land the + * area was built from, so changes made to it by hand are kept. + * @return the new workshop + * @throws IOException if the workshop cannot be saved + * @throws IllegalStateException if an area is already being worked on + */ + public Workshop start(long seed, String biomesFile, @Nullable Area area) throws IOException { + if (workshop != null) { + throw new IllegalStateException("An area is already being worked on"); + } + Workshop w = new Workshop(seed, biomesFile, area == null ? null : area.id()); + if (area != null) { + w.setCentre(Environment.NORMAL, area.centreX(), area.centreZ()); + w.setCentre(Environment.NETHER, area.netherCentreX(), area.netherCentreZ()); + if (seed == area.seed() && biomesFile.equals(area.biomes())) { + copySeedWorld(area, Environment.NORMAL); + copySeedWorld(area, Environment.NETHER); + } + } + w.save(file); + workshop = w; + return w; + } + + private void copySeedWorld(Area area, Environment env) { + File to = worldFolder(env); + if (to == null || to.exists()) { + return; + } + String name = area.seedWorldName("", env == Environment.NETHER).substring(1); + File from = new File(to.getParentFile(), name); + if (!from.isDirectory() || Bukkit.getWorld(area.seedWorldName( + addon.getSettings().getWorldName().toLowerCase(Locale.ENGLISH), env == Environment.NETHER)) != null) { + return; + } + try (Stream files = Files.walk(from.toPath())) { + for (Path path : files.toList()) { + Path target = to.toPath().resolve(from.toPath().relativize(path).toString()); + if (Files.isDirectory(path)) { + Files.createDirectories(target); + } else if (!path.getFileName().toString().equals("session.lock")) { + Files.copy(path, target); + } + } + } catch (IOException e) { + addon.logWarning("Could not copy the land of area " + area.id() + ", so it will be generated again: " + + e.getMessage()); + } + } + + /** + * Gets a world of the workshop, making or loading it if needed. This can take a few + * seconds the first time. Call on the main thread. + * @param env dimension + * @return the world, or null if there is no workshop or the world could not be made + */ + @Nullable + public World getWorld(Environment env) { + if (workshop == null || closing || !hasDimension(env)) { + return null; + } + World world = worlds.get(env); + if (world != null) { + return world; + } + int[] centre = workshop.getCentre(env); + AbstractSeedBiomeProvider provider = env == Environment.NETHER + ? new NetherSeedBiomeGenerator(addon, workshop.getBiomes(), centre[0], centre[1]) + : new SeedBiomeGenerator(addon, workshop.getBiomes(), centre[0], centre[1]); + world = WorldCreator.name(worldName(env)).generator(new BoxedSeedChunkGenerator(addon, env, provider)) + .environment(env).seed(workshop.getSeed()).createWorld(); + if (world == null) { + addon.logError("Could not make the workshop world " + worldName(env)); + return null; + } + // Nothing should change the land except the admin + world.setDifficulty(Difficulty.PEACEFUL); + for (SpawnCategory category : SpawnCategory.values()) { + if (category != SpawnCategory.MISC) { + world.setSpawnLimit(category, 0); + } + } + worlds.put(env, world); + biomes.put(env, provider); + return world; + } + + /** + * Takes a player to the middle of the workshop. + * @param player player + * @param env dimension + * @return true once the player is there, false if they could not be taken + */ + public CompletableFuture enter(Player player, Environment env) { + World world = getWorld(env); + if (world == null) { + return CompletableFuture.completedFuture(false); + } + int[] centre = workshop.getCentre(env); + return world.getChunkAtAsync(centre[0] >> 4, centre[1] >> 4).thenCompose(chunk -> player + .teleportAsync(new Location(world, centre[0] + 0.5, standingHeight(world, centre[0], centre[1]), + centre[1] + 0.5))); + } + + /** + * @return the height to put a player at so that they are standing on the ground + */ + static int standingHeight(World world, int x, int z) { + if (world.getEnvironment() != Environment.NETHER) { + return world.getHighestBlockYAt(x, z) + 1; + } + // The Nether has a roof, so look for a floor with room above it instead + for (int y = NETHER_ROOF; y > NETHER_FLOOR; y--) { + if (world.getBlockAt(x, y, z).getType().isSolid() && world.getBlockAt(x, y + 1, z).getType().isAir() + && world.getBlockAt(x, y + 2, z).getType().isAir()) { + return y + 1; + } + } + return 64; + } + + /** + * Notes that a player has come into the workshop. + * @param player player + * @param mode the game mode they had outside + */ + public void playerEntered(Player player, GameMode mode) { + if (workshop != null) { + workshop.addPlayer(player.getUniqueId(), mode); + save(); + } + } + + /** + * Notes that a player has left the workshop. + * @param player player + * @return the game mode they had outside, or null if it is not known + */ + @Nullable + public GameMode playerLeft(Player player) { + GameMode mode = workshop == null ? null : workshop.removePlayer(player.getUniqueId()); + if (mode != null) { + save(); + } + return mode; + } + + /** + * Checks whether a player was in the workshop when it was removed while they were away. + * @param uuid player + * @return the game mode they had before they went in, or null if they were not + */ + @Nullable + public GameMode takeDisplaced(UUID uuid) { + GameMode mode = displaced.remove(uuid); + if (mode != null) { + saveDisplaced(); + } + return mode; + } + + /** + * Sends a player out of the workshop: to their box if they have one, otherwise to the + * game's spawn, otherwise to the server's. + * @param player player + * @return completes when the player has been moved + */ + public CompletableFuture sendOut(Player player) { + World overWorld = addon.getOverWorld(); + if (overWorld != null && addon.getIslands().hasIsland(overWorld, player.getUniqueId())) { + return addon.getIslands().homeTeleportAsync(overWorld, player); + } + Location spawn = overWorld == null ? null : addon.getIslands().getSpawnPoint(overWorld); + return player.teleportAsync(spawn == null ? Bukkit.getWorlds().get(0).getSpawnLocation() : spawn); + } + + /** + * Throws the workshop away. Everyone in it is sent out first, and its worlds are deleted. + * @return completes with true when it has gone, or false if there was nothing to remove + */ + public CompletableFuture discard() { + if (workshop == null || closing) { + return CompletableFuture.completedFuture(false); + } + closing = true; + List> moves = new ArrayList<>(); + for (World world : worlds.values()) { + world.getPlayers().forEach(p -> moves.add(sendOut(p))); + } + CompletableFuture done = new CompletableFuture<>(); + CompletableFuture.allOf(moves.toArray(CompletableFuture[]::new)).whenComplete( + (v, error) -> Bukkit.getScheduler().runTask(addon.getPlugin(), () -> done.complete(remove()))); + return done; + } + + /** + * Unloads and deletes the worlds and forgets the workshop. Call on the main thread. + */ + private boolean remove() { + // Players who could not be sent anywhere better go to the server's spawn + Location fallback = Bukkit.getWorlds().get(0).getSpawnLocation(); + List folders = new ArrayList<>(); + boolean unloaded = true; + for (World world : worlds.values()) { + List.copyOf(world.getPlayers()).forEach(p -> p.teleport(fallback)); + File folder = world.getWorldFolder(); + if (Bukkit.unloadWorld(world, false)) { + folders.add(folder); + } else { + addon.logWarning("Could not unload " + world.getName() + ". Delete its folder when the server is stopped."); + unloaded = false; + } + } + // Players who are away will find the world gone when they come back + displaced.putAll(workshop.getPlayers()); + Bukkit.getOnlinePlayers().forEach(p -> displaced.remove(p.getUniqueId())); + saveDisplaced(); + worlds.clear(); + biomes.clear(); + workshop = null; + closing = false; + try { + Files.deleteIfExists(file.toPath()); + } catch (IOException e) { + addon.logError("Could not delete " + file + ": " + e.getMessage()); + } + Bukkit.getScheduler().runTaskAsynchronously(addon.getPlugin(), () -> folders.forEach(this::delete)); + return unloaded; + } + + private void delete(File folder) { + // Be very sure this is a workshop world before deleting anything + if (!folder.getName().startsWith(WORLD) || !folder.isDirectory()) { + return; + } + try (Stream files = Files.walk(folder.toPath())) { + for (Path path : files.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(path); + } + } catch (IOException e) { + addon.logWarning("Could not delete " + folder + ": " + e.getMessage()); + } + } + + private void save() { + try { + workshop.save(file); + } catch (IOException e) { + addon.logError("Could not save " + file + ": " + e.getMessage()); + } + } + + private void saveDisplaced() { + YamlConfiguration config = new YamlConfiguration(); + displaced.forEach((uuid, mode) -> config.set(uuid.toString(), mode.name())); + try { + if (displaced.isEmpty()) { + Files.deleteIfExists(displacedFile.toPath()); + } else { + Files.createDirectories(areasFolder.toPath()); + config.save(displacedFile); + } + } catch (IOException e) { + addon.logError("Could not save " + displacedFile + ": " + e.getMessage()); + } + } +} diff --git a/src/main/resources/areas.yml b/src/main/resources/areas.yml index 8c2435e..e330c3d 100644 --- a/src/main/resources/areas.yml +++ b/src/main/resources/areas.yml @@ -17,6 +17,8 @@ # structures, so the Nether has to be taken from a place that has one. # /boxadmin areas find lists places that do. # biomes - the file that says which biomes are placed around the middle of the area. +# biomes.yml is the original style. The biomes folder has others, for +# example biomes/natural.yml, and you can add your own there. # structures - the file that lists the structures placed in each new box of this area. # enabled - set to false to stop new boxes being made in this area. Boxes already there # are not affected. Default is true. @@ -33,6 +35,8 @@ # make one with /boxadmin areas create [seed], build one again with # /boxadmin areas rebuild [regenerate], check that one can be played to the end with # /boxadmin areas check and look for a better place to start with /boxadmin areas find. +# /boxadmin areas edit opens the workshop, where a seed and a biome style can be tried out +# in a temporary world. # # The land of an area is built once, when the server first starts with the area in this # file, and saved in the areas folder. Changing an area's seed, centres or biomes afterwards does diff --git a/src/main/resources/biomes/natural.yml b/src/main/resources/biomes/natural.yml new file mode 100644 index 0000000..aa076ff --- /dev/null +++ b/src/main/resources/biomes/natural.yml @@ -0,0 +1,79 @@ +# The original layout with the edges between biomes blended, so there are no straight lines. +# blend is how many blocks the edges wander. See biomes.yml for how the lists work. +blend: 28 +distribution: + overworld: + north-east: + - 0.05:CUSTOM + - 0.1:DESERT + - 0.2:SAVANNA + - 0.5:SPARSE_JUNGLE + - 0.65:JUNGLE + - 0.8:BAMBOO_JUNGLE + - 1.0:MANGROVE_SWAMP + south-east: + - 0.05:CUSTOM + - 0.8:SUNFLOWER_PLAINS + - 0.2:FLOWER_FOREST + - 0.3:SAVANNA + - 0.4:BEACH + - 0.5:COLD_OCEAN + north-west: + - 0.05:CUSTOM + - 0.8:WARM_OCEAN + - 1.5:COLD_OCEAN + - 2.0:OCEAN + south-west: + - 0.04:CUSTOM + - 0.05:DARK_FOREST + - 0.06:BIRCH_FOREST + - 0.07:FOREST + - 0.09:OLD_GROWTH_PINE_TAIGA + - 0.12:TAIGA + - 0.25:SNOWY_BEACH + - 0.3:FROZEN_OCEAN + - 0.5:ICE_SPIKES + - 0.7:TAIGA + - 1.1:SNOWY_PLAINS + - 2.1:SNOWY_TAIGA + nether: + north-east: + - 0.1:CUSTOM + - 0.14:CRIMSON_FOREST + - 0.26:NETHER_WASTES + - 0.51:WARPED_FOREST + - 0.76:NETHER_WASTES + - 1.1:CRIMSON_FOREST + - 1.36:SOUL_SAND_VALLEY + - 1.6:BASALT_DELTAS + - 2.1:NETHER_WASTES + south-east: + - 0.03:CUSTOM + - 0.05:CRIMSON_FOREST + - 0.23:NETHER_WASTES + - 0.48:WARPED_FOREST + - 0.70:NETHER_WASTES + - 1.0:CRIMSON_FOREST + - 1.2:SOUL_SAND_VALLEY + - 1.9:BASALT_DELTAS + - 2.0:NETHER_WASTES + north-west: + - 0.10:CUSTOM + - 0.15:CRIMSON_FOREST + - 0.20:NETHER_WASTES + - 0.3:WARPED_FOREST + - 0.5:NETHER_WASTES + - 1.0:CRIMSON_FOREST + - 1.25:SOUL_SAND_VALLEY + - 1.5:BASALT_DELTAS + - 2.0:NETHER_WASTES + south-west: + - 0.03:CUSTOM + - 0.11:CRIMSON_FOREST + - 0.22:NETHER_WASTES + - 0.51:WARPED_FOREST + - 0.73:NETHER_WASTES + - 1.1:CRIMSON_FOREST + - 1.26:SOUL_SAND_VALLEY + - 1.54:BASALT_DELTAS + - 2.1:NETHER_WASTES diff --git a/src/main/resources/biomes/none.yml b/src/main/resources/biomes/none.yml new file mode 100644 index 0000000..c820f83 --- /dev/null +++ b/src/main/resources/biomes/none.yml @@ -0,0 +1,2 @@ +# No chosen biomes: every box has the biomes that the seed has at that place. +distribution: {} diff --git a/src/main/resources/biomes/random.yml b/src/main/resources/biomes/random.yml new file mode 100644 index 0000000..e32dfc6 --- /dev/null +++ b/src/main/resources/biomes/random.yml @@ -0,0 +1,38 @@ +# Square patches of biomes picked at random from a list. +# size is the width of a patch in blocks. The patch in the middle of the box always gets the +# first biome in the list, and CUSTOM means "leave the biome the seed has". List a biome more +# than once to make it more common. The pattern is the same for every area that uses this file. +# blend is how many blocks the edges between patches wander. +blend: 24 +distribution: + overworld: + patches: + size: 96 + biomes: + - CUSTOM + - FOREST + - PLAINS + - DESERT + - SAVANNA + - JUNGLE + - TAIGA + - SNOWY_PLAINS + - SWAMP + - DARK_FOREST + - BIRCH_FOREST + - CHERRY_GROVE + - MANGROVE_SWAMP + - WARM_OCEAN + - ICE_SPIKES + - BADLANDS + - MUSHROOM_FIELDS + nether: + patches: + size: 64 + biomes: + - CUSTOM + - NETHER_WASTES + - CRIMSON_FOREST + - WARPED_FOREST + - SOUL_SAND_VALLEY + - BASALT_DELTAS diff --git a/src/main/resources/biomes/rings.yml b/src/main/resources/biomes/rings.yml new file mode 100644 index 0000000..4663b20 --- /dev/null +++ b/src/main/resources/biomes/rings.yml @@ -0,0 +1,25 @@ +# Biomes in rings around the middle of the box, the same all the way round. +# Each entry is distance:BIOME. The distance is a fraction of the area's radius, so 1.0 is the +# edge of the biggest possible box. CUSTOM means "leave the biome the seed has". +# blend is how many blocks the edges between biomes wander. 0 makes perfect circles. +blend: 16 +distribution: + overworld: + rings: + - 0.1:CUSTOM + - 0.25:FOREST + - 0.4:PLAINS + - 0.55:DESERT + - 0.7:JUNGLE + - 0.85:TAIGA + - 1.0:SNOWY_PLAINS + - 2.0:OCEAN + nether: + rings: + - 0.1:CUSTOM + - 0.3:CRIMSON_FOREST + - 0.5:NETHER_WASTES + - 0.7:WARPED_FOREST + - 0.85:SOUL_SAND_VALLEY + - 1.0:BASALT_DELTAS + - 2.0:NETHER_WASTES diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml index eb47dbd..4889fb7 100755 --- a/src/main/resources/locales/en-US.yml +++ b/src/main/resources/locales/en-US.yml @@ -609,6 +609,38 @@ boxed: started: '&a Surveying the land of [name]. This takes a few seconds...' result: '&a [description]' report: '&a The full report is in &e [file]' + edit: + description: work on a new area, or change one, in a temporary world + parameters: '[start [biome style] [area] | go [nether] | discard confirm]' + none: '&c No area is being worked on. Start one with &b /[label] areas edit' + exists: '&c An area is already being worked on. Finish it or discard it first.' + unknown-style: '&c There is no biome style with that name. Styles: &e [styles]' + started: '&a Started work on an area with seed &e [seed] &a and the &e [style] &a biome style.' + status: '&a An area is being worked on. Seed &e [seed]&a, biome style &e [style]&a, started from area &e [area]' + ready: '&a The world is ready.' + welcome: '&a You are in the area workshop, in creative mode. Nothing here is permanent until the area is made.' + failed: '&c That did not work. See the console for the reason.' + discard-confirm: '&c This deletes the area being worked on and its worlds. Type &b discard confirm &c to do it.' + discarded: '&a The area that was being worked on has been removed.' + discard-failed: '&c The area was removed, but a world could not be unloaded. See the console.' + dialog: + start-title: Work on an area + start-body: Pick an area to change, or make a new one. Leave the seed empty for a random seed, or to keep the seed of the area you picked. + area: Area + new-area: A new area + seed: Seed + style: Biome style + same-style: Same as the area (original for a new area) + go: Go + cancel: Cancel + status-title: Area in progress + status-body: 'Seed: [seed]. Biome style: [style]. Started from area: [area]' + go-overworld: Go to the overworld + go-nether: Go to the Nether + discard: Discard it + save-for-later: Save for later + discard-title: Discard this area? + discard-body: The temporary worlds and everything done in them will be deleted. Areas that are already made are not affected. find: description: look through a seed for good places to start a box parameters: [seed|random] [search radius] diff --git a/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java b/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java new file mode 100644 index 0000000..d03f5c7 --- /dev/null +++ b/src/test/java/world/bentobox/boxed/commands/AdminAreasEditCommandTest.java @@ -0,0 +1,227 @@ +package world.bentobox.boxed.commands; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +import org.bukkit.World.Environment; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import world.bentobox.bentobox.api.commands.CompositeCommand; +import world.bentobox.bentobox.api.user.User; +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.CommonTestSetup; +import world.bentobox.boxed.areas.Area; +import world.bentobox.boxed.areas.AreaManager; +import world.bentobox.boxed.workshop.Workshop; +import world.bentobox.boxed.workshop.WorkshopManager; + +/** + * Tests the typed form of the area workshop command. + */ +class AdminAreasEditCommandTest extends CommonTestSetup { + + private static final String PREFIX = "boxed.commands.boxadmin.areas.edit."; + + @TempDir + File folder; + + private AdminAreasEditCommand cmd; + private Boxed addon; + private WorkshopManager manager; + private AreaManager areas; + private User user; + + @BeforeEach + void setUpCommand() throws IOException { + addon = mock(Boxed.class); + manager = mock(WorkshopManager.class); + areas = mock(AreaManager.class); + when(addon.getWorkshop()).thenReturn(manager); + when(addon.getAreas()).thenReturn(areas); + when(addon.getDataFolder()).thenReturn(folder); + Files.createDirectories(new File(folder, "biomes").toPath()); + Files.writeString(new File(folder, "biomes/rings.yml").toPath(), ""); + when(manager.get()).thenReturn(Optional.empty()); + when(manager.hasDimension(any())).thenReturn(true); + when(manager.getWorld(any())).thenReturn(world); + when(areas.getArea("icelands")).thenReturn( + new Area("icelands", 99L, "biomes-icelands.yml", "s.yml", 1, true, null, 0, 0, 0, 0, 0)); + + // Once work has started, there is an area in progress + when(manager.start(anyLong(), anyString(), any())).thenAnswer(i -> { + inProgress(); + return manager.get().orElseThrow(); + }); + + CompositeCommand parent = mock(CompositeCommand.class); + when(parent.getAddon()).thenReturn(addon); + when(parent.getTopLabel()).thenReturn("boxadmin"); + when(parent.getPermissionPrefix()).thenReturn(""); + when(parent.getWorld()).thenReturn(world); + when(parent.getSubCommands()).thenReturn(new HashMap<>()); + cmd = new AdminAreasEditCommand(parent); + + // The console + user = mock(User.class); + when(user.isPlayer()).thenReturn(false); + } + + private void inProgress() { + when(manager.get()).thenReturn(Optional.of(new Workshop(5L, "biomes/rings.yml", null))); + } + + @Test + void testSetup() { + assertEquals("edit", cmd.getLabel()); + assertEquals("admin.areas.edit", cmd.getPermission()); + assertFalse(cmd.isOnlyPlayer()); + } + + @Test + void testConsoleIsToldThereIsNothing() { + assertTrue(cmd.execute(user, "edit", List.of())); + verify(user).sendMessage(PREFIX + "none", "[label]", "boxadmin"); + } + + @Test + void testConsoleIsToldWhatIsInProgress() { + inProgress(); + assertTrue(cmd.execute(user, "edit", List.of())); + verify(user).sendMessage(PREFIX + "status", "[seed]", "5", "[style]", "rings", "[area]", "-"); + } + + @Test + void testStartNewArea() throws IOException { + assertTrue(cmd.execute(user, "edit", List.of("start", "1234", "rings"))); + verify(manager).start(1234L, "biomes/rings.yml", null); + verify(user).sendMessage(PREFIX + "started", "[seed]", "1234", "[style]", "rings"); + // The console cannot go there, but the world is made + verify(manager).getWorld(Environment.NORMAL); + verify(user).sendMessage(PREFIX + "ready"); + } + + @Test + void testStartWithRandomSeedAndOriginalStyle() throws IOException { + assertTrue(cmd.execute(user, "edit", List.of("start", "random"))); + verify(manager).start(anyLong(), eq("biomes.yml"), isNull()); + when(manager.get()).thenReturn(Optional.empty()); + assertTrue(cmd.execute(user, "edit", List.of("start", "-1", "original"))); + } + + @Test + void testStartFromAnAreaKeepsItsSeedAndBiomes() throws IOException { + assertTrue(cmd.execute(user, "edit", List.of("start", "same", "same", "icelands"))); + verify(manager).start(99L, "biomes-icelands.yml", areas.getArea("icelands")); + } + + @Test + void testStartFromAnAreaWithAnotherStyle() throws IOException { + assertTrue(cmd.start(user, "", "rings", "ICELANDS")); + verify(manager).start(99L, "biomes/rings.yml", areas.getArea("icelands")); + } + + @Test + void testStartProblems() throws IOException { + assertFalse(cmd.execute(user, "edit", List.of("start", "abc"))); + verify(user).sendMessage("boxed.commands.boxadmin.areas.create.invalid-seed"); + assertFalse(cmd.execute(user, "edit", List.of("start", "1", "nosuch"))); + verify(user).sendMessage(PREFIX + "unknown-style", "[styles]", "original, rings"); + assertFalse(cmd.execute(user, "edit", List.of("start", "1", "rings", "nowhere"))); + verify(user).sendMessage("boxed.commands.boxadmin.areas.unknown-area"); + verify(manager, never()).start(anyLong(), anyString(), any()); + } + + @Test + void testStartWhenOneIsInProgress() throws IOException { + inProgress(); + assertFalse(cmd.execute(user, "edit", List.of("start", "1"))); + verify(user).sendMessage(PREFIX + "exists"); + verify(manager, never()).start(anyLong(), anyString(), any()); + } + + @Test + void testStartThatCannotBeSaved() throws IOException { + doThrow(new IOException("disk full")).when(manager).start(anyLong(), anyString(), any()); + assertFalse(cmd.execute(user, "edit", List.of("start", "1"))); + verify(user).sendMessage(PREFIX + "failed"); + } + + @Test + void testGo() { + assertFalse(cmd.execute(user, "edit", List.of("go"))); + verify(user).sendMessage(PREFIX + "none", "[label]", "boxadmin"); + inProgress(); + assertTrue(cmd.execute(user, "edit", List.of("go", "nether"))); + verify(manager).getWorld(Environment.NETHER); + when(manager.hasDimension(Environment.NETHER)).thenReturn(false); + assertFalse(cmd.execute(user, "edit", List.of("go", "nether"))); + verify(user).sendMessage(PREFIX + "failed"); + } + + @Test + void testPlayerIsTakenThere() { + inProgress(); + when(user.isPlayer()).thenReturn(true); + when(user.getPlayer()).thenReturn(mockPlayer); + when(manager.enter(mockPlayer, Environment.NORMAL)).thenReturn(CompletableFuture.completedFuture(true)); + assertTrue(cmd.execute(user, "edit", List.of("go"))); + verify(user).sendMessage(PREFIX + "welcome"); + } + + @Test + void testDiscardNeedsConfirming() { + inProgress(); + assertFalse(cmd.execute(user, "edit", List.of("discard"))); + verify(user).sendMessage(PREFIX + "discard-confirm"); + verify(manager, never()).discard(); + } + + @Test + void testDiscard() { + inProgress(); + when(manager.discard()).thenReturn(CompletableFuture.completedFuture(true)); + assertTrue(cmd.execute(user, "edit", List.of("discard", "confirm"))); + verify(user).sendMessage(PREFIX + "discarded"); + } + + @Test + void testDiscardNothing() { + assertFalse(cmd.execute(user, "edit", List.of("discard", "confirm"))); + verify(user).sendMessage(PREFIX + "none", "[label]", "boxadmin"); + } + + @Test + void testTabComplete() { + Area icelands = areas.getArea("icelands"); + when(areas.getAreas()).thenReturn(List.of(icelands)); + assertEquals(List.of("start", "go", "discard"), cmd.tabComplete(user, "edit", List.of("edit", "")).orElseThrow()); + assertEquals(List.of("random", "same"), cmd.tabComplete(user, "edit", List.of("edit", "start", "")).orElseThrow()); + assertEquals(List.of("same", "original", "rings"), + cmd.tabComplete(user, "edit", List.of("edit", "start", "1", "")).orElseThrow()); + assertEquals(List.of("icelands"), + cmd.tabComplete(user, "edit", List.of("edit", "start", "1", "rings", "")).orElseThrow()); + assertEquals(List.of("nether"), cmd.tabComplete(user, "edit", List.of("edit", "go", "")).orElseThrow()); + assertEquals(List.of("confirm"), cmd.tabComplete(user, "edit", List.of("edit", "discard", "c")).orElseThrow()); + } +} diff --git a/src/test/java/world/bentobox/boxed/generators/biomes/BiomeLayoutTest.java b/src/test/java/world/bentobox/boxed/generators/biomes/BiomeLayoutTest.java new file mode 100644 index 0000000..2b312ce --- /dev/null +++ b/src/test/java/world/bentobox/boxed/generators/biomes/BiomeLayoutTest.java @@ -0,0 +1,153 @@ +package world.bentobox.boxed.generators.biomes; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.bukkit.block.Biome; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import world.bentobox.boxed.CommonTestSetup; + +/** + * Tests the ways biomes can be laid out around the middle of an area. + */ +class BiomeLayoutTest extends CommonTestSetup { + + private static final int DIST = 320; + private final List errors = new ArrayList<>(); + private Map known; + + @Override + @BeforeEach + public void setUp() { + super.setUp(); + known = Map.of("DESERT", Biome.DESERT, "JUNGLE", Biome.JUNGLE, "FOREST", Biome.FOREST, "PLAINS", + Biome.PLAINS); + } + + @Override + @AfterEach + public void tearDown() throws Exception { + super.tearDown(); + } + + private BiomeLayout layout(String yaml, double blend) throws InvalidConfigurationException { + YamlConfiguration config = new YamlConfiguration(); + config.loadFromString(yaml); + return new BiomeLayout(config, blend, DIST, known::get, errors::add); + } + + @Test + void testQuarters() throws InvalidConfigurationException { + BiomeLayout l = layout(""" + north-east: + - 0.1:CUSTOM + - 0.5:DESERT + - 1.0:JUNGLE + south-west: + - 2.0:FOREST + """, 0); + // North is negative z + assertNull(l.get(10, -10)); + assertEquals(Biome.DESERT, l.get(60, -60)); + assertEquals(Biome.JUNGLE, l.get(200, -200)); + // Beyond the last entry of a quarter + assertNull(l.get(300, -300)); + assertEquals(Biome.FOREST, l.get(-300, 300)); + // Quarters with no list + assertNull(l.get(-60, -60)); + assertNull(l.get(60, 60)); + // Nothing is chosen further out than twice the radius + assertEquals(Biome.FOREST, l.get(0, 640)); + assertNull(l.get(0, 641)); + assertEquals(Set.of(Biome.DESERT, Biome.JUNGLE, Biome.FOREST), l.biomes()); + assertTrue(errors.isEmpty()); + } + + @Test + void testRingsAreTheSameAllTheWayRound() throws InvalidConfigurationException { + BiomeLayout l = layout(""" + rings: + - 0.5:DESERT + - 1.0:JUNGLE + """, 0); + for (int[] d : new int[][] { { 1, 1 }, { -1, 1 }, { 1, -1 }, { -1, -1 } }) { + assertEquals(Biome.DESERT, l.get(50 * d[0], 50 * d[1])); + assertEquals(Biome.JUNGLE, l.get(200 * d[0], 200 * d[1])); + } + } + + @Test + void testPatches() throws InvalidConfigurationException { + BiomeLayout l = layout(""" + patches: + size: 64 + biomes: [CUSTOM, DESERT, JUNGLE, FOREST] + """, 0); + // The patch in the middle gets the first in the list, which here is the seed's own biome + assertNull(l.get(0, 0)); + assertNull(l.get(31, -32)); + Set seen = new java.util.HashSet<>(); + for (int x = -384; x <= 384; x += 64) { + for (int z = -384; z <= 384; z += 64) { + Biome b = l.get(x, z); + seen.add(b); + // A patch is one biome all over, and the same every time it is asked for + assertEquals(b, l.get(x + 10, z - 10)); + } + } + // Every biome in the list is used somewhere + assertEquals(4, seen.size()); + } + + @Test + void testBlendMovesTheEdges() throws InvalidConfigurationException { + String yaml = """ + rings: + - 0.5:DESERT + - 1.0:JUNGLE + """; + BiomeLayout straight = layout(yaml, 0); + BiomeLayout blended = layout(yaml, 24); + int different = 0; + for (int x = -200; x <= 200; x++) { + // The edge between the two rings is 160 blocks out + if (straight.get(x, 160) != blended.get(x, 160)) { + different++; + } + // Blending does not reach far from an edge + assertEquals(Biome.DESERT, blended.get(x / 4, 0)); + } + assertNotEquals(0, different); + } + + @Test + void testMistakesAreReported() throws InvalidConfigurationException { + BiomeLayout l = layout(""" + rings: + - DESERT + - x:JUNGLE + - 1.0:FOREST + """, 0); + assertEquals(2, errors.size()); + assertEquals(Biome.FOREST, l.get(5, 5)); + } + + @Test + void testNoSection() { + BiomeLayout l = new BiomeLayout(null, 0, DIST, known::get, errors::add); + assertNull(l.get(0, 0)); + assertTrue(l.biomes().isEmpty()); + } +} diff --git a/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java b/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java new file mode 100644 index 0000000..b1f5897 --- /dev/null +++ b/src/test/java/world/bentobox/boxed/listeners/WorkshopListenerTest.java @@ -0,0 +1,156 @@ +package world.bentobox.boxed.listeners; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.World; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; + +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.CommonTestSetup; +import world.bentobox.boxed.workshop.WorkshopManager; + +/** + * Tests the rules for players in the workshop worlds. + */ +class WorkshopListenerTest extends CommonTestSetup { + + @Mock + private Boxed addon; + @Mock + private WorkshopManager manager; + @Mock + private World workshopWorld; + + private final UUID uuid = UUID.randomUUID(); + private WorkshopListener listener; + + @Override + @BeforeEach + public void setUp() { + super.setUp(); + when(addon.getPlugin()).thenReturn(plugin); + when(manager.isWorkshopWorld(workshopWorld)).thenReturn(true); + when(mockPlayer.getUniqueId()).thenReturn(uuid); + when(mockPlayer.getGameMode()).thenReturn(GameMode.SURVIVAL); + mockedBukkit.when(Bukkit::getDefaultGameMode).thenReturn(GameMode.ADVENTURE); + listener = new WorkshopListener(addon, manager); + } + + @Override + @AfterEach + public void tearDown() throws Exception { + super.tearDown(); + } + + private void runScheduled() { + ArgumentCaptor task = ArgumentCaptor.forClass(Runnable.class); + verify(sch).runTask(any(), task.capture()); + task.getValue().run(); + } + + @Test + void testComingInGivesCreative() { + when(mockPlayer.getWorld()).thenReturn(workshopWorld); + listener.onChangedWorld(new PlayerChangedWorldEvent(mockPlayer, world)); + verify(manager).playerEntered(mockPlayer, GameMode.SURVIVAL); + verify(mockPlayer).setGameMode(GameMode.CREATIVE); + } + + @Test + void testLeavingGivesTheOldGameModeBack() { + when(mockPlayer.getWorld()).thenReturn(world); + when(manager.playerLeft(mockPlayer)).thenReturn(GameMode.SPECTATOR); + listener.onChangedWorld(new PlayerChangedWorldEvent(mockPlayer, workshopWorld)); + verify(mockPlayer).setGameMode(GameMode.SPECTATOR); + } + + @Test + void testLeavingWithNoOldGameModeGivesTheServerDefault() { + when(mockPlayer.getWorld()).thenReturn(world); + listener.onChangedWorld(new PlayerChangedWorldEvent(mockPlayer, workshopWorld)); + verify(mockPlayer).setGameMode(GameMode.ADVENTURE); + } + + @Test + void testOtherWorldChangesAreLeftAlone() { + when(mockPlayer.getWorld()).thenReturn(world); + listener.onChangedWorld(new PlayerChangedWorldEvent(mockPlayer, mock(World.class))); + // Moving between the workshop's own dimensions changes nothing either + World nether = mock(World.class); + when(manager.isWorkshopWorld(nether)).thenReturn(true); + when(mockPlayer.getWorld()).thenReturn(nether); + listener.onChangedWorld(new PlayerChangedWorldEvent(mockPlayer, workshopWorld)); + verify(mockPlayer, never()).setGameMode(any()); + } + + @Test + void testJoiningInsideGivesCreative() { + when(mockPlayer.getWorld()).thenReturn(workshopWorld); + listener.onJoin(new PlayerJoinEvent(mockPlayer, net.kyori.adventure.text.Component.empty())); + verify(mockPlayer).setGameMode(GameMode.CREATIVE); + verify(manager, never()).takeDisplaced(any()); + } + + @Test + void testJoiningAfterTheWorkshopWentSendsThePlayerOut() { + when(mockPlayer.getWorld()).thenReturn(world); + when(manager.takeDisplaced(uuid)).thenReturn(GameMode.SURVIVAL); + listener.onJoin(new PlayerJoinEvent(mockPlayer, net.kyori.adventure.text.Component.empty())); + verify(mockPlayer).setGameMode(GameMode.SURVIVAL); + runScheduled(); + verify(manager).sendOut(mockPlayer); + } + + @Test + void testJoiningNormallyDoesNothing() { + when(mockPlayer.getWorld()).thenReturn(world); + listener.onJoin(new PlayerJoinEvent(mockPlayer, net.kyori.adventure.text.Component.empty())); + verify(mockPlayer, never()).setGameMode(any()); + verify(manager, never()).sendOut(any()); + } + + @Test + void testDyingInsideComesBackWhereTheyDied() { + when(mockPlayer.getWorld()).thenReturn(workshopWorld); + when(mockPlayer.getLocation()).thenReturn(location); + when(location.getWorld()).thenReturn(workshopWorld); + PlayerDeathEvent death = mock(PlayerDeathEvent.class); + when(death.getEntity()).thenReturn(mockPlayer); + listener.onDeath(death); + + PlayerRespawnEvent respawn = mock(PlayerRespawnEvent.class); + when(respawn.getPlayer()).thenReturn(mockPlayer); + listener.onRespawn(respawn); + verify(respawn).setRespawnLocation(location); + runScheduled(); + verify(mockPlayer).setGameMode(GameMode.CREATIVE); + } + + @Test + void testDyingElsewhereIsLeftAlone() { + when(mockPlayer.getWorld()).thenReturn(world); + PlayerDeathEvent death = mock(PlayerDeathEvent.class); + when(death.getEntity()).thenReturn(mockPlayer); + listener.onDeath(death); + PlayerRespawnEvent respawn = mock(PlayerRespawnEvent.class); + when(respawn.getPlayer()).thenReturn(mockPlayer); + listener.onRespawn(respawn); + verify(respawn, never()).setRespawnLocation(any()); + } +} diff --git a/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java b/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java new file mode 100644 index 0000000..ce51f05 --- /dev/null +++ b/src/test/java/world/bentobox/boxed/workshop/WorkshopManagerTest.java @@ -0,0 +1,267 @@ +package world.bentobox.boxed.workshop; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +import org.bukkit.Bukkit; +import org.bukkit.Difficulty; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.WorldCreator; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.entity.SpawnCategory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; + +import world.bentobox.boxed.Boxed; +import world.bentobox.boxed.CommonTestSetup; +import world.bentobox.boxed.Settings; +import world.bentobox.boxed.areas.Area; + +/** + * Tests the life of the workshop: starting, its worlds, players and throwing it away. + */ +class WorkshopManagerTest extends CommonTestSetup { + + @TempDir + File folder; + @Mock + private Boxed addon; + @Mock + private World workshopWorld; + @Mock + private World mainWorld; + + private File worldFolder; + private File workshopFile; + private WorkshopManager manager; + + @Override + @BeforeEach + public void setUp() { + super.setUp(); + File data = new File(folder, "data"); + worldFolder = new File(folder, "boxed_world"); + workshopFile = new File(data, "areas/workshop.yml"); + when(addon.getDataFolder()).thenReturn(data); + when(addon.getSettings()).thenReturn(new Settings()); + when(addon.getPlugin()).thenReturn(plugin); + when(addon.getOverWorld()).thenReturn(world); + when(addon.getIslands()).thenReturn(im); + when(world.getWorldFolder()).thenReturn(worldFolder); + when(workshopWorld.getWorldFolder()).thenReturn(new File(worldFolder, "workshop")); + when(workshopWorld.getEnvironment()).thenReturn(Environment.NORMAL); + when(workshopWorld.getPlayers()).thenReturn(List.of()); + mockedBukkit.when(() -> Bukkit.createWorld(any(WorldCreator.class))).thenReturn(workshopWorld); + mockedBukkit.when(() -> Bukkit.unloadWorld(any(World.class), any(Boolean.class))).thenReturn(true); + mockedBukkit.when(Bukkit::getWorlds).thenReturn(List.of(mainWorld)); + mockedBukkit.when(Bukkit::getOnlinePlayers).thenReturn(List.of()); + when(mainWorld.getSpawnLocation()).thenReturn(location); + manager = new WorkshopManager(addon); + } + + @Override + @AfterEach + public void tearDown() throws Exception { + super.tearDown(); + } + + private void runScheduled() { + ArgumentCaptor task = ArgumentCaptor.forClass(Runnable.class); + verify(sch).runTask(any(), task.capture()); + task.getValue().run(); + } + + @Test + void testNothingToBeginWith() { + manager.load(); + assertTrue(manager.get().isEmpty()); + assertNull(manager.getWorld(Environment.NORMAL)); + assertFalse(manager.isWorkshopWorld(world)); + assertFalse(manager.discard().join()); + } + + @Test + void testStartSavesAndOnlyOneAtATime() throws IOException { + Workshop w = manager.start(11L, "biomes.yml", null); + assertSame(w, manager.get().orElseThrow()); + assertTrue(workshopFile.exists()); + assertThrows(IllegalStateException.class, () -> manager.start(12L, "biomes.yml", null)); + } + + @Test + void testStartFromAnAreaUsesItsCentres() throws IOException { + Area area = new Area("icelands", 99L, "biomes.yml", "s.yml", 1, true, null, 0, 160, -320, 48, 64); + Workshop w = manager.start(5L, "biomes.yml", area); + assertEquals("icelands", w.getArea()); + assertEquals(160, w.getCentre(Environment.NORMAL)[0]); + assertEquals(64, w.getCentre(Environment.NETHER)[1]); + } + + @Test + void testStartFromAnUnchangedAreaCopiesItsLand() throws IOException { + File seed = new File(worldFolder, "seed_icelands/region"); + Files.createDirectories(seed.toPath()); + Files.writeString(new File(seed, "r.0.0.mca").toPath(), "land"); + Files.writeString(new File(seed.getParentFile(), "session.lock").toPath(), ""); + mockedBukkit.when(() -> Bukkit.getWorld("boxed_world/seed_icelands")).thenReturn(null); + mockedBukkit.when(() -> Bukkit.getWorld("boxed_world/seed_icelands_nether")).thenReturn(null); + Area area = new Area("icelands", 99L, "biomes.yml", "s.yml", 1, true, null, 0, 0, 0, 0, 0); + + manager.start(99L, "biomes.yml", area); + assertEquals("land", Files.readString(new File(worldFolder, "workshop/region/r.0.0.mca").toPath())); + assertFalse(new File(worldFolder, "workshop/session.lock").exists()); + } + + @Test + void testAChangedSeedDoesNotCopyTheLand() throws IOException { + Files.createDirectories(new File(worldFolder, "seed_icelands/region").toPath()); + Area area = new Area("icelands", 99L, "biomes.yml", "s.yml", 1, true, null, 0, 0, 0, 0, 0); + manager.start(100L, "biomes.yml", area); + assertFalse(new File(worldFolder, "workshop").exists()); + } + + @Test + void testWorldIsPeacefulWithNoSpawning() throws IOException { + manager.start(11L, "biomes.yml", null); + World w = manager.getWorld(Environment.NORMAL); + assertSame(workshopWorld, w); + assertTrue(manager.isWorkshopWorld(w)); + verify(workshopWorld).setDifficulty(Difficulty.PEACEFUL); + verify(workshopWorld).setSpawnLimit(SpawnCategory.MONSTER, 0); + verify(workshopWorld).setSpawnLimit(SpawnCategory.ANIMAL, 0); + // Asking again does not make it again + assertSame(w, manager.getWorld(Environment.NORMAL)); + mockedBukkit.verify(() -> Bukkit.createWorld(any(WorldCreator.class))); + // There is no End yet + assertNull(manager.getWorld(Environment.THE_END)); + } + + @Test + void testLoadBringsTheWorldsBack() throws IOException { + new Workshop(11L, "biomes.yml", null).save(workshopFile); + Files.createDirectories(new File(worldFolder, "workshop").toPath()); + manager.load(); + assertNotNull(manager.get().orElseThrow()); + assertTrue(manager.isWorkshopWorld(workshopWorld)); + // The Nether was never visited, so it is not made + mockedBukkit.verify(() -> Bukkit.createWorld(any(WorldCreator.class))); + } + + @Test + void testPlayersAreRemembered() throws IOException { + manager.start(11L, "biomes.yml", null); + when(mockPlayer.getUniqueId()).thenReturn(UUID.randomUUID()); + manager.playerEntered(mockPlayer, GameMode.SURVIVAL); + assertEquals(GameMode.SURVIVAL, Workshop.load(workshopFile).getPlayers().get(mockPlayer.getUniqueId())); + assertEquals(GameMode.SURVIVAL, manager.playerLeft(mockPlayer)); + assertNull(manager.playerLeft(mockPlayer)); + assertTrue(Workshop.load(workshopFile).getPlayers().isEmpty()); + } + + @Test + void testDiscardRemovesEverything() throws IOException { + manager.start(11L, "biomes.yml", null); + manager.getWorld(Environment.NORMAL); + // Someone who is inside but not online + UUID away = UUID.randomUUID(); + Player awayPlayer = mock(Player.class); + when(awayPlayer.getUniqueId()).thenReturn(away); + manager.playerEntered(awayPlayer, GameMode.ADVENTURE); + // Someone who is inside and online, and has no box + when(workshopWorld.getPlayers()).thenReturn(List.of(mockPlayer)); + when(mockPlayer.teleportAsync(any())).thenReturn(CompletableFuture.completedFuture(true)); + + CompletableFuture done = manager.discard(); + // Nothing can be started while it is going + assertTrue(manager.get().isEmpty()); + runScheduled(); + assertTrue(done.join()); + verify(mockPlayer).teleportAsync(location); + mockedBukkit.verify(() -> Bukkit.unloadWorld(workshopWorld, false)); + assertFalse(workshopFile.exists()); + assertFalse(manager.isWorkshopWorld(workshopWorld)); + // The player who was away gets their game mode back when they return, once + assertEquals(GameMode.ADVENTURE, manager.takeDisplaced(away)); + assertNull(manager.takeDisplaced(away)); + // And it is remembered over a restart until then + manager.start(12L, "biomes.yml", null); + } + + @Test + void testDisplacedPlayersSurviveARestart() throws IOException { + manager.start(11L, "biomes.yml", null); + manager.getWorld(Environment.NORMAL); + UUID away = UUID.randomUUID(); + Player awayPlayer = mock(Player.class); + when(awayPlayer.getUniqueId()).thenReturn(away); + manager.playerEntered(awayPlayer, GameMode.ADVENTURE); + manager.discard(); + runScheduled(); + + WorkshopManager restarted = new WorkshopManager(addon); + restarted.load(); + assertEquals(GameMode.ADVENTURE, restarted.takeDisplaced(away)); + } + + @Test + void testSendOutGoesToTheBoxIfThereIsOne() { + UUID uuid = UUID.randomUUID(); + when(mockPlayer.getUniqueId()).thenReturn(uuid); + when(im.hasIsland(world, uuid)).thenReturn(true); + when(im.homeTeleportAsync(world, mockPlayer)).thenReturn(CompletableFuture.completedFuture(true)); + assertTrue(manager.sendOut(mockPlayer).join()); + verify(mockPlayer, never()).teleportAsync(any()); + } + + @Test + void testSendOutGoesToTheGameSpawnNext() { + Location spawn = mock(Location.class); + when(mockPlayer.getUniqueId()).thenReturn(UUID.randomUUID()); + when(im.getSpawnPoint(world)).thenReturn(spawn); + when(mockPlayer.teleportAsync(spawn)).thenReturn(CompletableFuture.completedFuture(true)); + assertTrue(manager.sendOut(mockPlayer).join()); + } + + @Test + void testStandingHeight() { + when(workshopWorld.getHighestBlockYAt(3, 4)).thenReturn(70); + assertEquals(71, WorkshopManager.standingHeight(workshopWorld, 3, 4)); + // The Nether has a roof, so the floor is looked for under it + World nether = mock(World.class); + when(nether.getEnvironment()).thenReturn(Environment.NETHER); + Block air = mock(Block.class); + when(air.getType()).thenReturn(Material.AIR); + Block rock = mock(Block.class); + when(rock.getType()).thenReturn(Material.NETHERRACK); + when(nether.getBlockAt(any(Integer.class), any(Integer.class), any(Integer.class))).thenReturn(rock); + when(nether.getBlockAt(3, 51, 4)).thenReturn(air); + when(nether.getBlockAt(3, 52, 4)).thenReturn(air); + assertEquals(51, WorkshopManager.standingHeight(nether, 3, 4)); + } +} diff --git a/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java b/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java new file mode 100644 index 0000000..9534cf5 --- /dev/null +++ b/src/test/java/world/bentobox/boxed/workshop/WorkshopTest.java @@ -0,0 +1,108 @@ +package world.bentobox.boxed.workshop; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; +import java.util.UUID; + +import org.bukkit.GameMode; +import org.bukkit.World.Environment; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Tests that an area being worked on is saved and read back, and the names of biome styles. + */ +class WorkshopTest { + + @TempDir + File folder; + + @Test + void testSaveAndLoad() throws IOException { + UUID uuid = UUID.randomUUID(); + Workshop w = new Workshop(-42L, "biomes/natural.yml", "icelands"); + w.setCentre(Environment.NORMAL, 1664, -1536); + w.addPlayer(uuid, GameMode.SURVIVAL); + // The first game mode is the one from outside, so it is kept + w.addPlayer(uuid, GameMode.CREATIVE); + File file = new File(folder, "areas/workshop.yml"); + w.save(file); + + Workshop loaded = Workshop.load(file); + assertNotNull(loaded); + assertEquals(-42L, loaded.getSeed()); + assertEquals("biomes/natural.yml", loaded.getBiomes()); + assertEquals("icelands", loaded.getArea()); + assertArrayEquals(new int[] { 1664, -1536 }, loaded.getCentre(Environment.NORMAL)); + assertArrayEquals(new int[] { 0, 0 }, loaded.getCentre(Environment.NETHER)); + assertEquals(GameMode.SURVIVAL, loaded.getPlayers().get(uuid)); + assertEquals(GameMode.SURVIVAL, loaded.removePlayer(uuid)); + assertNull(loaded.removePlayer(uuid)); + } + + @Test + void testNewAreaHasNoName() throws IOException { + File file = new File(folder, "workshop.yml"); + new Workshop(7L, "biomes.yml", null).save(file); + Workshop loaded = Workshop.load(file); + assertNotNull(loaded); + assertNull(loaded.getArea()); + assertTrue(loaded.getPlayers().isEmpty()); + } + + @Test + void testLoadNothing() throws IOException { + assertNull(Workshop.load(new File(folder, "missing.yml"))); + File junk = new File(folder, "junk.yml"); + Files.writeString(junk.toPath(), "hello: world\n"); + assertNull(Workshop.load(junk)); + } + + @Test + void testBadEntriesAreIgnored() throws IOException { + File file = new File(folder, "workshop.yml"); + Files.writeString(file.toPath(), """ + seed: 5 + biomes: biomes.yml + centres: + normal: here + moon: 1,2 + players: + nobody: SURVIVAL + """); + Workshop loaded = Workshop.load(file); + assertNotNull(loaded); + assertArrayEquals(new int[] { 0, 0 }, loaded.getCentre(Environment.NORMAL)); + assertTrue(loaded.getPlayers().isEmpty()); + } + + @Test + void testBiomeStyles() throws IOException { + Files.createDirectories(new File(folder, "biomes").toPath()); + Files.writeString(new File(folder, "biomes/rings.yml").toPath(), ""); + Files.writeString(new File(folder, "biomes/natural.yml").toPath(), ""); + Files.writeString(new File(folder, "biomes/notes.txt").toPath(), ""); + Files.writeString(new File(folder, "biomes-icelands.yml").toPath(), ""); + + assertEquals(List.of("original", "natural", "rings"), BiomeStyles.list(folder)); + assertEquals("biomes.yml", BiomeStyles.file(folder, "Original")); + assertEquals("biomes/rings.yml", BiomeStyles.file(folder, "RINGS")); + // A biomes file that an older area uses can be named in full + assertEquals("biomes-icelands.yml", BiomeStyles.file(folder, "biomes-icelands.yml")); + assertNull(BiomeStyles.file(folder, "nosuch")); + assertNull(BiomeStyles.file(folder, "../config.yml")); + assertNull(BiomeStyles.file(folder, "biomes/rings")); + + assertEquals("original", BiomeStyles.name("biomes.yml")); + assertEquals("rings", BiomeStyles.name("biomes/rings.yml")); + assertEquals("biomes-icelands.yml", BiomeStyles.name("biomes-icelands.yml")); + } +}