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/generators/biomes/NetherSeedBiomeGenerator.java b/src/main/java/world/bentobox/boxed/generators/biomes/NetherSeedBiomeGenerator.java
index 5119080..86f6341 100644
--- a/src/main/java/world/bentobox/boxed/generators/biomes/NetherSeedBiomeGenerator.java
+++ b/src/main/java/world/bentobox/boxed/generators/biomes/NetherSeedBiomeGenerator.java
@@ -22,4 +22,14 @@ public NetherSeedBiomeGenerator(Boxed boxed) {
public NetherSeedBiomeGenerator(Boxed boxed, String biomesFile) {
super(boxed, Environment.NETHER, biomesFile);
}
+
+ /**
+ * @param boxed addon
+ * @param biomesFile name of the file that defines the biomes
+ * @param centreX block x of the spot the biomes are laid out around
+ * @param centreZ block z of the spot the biomes are laid out around
+ */
+ public NetherSeedBiomeGenerator(Boxed boxed, String biomesFile, int centreX, int centreZ) {
+ super(boxed, Environment.NETHER, biomesFile, centreX, centreZ);
+ }
}
diff --git a/src/main/java/world/bentobox/boxed/generators/biomes/SeedBiomeGenerator.java b/src/main/java/world/bentobox/boxed/generators/biomes/SeedBiomeGenerator.java
index 4456b9f..97c957e 100644
--- a/src/main/java/world/bentobox/boxed/generators/biomes/SeedBiomeGenerator.java
+++ b/src/main/java/world/bentobox/boxed/generators/biomes/SeedBiomeGenerator.java
@@ -22,4 +22,14 @@ public SeedBiomeGenerator(Boxed boxed) {
public SeedBiomeGenerator(Boxed boxed, String biomesFile) {
super(boxed, Environment.NORMAL, biomesFile);
}
+
+ /**
+ * @param boxed addon
+ * @param biomesFile name of the file that defines the biomes
+ * @param centreX block x of the spot the biomes are laid out around
+ * @param centreZ block z of the spot the biomes are laid out around
+ */
+ public SeedBiomeGenerator(Boxed boxed, String biomesFile, int centreX, int centreZ) {
+ super(boxed, Environment.NORMAL, biomesFile, centreX, centreZ);
+ }
}
diff --git a/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java b/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java
index efa16e0..2e4dbb1 100644
--- a/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java
+++ b/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java
@@ -7,12 +7,15 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
+import java.util.function.IntConsumer;
+import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.ChunkSnapshot;
@@ -37,6 +40,7 @@
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Colorable;
+import org.bukkit.plugin.Plugin;
import com.google.gson.Gson;
@@ -121,6 +125,118 @@ public void build(File file, long seed) throws IOException {
}
}
+ /**
+ * Builds the template file while the server keeps running. A column of chunks is
+ * captured each time the server has them ready, so no tick is held up for long. The
+ * chunks are left for the server to unload, which saves them.
+ * @param file file to make
+ * @param seed seed to record in the file
+ * @param plugin plugin to schedule with
+ * @param progress told the percentage done as it goes up, on the main thread
+ * @return completes on the main thread when the file is in place, or with the reason it could not be made
+ */
+ public CompletableFuture buildAsync(File file, long seed, Plugin plugin, IntConsumer progress) {
+ CompletableFuture result = new CompletableFuture<>();
+ int threads = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
+ TemplateFile.Writer writer;
+ try {
+ writer = new TemplateFile.Writer(file, size, seed);
+ } catch (IOException e) {
+ result.completeExceptionally(e);
+ return result;
+ }
+ ExecutorService pool = Executors.newFixedThreadPool(threads, r -> {
+ Thread t = new Thread(r, "Boxed template builder");
+ t.setDaemon(true);
+ return t;
+ });
+ AsyncBuild build = new AsyncBuild(file, writer, pool, new Semaphore(size * 4), new AtomicReference<>(), plugin,
+ progress, result);
+ captureColumn(build, -size);
+ return result;
+ }
+
+ /**
+ * What a build that runs alongside the server carries from one column to the next
+ */
+ private record AsyncBuild(File file, TemplateFile.Writer writer, ExecutorService pool, Semaphore permits,
+ AtomicReference failure, Plugin plugin, IntConsumer progress, CompletableFuture result) {
+ }
+
+ /**
+ * Captures one column of chunks when the server has them, then moves on to the next.
+ */
+ private void captureColumn(AsyncBuild build, int x) {
+ if (x >= size || build.failure().get() != null) {
+ finishAsync(build);
+ return;
+ }
+ List> chunks = new ArrayList<>();
+ for (int z = -size; z < size; z++) {
+ chunks.add(world.getChunkAtAsync(centerX + x, centerZ + z));
+ }
+ CompletableFuture.allOf(chunks.toArray(CompletableFuture[]::new)).whenComplete((v, error) ->
+ // Chunks have to be read on the main thread
+ Bukkit.getScheduler().runTask(build.plugin(), () -> {
+ if (error != null) {
+ build.failure().compareAndSet(null, new IOException(error));
+ } else {
+ captureLoadedColumn(build, x);
+ }
+ captureColumn(build, x + 1);
+ }));
+ }
+
+ private void captureLoadedColumn(AsyncBuild build, int x) {
+ try {
+ for (int z = -size; z < size; z++) {
+ capture(x, z, build.writer(), build.pool(), build.permits(), build.failure());
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ build.failure().compareAndSet(null, e);
+ } catch (RuntimeException e) {
+ build.failure().compareAndSet(null, e);
+ }
+ build.progress().accept((x + size + 1) * 100 / (size * 2));
+ }
+
+ /**
+ * Waits for the last chunks to be compressed, off the main thread, and closes the file.
+ */
+ private void finishAsync(AsyncBuild build) {
+ Bukkit.getScheduler().runTaskAsynchronously(build.plugin(), () -> {
+ build.pool().shutdown();
+ try {
+ if (!build.pool().awaitTermination(10, TimeUnit.MINUTES)) {
+ build.failure().compareAndSet(null, new IOException("Timed out compressing chunks"));
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ build.failure().compareAndSet(null, e);
+ }
+ build.pool().shutdownNow();
+ try {
+ if (build.failure().get() != null) {
+ build.writer().abort();
+ } else {
+ build.writer().close();
+ }
+ } catch (IOException e) {
+ build.failure().compareAndSet(null, e);
+ }
+ Exception failed = build.failure().get();
+ Bukkit.getScheduler().runTask(build.plugin(), () -> {
+ if (failed == null) {
+ build.result().complete(null);
+ } else {
+ build.result().completeExceptionally(
+ new IOException("Could not build " + build.file().getName(), failed));
+ }
+ });
+ });
+ }
+
private void captureAll(File file, TemplateFile.Writer writer, ExecutorService pool, Semaphore permits,
AtomicReference failure) throws InterruptedException {
int total = size * 2 * size * 2;
diff --git a/src/main/java/world/bentobox/boxed/listeners/FortressMobsListener.java b/src/main/java/world/bentobox/boxed/listeners/FortressMobsListener.java
new file mode 100644
index 0000000..bb0610f
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/listeners/FortressMobsListener.java
@@ -0,0 +1,111 @@
+package world.bentobox.boxed.listeners;
+
+import java.util.Random;
+
+import org.bukkit.Location;
+import org.bukkit.Material;
+import org.bukkit.block.Block;
+import org.bukkit.block.BlockFace;
+import org.bukkit.entity.EntityType;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.event.entity.CreatureSpawnEvent;
+import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
+
+import world.bentobox.boxed.Boxed;
+
+/**
+ * Makes the fortress in the Nether of a box work. The Nether is copied block by block, so
+ * the game does not know there is a fortress there and never spawns its mobs. This swaps
+ * some of the mobs that spawn on nether bricks for wither skeletons, blazes and skeletons,
+ * in the same proportions as a real fortress.
+ *
+ * @author tastybento
+ */
+public class FortressMobsListener implements Listener {
+
+ /**
+ * How often each mob spawns in a real fortress, out of {@link #TOTAL}. The rest of the
+ * time the mob the game picked is left alone.
+ */
+ private static final int WITHER_SKELETON = 8;
+ private static final int BLAZE = 10;
+ private static final int SKELETON = 2;
+ private static final int TOTAL = 28;
+ /**
+ * Skeletons need it this dark. Blazes spawn in a little more light.
+ */
+ private static final int DARK = 7;
+ private static final int BLAZE_LIGHT = 11;
+
+ private final Boxed addon;
+ private final Random random;
+ private boolean swapping;
+
+ /**
+ * @param addon addon
+ */
+ public FortressMobsListener(Boxed addon) {
+ this(addon, new Random());
+ }
+
+ /**
+ * @param addon addon
+ * @param random source of the dice rolls
+ */
+ FortressMobsListener(Boxed addon, Random random) {
+ this.addon = addon;
+ this.random = random;
+ }
+
+ /**
+ * Swaps a mob that is spawning on nether bricks for a fortress mob.
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void onSpawn(CreatureSpawnEvent e) {
+ Location loc = e.getLocation();
+ if (swapping || e.getSpawnReason() != SpawnReason.NATURAL || !addon.getSettings().isNetherFortressMobs()
+ || loc.getWorld() == null || !loc.getWorld().equals(addon.getNetherWorld())) {
+ return;
+ }
+ Block feet = loc.getBlock();
+ if (feet.getRelative(BlockFace.DOWN).getType() != Material.NETHER_BRICKS) {
+ return;
+ }
+ EntityType type = pick(feet);
+ if (type == null || type == e.getEntityType()) {
+ return;
+ }
+ e.setCancelled(true);
+ // The new mob fires this event too
+ swapping = true;
+ try {
+ loc.getWorld().spawnEntity(loc, type, SpawnReason.NATURAL);
+ } finally {
+ swapping = false;
+ }
+ }
+
+ /**
+ * @param feet the block the mob spawns in
+ * @return the fortress mob to spawn instead, or null to leave the spawn alone
+ */
+ private EntityType pick(Block feet) {
+ int roll = random.nextInt(TOTAL);
+ int light = feet.getLightFromBlocks();
+ if (roll < WITHER_SKELETON) {
+ // Wither skeletons are nearly three blocks tall
+ boolean room = feet.getRelative(BlockFace.UP).isPassable() && feet.getRelative(BlockFace.UP, 2).isPassable();
+ return light <= DARK && room ? EntityType.WITHER_SKELETON : null;
+ }
+ if (roll < WITHER_SKELETON + BLAZE) {
+ return light <= BLAZE_LIGHT ? EntityType.BLAZE : null;
+ }
+ if (roll < WITHER_SKELETON + BLAZE + SKELETON) {
+ return light <= DARK ? EntityType.SKELETON : null;
+ }
+ return null;
+ }
+}
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..5839822
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/listeners/WorkshopListener.java
@@ -0,0 +1,111 @@
+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 org.bukkit.event.player.PlayerSwapHandItemsEvent;
+
+import world.bentobox.bentobox.api.commands.CompositeCommand;
+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) {
+ // The border that shows the limit of the box does not belong anywhere else
+ player.setWorldBorder(null);
+ 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));
+ }
+ }
+
+ /**
+ * The swap hands key (F by default) opens the list of places in the workshop, so admins
+ * do not have to go back to chat for it.
+ */
+ @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
+ public void onSwapHands(PlayerSwapHandItemsEvent e) {
+ if (manager.isWorkshopWorld(e.getPlayer().getWorld())) {
+ e.setCancelled(true);
+ String label = addon.getAdminCommand().map(CompositeCommand::getTopLabel).orElse("boxadmin");
+ Bukkit.dispatchCommand(e.getPlayer(), label + " areas spots");
+ }
+ }
+
+ @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/reach/AreaCheck.java b/src/main/java/world/bentobox/boxed/reach/AreaCheck.java
new file mode 100644
index 0000000..7240fd3
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/reach/AreaCheck.java
@@ -0,0 +1,118 @@
+package world.bentobox.boxed.reach;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Stream;
+
+import org.bukkit.configuration.ConfigurationSection;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.util.Vector;
+import org.eclipse.jdt.annotation.Nullable;
+
+import world.bentobox.bentobox.blueprints.Blueprint;
+import world.bentobox.boxed.Boxed;
+import world.bentobox.boxed.areas.Area;
+import world.bentobox.boxed.areas.BoxHeight;
+import world.bentobox.boxed.generators.template.Template;
+
+/**
+ * Works out whether some land can be played to the end: what a box holds at each size, and
+ * how far a box grows when every advancement in reach is earned. Everything the check needs
+ * from the server is collected first, on the main thread, so the check itself can run off it.
+ *
+ * @author tastybento
+ */
+public class AreaCheck {
+
+ private static final String REQUIREMENTS_FILE = "requirements.yml";
+
+ /**
+ * What a check found.
+ * @param survey what the land holds at each box size
+ * @param result how the box grew
+ * @param summary the result in a sentence
+ */
+ public record Outcome(LandSurvey survey, GrowthSimulator.Result result, String summary) {
+ }
+
+ private final Template normal;
+ private final Template nether;
+ private final Requirements requirements;
+ private final YamlConfiguration structures;
+ private final Map scores;
+ private final Map starter;
+ private final int startSize;
+
+ /**
+ * Collects what a check needs. Call on the main thread.
+ * @param addon Boxed
+ * @param normal the overworld land
+ * @param nether the Nether land, or null if there is none
+ * @param structuresFile name of the file that lists the structures placed in each new box,
+ * or null if there are none
+ * @param blueprintArea the area whose starter blueprint new boxes will be given
+ */
+ public AreaCheck(Boxed addon, Template normal, @Nullable Template nether, @Nullable String structuresFile,
+ Area blueprintArea) {
+ this.normal = normal;
+ this.nether = nether;
+ File folder = addon.getDataFolder();
+ if (!new File(folder, REQUIREMENTS_FILE).exists()) {
+ addon.saveResource(REQUIREMENTS_FILE, false);
+ }
+ this.requirements = new Requirements(YamlConfiguration.loadConfiguration(new File(folder, REQUIREMENTS_FILE)),
+ addon::logWarning);
+ this.structures = structuresFile == null ? new YamlConfiguration()
+ : YamlConfiguration.loadConfiguration(new File(folder, structuresFile));
+ this.scores = getScores(folder);
+ this.starter = getStarterBlocks(addon, blueprintArea);
+ this.startSize = Math.max(1, addon.getSettings().getIslandProtectionRange());
+ }
+
+ /**
+ * Runs the check. Can be called from any thread.
+ * @return what was found
+ */
+ public Outcome run() {
+ LandSurvey survey = new LandSurvey(normal.getSize() * 16);
+ survey.addTemplate(normal, false);
+ if (nether != null) {
+ survey.addTemplate(nether, true);
+ }
+ survey.addBlueprint(starter);
+ survey.addStructures(structures.getConfigurationSection("normal"), false);
+ survey.addStructures(structures.getConfigurationSection("nether"), true);
+ requirements.applyTo(survey);
+ GrowthSimulator.Result result = new GrowthSimulator(survey, requirements, scores, startSize).run();
+ return new Outcome(survey, result, ReachReport.summary(result));
+ }
+
+ /**
+ * @return how much each advancement grows the box, from advancements.yml
+ */
+ private static Map getScores(File folder) {
+ Map scores = new HashMap<>();
+ ConfigurationSection adv = YamlConfiguration.loadConfiguration(new File(folder, "advancements.yml"))
+ .getConfigurationSection("advancements");
+ if (adv != null) {
+ adv.getKeys(false).forEach(k -> scores.put(k.contains(":") ? k : "minecraft:" + k, adv.getInt(k)));
+ }
+ return scores;
+ }
+
+ /**
+ * @return the starter blocks of an area, by position relative to the centre of the box
+ */
+ private static Map getStarterBlocks(Boxed addon, Area area) {
+ Map starter = new HashMap<>();
+ Blueprint bp = new BoxHeight(addon).getBlueprint(area);
+ if (bp != null) {
+ Vector bedrock = bp.getBedrock() == null ? new Vector() : bp.getBedrock();
+ Stream.of(bp.getBlocks(), bp.getAttached()).filter(Objects::nonNull).forEach(
+ m -> m.forEach((pos, block) -> starter.put(pos.clone().subtract(bedrock), block.getBlockData())));
+ }
+ return starter;
+ }
+}
diff --git a/src/main/java/world/bentobox/boxed/reach/FortressSpot.java b/src/main/java/world/bentobox/boxed/reach/FortressSpot.java
new file mode 100644
index 0000000..b2229e9
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/reach/FortressSpot.java
@@ -0,0 +1,76 @@
+package world.bentobox.boxed.reach;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.function.IntBinaryOperator;
+
+/**
+ * Picks where the middle of an area's Nether should be so that its boxes get a fortress.
+ * A fortress cannot be placed like other structures, so the only way to have one is to take
+ * the land from a part of the seed that has one. The middle is put on open ground a short
+ * way from a blaze spawner: close enough that the box soon grows to take it in, but not so
+ * close that new arrivals land among the blazes.
+ *
+ * @author tastybento
+ */
+public final class FortressSpot {
+
+ /**
+ * The nearest a blaze spawner may be, as a box size
+ */
+ public static final int MIN_SPAWNER_SIZE = 32;
+ /**
+ * The nearest any part of the fortress may be, as a box size
+ */
+ public static final int MIN_FORTRESS_SIZE = 8;
+
+ /**
+ * A place for the middle of the Nether.
+ * @param x block x
+ * @param z block z
+ * @param spawnerSize the box size that takes in a blaze spawner
+ * @param fortressSize the box size that takes in the first of the fortress
+ */
+ public record Spot(int x, int z, int spawnerSize, int fortressSize) {
+ }
+
+ private FortressSpot() {
+ }
+
+ /**
+ * Looks over the chunk corners of a piece of land for the best place.
+ * @param min lowest block x and z of the land
+ * @param max highest block x and z of the land
+ * @param spawners block x and z of each blaze spawner
+ * @param bricks block x and z of each column that has fortress in it
+ * @param open says if a column is open ground: 1 if it is, 0 if not
+ * @return the best place, or empty if the land has no spawner or no open ground near one
+ */
+ public static Optional choose(int[] min, int[] max, List spawners, List bricks,
+ IntBinaryOperator open) {
+ Spot best = null;
+ for (int x = (min[0] + 15) >> 4 << 4; x <= max[0]; x += 16) {
+ for (int z = (min[1] + 15) >> 4 << 4; z <= max[1]; z += 16) {
+ int spawner = nearest(spawners, x, z);
+ int fortress = nearest(bricks, x, z);
+ if (spawner >= MIN_SPAWNER_SIZE && spawner != Integer.MAX_VALUE && fortress >= MIN_FORTRESS_SIZE
+ && open.applyAsInt(x, z) == 1 && (best == null || spawner < best.spawnerSize()
+ || (spawner == best.spawnerSize() && fortress < best.fortressSize()))) {
+ best = new Spot(x, z, spawner, fortress);
+ }
+ }
+ }
+ return Optional.ofNullable(best);
+ }
+
+ /**
+ * @return the smallest box around a place that takes in one of the columns
+ */
+ private static int nearest(List columns, int x, int z) {
+ int nearest = Integer.MAX_VALUE;
+ for (int[] c : columns) {
+ nearest = Math.min(nearest, LandSurvey.sizeFor(c[0] - x, c[1] - z));
+ }
+ return nearest;
+ }
+}
diff --git a/src/main/java/world/bentobox/boxed/reach/LandSurvey.java b/src/main/java/world/bentobox/boxed/reach/LandSurvey.java
index bc79f48..9d39067 100644
--- a/src/main/java/world/bentobox/boxed/reach/LandSurvey.java
+++ b/src/main/java/world/bentobox/boxed/reach/LandSurvey.java
@@ -11,6 +11,8 @@
import org.bukkit.block.data.BlockData;
import org.bukkit.configuration.ConfigurationSection;
+import world.bentobox.bentobox.blueprints.dataobjects.BlueprintCreatureSpawner;
+import world.bentobox.boxed.generators.chunks.AbstractBoxedChunkGenerator.ChestData;
import world.bentobox.boxed.generators.chunks.AbstractBoxedChunkGenerator.EntityData;
import world.bentobox.boxed.generators.template.Template;
import world.bentobox.boxed.generators.template.TemplateChunk;
@@ -186,6 +188,7 @@ public void addTemplate(Template template, boolean nether) {
addBlocks(chunk, chunkX << 4, chunkZ << 4, nether, blockCounters);
addBiomes(template, chunkX, chunkZ, nether, biomeCounters);
addEntities(chunk, chunkX << 4, chunkZ << 4, nether);
+ addSpawners(chunk, chunkX << 4, chunkZ << 4, nether);
}
}
}
@@ -227,6 +230,19 @@ private void addEntities(TemplateChunk chunk, int baseX, int baseZ, boolean neth
}
}
+ /**
+ * A spawner is as good as the mob it makes, so it is recorded as that mob.
+ */
+ private void addSpawners(TemplateChunk chunk, int baseX, int baseZ, boolean nether) {
+ for (ChestData tile : chunk.getChests()) {
+ BlueprintCreatureSpawner spawner = tile.chest().getCreatureSpawner();
+ if (spawner != null && spawner.getSpawnedType() != null) {
+ add(nether ? Kind.NETHER_ENTITY : Kind.ENTITY, spawner.getSpawnedType().getKey().getKey(),
+ sizeFor(baseX + tile.relativeLoc().getBlockX(), baseZ + tile.relativeLoc().getBlockZ()), 1);
+ }
+ }
+ }
+
private static final int[] BIOME_HEIGHTS = { 64, 32, 0, -32, -52, 100, 160 };
/**
diff --git a/src/main/java/world/bentobox/boxed/reach/SpotFinder.java b/src/main/java/world/bentobox/boxed/reach/SpotFinder.java
new file mode 100644
index 0000000..45be866
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/reach/SpotFinder.java
@@ -0,0 +1,218 @@
+package world.bentobox.boxed.reach;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Looks through the biomes of a seed for places where a box could start: wooded land with
+ * water a short walk away and no mountains close enough to block the view. Looking up a biome is cheap, so a lot of ground can be covered.
+ * The best places are then looked at properly with a {@link SpotSurvey}.
+ *
+ * @author tastybento
+ */
+public class SpotFinder {
+
+ /**
+ * Something that knows the biome at the surface of a seed.
+ */
+ @FunctionalInterface
+ public interface BiomeLookup {
+ /**
+ * @param x block x
+ * @param z block z
+ * @return name of the biome, e.g. birch_forest
+ */
+ String biomeAt(int x, int z);
+ }
+
+ /**
+ * A place that looks promising from its biomes.
+ * @param x block x of the middle
+ * @param z block z of the middle
+ * @param biome biome at the middle
+ * @param waterDistance how far away the nearest river or sea is, or -1 if there is none nearby
+ * @param landPercent how much of the land a box can grow into is not sea or river
+ * @param rating how promising the place is. Higher is better.
+ */
+ public record Candidate(int x, int z, String biome, int waterDistance, int landPercent, int rating) {
+ }
+
+ private static final int[] WATER_RINGS = { 32, 48, 64, 96, 128 };
+ private static final int[][] DIRECTIONS = { { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 },
+ { 0, -1 }, { 1, -1 } };
+ /**
+ * Mountains nearer than the last of these block the view from the start
+ */
+ private static final int[] MOUNTAIN_RINGS = { 32, 64, 96, 128 };
+ /**
+ * How much is taken off the rating of a place that has mountains next to it
+ */
+ private static final int MOUNTAIN_PENALTY = 50;
+ /**
+ * The best distance to water. Nearer and the box may start on a beach.
+ */
+ private static final int IDEAL_WATER = 40;
+ /**
+ * How many times more places have the rest of their land looked at than are returned
+ */
+ private static final int SHORTLIST = 5;
+ private static final Comparator BEST = Comparator.comparingInt(Candidate::rating).reversed()
+ .thenComparingLong(c -> (long) c.x() * c.x() + (long) c.z() * c.z()).thenComparingInt(Candidate::x)
+ .thenComparingInt(Candidate::z);
+
+ private final BiomeLookup lookup;
+ private final int landRadius;
+
+ /**
+ * @param lookup the biomes of the seed
+ * @param landRadius how far a box can grow from its middle
+ */
+ public SpotFinder(BiomeLookup lookup, int landRadius) {
+ this.lookup = lookup;
+ this.landRadius = landRadius;
+ }
+
+ /**
+ * @param biome biome name
+ * @return true if the biome is open water
+ */
+ public static boolean isWater(String biome) {
+ return biome.contains("ocean") || biome.contains("river");
+ }
+
+ /**
+ * @param biome biome name
+ * @return true if the biome is fairly level dry land that grows plenty of trees
+ */
+ public static boolean isWooded(String biome) {
+ if (biome.contains("windswept") || biome.contains("swamp") || biome.contains("badlands")) {
+ return false;
+ }
+ return biome.contains("forest") || biome.contains("taiga") || biome.contains("jungle")
+ || biome.equals("cherry_grove");
+ }
+
+ /**
+ * @param biome biome name
+ * @return true if the biome is high, steep ground
+ */
+ public static boolean isMountain(String biome) {
+ return biome.contains("peaks") || biome.contains("slopes") || biome.contains("windswept")
+ || biome.equals("grove");
+ }
+
+ /**
+ * A box should start with a view of what can be reached. Mountains in the distance are
+ * good to see, but right next to the start they are a wall.
+ * @return true if there are mountains close enough to block the view
+ */
+ private boolean isMountainNear(int x, int z) {
+ for (int ring : MOUNTAIN_RINGS) {
+ for (int[] d : DIRECTIONS) {
+ if (isMountain(lookup.biomeAt(x + d[0] * ring, z + d[1] * ring))) {
+ return true;
+ }
+ }
+ }
+ return isMountain(lookup.biomeAt(x, z));
+ }
+
+ /**
+ * Searches a square of the seed.
+ * @param radius how far from the middle of the seed to look, in blocks
+ * @param step distance between the places tried. It is rounded to whole chunks.
+ * @param count how many places to return
+ * @param separation the least distance between any two places returned
+ * @return the most promising places, best first
+ */
+ public List find(int radius, int step, int count, int separation) {
+ int grid = Math.max(16, step >> 4 << 4);
+ int limit = radius / grid * grid;
+ List found = new ArrayList<>();
+ for (int x = -limit; x <= limit; x += grid) {
+ for (int z = -limit; z <= limit; z += grid) {
+ String biome = lookup.biomeAt(x, z);
+ if (isWooded(biome) && isDryAround(x, z) && !isMountainNear(x, z)) {
+ int water = waterDistance(x, z);
+ found.add(new Candidate(x, z, biome, water, 0, waterRating(water)));
+ }
+ }
+ }
+ // The land a box grows into is only looked at for the best of them, because it is slower
+ List shortlist = apart(found.stream().sorted(BEST).toList(), count * SHORTLIST, separation)
+ .stream().map(c -> at(c.x(), c.z())).sorted(BEST).toList();
+ return apart(shortlist, count, separation);
+ }
+
+ /**
+ * Describes a place, whether or not it is a good one.
+ * @param x block x of the middle
+ * @param z block z of the middle
+ * @return the place
+ */
+ public Candidate at(int x, int z) {
+ int water = waterDistance(x, z);
+ int land = landPercent(x, z);
+ int rating = waterRating(water) + land / 2 - (isMountainNear(x, z) ? MOUNTAIN_PENALTY : 0);
+ return new Candidate(x, z, lookup.biomeAt(x, z), water, land, rating);
+ }
+
+ private static int waterRating(int water) {
+ return water < 0 ? 0 : 100 - Math.abs(water - IDEAL_WATER);
+ }
+
+ /**
+ * Takes the first places from a list, skipping any that are too close to one already taken.
+ */
+ private static List apart(List sorted, int count, int separation) {
+ List chosen = new ArrayList<>();
+ for (Candidate c : sorted) {
+ if (chosen.size() < count && chosen.stream().noneMatch(o -> Math.abs(o.x() - c.x()) < separation
+ && Math.abs(o.z() - c.z()) < separation)) {
+ chosen.add(c);
+ }
+ }
+ return chosen;
+ }
+
+ /**
+ * @return true if there is no open water right next to the place
+ */
+ private boolean isDryAround(int x, int z) {
+ for (int dx = -12; dx <= 12; dx += 24) {
+ for (int dz = -12; dz <= 12; dz += 24) {
+ if (isWater(lookup.biomeAt(x + dx, z + dz))) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private int waterDistance(int x, int z) {
+ for (int ring : WATER_RINGS) {
+ for (int[] d : DIRECTIONS) {
+ if (isWater(lookup.biomeAt(x + d[0] * ring, z + d[1] * ring))) {
+ return ring;
+ }
+ }
+ }
+ return -1;
+ }
+
+ private int landPercent(int x, int z) {
+ int land = 0;
+ int total = 0;
+ int gap = Math.max(16, landRadius / 4);
+ for (int dx = -landRadius; dx <= landRadius; dx += gap) {
+ for (int dz = -landRadius; dz <= landRadius; dz += gap) {
+ total++;
+ if (!isWater(lookup.biomeAt(x + dx, z + dz))) {
+ land++;
+ }
+ }
+ }
+ return land * 100 / total;
+ }
+}
diff --git a/src/main/java/world/bentobox/boxed/reach/SpotScorer.java b/src/main/java/world/bentobox/boxed/reach/SpotScorer.java
new file mode 100644
index 0000000..dbe147e
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/reach/SpotScorer.java
@@ -0,0 +1,71 @@
+package world.bentobox.boxed.reach;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.ChunkSnapshot;
+import org.bukkit.World;
+import org.bukkit.plugin.Plugin;
+
+/**
+ * Generates the land around a place in a world and scores it as a place to start a box.
+ *
+ * @author tastybento
+ */
+public final class SpotScorer {
+
+ private SpotScorer() {
+ }
+
+ /**
+ * Scores a place. The chunks are generated without stopping the server and the counting
+ * is done off the main thread.
+ * @param plugin plugin to schedule with
+ * @param world world to look in
+ * @param x block x of the place
+ * @param z block z of the place
+ * @param discard true to drop the generated chunks without saving them, for a world that
+ * is going to be thrown away
+ * @return the score. Completes on the main thread, with an error if the land could not be generated.
+ */
+ public static CompletableFuture score(Plugin plugin, World world, int x, int z,
+ boolean discard) {
+ CompletableFuture result = new CompletableFuture<>();
+ int reach = SpotSurvey.RADIUS >> 4;
+ int chunkX = x >> 4;
+ int chunkZ = z >> 4;
+ List> chunks = new ArrayList<>();
+ for (int cx = -reach; cx < reach; cx++) {
+ for (int cz = -reach; cz < reach; cz++) {
+ chunks.add(world.getChunkAtAsync(chunkX + cx, chunkZ + cz));
+ }
+ }
+ CompletableFuture.allOf(chunks.toArray(CompletableFuture[]::new)).whenComplete((v, error) ->
+ // Chunks have to be read on the main thread
+ Bukkit.getScheduler().runTask(plugin, () -> {
+ if (error != null) {
+ result.completeExceptionally(error);
+ return;
+ }
+ List snapshots = new ArrayList<>();
+ for (CompletableFuture chunk : chunks) {
+ Chunk c = chunk.join();
+ snapshots.add(c.getChunkSnapshot(true, false, false));
+ if (discard) {
+ world.unloadChunk(c.getX(), c.getZ(), false);
+ }
+ }
+ int minY = world.getMinHeight();
+ Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
+ SpotSurvey spotSurvey = new SpotSurvey();
+ snapshots.forEach(s -> spotSurvey.add(s, (s.getX() - chunkX) << 4, (s.getZ() - chunkZ) << 4, minY));
+ SpotSurvey.Score score = spotSurvey.score();
+ Bukkit.getScheduler().runTask(plugin, () -> result.complete(score));
+ });
+ }));
+ return result;
+ }
+}
diff --git a/src/main/java/world/bentobox/boxed/reach/SpotSurvey.java b/src/main/java/world/bentobox/boxed/reach/SpotSurvey.java
new file mode 100644
index 0000000..25bce2b
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/reach/SpotSurvey.java
@@ -0,0 +1,174 @@
+package world.bentobox.boxed.reach;
+
+import java.util.EnumMap;
+import java.util.Map;
+
+import org.bukkit.ChunkSnapshot;
+import org.bukkit.Material;
+import org.bukkit.Tag;
+
+import world.bentobox.boxed.reach.LandSurvey.Kind;
+
+/**
+ * A close look at the land around a place where boxes could start. It counts the blocks a
+ * new box would hold as it grows and works out how good a start the place gives: dry land
+ * with trees in the middle, and water, stone, iron ore and coal soon after.
+ *
+ * @author tastybento
+ */
+public class SpotSurvey {
+
+ /**
+ * How far from the middle the land is looked at, in blocks
+ */
+ public static final int RADIUS = 48;
+ /**
+ * How far from the middle the land should be dry
+ */
+ private static final int DRY_RADIUS = 8;
+ /**
+ * How far below the ground something still counts as near the surface
+ */
+ private static final int SHALLOW = 8;
+
+ private static final String WOOD = "*_log";
+ private static final String WATER = "water";
+ private static final String STONE = "stone|cobblestone|deepslate|cobbled_deepslate|blackstone";
+ private static final String IRON = "iron_ore|deepslate_iron_ore";
+ private static final String COAL = "coal_ore|deepslate_coal_ore";
+
+ /**
+ * How good a start a place gives. The sizes are the box sizes at which there is enough
+ * of each thing, or -1 if there is not enough within {@link SpotSurvey#RADIUS} blocks.
+ * @param dryCentre true if the very middle is dry land
+ * @param dryPercent how much of the land around the middle is dry
+ * @param wood size that takes in four logs
+ * @param water size that takes in water at the surface
+ * @param stone size that takes in three blocks of stone near the surface
+ * @param iron size that takes in three iron ore
+ * @param coal size that takes in coal ore
+ * @param score marks out of 100
+ */
+ public record Score(boolean dryCentre, int dryPercent, int wood, int water, int stone, int iron, int coal,
+ int score) {
+
+ /**
+ * @return the score in words
+ */
+ public String describe() {
+ return (dryCentre ? "dry land" : "middle is under water") + " (" + dryPercent + "% dry), wood at "
+ + at(wood) + ", water at " + at(water) + ", stone at " + at(stone) + ", iron ore at " + at(iron)
+ + ", coal at " + at(coal);
+ }
+
+ private static String at(int size) {
+ return size < 0 ? "more than " + RADIUS : "size " + size;
+ }
+ }
+
+ private final Map all = new EnumMap<>(Material.class);
+ private final Map nearSurface = new EnumMap<>(Material.class);
+ private int dry;
+ private int columns;
+ private int dryCentre;
+
+ /**
+ * Counts the blocks of a chunk.
+ * @param snapshot the chunk, with its highest blocks
+ * @param baseX block x of the chunk's corner relative to the middle of the place
+ * @param baseZ block z of the chunk's corner relative to the middle of the place
+ * @param minY lowest block y of the world
+ */
+ public void add(ChunkSnapshot snapshot, int baseX, int baseZ, int minY) {
+ for (int x = 0; x < 16; x++) {
+ for (int z = 0; z < 16; z++) {
+ int size = LandSurvey.sizeFor(baseX + x, baseZ + z);
+ if (size <= RADIUS) {
+ addColumn(snapshot, x, z, minY, size);
+ }
+ }
+ }
+ }
+
+ private void addColumn(ChunkSnapshot snapshot, int x, int z, int minY, int size) {
+ int ground = Integer.MIN_VALUE;
+ for (int y = snapshot.getHighestBlockYAt(x, z); y >= minY; y--) {
+ Material m = snapshot.getBlockType(x, y, z);
+ if (m.isAir()) {
+ continue;
+ }
+ all.computeIfAbsent(m, k -> new int[RADIUS + 1])[size]++;
+ if (ground == Integer.MIN_VALUE && isGround(m)) {
+ ground = y;
+ countDry(m, size);
+ }
+ if (ground != Integer.MIN_VALUE && ground - y < SHALLOW) {
+ nearSurface.computeIfAbsent(m, k -> new int[RADIUS + 1])[size]++;
+ }
+ }
+ }
+
+ /**
+ * @return true if the block is the ground or open water, not something growing or lying on it
+ */
+ private static boolean isGround(Material m) {
+ return m == Material.WATER || m == Material.LAVA
+ || (m.isSolid() && !Tag.LEAVES.isTagged(m) && !Tag.LOGS.isTagged(m));
+ }
+
+ private void countDry(Material ground, int size) {
+ boolean wet = ground == Material.WATER || ground == Material.LAVA || Tag.ICE.isTagged(ground);
+ if (size <= DRY_RADIUS) {
+ columns++;
+ dry += wet ? 0 : 1;
+ }
+ if (size == 1 && !wet) {
+ dryCentre++;
+ }
+ }
+
+ /**
+ * @return how good a start the place gives
+ */
+ public Score score() {
+ LandSurvey everything = toSurvey(all);
+ LandSurvey near = toSurvey(nearSurface);
+ // The middle is the four columns of a box of size 1
+ boolean centre = dryCentre == 4;
+ int dryPercent = columns == 0 ? 0 : dry * 100 / columns;
+ int wood = everything.sizeNeeded(Kind.BLOCK, WOOD, 4);
+ int water = near.sizeNeeded(Kind.BLOCK, WATER, 1);
+ int stone = near.sizeNeeded(Kind.BLOCK, STONE, 3);
+ int iron = everything.sizeNeeded(Kind.BLOCK, IRON, 3);
+ int coal = everything.sizeNeeded(Kind.BLOCK, COAL, 1);
+ double score = (centre ? 30.0 * dryPercent / 100 : 0) + marks(25, wood, 4) + marks(15, water, 16)
+ + marks(10, stone, 4) + marks(10, iron, 4) + marks(10, coal, 4);
+ return new Score(centre, dryPercent, wood, water, stone, iron, coal, (int) Math.round(score));
+ }
+
+ /**
+ * @param most the marks for having the thing within the good size
+ * @param size the box size that has enough of the thing, or -1
+ * @param good the size that earns full marks
+ * @return the marks, which fall to nothing at the edge of the land looked at
+ */
+ private static double marks(int most, int size, int good) {
+ if (size < 0) {
+ return 0;
+ }
+ return most * Math.clamp((double) (RADIUS - size) / (RADIUS - good), 0D, 1D);
+ }
+
+ private static LandSurvey toSurvey(Map counts) {
+ LandSurvey survey = new LandSurvey(RADIUS);
+ counts.forEach((m, bySize) -> {
+ String name = m.getKey().getKey();
+ for (int size = 1; size <= RADIUS; size++) {
+ if (bySize[size] > 0) {
+ survey.add(Kind.BLOCK, name, size, bySize[size]);
+ }
+ }
+ });
+ return survey;
+ }
+}
diff --git a/src/main/java/world/bentobox/boxed/workshop/AreaMaker.java b/src/main/java/world/bentobox/boxed/workshop/AreaMaker.java
new file mode 100644
index 0000000..a863b37
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/workshop/AreaMaker.java
@@ -0,0 +1,292 @@
+package world.bentobox.boxed.workshop;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
+import java.util.EnumMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.IntConsumer;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.World;
+import org.bukkit.World.Environment;
+import org.bukkit.configuration.file.YamlConfiguration;
+import org.eclipse.jdt.annotation.Nullable;
+
+import world.bentobox.boxed.Boxed;
+import world.bentobox.boxed.areas.Area;
+import world.bentobox.boxed.areas.AreaManager;
+import world.bentobox.boxed.commands.AdminAreasCommand;
+import world.bentobox.boxed.generators.template.Template;
+import world.bentobox.boxed.generators.template.TemplateBuilder;
+import world.bentobox.boxed.reach.AreaCheck;
+
+/**
+ * Turns the workshop into an area that players can use straight away. It is done in two
+ * parts so that the admin can see what they are about to make: {@link #prepare} copies the
+ * land and works out how far a box can grow in it, and {@link #finish} makes the area.
+ *
+ * @author tastybento
+ */
+public class AreaMaker {
+
+ /**
+ * Why an area cannot be made
+ */
+ public enum Problem {
+ NO_WORKSHOP, BUSY, NO_CENTRE, INVALID_NAME, HAS_BOXES
+ }
+
+ /**
+ * Land that has been copied and checked and is ready to become an area.
+ * @param name name of the area
+ * @param files the template file of each dimension
+ * @param summary how far a box can grow in the land, in a sentence
+ * @param workshop the workshop the land was copied from
+ * @param centre block x and z of the middle of the overworld land
+ * @param netherCentre block x and z of the middle of the Nether land
+ */
+ public record Prepared(String name, Map files, String summary, Workshop workshop,
+ Centre centre, Centre netherCentre) {
+ }
+
+ /**
+ * The middle of the land in one dimension.
+ * @param x block x
+ * @param z block z
+ */
+ public record Centre(int x, int z) {
+ static Centre of(int[] xz) {
+ return new Centre(xz[0], xz[1]);
+ }
+
+ int[] xz() {
+ return new int[] { x, z };
+ }
+ }
+
+ private static final String STAGING = "workshop-build";
+ private static final String AREAS = "areas.";
+ /**
+ * How many box positions each side of the middle of a row are put right when an area's
+ * land is replaced
+ */
+ private static final int CLEAN_COLUMNS = 8;
+
+ private final Boxed addon;
+ private final WorkshopManager manager;
+
+ /**
+ * @param addon Boxed
+ * @param manager the workshop
+ */
+ public AreaMaker(Boxed addon, WorkshopManager manager) {
+ this.addon = addon;
+ this.manager = manager;
+ }
+
+ /**
+ * Checks whether the workshop can be made into an area with a name.
+ * @param name name for the area
+ * @return what is in the way, or null if nothing is
+ */
+ @Nullable
+ public Problem problem(String name) {
+ Workshop workshop = manager.get().orElse(null);
+ if (workshop == null) {
+ return Problem.NO_WORKSHOP;
+ }
+ if (manager.isBusy()) {
+ return Problem.BUSY;
+ }
+ if (!workshop.hasCentre(Environment.NORMAL)) {
+ return Problem.NO_CENTRE;
+ }
+ if (!AreaManager.isValidName(name)) {
+ return Problem.INVALID_NAME;
+ }
+ Area existing = addon.getAreas().getArea(name);
+ // The land of an area can only be replaced while nobody has a box in it
+ return existing != null && countBoxes(existing) > 0 ? Problem.HAS_BOXES : null;
+ }
+
+ /**
+ * @param area area
+ * @return how many boxes players have in the area
+ */
+ public long countBoxes(Area area) {
+ World overWorld = addon.getOverWorld();
+ return overWorld == null ? 0
+ : addon.getIslands().getIslands(overWorld).stream().filter(i -> i.getOwner() != null)
+ .filter(i -> addon.getAreaAt(i.getCenter().getBlockZ() >> 4).equals(area)).count();
+ }
+
+ /**
+ * Copies the land of the workshop and works out how far a box can grow in it. This takes
+ * a while, but the server keeps running. Nothing is changed that players can see.
+ * @param name name for the area. Check it with {@link #problem(String)} first.
+ * @param progress told the percentage done as it goes up
+ * @return the land, ready to become an area
+ */
+ public CompletableFuture prepare(String name, IntConsumer progress) {
+ Workshop workshop = manager.get().orElseThrow();
+ manager.setBusy(true);
+ File staging = new File(addon.getDataFolder(), "areas" + File.separator + STAGING);
+ boolean nether = manager.hasDimension(Environment.NETHER);
+ Map files = new EnumMap<>(Environment.class);
+ CompletableFuture result = build(workshop, Environment.NORMAL, staging, files,
+ p -> progress.accept(nether ? p / 2 : p))
+ .thenCompose(v -> nether ? build(workshop, Environment.NETHER, staging, files,
+ p -> progress.accept(50 + p / 2)) : CompletableFuture.completedFuture(null))
+ .thenCompose(v -> check(name, files))
+ .thenApply(summary -> new Prepared(name, files, summary, workshop,
+ Centre.of(workshop.getCentre(Environment.NORMAL)),
+ Centre.of(workshop.getCentre(Environment.NETHER))));
+ // Whatever happens, the workshop can be used again afterwards
+ return result.whenComplete((p, error) -> manager.setBusy(false));
+ }
+
+ private CompletableFuture build(Workshop workshop, Environment env, File staging,
+ Map files, IntConsumer progress) {
+ World world = manager.getWorld(env);
+ if (world == null) {
+ return CompletableFuture.failedFuture(new IOException("There is no " + env + " world to copy"));
+ }
+ File file = new File(staging, env.name().toLowerCase(Locale.ENGLISH) + ".bxt");
+ files.put(env, file);
+ int[] centre = workshop.getCentre(env);
+ try {
+ Files.createDirectories(staging.toPath());
+ } catch (IOException e) {
+ return CompletableFuture.failedFuture(e);
+ }
+ return new TemplateBuilder(world, centre[0] >> 4, centre[1] >> 4,
+ addon.getChunkGenerator(Environment.NORMAL).getSize(), addon.templateGson(), addon::log)
+ .buildAsync(file, workshop.getSeed(), addon.getPlugin(), progress);
+ }
+
+ /**
+ * Works out how far a box can grow in the copied land. Completes on the main thread.
+ */
+ private CompletableFuture check(String name, Map files) {
+ CompletableFuture result = new CompletableFuture<>();
+ Template normal;
+ Template nether;
+ AreaCheck check;
+ try {
+ normal = addon.readTemplate(files.get(Environment.NORMAL));
+ nether = files.containsKey(Environment.NETHER) ? addon.readTemplate(files.get(Environment.NETHER)) : null;
+ Area existing = addon.getAreas().getArea(name);
+ // A new area has no structures yet, and starts with the default area's blueprint. An
+ // area that is being replaced keeps its own.
+ check = new AreaCheck(addon, normal, nether, existing == null ? null : existing.structures(),
+ existing == null ? addon.getAreas().getDefaultArea() : existing);
+ } catch (IOException e) {
+ return CompletableFuture.failedFuture(e);
+ }
+ Bukkit.getScheduler().runTaskAsynchronously(addon.getPlugin(), () -> {
+ String summary;
+ try {
+ summary = check.run().summary();
+ } catch (RuntimeException e) {
+ summary = null;
+ addon.logError("Could not check the land: " + e);
+ }
+ close(normal);
+ close(nether);
+ String found = summary;
+ Bukkit.getScheduler().runTask(addon.getPlugin(), () -> result.complete(found == null ? "?" : found));
+ });
+ return result;
+ }
+
+ private void close(@Nullable Template template) {
+ if (template != null) {
+ try {
+ template.close();
+ } catch (IOException e) {
+ addon.logError("Could not close a template: " + e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Makes the area from land that has been prepared. Players can pick it as soon as this
+ * returns. The workshop ends and its worlds become the area's seed worlds.
+ * @param prepared the land
+ * @return the area
+ * @throws IOException if the area could not be made. Nothing players can see has changed.
+ */
+ public Area finish(Prepared prepared) throws IOException {
+ if (manager.get().orElse(null) != prepared.workshop() || manager.isBusy()) {
+ throw new IOException("The workshop has changed since the land was copied");
+ }
+ Workshop workshop = prepared.workshop();
+ String name = prepared.name();
+ Area old = addon.getAreas().getArea(name);
+ if (old != null && countBoxes(old) > 0) {
+ throw new IOException("Area " + name + " has boxes in it");
+ }
+ int[] centre = prepared.centre().xz();
+ int[] netherCentre = prepared.netherCentre().xz();
+ if (!prepared.centre().equals(Centre.of(workshop.getCentre(Environment.NORMAL)))
+ || !prepared.netherCentre().equals(Centre.of(workshop.getCentre(Environment.NETHER)))) {
+ throw new IOException("The middle of the box has moved since the land was copied");
+ }
+ File folder = addon.getDataFolder();
+ String structures = old == null ? "structures-" + name + ".yml" : old.structures();
+ File structuresFile = new File(folder, structures);
+ if (!structuresFile.exists()) {
+ Files.writeString(structuresFile.toPath(), "# This file is written by the /boxadmin place command\n");
+ }
+ // The settings are written first, so that a restart finds the land that matches them
+ File areasFile = new File(folder, "areas.yml");
+ YamlConfiguration config = YamlConfiguration.loadConfiguration(areasFile);
+ config.set(AREAS + name + ".seed", workshop.getSeed());
+ config.set(AREAS + name + ".centre", centre[0] + "," + centre[1]);
+ config.set(AREAS + name + ".nether-centre", netherCentre[0] + "," + netherCentre[1]);
+ config.set(AREAS + name + ".biomes", workshop.getBiomes());
+ config.set(AREAS + name + ".structures", structures);
+ config.save(areasFile);
+
+ if (old != null) {
+ addon.clearLand(old);
+ }
+ Area area = addon.getAreas().put(name, workshop.getSeed(), workshop.getBiomes(), structures, centre,
+ netherCentre);
+ Files.createDirectories(addon.getAreaFolder(area).toPath());
+ for (Map.Entry en : prepared.files().entrySet()) {
+ File file = addon.getTemplateFile(area, en.getKey());
+ Files.move(en.getValue().toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
+ addon.setLand(area, en.getKey(), file);
+ }
+ // The folder the land was copied into is empty now
+ Files.deleteIfExists(new File(folder, "areas" + File.separator + STAGING).toPath());
+ addon.registerSeedGenerators(area);
+ AdminAreasCommand.createBundle(addon, name);
+ if (old != null) {
+ restoreRow(area);
+ }
+ manager.keepAs(area);
+ return area;
+ }
+
+ /**
+ * Land of the old kind that has already been generated in the game world is put right.
+ * Nobody has a box in the area, so this is only where admins have been and around spawn.
+ */
+ private void restoreRow(Area area) {
+ World overWorld = addon.getOverWorld();
+ if (overWorld == null || addon.getBoxCleaner() == null) {
+ return;
+ }
+ int pitch = addon.getChunkGenerator(Environment.NORMAL).getSize() * 2 * 16;
+ for (int column = -CLEAN_COLUMNS; column <= CLEAN_COLUMNS; column++) {
+ addon.getBoxCleaner().clean(new Location(overWorld, (double) column * pitch, 0, (double) area.row() * pitch));
+ }
+ }
+}
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..0cd2a9f
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/workshop/Workshop.java
@@ -0,0 +1,249 @@
+package world.bentobox.boxed.workshop;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.EnumMap;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+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 static final String SPOTS_KEY = "spots";
+
+ /**
+ * A place that could be the middle of every box.
+ * @param x block x
+ * @param z block z
+ * @param biome the biome the seed has there
+ * @param score how good a start it gives out of 100, or -1 if its land has not been looked at yet
+ * @param description what the score is made of
+ */
+ public record Spot(int x, int z, String biome, int score, String description) {
+ /**
+ * @return true if the land has been looked at
+ */
+ public boolean scored() {
+ return score >= 0;
+ }
+ }
+
+ 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<>();
+ private final List spots = new ArrayList<>();
+
+ /**
+ * @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 });
+ }
+
+ /**
+ * @param env dimension
+ * @return true if a place has been picked for the middle of every box
+ */
+ public boolean hasCentre(Environment env) {
+ return centres.containsKey(env);
+ }
+
+ /**
+ * @return the places found so far that could be the middle of every box. Their order
+ * never changes, so a place can be named by its position in the list.
+ */
+ public List getSpots() {
+ return List.copyOf(spots);
+ }
+
+ /**
+ * @param found the places to choose from
+ */
+ public void setSpots(List found) {
+ spots.clear();
+ spots.addAll(found);
+ }
+
+ /**
+ * @param index position in the list
+ * @param spot the place, now that its land has been looked at
+ */
+ public void setSpot(int index, Spot spot) {
+ spots.set(index, spot);
+ }
+
+ /**
+ * 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()));
+ List