diff --git a/CLAUDE.md b/CLAUDE.md
index 6c84a49..670bded 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -40,6 +40,10 @@ Never hold the whole region in memory or load the seed world on a normal boot
`reach/` answers whether an area can be played. `LandSurvey` counts, per box size, the blocks, biomes and template entities of an area's templates plus the starter blueprint and the structures file. `Requirements` reads `requirements.yml`, a hand-written model of what each scored advancement needs (and `provides` rules that turn biomes and structures into mobs). `GrowthSimulator` earns everything in reach, grows the box by the scores and repeats; `ReachReport` writes it up. `/boxadmin areas check ` runs the survey off the main thread. Every advancement with a score in `advancements.yml` must have an entry in `requirements.yml` (a test enforces it).
+### Finding a place to start
+
+`/boxadmin areas find [seed|random] [radius]` (`AdminAreasFindCommand`) looks for good spots in a seed. `reach/SpotFinder` searches the vanilla biomes (no chunks needed) for wooded land with water nearby; the best few are generated in a throwaway `/finder_` world, using the area's biomes file laid out around every spot at once (`AbstractSeedBiomeProvider.setCentres`), and scored by `reach/SpotSurvey` (dry middle, then the box size that takes in logs, surface water, shallow stone, iron ore and coal). The world is unloaded without saving and deleted. An area uses a spot through `centre: x,z` in `areas.yml` (`Area.centreX/centreZ`, overworld only; the Nether template is still taken from 0,0).
+
### 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 3eacb70..0cfdfe6 100644
--- a/README.md
+++ b/README.md
@@ -75,9 +75,10 @@ You can also do the same by hand: add the area to `areas.yml` and make a bluepri
| `/boxadmin areas` | Lists the areas with their row, seed and number of boxes. |
| `/boxadmin areas tp ` | Takes you to the land where the area's next box will be, so you can look at it and place structures before any player has a box there. |
| `/boxadmin areas create [seed]` | Makes a new area and its blueprint bundle. Needs a restart. |
-| `/boxadmin areas rebuild [regenerate]` | Builds the area's land again at the next restart. With `regenerate` the seed worlds are thrown away first, which is needed after changing the area's seed or biomes. Without it, the land is rebuilt from the seed worlds as they are, which keeps changes made to them by hand. |
+| `/boxadmin areas rebuild [regenerate]` | Builds the area's land again at the next restart. With `regenerate` the seed worlds are thrown away first, which is needed after changing the area's seed, centre or biomes. Without it, the land is rebuilt from the seed worlds as they are, which keeps changes made to them by hand. |
| `/boxadmin areas clean [x z]` | Puts the land of the box position you are in (or the one at x, z) back the way it was. Use it after trying out structures in a position nobody has a box in. Positions with a box in use are refused. |
| `/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). |
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:
@@ -164,6 +165,27 @@ What each advancement needs is set in `requirements.yml`, which is written to th
An advancement that scores points but can never be earned is worth either removing from `advancements.yml` or making possible, for example by placing a structure with `/boxadmin place`.
+### Finding a good place to start
+
+Every box in an area is a copy of the land around one place in the area's seed. By default that place is 0,0, so whether new players start in a forest or in the sea depends on the seed. `/boxadmin areas find [seed|random] [radius]` finds better places for you:
+
+* with no seed it searches the seed the area already has, so you can see how the current place compares,
+* with a seed it searches that seed, and with `random` it picks a new seed,
+* `radius` is how far from 0,0 to search in blocks. The default is 5000.
+
+The search looks for dry, wooded land with a river or the sea a short walk away. It then generates the land around the best dozen places in a temporary world, which is deleted afterwards, and gives each a score out of 100. The score is highest when the middle is dry land and a small box already holds logs, water at the surface, stone near the surface, iron ore and coal. The area's biomes file is used, so the land is what a box there would really have. It takes around 10 seconds.
+
+The three best places are shown and the full list is written to `areas/ /spots.txt`:
+
+```
+100/100 centre: 1664,1536 (forest, river or sea about 32 blocks away, 92% land)
+ dry land (100% dry), wood at size 4, water at size 14, stone at size 1, iron ore at size 2, coal at size 2
+```
+
+To use a place, set the area's `seed` and `centre` in `areas.yml`, run `/boxadmin areas rebuild regenerate` and restart the server. Boxes that players have already explored do not change, so do this before the area is in use. `centre` moves the overworld only. The Nether of an area is always taken from 0,0 of its seed.
+
+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.
diff --git a/src/main/java/world/bentobox/boxed/Boxed.java b/src/main/java/world/bentobox/boxed/Boxed.java
index 5f3e162..ea7d389 100644
--- a/src/main/java/world/bentobox/boxed/Boxed.java
+++ b/src/main/java/world/bentobox/boxed/Boxed.java
@@ -151,7 +151,7 @@ private boolean loadSettings() {
String worldName = settings.getWorldName().toLowerCase(Locale.ENGLISH);
for (Area area : areas.getAreas()) {
generatorMaps.put(area.seedWorldName(worldName, false), new BoxedSeedChunkGenerator(this,
- Environment.NORMAL, new SeedBiomeGenerator(this, area.biomes())));
+ Environment.NORMAL, new SeedBiomeGenerator(this, area.biomes(), area.centreX(), area.centreZ())));
generatorMaps.put(area.seedWorldName(worldName, true), new BoxedSeedChunkGenerator(this,
Environment.NETHER, new NetherSeedBiomeGenerator(this, area.biomes())));
}
@@ -229,7 +229,7 @@ public void createWorlds() {
// Get the land of every area ready before the game worlds ask for it
for (Area area : areas.getAreas()) {
boolean regenerate = checkRebuildRequest(area);
- loadTemplate(area, worldName, Environment.NORMAL, settings.getSeedX(), settings.getSeedZ(), regenerate);
+ loadTemplate(area, worldName, Environment.NORMAL, area.centreX(), area.centreZ(), regenerate);
if (settings.isNetherGenerate()) {
loadTemplate(area, worldName, Environment.NETHER, settings.getNetherSeedX(),
settings.getNetherSeedZ(), regenerate);
diff --git a/src/main/java/world/bentobox/boxed/areas/Area.java b/src/main/java/world/bentobox/boxed/areas/Area.java
index f47f801..31fbc07 100644
--- a/src/main/java/world/bentobox/boxed/areas/Area.java
+++ b/src/main/java/world/bentobox/boxed/areas/Area.java
@@ -13,10 +13,12 @@
* @param unlockSize the size a player's box in this area must reach to unlock the areas that
* require it. Each area sets its own, so some can be harder than others.
* 0 means that just having a box in the area is enough.
+ * @param centreX block x in the overworld seed world that the middle of every box is taken from
+ * @param centreZ block z in the overworld seed world that the middle of every box is taken from
* @author tastybento
*/
public record Area(String id, long seed, String biomes, String structures, int row, boolean enabled,
- String requires, int unlockSize) {
+ String requires, int unlockSize, int centreX, int centreZ) {
/**
* Name of the area that always exists
diff --git a/src/main/java/world/bentobox/boxed/areas/AreaManager.java b/src/main/java/world/bentobox/boxed/areas/AreaManager.java
index 8de1bb7..97f72c8 100644
--- a/src/main/java/world/bentobox/boxed/areas/AreaManager.java
+++ b/src/main/java/world/bentobox/boxed/areas/AreaManager.java
@@ -68,9 +68,10 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed,
s = new YamlConfiguration();
}
String requires = getRequirement(s, id, ids, errorLog);
+ int[] centre = parseCentre(s.getString("centre", s.getString("center", "")), id, errorLog);
Area area = new Area(id, s.getLong("seed", defaultSeed), s.getString("biomes", "biomes.yml"),
s.getString("structures", "structures.yml"), grid.getInt(path), s.getBoolean("enabled", true),
- requires, Math.max(0, s.getInt("unlocks-next-at", 0)));
+ requires, Math.max(0, s.getInt("unlocks-next-at", 0)), centre[0], centre[1]);
areas.put(id, area);
areaByRow.put(area.row(), area);
}
@@ -80,6 +81,28 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed,
}
}
+ /**
+ * Reads where in the seed world the middle of an area is. Land is copied in whole chunks,
+ * so the spot is moved to the corner of its chunk.
+ * @param text "x,z", or empty for the middle of the seed world
+ * @return block x and z
+ */
+ static int[] parseCentre(String text, String id, java.util.function.Consumer errorLog) {
+ if (text.isBlank()) {
+ return new int[] { 0, 0 };
+ }
+ String[] xz = text.split(",");
+ try {
+ if (xz.length == 2) {
+ return new int[] { Integer.parseInt(xz[0].trim()) >> 4 << 4, Integer.parseInt(xz[1].trim()) >> 4 << 4 };
+ }
+ } catch (NumberFormatException _) {
+ // Reported below
+ }
+ errorLog.accept("Area " + id + ": centre must be two whole numbers like 1200,-640. Using 0,0.");
+ return new int[] { 0, 0 };
+ }
+
/**
* Lists the names of the areas in the config. The default area always exists and always
* comes first.
diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java
index cfe138b..4c1669a 100644
--- a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java
+++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java
@@ -70,6 +70,7 @@ public void setup() {
new Rebuild(this);
new Clean(this);
new Check(this);
+ new AdminAreasFindCommand(this);
}
@Override
diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java
new file mode 100644
index 0000000..3bde1a7
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasFindCommand.java
@@ -0,0 +1,339 @@
+package world.bentobox.boxed.commands;
+
+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.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Stream;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.ChunkSnapshot;
+import org.bukkit.World;
+import org.bukkit.World.Environment;
+import org.bukkit.WorldCreator;
+import org.bukkit.generator.BiomeProvider;
+
+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.generators.biomes.SeedBiomeGenerator;
+import world.bentobox.boxed.generators.chunks.BoxedSeedChunkGenerator;
+import world.bentobox.boxed.reach.SpotFinder;
+import world.bentobox.boxed.reach.SpotFinder.Candidate;
+import world.bentobox.boxed.reach.SpotSurvey;
+
+/**
+ * Looks through a seed for good places to start a box, so that admins do not have to find
+ * one by trial and error. The biomes of the seed are searched first, which is quick, and then
+ * the land around the most promising places is generated in a throwaway world and scored.
+ *
+ * @author tastybento
+ */
+public class AdminAreasFindCommand extends CompositeCommand {
+
+ private static final String PREFIX = "boxed.commands.boxadmin.areas.find.";
+ private static final String RANDOM = "random";
+ private static final String WORLD_PREFIX = "finder_";
+ private static final int DEFAULT_RADIUS = 5000;
+ private static final int MIN_RADIUS = 500;
+ private static final int MAX_RADIUS = 20000;
+ /**
+ * Distance between the places whose biomes are looked at
+ */
+ private static final int STEP = 64;
+ /**
+ * How many places have their land generated and scored
+ */
+ private static final int SPOTS = 12;
+ /**
+ * How many of the best places are shown to whoever ran the command
+ */
+ private static final int SHOWN = 3;
+
+ private final AtomicBoolean running = new AtomicBoolean();
+
+ /**
+ * A place and how good a start it gives
+ */
+ private record Scored(Candidate spot, SpotSurvey.Score score) {
+ }
+
+ /**
+ * One search from start to finish
+ */
+ private final class Search {
+ private final User user;
+ private final Area area;
+ private final long seed;
+ private final int radius;
+ private final SeedBiomeGenerator biomes;
+ private final List scored = new ArrayList<>();
+ private World world;
+ private List spots = List.of();
+
+ Search(User user, Area area, long seed, int radius) {
+ this.user = user;
+ this.area = area;
+ this.seed = seed;
+ this.radius = radius;
+ this.biomes = new SeedBiomeGenerator(getAddon(), area.biomes());
+ }
+
+ /**
+ * Makes the throwaway world and searches its biomes. Call on the main thread.
+ */
+ void start() {
+ Boxed addon = getAddon();
+ String name = addon.getSettings().getWorldName().toLowerCase(Locale.ENGLISH) + "/" + WORLD_PREFIX
+ + System.currentTimeMillis();
+ world = WorldCreator.name(name).generator(new BoxedSeedChunkGenerator(addon, Environment.NORMAL, biomes))
+ .environment(Environment.NORMAL).seed(seed).createWorld();
+ if (world == null) {
+ finish(PREFIX + "failed");
+ return;
+ }
+ world.setAutoSave(false);
+ BiomeProvider vanilla = world.vanillaBiomeProvider();
+ int seaLevel = world.getSeaLevel();
+ int land = addon.getSettings().getIslandDistance();
+ SpotFinder finder = new SpotFinder(
+ (x, z) -> vanilla.getBiome(world, x, seaLevel, z).getKey().getKey(), land);
+ Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> {
+ // Places are kept apart so that the custom biomes around each do not overlap
+ List found = new ArrayList<>(finder.find(radius, STEP, SPOTS, land * 4));
+ if (seed == area.seed()) {
+ // The place the area uses now is scored too, for comparison
+ found.removeIf(c -> c.x() == area.centreX() && c.z() == area.centreZ());
+ found.add(finder.at(area.centreX(), area.centreZ()));
+ }
+ Bukkit.getScheduler().runTask(getPlugin(), () -> {
+ spots = found;
+ if (found.isEmpty()) {
+ finish(PREFIX + "none");
+ } else {
+ biomes.setCentres(found.stream().map(c -> new int[] { c.x(), c.z() }).toList());
+ survey(0);
+ }
+ });
+ });
+ }
+
+ /**
+ * Generates the land around a place and scores it, then moves on to the next.
+ */
+ private void survey(int index) {
+ if (index >= spots.size()) {
+ finish(null);
+ return;
+ }
+ Candidate spot = spots.get(index);
+ int reach = SpotSurvey.RADIUS >> 4;
+ int chunkX = spot.x() >> 4;
+ int chunkZ = spot.z() >> 4;
+ List> chunks = new ArrayList<>();
+ for (int x = -reach; x < reach; x++) {
+ for (int z = -reach; z < reach; z++) {
+ chunks.add(world.getChunkAtAsync(chunkX + x, chunkZ + z));
+ }
+ }
+ CompletableFuture.allOf(chunks.toArray(CompletableFuture[]::new)).whenComplete((v, error) ->
+ // Chunks have to be read on the main thread
+ Bukkit.getScheduler().runTask(getPlugin(), () -> {
+ if (error != null) {
+ getAddon().logError("Could not generate the land at " + spot.x() + "," + spot.z() + ": " + error);
+ survey(index + 1);
+ return;
+ }
+ List snapshots = new ArrayList<>();
+ for (CompletableFuture chunk : chunks) {
+ Chunk c = chunk.join();
+ snapshots.add(c.getChunkSnapshot(true, false, false));
+ world.unloadChunk(c.getX(), c.getZ(), false);
+ }
+ int minY = world.getMinHeight();
+ Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> {
+ 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(getPlugin(), () -> {
+ scored.add(new Scored(spot, score));
+ survey(index + 1);
+ });
+ });
+ }));
+ }
+
+ /**
+ * Reports what was found and throws the world away. Call on the main thread.
+ * @param problem message to send if the search did not work, or null if it did
+ */
+ private void finish(String problem) {
+ File folder = world == null ? null : world.getWorldFolder();
+ if (world != null && !Bukkit.unloadWorld(world, false)) {
+ getAddon().logWarning("Could not unload " + world.getName());
+ folder = null;
+ }
+ File toDelete = folder;
+ File report = new File(AdminAreasFindCommand.this.getAddon().getAreaFolder(area), "spots.txt");
+ scored.sort(Comparator.comparingInt((Scored s) -> s.score().score()).reversed());
+ Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> {
+ deleteWorlds(toDelete);
+ boolean written = problem == null && write(report);
+ Bukkit.getScheduler().runTask(getPlugin(), () -> {
+ running.set(false);
+ if (problem != null) {
+ user.sendMessage(problem);
+ return;
+ }
+ scored.stream().limit(SHOWN).forEach(s -> user.sendMessage(PREFIX + "result", TextVariables.XYZ,
+ s.spot().x() + "," + s.spot().z(), TextVariables.NUMBER,
+ String.valueOf(s.score().score()), TextVariables.DESCRIPTION, s.score().describe()));
+ user.sendMessage(PREFIX + "report", "[file]", written ? report.getPath() : "-");
+ user.sendMessage(PREFIX + "how-to", TextVariables.NAME, area.id(), "[seed]", String.valueOf(seed));
+ });
+ });
+ }
+
+ /**
+ * Deletes the world a search used, and any that were left behind by a search that the
+ * server stopped in the middle of.
+ * @param folder folder of the world that was just used, or null if it is still loaded
+ */
+ private void deleteWorlds(File folder) {
+ File[] siblings = folder == null || folder.getParentFile() == null ? null
+ : folder.getParentFile().listFiles((dir, name) -> name.startsWith(WORLD_PREFIX));
+ if (siblings == null) {
+ return;
+ }
+ for (File old : siblings) {
+ try (Stream files = Files.walk(old.toPath())) {
+ for (Path path : files.sorted(Comparator.reverseOrder()).toList()) {
+ Files.delete(path);
+ }
+ } catch (IOException e) {
+ getAddon().logWarning("Could not delete " + old + ": " + e.getMessage());
+ }
+ }
+ }
+
+ private boolean isCurrent(Candidate c) {
+ return seed == area.seed() && c.x() == area.centreX() && c.z() == area.centreZ();
+ }
+
+ private boolean write(File report) {
+ List lines = new ArrayList<>();
+ lines.add("Places to start a box in seed " + seed + ", searched " + radius + " blocks each way from 0,0");
+ lines.add("Biomes file: " + area.biomes());
+ lines.add("");
+ lines.add("To use one, give the area this seed and centre in areas.yml, for example");
+ lines.add(" seed: " + seed);
+ lines.add(" centre: " + (scored.isEmpty() ? "0,0" : scored.get(0).spot().x() + "," + scored.get(0).spot().z()));
+ lines.add("then run /boxadmin areas rebuild " + area.id() + " regenerate and restart the server.");
+ lines.add("");
+ lines.add("Sizes are the box size that takes in four logs, water at the surface, stone within");
+ lines.add(SHALLOW_NOTE);
+ lines.add("");
+ for (Scored s : scored) {
+ Candidate c = s.spot();
+ lines.add(String.format("%3d/100 centre: %d,%d%s (%s, river or sea about %s blocks away, %d%% land)",
+ s.score().score(), c.x(), c.z(), isCurrent(c) ? " <- used by " + area.id() + " now" : "",
+ c.biome(),
+ c.waterDistance() < 0 ? "more than 128" : String.valueOf(c.waterDistance()), c.landPercent()));
+ lines.add(" " + s.score().describe());
+ }
+ try {
+ Files.createDirectories(report.getParentFile().toPath());
+ Files.write(report.toPath(), lines);
+ return true;
+ } catch (IOException e) {
+ getAddon().logError("Could not write " + report + ": " + e.getMessage());
+ return false;
+ }
+ }
+ }
+
+ private static final String SHALLOW_NOTE = "eight blocks of the surface, three iron ore and one coal ore at any depth.";
+
+ /**
+ * @param parent the areas command
+ */
+ public AdminAreasFindCommand(CompositeCommand parent) {
+ super(parent, "find");
+ }
+
+ @Override
+ public void setup() {
+ this.setPermission("admin.areas.find");
+ this.setOnlyPlayer(false);
+ this.setParametersHelp(PREFIX + "parameters");
+ this.setDescription(PREFIX + "description");
+ }
+
+ @Override
+ public boolean execute(User user, String label, List args) {
+ Boxed addon = getAddon();
+ if (args.isEmpty() || args.size() > 3) {
+ this.showHelp(this, user);
+ return false;
+ }
+ Area area = addon.getAreas().getArea(args.get(0).toLowerCase(Locale.ENGLISH));
+ if (area == null) {
+ user.sendMessage("boxed.commands.boxadmin.areas.unknown-area");
+ return false;
+ }
+ long seed = area.seed();
+ if (args.size() > 1) {
+ if (RANDOM.equalsIgnoreCase(args.get(1))) {
+ seed = ThreadLocalRandom.current().nextLong();
+ } else {
+ try {
+ seed = Long.parseLong(args.get(1));
+ } catch (NumberFormatException _) {
+ user.sendMessage("boxed.commands.boxadmin.areas.create.invalid-seed");
+ return false;
+ }
+ }
+ }
+ int radius = DEFAULT_RADIUS;
+ if (args.size() > 2) {
+ if (!Util.isInteger(args.get(2), true) || Integer.parseInt(args.get(2)) < MIN_RADIUS
+ || Integer.parseInt(args.get(2)) > MAX_RADIUS) {
+ user.sendMessage(PREFIX + "invalid-radius", "[min]", String.valueOf(MIN_RADIUS), "[max]",
+ String.valueOf(MAX_RADIUS));
+ return false;
+ }
+ radius = Integer.parseInt(args.get(2));
+ }
+ if (!running.compareAndSet(false, true)) {
+ user.sendMessage(PREFIX + "running");
+ return false;
+ }
+ user.sendMessage(PREFIX + "started", "[seed]", String.valueOf(seed));
+ new Search(user, area, seed, radius).start();
+ return true;
+ }
+
+ @Override
+ public Optional> tabComplete(User user, String alias, List args) {
+ if (args.size() == 3) {
+ return Optional.of(Util.tabLimit(List.of(RANDOM), args.get(2)));
+ }
+ if (args.size() > 3) {
+ return Optional.empty();
+ }
+ return Optional.of(Util.tabLimit(this.getAddon().getAreas().getAreas().stream().map(Area::id).toList(),
+ args.isEmpty() ? "" : args.get(args.size() - 1)));
+ }
+}
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 3c9e20e..81a3436 100644
--- a/src/main/java/world/bentobox/boxed/generators/biomes/AbstractSeedBiomeProvider.java
+++ b/src/main/java/world/bentobox/boxed/generators/biomes/AbstractSeedBiomeProvider.java
@@ -13,6 +13,7 @@
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;
@@ -302,8 +303,11 @@ static ContLoc getCont(double continentalness) {
private final Boxed addon;
private final Environment env;
protected final int dist;
- private final int spawnX;
- private final int spawnZ;
+ /**
+ * Block x and z of the spots that the custom biomes are laid out around. A seed world has
+ * one. The spot finder tries out several in one world.
+ */
+ private final AtomicReference centres = new AtomicReference<>();
protected final Map> quadrants;
protected AbstractSeedBiomeProvider(Boxed boxed, Environment env) {
@@ -316,17 +320,21 @@ protected AbstractSeedBiomeProvider(Boxed boxed, Environment env) {
* @param biomesFile name of the file in the addon folder that defines the biomes
*/
protected AbstractSeedBiomeProvider(Boxed boxed, Environment env, String biomesFile) {
+ this(boxed, env, biomesFile, 0, 0);
+ }
+
+ /**
+ * @param boxed addon
+ * @param env environment
+ * @param biomesFile name of the file in the addon folder 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
+ */
+ protected AbstractSeedBiomeProvider(Boxed boxed, Environment env, String biomesFile, int centreX, int centreZ) {
this.addon = boxed;
this.env = env;
- // These fields are used to determine the biomes around the spawn point
this.dist = addon.getSettings().getIslandDistance();
- if (env.equals(Environment.NORMAL)) {
- spawnX = addon.getSettings().getSeedX();
- spawnZ = addon.getSettings().getSeedZ();
- } else {
- spawnX = addon.getSettings().getNetherSeedX();
- spawnZ = addon.getSettings().getNetherSeedZ();
- }
+ this.centres.set(new int[][] { { centreX, centreZ } });
// Load the config
File biomeFile = new File(addon.getDataFolder(), biomesFile);
// The default file is saved from the jar. Other areas' files are made by the admin.
@@ -350,6 +358,37 @@ protected AbstractSeedBiomeProvider(Boxed boxed, Environment env, String biomesF
quadrants.put(BlockFace.SOUTH_WEST, southWest);
}
+ /**
+ * Lays the custom biomes out around several spots instead of one. The spots should be
+ * far enough apart that their biomes do not overlap.
+ * @param spots block x and z of each spot. There must be at least one.
+ */
+ public void setCentres(List spots) {
+ if (spots.isEmpty()) {
+ throw new IllegalArgumentException("There must be at least one spot");
+ }
+ this.centres.set(spots.stream().map(int[]::clone).toArray(int[][]::new));
+ }
+
+ /**
+ * @return the spot nearest to a block
+ */
+ private int[] nearestCentre(int x, int z) {
+ int[][] all = centres.get();
+ int[] nearest = all[0];
+ long best = Long.MAX_VALUE;
+ for (int[] c : all) {
+ long dx = (long) x - c[0];
+ long dz = (long) z - c[1];
+ long d = dx * dx + dz * dz;
+ if (d < best) {
+ best = d;
+ nearest = c;
+ }
+ }
+ return nearest;
+ }
+
private Biome getQuadrantBiome(BlockFace dir, double d) {
Entry en = ((TreeMap) quadrants.get(dir)).ceilingEntry(d);
return en == null ? null : en.getValue();
@@ -879,7 +918,8 @@ private Biome getMappedBiome(WorldInfo worldInfo, int x, int y, int z, BiomePara
*/
Vector s = new Vector(x, 0, z);
- Vector l = new Vector(spawnX, 0, spawnZ);
+ 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
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/reach/SpotFinder.java b/src/main/java/world/bentobox/boxed/reach/SpotFinder.java
new file mode 100644
index 0000000..86f3d60
--- /dev/null
+++ b/src/main/java/world/bentobox/boxed/reach/SpotFinder.java
@@ -0,0 +1,184 @@
+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. 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 } };
+ /**
+ * 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");
+ }
+
+ /**
+ * 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)) {
+ 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);
+ return new Candidate(x, z, lookup.biomeAt(x, z), water, land, waterRating(water) + land / 2);
+ }
+
+ 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/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/resources/areas.yml b/src/main/resources/areas.yml
index e38b4ba..3b8cfad 100644
--- a/src/main/resources/areas.yml
+++ b/src/main/resources/areas.yml
@@ -10,6 +10,9 @@
# Settings for each area:
# seed - the world seed the land is generated from. The default area uses the seed
# in config.yml unless one is given here.
+# centre - the place in the seed that the middle of every box is taken from, as x,z.
+# The default is 0,0. /boxadmin areas find [seed|random] looks through
+# a seed for good places to start and lists them with their scores.
# biomes - the file that says which biomes are placed around the middle of the area.
# 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
@@ -24,11 +27,12 @@
# more than one area at a time: see world.concurrent-area in config.yml.
#
# Admins can list areas with /boxadmin areas, visit one with /boxadmin areas tp ,
-# make one with /boxadmin areas create [seed] and build one again with
-# /boxadmin areas rebuild [regenerate].
+# 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.
#
# 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 or biomes afterwards does
+# file, and saved in the areas folder. Changing an area's seed, centre or biomes afterwards does
# nothing until you run /boxadmin areas rebuild regenerate and restart.
# Boxes that players have already explored do not change.
#
@@ -40,6 +44,7 @@ areas:
# unlocks-next-at: 100
# icelands:
# seed: 1234567890
+# centre: 1664,1536
# biomes: biomes-icelands.yml
# structures: structures-icelands.yml
# requires: default
diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml
index 9a06f5f..394874d 100755
--- a/src/main/resources/locales/en-US.yml
+++ b/src/main/resources/locales/en-US.yml
@@ -609,6 +609,17 @@ 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]'
+ find:
+ description: look through a seed for good places to start a box
+ parameters: [seed|random] [search radius]
+ invalid-radius: '&c The search radius must be a whole number from [min] to [max]'
+ running: '&c A search is already running. Wait for it to finish.'
+ started: '&a Searching seed [seed] for good places to start a box. This takes a minute or two...'
+ none: '&c No dry, wooded land was found. Try another seed or a bigger search radius.'
+ failed: '&c The search could not be run. Check the console for the error'
+ result: '&e [xyz] &a scores [number]: &7 [description]'
+ report: '&a The full list is in &e [file]'
+ how-to: '&a To use a place, set &e seed: [seed] &a and &e centre: x,z &a for [name] in areas.yml, run &e /boxadmin areas rebuild [name] regenerate &a and restart.'
island:
go:
parameters: '[home number]'
diff --git a/src/test/java/world/bentobox/boxed/areas/AreaManagerTest.java b/src/test/java/world/bentobox/boxed/areas/AreaManagerTest.java
index ece5eee..a80215a 100644
--- a/src/test/java/world/bentobox/boxed/areas/AreaManagerTest.java
+++ b/src/test/java/world/bentobox/boxed/areas/AreaManagerTest.java
@@ -192,4 +192,26 @@ void testRowCalc() {
assertEquals(1, AbstractBoxedChunkGenerator.rowCalc(59, 20));
assertEquals(-1, AbstractBoxedChunkGenerator.rowCalc(-21, 20));
}
+
+ @Test
+ void testCentre() throws Exception {
+ AreaManager am = manager("""
+ areas:
+ moved:
+ centre: 1210, -650
+ american:
+ center: "32,48"
+ broken:
+ centre: here
+ """);
+ assertEquals(0, am.getDefaultArea().centreX());
+ assertEquals(0, am.getDefaultArea().centreZ());
+ // The spot is moved to the corner of its chunk
+ assertEquals(1200, am.getArea("moved").centreX());
+ assertEquals(-656, am.getArea("moved").centreZ());
+ assertEquals(32, am.getArea("american").centreX());
+ assertEquals(48, am.getArea("american").centreZ());
+ assertEquals(0, am.getArea("broken").centreX());
+ assertEquals(0, am.getArea("broken").centreZ());
+ }
}
diff --git a/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java b/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java
new file mode 100644
index 0000000..e55fc42
--- /dev/null
+++ b/src/test/java/world/bentobox/boxed/reach/SpotFinderTest.java
@@ -0,0 +1,92 @@
+package world.bentobox.boxed.reach;
+
+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 java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import world.bentobox.boxed.reach.SpotFinder.Candidate;
+
+/**
+ * Tests the search of a seed's biomes for places to start a box.
+ */
+class SpotFinderTest {
+
+ /**
+ * A plain with a forest from x = 0 to 255 and a river along its west edge
+ */
+ private static String strip(int x, int z) {
+ if (x >= -16 && x < 0) {
+ return "river";
+ }
+ return x >= 0 && x < 256 ? "forest" : "plains";
+ }
+
+ @Test
+ void testBiomeKinds() {
+ assertTrue(SpotFinder.isWooded("birch_forest"));
+ assertTrue(SpotFinder.isWooded("old_growth_pine_taiga"));
+ assertTrue(SpotFinder.isWooded("cherry_grove"));
+ assertFalse(SpotFinder.isWooded("windswept_forest"));
+ assertFalse(SpotFinder.isWooded("mangrove_swamp"));
+ assertFalse(SpotFinder.isWooded("plains"));
+ assertTrue(SpotFinder.isWater("frozen_river"));
+ assertTrue(SpotFinder.isWater("deep_lukewarm_ocean"));
+ assertFalse(SpotFinder.isWater("beach"));
+ }
+
+ @Test
+ void testFindsWoodedLandNearWater() {
+ List found = new SpotFinder(SpotFinderTest::strip, 320).find(1000, 16, 3, 100);
+ assertEquals(3, found.size());
+ for (Candidate c : found) {
+ assertEquals("forest", c.biome());
+ // The best places have the river 32 or 48 blocks away
+ assertTrue(c.waterDistance() == 32 || c.waterDistance() == 48, c.toString());
+ assertTrue(c.landPercent() > 80);
+ }
+ // Best first, and the nearest to the middle of the seed wins a tie
+ assertEquals(0, found.get(0).z());
+ assertTrue(found.get(0).rating() >= found.get(1).rating());
+ }
+
+ @Test
+ void testPlacesAreKeptApart() {
+ List found = new SpotFinder(SpotFinderTest::strip, 320).find(1000, 16, 50, 400);
+ assertTrue(found.size() > 1);
+ for (Candidate a : found) {
+ for (Candidate b : found) {
+ assertTrue(a == b || Math.abs(a.x() - b.x()) >= 400 || Math.abs(a.z() - b.z()) >= 400);
+ }
+ }
+ }
+
+ @Test
+ void testPlacesAreOnChunkCorners() {
+ List found = new SpotFinder(SpotFinderTest::strip, 320).find(500, 50, 10, 64);
+ assertFalse(found.isEmpty());
+ found.forEach(c -> assertEquals(0, (c.x() | c.z()) & 15));
+ }
+
+ @Test
+ void testNoWaterNearbyRatesLower() {
+ SpotFinder finder = new SpotFinder(SpotFinderTest::strip, 320);
+ // 200 blocks from the river is further than the search for water goes
+ Candidate far = finder.at(200, 0);
+ Candidate near = finder.at(16, 0);
+ assertEquals(-1, far.waterDistance());
+ assertEquals(32, near.waterDistance());
+ assertTrue(near.rating() > far.rating());
+ }
+
+ @Test
+ void testNothingFoundInTheSea() {
+ assertTrue(new SpotFinder((x, z) -> "ocean", 320).find(500, 64, 5, 100).isEmpty());
+ // Wooded, but with water right beside it
+ assertTrue(new SpotFinder((x, z) -> x == 0 && z == 0 ? "forest" : "river", 320).find(64, 64, 5, 100)
+ .isEmpty());
+ }
+}
diff --git a/src/test/java/world/bentobox/boxed/reach/SpotSurveyTest.java b/src/test/java/world/bentobox/boxed/reach/SpotSurveyTest.java
new file mode 100644
index 0000000..c11b1ea
--- /dev/null
+++ b/src/test/java/world/bentobox/boxed/reach/SpotSurveyTest.java
@@ -0,0 +1,143 @@
+package world.bentobox.boxed.reach;
+
+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.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.bukkit.ChunkSnapshot;
+import org.bukkit.Material;
+import org.junit.jupiter.api.Test;
+
+import world.bentobox.boxed.CommonTestSetup;
+import world.bentobox.boxed.reach.SpotSurvey.Score;
+
+/**
+ * Tests the scoring of the land around a place to start a box.
+ */
+class SpotSurveyTest extends CommonTestSetup {
+
+ /**
+ * Something that says which block is at a place in the land
+ */
+ @FunctionalInterface
+ private interface Land {
+ Material at(int x, int y, int z);
+ }
+
+ /**
+ * Surveys the four chunks around the middle of some land that is 70 blocks high.
+ */
+ private static Score survey(Land land) {
+ SpotSurvey survey = new SpotSurvey();
+ for (int cx = -1; cx <= 0; cx++) {
+ for (int cz = -1; cz <= 0; cz++) {
+ int baseX = cx << 4;
+ int baseZ = cz << 4;
+ ChunkSnapshot snapshot = mock(ChunkSnapshot.class);
+ when(snapshot.getHighestBlockYAt(anyInt(), anyInt())).thenReturn(70);
+ when(snapshot.getBlockType(anyInt(), anyInt(), anyInt())).thenAnswer(i -> land.at(
+ baseX + i.getArgument(0), i.getArgument(1), baseZ + i.getArgument(2)));
+ survey.add(snapshot, baseX, baseZ, 40);
+ }
+ }
+ return survey.score();
+ }
+
+ /**
+ * Grass over dirt over stone, with the surface at y = 64
+ */
+ private static Material plain(int y) {
+ if (y > 64) {
+ return Material.AIR;
+ }
+ if (y == 64) {
+ return Material.GRASS_BLOCK;
+ }
+ return y > 60 ? Material.DIRT : Material.STONE;
+ }
+
+ @Test
+ void testGoodStart() {
+ Score score = survey((x, y, z) -> {
+ if (x == 2 && z == 2 && y > 64 && y < 70) {
+ return Material.OAK_LOG;
+ }
+ if (y == 70) {
+ // A canopy over everything, which is not the ground
+ return Material.OAK_LEAVES;
+ }
+ if (x == 10 && y == 64) {
+ return Material.WATER;
+ }
+ if (x == -3 && y == 50) {
+ return z == 0 ? Material.COAL_ORE : Material.IRON_ORE;
+ }
+ return plain(y);
+ });
+ assertTrue(score.dryCentre());
+ assertEquals(100, score.dryPercent());
+ assertEquals(3, score.wood());
+ assertEquals(11, score.water());
+ assertEquals(1, score.stone());
+ assertEquals(3, score.iron());
+ assertEquals(3, score.coal());
+ assertEquals(100, score.score());
+ assertTrue(score.describe().contains("wood at size 3"));
+ }
+
+ @Test
+ void testBareLandScoresLow() {
+ Score score = survey((x, y, z) -> plain(y));
+ assertTrue(score.dryCentre());
+ assertEquals(-1, score.wood());
+ assertEquals(-1, score.water());
+ assertEquals(-1, score.iron());
+ assertEquals(-1, score.coal());
+ // Dry land and stone are all it has
+ assertEquals(40, score.score());
+ assertTrue(score.describe().contains("wood at more than " + SpotSurvey.RADIUS));
+ }
+
+ @Test
+ void testSea() {
+ Score score = survey((x, y, z) -> {
+ if (y > 64) {
+ return Material.AIR;
+ }
+ return y > 50 ? Material.WATER : Material.STONE;
+ });
+ assertFalse(score.dryCentre());
+ assertEquals(0, score.dryPercent());
+ assertEquals(1, score.water());
+ // The stone is too far under the water to count
+ assertEquals(-1, score.stone());
+ assertEquals(15, score.score());
+ assertTrue(score.describe().contains("under water"));
+ }
+
+ @Test
+ void testIceIsNotDryLand() {
+ Score score = survey((x, y, z) -> y == 64 && x >= 0 ? Material.ICE : plain(y));
+ assertFalse(score.dryCentre());
+ assertTrue(score.dryPercent() > 40 && score.dryPercent() < 60);
+ }
+
+ @Test
+ void testDeepWaterAndDeepStoneDoNotCount() {
+ // Water in a cave and a thick layer of dirt over the stone
+ Score score = survey((x, y, z) -> {
+ if (y > 64) {
+ return Material.AIR;
+ }
+ if (y == 45) {
+ return Material.WATER;
+ }
+ return y > 50 ? Material.DIRT : Material.STONE;
+ });
+ assertEquals(-1, score.water());
+ assertEquals(-1, score.stone());
+ }
+}