diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index c3ca450c..7ef1af41 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -38,6 +38,8 @@ import net.william278.huskhomes.util.*; import org.bstats.bukkit.Metrics; import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; +import org.bukkit.ChunkSnapshot; +import org.bukkit.Material; import org.bukkit.command.PluginCommand; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.Plugin; @@ -49,6 +51,7 @@ import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.CompletableFuture; @@ -73,10 +76,10 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { private EventListener eventListener; private RandomTeleportEngine randomTeleportEngine; private CachedSpawn serverSpawn; + private UnsafeBlocks unsafeBlocks; private EventDispatcher eventDispatcher; private Set pluginHooks; private List registeredCommands; - private List migrators; @Nullable @@ -117,7 +120,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Load settings and locales getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales..."); - initialized.set(reload().join()); + initialized.set(reload()); if (initialized.get()) { logger.showDebugLogs(settings.debugLogging); if (upgradeData != null) { @@ -139,8 +142,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { if (initialized.get()) { getLoggingAdapter().log(Level.INFO, "Successfully established a connection to the database"); } else { - throw new HuskHomesInitializationException("Failed to establish a connection to the database. " + - "Please check the supplied database credentials in the config file"); + throw new HuskHomesInitializationException("Failed to establish a connection to the database. " + "Please check the supplied database credentials in the config file"); } // Initialize the network messenger if proxy mode is enabled @@ -165,8 +167,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { cache.initialize(database); // Prepare the home and warp position manager - this.savedPositionManager = new SavedPositionManager(database, cache, eventDispatcher, - settings.allowUnicodeNames, settings.allowUnicodeDescriptions, settings.overwriteExistingHomesWarps); + this.savedPositionManager = new SavedPositionManager(database, cache, eventDispatcher, settings.allowUnicodeNames, settings.allowUnicodeDescriptions, settings.overwriteExistingHomesWarps); // Initialize the RTP engine with the default normal distribution engine setRandomTeleportEngine(new NormalDistributionEngine(this)); @@ -202,9 +203,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { if (pluginHooks.size() > 0) { pluginHooks.forEach(PluginHook::initialize); - getLoggingAdapter().log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " + - pluginHooks.stream().map(PluginHook::getHookName) - .collect(Collectors.joining(", "))); + getLoggingAdapter().log(Level.INFO, "Registered " + pluginHooks.size() + " plugin hooks: " + pluginHooks.stream().map(PluginHook::getHookName).collect(Collectors.joining(", "))); } // Register events @@ -214,13 +213,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Register permissions getLoggingAdapter().log(Level.INFO, "Registering permissions & commands..."); - Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager().addPermission( - new org.bukkit.permissions.Permission(permission.node, - switch (permission.defaultAccess) { - case EVERYONE -> PermissionDefault.TRUE; - case NOBODY -> PermissionDefault.FALSE; - case OPERATORS -> PermissionDefault.OP; - }))); + Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager().addPermission(new org.bukkit.permissions.Permission(permission.node, switch (permission.defaultAccess) { + case EVERYONE -> PermissionDefault.TRUE; + case NOBODY -> PermissionDefault.FALSE; + case OPERATORS -> PermissionDefault.OP; + }))); // Register commands this.registeredCommands = new ArrayList<>(); @@ -233,9 +230,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // If the command is disabled, use the disabled CommandBase if (settings.disabledCommands.stream().anyMatch(disabledCommand -> { final String command = (disabledCommand.startsWith("/") ? disabledCommand.substring(1) : disabledCommand); - return command.equalsIgnoreCase(commandType.commandBase.command) || - Arrays.stream(commandType.commandBase.aliases) - .anyMatch(alias -> alias.equalsIgnoreCase(command)); + return command.equalsIgnoreCase(commandType.commandBase.command) || Arrays.stream(commandType.commandBase.aliases).anyMatch(alias -> alias.equalsIgnoreCase(command)); })) { new BukkitCommand(new DisabledCommand(this), this).register(pluginCommand); return; @@ -259,10 +254,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Check for updates if (settings.checkForUpdates) { getLoggingAdapter().log(Level.INFO, "Checking for updates..."); - getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresent(newVersion -> getLoggingAdapter().log(Level.WARNING, - "An update is available for HuskHomes, v" + newVersion - + " (Currently running v" + getPluginVersion() + ")"))); + getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> getLoggingAdapter().log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getPluginVersion() + ")"))); } // Perform automatic upgrade if detected @@ -328,8 +320,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { @NotNull @Override public List getOnlinePlayers() { - return Bukkit.getOnlinePlayers().stream().map( - player -> (OnlineUser) BukkitPlayer.adapt(player)).toList(); + return Bukkit.getOnlinePlayers().stream().map(player -> (OnlineUser) BukkitPlayer.adapt(player)).toList(); } @NotNull @@ -345,7 +336,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } @Override - public @NotNull Database getDatabase() { + @NotNull + public Database getDatabase() { return database; } @@ -356,7 +348,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } @Override - public @NotNull RequestManager getRequestManager() { + @NotNull + public RequestManager getRequestManager() { return requestManager; } @@ -387,7 +380,8 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } @Override - public @NotNull EventDispatcher getEventDispatcher() { + @NotNull + public EventDispatcher getEventDispatcher() { return eventDispatcher; } @@ -419,41 +413,55 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } @Override - public @NotNull Set getPluginHooks() { + @NotNull + public Set getPluginHooks() { return pluginHooks; } @Override public CompletableFuture> resolveSafeGroundLocation(@NotNull Location location) { - final CompletableFuture> future = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(getInstance(), () -> BukkitAdapter.adaptLocation(location).ifPresentOrElse( - bukkitLocation -> { - // Validate the location is within the world's border - assert bukkitLocation.getWorld() != null; - if (!bukkitLocation.getWorld().getWorldBorder().isInside(bukkitLocation)) { - future.complete(Optional.empty()); - return; - } + final org.bukkit.Location bukkitLocation = BukkitAdapter.adaptLocation(location).orElse(null); + if (bukkitLocation == null || bukkitLocation.getWorld() == null) { + return CompletableFuture.completedFuture(Optional.empty()); + } - // Find a safe position and return - PaperLib.getChunkAtAsync(bukkitLocation).thenAcceptAsync(chunk -> - future.complete(BukkitSafetyUtil.findSafeLocation(location.world, bukkitLocation, - chunk.getChunkSnapshot()))).exceptionally(throwable -> { - throwable.printStackTrace(); - return null; - }); - }, - () -> future.complete(Optional.empty()))); - return future; + final CompletableFuture> locationFuture = new CompletableFuture<>(); + Bukkit.getScheduler().runTask(this, () -> PaperLib.getChunkAtAsync(bukkitLocation).thenApply(chunk -> { + final ChunkSnapshot snapshot = chunk.getChunkSnapshot(); + final int chunkX = bukkitLocation.getBlockX() & 0xF; + final int chunkZ = bukkitLocation.getBlockZ() & 0xF; + + for (int dX = -1; dX <= 2; dX++) { + for (int dZ = -1; dZ <= 2; dZ++) { + final int x = chunkX + dX; + final int z = chunkZ + dZ; + if (x < 0 || x >= 16 || z < 0 || z >= 16) { + continue; + } + final int y = snapshot.getHighestBlockYAt(x, z); + final Material blockType = snapshot.getBlockType(chunkX, y, chunkZ); + if (!isBlockUnsafe(blockType.getKey().toString())) { + Bukkit.broadcastMessage("✔ Safe block: " + blockType.getKey()); + return new Location((location.x + dX) + 0.5d, y + 1.25d, (location.z + dZ) + 0.5d, location.world); + } else { + Bukkit.broadcastMessage("❌ Unsafe block: " + blockType.getKey()); + } + } + } + return null; + }).thenAccept(resolved -> locationFuture.complete(Optional.ofNullable(resolved)))); + return locationFuture; } @Override - public @NotNull Version getPluginVersion() { + @NotNull + public Version getPluginVersion() { return Version.fromString(getDescription().getVersion(), "-"); } @Override - public @NotNull List getCommands() { + @NotNull + public List getCommands() { return registeredCommands; } @@ -471,72 +479,71 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { if (!getSettings().crossServer || this.server != null) { return CompletableFuture.completedFuture(null); } - return getNetworkMessenger() - .fetchServerName(requester) - .orTimeout(5, TimeUnit.SECONDS) - .exceptionally(throwable -> null) - .thenAccept(serverName -> { - if (serverName == null) { - throw new HuskHomesException("GetServer plugin message call operation timed out"); - } - try { - this.server = new Server(serverName); - Annotaml.create(new File(getDataFolder(), "server.yml"), new CachedServer(serverName)); - getLoggingAdapter().log(Level.INFO, "Successfully cached server name to disk (" + serverName + ")"); - } catch (IOException e) { - throw new HuskHomesException("Failed to write cached server name to disk", e); - } - }) - .exceptionally(throwable -> { - getLoggingAdapter().log(Level.SEVERE, "Failed to fetch and cache server name", throwable); - return null; - }); - } - - @Override - public @NotNull List getWorlds() { - return getServer().getWorlds().stream().filter(world -> BukkitAdapter.adaptWorld(world).isPresent()) - .map(world -> BukkitAdapter.adaptWorld(world).orElse(null)).collect(Collectors.toList()); - } - - @Override - public CompletableFuture reload() { - return CompletableFuture.supplyAsync(() -> { + return getNetworkMessenger().fetchServerName(requester).orTimeout(5, TimeUnit.SECONDS).exceptionally(throwable -> null).thenAccept(serverName -> { + if (serverName == null) { + throw new HuskHomesException("GetServer plugin message call operation timed out"); + } try { - // Load settings - this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), new Settings()).get(); - - // Load locales from language preset default - final Locales languagePresets = Annotaml.create(Locales.class, - Objects.requireNonNull(getResource("locales/" + settings.language + ".yml"))).get(); - this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.language + ".yml"), - languagePresets).get(); - - // Load cached server from file - if (settings.crossServer) { - final File serverFile = new File(getDataFolder(), "server.yml"); - if (serverFile.exists()) { - this.server = Annotaml.create(serverFile, CachedServer.class).get().getServer(); - } - } else { - this.server = new Server("server"); - } - - // Load spawn location from file - final File spawnFile = new File(getDataFolder(), "spawn.yml"); - if (spawnFile.exists()) { - this.serverSpawn = Annotaml.create(spawnFile, CachedSpawn.class).get(); - } - } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { - throw new HuskHomesException("Failed to load config data", e); + this.server = new Server(serverName); + Annotaml.create(new File(getDataFolder(), "server.yml"), new CachedServer(serverName)); + getLoggingAdapter().log(Level.INFO, "Successfully cached server name to disk (" + serverName + ")"); + } catch (IOException e) { + throw new HuskHomesException("Failed to write cached server name to disk", e); } - return true; }).exceptionally(throwable -> { - getLoggingAdapter().log(Level.SEVERE, "Failed to load data from the config", throwable); - return false; + getLoggingAdapter().log(Level.SEVERE, "Failed to fetch and cache server name", throwable); + return null; }); } + @Override + @NotNull + public List getWorlds() { + return getServer().getWorlds().stream().filter(world -> BukkitAdapter.adaptWorld(world).isPresent()).map(world -> BukkitAdapter.adaptWorld(world).orElse(null)).collect(Collectors.toList()); + } + + @Override + public boolean reload() { + try { + // Load settings + this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), new Settings()).get(); + + // Load locales from language preset default + final Locales languagePresets = Annotaml.create(Locales.class, Objects.requireNonNull(getResource("locales/" + settings.language + ".yml"))).get(); + this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.language + ".yml"), languagePresets).get(); + + // Load cached server from file + if (settings.crossServer) { + final File serverFile = new File(getDataFolder(), "server.yml"); + if (serverFile.exists()) { + this.server = Annotaml.create(serverFile, CachedServer.class).get().getServer(); + } + } else { + this.server = new Server("server"); + } + + // Load spawn location from file + final File spawnFile = new File(getDataFolder(), "spawn.yml"); + if (spawnFile.exists()) { + this.serverSpawn = Annotaml.create(spawnFile, CachedSpawn.class).get(); + } + + // Load unsafe blocks from resources + final InputStream blocksResource = getResource("safety/unsafe_blocks.yml"); + this.unsafeBlocks = Annotaml.create(new UnsafeBlocks(), Objects.requireNonNull(blocksResource)).get(); + + return true; + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + getLoggingAdapter().log(Level.SEVERE, "Failed to reload HuskHomes config or messages file", e); + } + return false; + } + + @Override + public boolean isBlockUnsafe(@NotNull String blockId) { + return unsafeBlocks.isUnsafe(blockId); + } + @Override public void registerMetrics(int metricsId) { try { @@ -565,8 +572,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { // Super constructor for unit testing @SuppressWarnings("unused") - protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, - @NotNull File dataFolder, @NotNull File file) { + protected BukkitHuskHomes(@NotNull JavaPluginLoader loader, @NotNull PluginDescriptionFile description, @NotNull File dataFolder, @NotNull File file) { super(loader, description, dataFolder, file); } diff --git a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyUtil.java b/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyUtil.java deleted file mode 100644 index 5c19a28c..00000000 --- a/bukkit/src/main/java/net/william278/huskhomes/util/BukkitSafetyUtil.java +++ /dev/null @@ -1,78 +0,0 @@ -package net.william278.huskhomes.util; - -import net.william278.huskhomes.position.Location; -import net.william278.huskhomes.position.World; -import org.bukkit.ChunkSnapshot; -import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; - -import java.util.Optional; - -public class BukkitSafetyUtil { - - /** - * Finds a safe location to teleport to about a point. - * - * @param world The world to search in - * @param bukkitLocation The location to search around - * @param chunkSnapshot The chunk snapshot to search in - * @return The safe location, if found - */ - public static Optional findSafeLocation(@NotNull World world, @NotNull org.bukkit.Location bukkitLocation, - @NotNull ChunkSnapshot chunkSnapshot) { - // Validate world - final org.bukkit.World bukkitWorld = bukkitLocation.getWorld(); - if (bukkitWorld == null) { - return Optional.empty(); - } - - // Search nearby blocks for a safe, valid position - for (int i = -1; i <= 1; i++) { - for (int j = -1; j <= 1; j++) { - int chunkX = Math.abs(bukkitLocation.getBlockX() % 16) + i; - int chunkZ = Math.abs(bukkitLocation.getBlockZ() % 16) + j; - if (chunkX < 0 || chunkX > 15 || chunkZ < 0 || chunkZ > 15) { - continue; - } - int chunkY = chunkSnapshot.getHighestBlockYAt(chunkX, chunkZ); - if (isSafePosition(chunkSnapshot, chunkX, chunkY, chunkZ, bukkitWorld)) { - return Optional.of(new Location(bukkitLocation.getBlockX() + i, - chunkY + 1.5d, bukkitLocation.getBlockZ() + j, - 90, 0, world)); - } - } - } - return Optional.empty(); - } - - /** - * Searches a chunk and returns if a block is safe to teleport to. - * - * @param chunkSnapshot The chunk snapshot to search in - * @param chunkX The chunk x coordinate to search at - * @param chunkY The chunk y coordinate to search at - * @param chunkZ The chunk z coordinate to search at - * @param world The world to search in - * @return True if the block is safe, false otherwise - */ - public static boolean isSafePosition(@NotNull ChunkSnapshot chunkSnapshot, - final int chunkX, final int chunkY, final int chunkZ, - @NotNull org.bukkit.World world) { - // Check validity of the y-coordinate - if (chunkY < world.getMinHeight() || chunkY > world.getMaxHeight()) { - return false; - } - - // Check block safety - final Material blockType = chunkSnapshot.getBlockType(chunkX, chunkY, chunkZ); - return switch (blockType) { - // Special case handling for safe, un-solid blocks - case TALL_GRASS, TALL_SEAGRASS, FERN, LARGE_FERN, DANDELION, POPPY, BLUE_ORCHID, ALLIUM, AZURE_BLUET, - RED_TULIP, ORANGE_TULIP, WHITE_TULIP, PINK_TULIP, OXEYE_DAISY, CORNFLOWER, LILY_OF_THE_VALLEY, - ROSE_BUSH, WHEAT_SEEDS, BEETROOT_SEEDS, MELON_SEEDS, PUMPKIN_SEEDS, GRASS_PATH, FARMLAND, - OAK_LEAVES, BIRCH_LEAVES, DEAD_BUSH, SUGAR_CANE, SNOW, ICE, BLUE_ICE, FROSTED_ICE -> true; - default -> blockType.isSolid() || blockType.isOccluding(); - }; - } - -} diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index 2d755bd7..84bb746f 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -358,7 +358,15 @@ public interface HuskHomes { * * @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful */ - CompletableFuture reload(); + boolean reload(); + + /** + * Returns if the block, by provided identifier, is unsafe + * + * @param blockId The block identifier (e.g. {@code minecraft:stone}) + * @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise + */ + boolean isBlockUnsafe(@NotNull String blockId); /** * Registers the plugin with bStats metrics diff --git a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java index 77dd2ef9..e81e5856 100644 --- a/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/HuskHomesCommand.java @@ -86,13 +86,11 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, .ifPresent(onlineUser::sendMessage); return; } - plugin.reload().thenAccept(reloaded -> { - if (!reloaded) { - onlineUser.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)")); - return; - } - onlineUser.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) �fb9a&| Reloaded config & message files.")); - }); + if (!plugin.reload()) { + onlineUser.sendMessage(new MineDown("[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)")); + return; + } + onlineUser.sendMessage(new MineDown("[HuskHomes](#00fb9a bold) �fb9a&| Reloaded config & message files.")); } case "update" -> { if (!onlineUser.hasPermission(Permission.COMMAND_HUSKHOMES_UPDATE.node)) { @@ -135,13 +133,13 @@ public class HuskHomesCommand extends CommandBase implements ConsoleExecutable, (command.command.length() < 16 ? " ".repeat(16 - command.command.length()) : "") + " - " + command.getDescription())); } - case "reload" -> plugin.reload().thenAccept(reloaded -> { - if (!reloaded) { + case "reload" -> { + if (!plugin.reload()) { plugin.getLoggingAdapter().log(Level.SEVERE, "Failed to reload the plugin."); return; } plugin.getLoggingAdapter().log(Level.INFO, "Reloaded config & message files."); - }); + } case "update" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresentOrElse(newVersion -> plugin.getLoggingAdapter().log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion diff --git a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java index a2058462..f61f1edf 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -62,9 +62,9 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } final Instant currentTime = Instant.now(); if (isExecutorTeleporting && !currentTime.isAfter(userData.get().rtpCooldown()) - && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { + && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { plugin.getLocales().getLocale("error_rtp_cooldown", - Long.toString(currentTime.until(userData.get().rtpCooldown(), ChronoUnit.MINUTES))) + Long.toString(currentTime.until(userData.get().rtpCooldown(), ChronoUnit.MINUTES) + 1)) .ifPresent(onlineUser::sendMessage); return; } @@ -86,7 +86,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { teleportFuture.thenAccept(teleport -> teleport.execute() .thenAccept(result -> { if (isExecutorTeleporting && - result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { + result.successful() && !onlineUser.hasPermission(Permission.BYPASS_RTP_COOLDOWN.node)) { plugin.getDatabase().updateUserData(new UserData(onlineUser, userData.get().homeSlots(), userData.get().ignoringTeleports(), Instant.now().plus(plugin.getSettings().rtpCooldownLength, ChronoUnit.MINUTES))); diff --git a/common/src/main/java/net/william278/huskhomes/config/Settings.java b/common/src/main/java/net/william278/huskhomes/config/Settings.java index 788c0c30..7cdd3e47 100644 --- a/common/src/main/java/net/william278/huskhomes/config/Settings.java +++ b/common/src/main/java/net/william278/huskhomes/config/Settings.java @@ -203,9 +203,6 @@ public class Settings { @YamlKey("rtp.distribution_deviation") public float rtpDistributionStandardDeviation = 2f; - @YamlKey("rtp.location_cache_size") - public int rtpLocationCacheSize = 10; - @YamlKey("rtp.restricted_worlds") public List rtpRestrictedWorlds = List.of("world_nether", "world_the_end"); diff --git a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java index f385ecb2..a33f4441 100644 --- a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java @@ -3,11 +3,11 @@ package net.william278.huskhomes.random; import net.william278.huskhomes.HuskHomes; import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; -import net.william278.huskhomes.position.Server; import net.william278.huskhomes.position.World; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.Optional; +import java.util.Random; import java.util.concurrent.CompletableFuture; /** @@ -19,11 +19,6 @@ public class NormalDistributionEngine extends RandomTeleportEngine { protected final int spawnRadius; private final float mean; private final float standardDeviation; - private final int cacheSize; - - // Cache of random positions - @NotNull - private final Map> cache; public NormalDistributionEngine(@NotNull HuskHomes implementor) { super(implementor, "Normal Distribution"); @@ -31,16 +26,6 @@ public class NormalDistributionEngine extends RandomTeleportEngine { this.spawnRadius = implementor.getSettings().rtpSpawnRadius; this.mean = implementor.getSettings().rtpDistributionMean; this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation; - this.cacheSize = implementor.getSettings().rtpLocationCacheSize; - this.cache = new HashMap<>(); - - // Prepare cache - for (final World world : implementor.getWorlds()) { - if (implementor.getSettings().rtpRestrictedWorlds.contains(world.name)) { - continue; - } - cache.put(world.uuid, new LinkedList<>()); - } } /** @@ -52,7 +37,7 @@ public class NormalDistributionEngine extends RandomTeleportEngine { */ @NotNull protected static Location generateLocation(@NotNull Location origin, float mean, float standardDeviation, - float spawnRadius, float maxRadius) { + float spawnRadius, float maxRadius) { // Generate random values final float radius = generateNormallyDistributedRadius(mean, standardDeviation, spawnRadius, maxRadius); final float angle = generateRandomAngle(); @@ -100,34 +85,18 @@ public class NormalDistributionEngine extends RandomTeleportEngine { return (float) (Math.random() * 360); } - /** - * Populate the cache with a set of random locations - */ - private void populateCache(@NotNull World world) { - final Server server = plugin.getPluginServer(); - while (cache.size() < cacheSize) { - generateSafeLocation(world).thenAccept(location -> location - .ifPresent(value -> cache.getOrDefault(world.uuid, new LinkedList<>()) - .addLast(new Position(value, server)))); - } - } @Override - public CompletableFuture findRandomPosition(@NotNull World world, @NotNull String[] args) { - CompletableFuture position; - if (!cache.getOrDefault(world.uuid, new LinkedList<>()).isEmpty()) { - position = CompletableFuture.completedFuture(cache.get(world.uuid).removeFirst()); - } else { - position = CompletableFuture.supplyAsync(() -> { - Optional resolved = Optional.empty(); - while (resolved.isEmpty()) { - resolved = generateSafeLocation(world).join(); - } - return new Position(resolved.get(), plugin.getPluginServer()); - }); + public CompletableFuture> getRandomPosition(@NotNull World world, @NotNull String[] args) { + Optional location = generateSafeLocation(world).join(); + int attempts = 0; + while (location.isEmpty()) { + location = generateSafeLocation(world).join(); + if (attempts > randomTimeout) { + return CompletableFuture.completedFuture(null); + } } - - CompletableFuture.runAsync(() -> populateCache(world)); - return position; + return CompletableFuture.completedFuture(location.map(resolved -> + new Position(resolved, plugin.getPluginServer()))); } } diff --git a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java index c4a90e3f..575e5542 100644 --- a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java @@ -7,7 +7,6 @@ import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; public abstract class RandomTeleportEngine { @@ -18,7 +17,7 @@ public abstract class RandomTeleportEngine { public final String name; /** - * How long before {@link #getRandomPosition} future calls time out + * How many attempts to allow {@link #getRandomPosition} lookups before timing out */ public long randomTimeout = 8; @@ -44,15 +43,6 @@ public abstract class RandomTeleportEngine { world, plugin.getPluginServer())); } - /** - * Finds a random position in the {@link World} - * - * @param world The world to find a random position in - * @param args The arguments to pass to the random teleport engine - * @return A {@link CompletableFuture} containing the random position - */ - public abstract CompletableFuture findRandomPosition(@NotNull World world, @NotNull String[] args); - /** * Gets a random position in the {@link World}, supplying a future to be completed with the optional position * is found, or empty if the operation times out @@ -62,11 +52,6 @@ public abstract class RandomTeleportEngine { * @return A {@link CompletableFuture} containing the random position, if one was found before the * {@link #randomTimeout operation timed out} */ - public final CompletableFuture> getRandomPosition(@NotNull World world, @NotNull String[] args) { - return findRandomPosition(world, args) - .orTimeout(Math.max(1, randomTimeout), TimeUnit.SECONDS) - .exceptionally(e -> null) - .thenApplyAsync(Optional::ofNullable); - } + public abstract CompletableFuture> getRandomPosition(@NotNull World world, @NotNull String[] args); } diff --git a/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java b/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java new file mode 100644 index 00000000..8e506951 --- /dev/null +++ b/common/src/main/java/net/william278/huskhomes/util/UnsafeBlocks.java @@ -0,0 +1,36 @@ +package net.william278.huskhomes.util; + +import net.william278.annotaml.YamlFile; +import net.william278.annotaml.YamlKey; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +@YamlFile(header = """ + ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ + ┃ Unsafe /rtp Blocks ┃ + ┃ Developed by William278 ┃ + ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛""") +public class UnsafeBlocks { + + @YamlKey("unsafe_blocks") + public List unsafeBlocks; + + /** + * Returns if the block, by provided identifier, is unsafe + * + * @param blockId The block identifier (e.g. {@code minecraft:stone}) + * @return {@code true} if the block is on the unsafe blocks list, {@code false} otherwise + */ + public boolean isUnsafe(@NotNull String blockId) { + if (!blockId.startsWith("minecraft:")) { + blockId = "minecraft:" + blockId; + } + return unsafeBlocks.contains(blockId); + } + + @SuppressWarnings("unused") + public UnsafeBlocks() { + } + +} diff --git a/common/src/main/resources/locales/en-gb.yml b/common/src/main/resources/locales/en-gb.yml index 19b03813..38ff371e 100644 --- a/common/src/main/resources/locales/en-gb.yml +++ b/common/src/main/resources/locales/en-gb.yml @@ -129,7 +129,7 @@ error_invalid_teleport_request: '[Error:](#ff3300) [You do not have a pending te error_teleport_request_self: '[Error:](#ff3300) [You cannot send a teleport request to yourself.](#ff7e5e)' error_player_not_found: '[Error:](#ff3300) [Could not find the player %1%.](#ff7e5e)' error_rtp_restricted_world: '[Error:](#ff3300) [You cannot randomly teleport in this world.](#ff7e5e)' -error_rtp_cooldown: '[Error:](#ff3300) [You must wait %1% minutes before randomly teleporting again.](#ff7e5e)' +error_rtp_cooldown: '[Error:](#ff3300) [You must wait %1% minute(s) before randomly teleporting again.](#ff7e5e)' error_command_disabled: '[Error:](#ff3300) [That command is disabled!](#ff7e5e)' error_console_command_only: '[Error:](#ff3300) [That command can only be run from the server console.](#ff7e5e)' error_rtp_randomization_timeout: '[Error:](#ff3300) [Failed to find a safe random location to teleport you.](#ff7e5e)' diff --git a/common/src/main/resources/safety/unsafe_blocks.yml b/common/src/main/resources/safety/unsafe_blocks.yml new file mode 100644 index 00000000..e8ff7563 --- /dev/null +++ b/common/src/main/resources/safety/unsafe_blocks.yml @@ -0,0 +1,25 @@ +# ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +# ┃ Unsafe /rtp Blocks ┃ +# ┃ Developed by William278 ┃ +# ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ +unsafe_blocks: + - 'minecraft:water' + - 'minecraft:lava' + - 'minecraft:fire' + - 'minecraft:flowing_water' + - 'minecraft:flowing_lava' + - 'minecraft:standing_sign' + - 'minecraft:wall_sign' + - 'minecraft:chest' + - 'minecraft:trapped_chest' + - 'minecraft:ender_chest' + - 'minecraft:bed' + - 'minecraft:jungle_leaves' + - 'minecraft:spruce_leaves' + - 'minecraft:bedrock' + - 'minecraft:powder_snow' + - 'minecraft:air' + - 'minecraft:cave_air' + - 'minecraft:void_air' + - 'minecraft:pointed_dripstone' + - 'minecraft:cactus' \ No newline at end of file