From 6b55327e524a4532476a7c8f071b154feb861eee Mon Sep 17 00:00:00 2001 From: William278 Date: Wed, 23 Nov 2022 11:56:58 +0000 Subject: [PATCH] Refactor and simplify RandomTeleportEngine API and logic --- .../william278/huskhomes/BukkitHuskHomes.java | 3 +- .../net/william278/huskhomes/HuskHomes.java | 4 +- .../huskhomes/api/BaseHuskHomesAPI.java | 2 +- .../huskhomes/command/RtpCommand.java | 8 +- .../random/NormalDistributionEngine.java | 76 +++++-- .../random/RandomTeleportEngine.java | 194 ++++-------------- 6 files changed, 109 insertions(+), 178 deletions(-) diff --git a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java index f7bf0656..c3ca450c 100644 --- a/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java +++ b/bukkit/src/main/java/net/william278/huskhomes/BukkitHuskHomes.java @@ -384,7 +384,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { @Override public void setRandomTeleportEngine(@NotNull RandomTeleportEngine randomTeleportEngine) { this.randomTeleportEngine = randomTeleportEngine; - this.randomTeleportEngine.initialize(); } @Override @@ -425,7 +424,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes { } @Override - public CompletableFuture> getSafeGroundLocation(@NotNull Location location) { + public CompletableFuture> resolveSafeGroundLocation(@NotNull Location location) { final CompletableFuture> future = new CompletableFuture<>(); Bukkit.getScheduler().runTask(getInstance(), () -> BukkitAdapter.adaptLocation(location).ifPresentOrElse( bukkitLocation -> { diff --git a/common/src/main/java/net/william278/huskhomes/HuskHomes.java b/common/src/main/java/net/william278/huskhomes/HuskHomes.java index e20dd324..2d755bd7 100644 --- a/common/src/main/java/net/william278/huskhomes/HuskHomes.java +++ b/common/src/main/java/net/william278/huskhomes/HuskHomes.java @@ -155,7 +155,7 @@ public interface HuskHomes { RandomTeleportEngine getRandomTeleportEngine(); /** - * Set the {@link RandomTeleportEngine} to use and initialize it, calling {@link RandomTeleportEngine#initialize()} + * Sets the {@link RandomTeleportEngine} to be used for processing random teleports * * @param randomTeleportEngine the {@link RandomTeleportEngine} to use */ @@ -291,7 +291,7 @@ public interface HuskHomes { * @return a {@link CompletableFuture} that will complete with an optional of the safe ground position, if it is * possible to find one */ - CompletableFuture> getSafeGroundLocation(@NotNull Location location); + CompletableFuture> resolveSafeGroundLocation(@NotNull Location location); /** * Returns the {@link Server} the plugin is on diff --git a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java index 27633174..e057d362 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -389,7 +389,7 @@ public abstract class BaseHuskHomesAPI { final boolean timedTeleport, @NotNull String... rtpArgs) { return CompletableFuture.supplyAsync(() -> plugin.getRandomTeleportEngine() - .getRandomPosition(user, rtpArgs) + .getRandomPosition(user.getPosition().world, rtpArgs) .thenApply(position -> { if (position.isPresent()) { final TeleportBuilder builder = Teleport.builder(plugin, user) 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 839c35ce..a2058462 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -62,7 +62,7 @@ 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))) .ifPresent(onlineUser::sendMessage); @@ -70,7 +70,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } // Get a random position and teleport - plugin.getRandomTeleportEngine().getRandomPosition(onlineUser, rtpArguments).thenAccept(position -> { + plugin.getRandomTeleportEngine().getRandomPosition(onlineUser.getPosition().world, rtpArguments).thenAccept(position -> { if (position.isEmpty()) { plugin.getLocales().getLocale("error_rtp_randomization_timeout") .ifPresent(onlineUser::sendMessage); @@ -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))); @@ -109,7 +109,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } plugin.getLoggingAdapter().log(Level.INFO, "Finding a random position for " + foundUser.get().username + "..."); - plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get(), ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> { + plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition().world, ArrayUtils.subarray(args, 1, args.length)).thenAccept(position -> { if (position.isEmpty()) { plugin.getLoggingAdapter().log(Level.WARNING, "Failed to teleport " + foundUser.get().username + " to a random position; randomization timed out!"); return; 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 8f6b795b..9c1c5b1e 100644 --- a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java @@ -2,10 +2,12 @@ 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.Optional; -import java.util.Random; +import java.util.*; import java.util.concurrent.CompletableFuture; /** @@ -13,11 +15,15 @@ import java.util.concurrent.CompletableFuture; */ public class NormalDistributionEngine extends RandomTeleportEngine { - private final HuskHomes plugin; protected final int radius; 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"); @@ -25,24 +31,28 @@ public class NormalDistributionEngine extends RandomTeleportEngine { this.spawnRadius = implementor.getSettings().rtpSpawnRadius; this.mean = implementor.getSettings().rtpDistributionMean; this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation; - this.plugin = implementor; - } + this.cacheSize = implementor.getSettings().rtpLocationCacheSize; + this.cache = new HashMap<>(); - @Override - protected @NotNull CompletableFuture> generateRandomLocation(@NotNull Location origin, - @NotNull String... args) { - return plugin.getSafeGroundLocation(generateLocation(origin, mean, standardDeviation, spawnRadius, radius)); + // Prepare cache + for (final World world : implementor.getWorlds()) { + if (implementor.getSettings().rtpRestrictedWorlds.contains(world.name)) { + continue; + } + cache.put(world.uuid, new LinkedList<>()); + } } /** - * Generate a location through a randomized normally-distributed radius and random angle using the mean and + * Generate a {@link Location} through a randomized normally-distributed radius and random angle using the mean and * standard deviation, about the origin position. * * @param origin The origin position * @return A generated location */ - protected static Location generateLocation(@NotNull Location origin, float mean, float standardDeviation, - float spawnRadius, float maxRadius) { + @NotNull + private static Location generateLocation(@NotNull Location origin, float mean, float standardDeviation, + float spawnRadius, float maxRadius) { // Generate random values final float radius = generateNormallyDistributedRadius(mean, standardDeviation, spawnRadius, maxRadius); final float angle = generateRandomAngle(); @@ -55,6 +65,17 @@ public class NormalDistributionEngine extends RandomTeleportEngine { origin.yaw, origin.pitch, origin.world); } + /** + * Generate a safe ground-level {@link Location} through a randomized normally-distributed radius and random angle + * + * @param world The world to generate the location in + * @return A generated location + */ + private CompletableFuture> generateSafeLocation(@NotNull World world) { + return plugin.resolveSafeGroundLocation(generateLocation( + getOrigin(world), mean, standardDeviation, spawnRadius, radius)); + } + /** * Generates a normally distributed radius between the spawnRadius and the maximum radius value, * using the provided standard deviation and mean. @@ -78,4 +99,35 @@ public class NormalDistributionEngine extends RandomTeleportEngine { private static float generateRandomAngle() { 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()); + }); + } + + CompletableFuture.runAsync(() -> populateCache(world)); + return position; + } } 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 25330bfe..c4a90e3f 100644 --- a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java @@ -1,192 +1,72 @@ package net.william278.huskhomes.random; import net.william278.huskhomes.HuskHomes; -import net.william278.huskhomes.player.OnlineUser; -import net.william278.huskhomes.position.Location; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.position.World; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -/** - * An engine for random teleportation, that generates and caches random locations and serves them as requested - *

- * See {@link #generateRandomLocation(Location, String...)} for details on how to generate positions - * - * @since 3.0 - */ public abstract class RandomTeleportEngine { - /** - * Name of the engine - */ @NotNull - protected final String name; - /** - * Number of random positions to cache on each world - */ - protected final int cacheSize; - /** - * {@link World}s to serve random positions in - */ + protected final HuskHomes plugin; + @NotNull - private final List worlds; - /** - * A cache of random {@link Location}s for each random teleport world - */ - @NotNull - private final Map> cachedPositions; + public final String name; /** - * (Internal use only) Create a new random teleport engine, using HuskHomes config settings - * - * @param implementor The HuskHomes instance - * @param name The name of the engine + * How long before {@link #getRandomPosition} future calls time out */ - protected RandomTeleportEngine(@NotNull HuskHomes implementor, @NotNull String name) { + public long randomTimeout = 8; + + protected RandomTeleportEngine(@NotNull HuskHomes plugin, @NotNull String name) { + this.plugin = plugin; this.name = name; - this.cacheSize = implementor.getSettings().rtpLocationCacheSize; - this.worlds = implementor.getWorlds().stream() - .filter(world -> world.environment != World.Environment.NETHER) - .filter(world -> !implementor.getSettings().rtpRestrictedWorlds.contains(world.name)) - .collect(Collectors.toList()); - this.cachedPositions = new HashMap<>(); } /** - * Create a new random teleport engine + * Get the origin position (spawn) of this server * - * @param name The name of the engine - * @param worlds The worlds to serve random locations for. Random locations will be generated using - * {@link #generateRandomLocation(Location, String...)} for each world in this list when - * {@link #initialize()} is called. - * @since 3.0 + * @return The origin position */ - @SuppressWarnings("unused") - protected RandomTeleportEngine(@NotNull String name, @NotNull List worlds) { - this.name = name; - this.cacheSize = 10; - this.worlds = worlds; - this.cachedPositions = new HashMap<>(); + protected final Position getOrigin(@NotNull World world) { + return plugin.getLocalCachedSpawn() + .flatMap(spawn -> { + if (!spawn.worldUuid.equals(world.uuid.toString())) { + return Optional.empty(); + } + return spawn.getPosition(plugin.getPluginServer()); + }) + .orElse(new Position(0d, 128d, 0d, 0f, 0f, + world, plugin.getPluginServer())); } /** - * Initializes the RTP engine, populating the cache with random positons for each world. - * This is called after the engine is registered. + * Finds a random position in the {@link World} * - * @since 3.0 + * @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 void initialize() { - CompletableFuture.runAsync(() -> { - for (final World world : worlds) { - cachedPositions.put(world, new LinkedList<>()); - populateCache(world, cacheSize); - } - }); - } + public abstract CompletableFuture findRandomPosition(@NotNull World world, @NotNull String[] args); /** - * Attempts to populate the cache with new random locations, by calling - * {@link #generateRandomLocation(Location, String...)} + * 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 * - * @param world The world to populate the cache for - * @param cacheSize The size of the cache - * @since 3.0 + * @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, if one was found before the + * {@link #randomTimeout operation timed out} */ - private void populateCache(@NotNull World world, final int cacheSize) { - if (cacheSize <= 0) { - return; - } - CompletableFuture.runAsync(() -> { - final int amountToPopulate = cacheSize - cachedPositions.get(world).size(); - final Location originLocation = new Location(0, 0, 0, world); - for (int i = 0; i < amountToPopulate; i++) { - generateRandomLocation(originLocation) - .thenAcceptAsync(location -> location - .ifPresent(generated -> cachedPositions.get(world).add(generated))) - .orTimeout(10, TimeUnit.SECONDS) - .exceptionally(throwable -> null); - } - }); - } - - /** - * Generates a new random {@link Location} on this server within the radius of the origin position. - *

- * The default implementation of a {@link RandomTeleportEngine} will only invoke this message in three occasions: - *

    - *
  • If the cache is empty (the arguments specified by the permission request command will be passed).
  • - *
  • When a position has been requested from the cache ({@link #getRandomLocation(World, String...)}, this will - * be called as many times as needed to replenish the cache. (no arguments will be passed).
  • - *
  • When {@link #initialize()} is called while the plugin is enabling (no arguments will be passed).
  • - *
- * Locations returned by this method should be safe for players to teleport to. This means that the location has - * solid ground to stand on and that the player will not die by standing still at the location. - * Implementations of HuskHomes validate location safety using {@link HuskHomes#getSafeGroundLocation(Location)}. - *

- * RandomTeleportEngines that wish to return cross-server random {@link Position}s can use this method to cache - * locations on this server, and override {@link #getRandomPosition(OnlineUser, String...)} to return a random position - * from the caches of the engine on other servers. - *

- * If you'd prefer not to use caching for whatever reason, you can simply override {@link #getRandomLocation(World, String...)} - * to call this method directly, though this will affect the speed at which positions can be served to users. - * - * @param origin The origin {@link Location} to generate a random position around, such as the server spawn, or - * ({@code x: 0, z: 0}) - * @param args Arguments specified by the random location request. These may be used to alter which locations are - * generated by the randomizer. - * @return a generated {@link Location} if one was found; an {@link Optional#empty()} otherwise - * @since 3.0 - */ - @NotNull - protected abstract CompletableFuture> generateRandomLocation(@NotNull Location origin, - @NotNull String... args); - - /** - * Returns a random {@link Position} from the cache, generating if the cache is empty - * - * @param onlineUser The {@link OnlineUser} requesting the random position - * @param args Arguments specified by the random location request. These may be used to alter which locations are - * generated by the randomizer. - * @return a generated {@link Location} if one was found; an {@link Optional#empty()} otherwise - * @since 3.0 - */ - public CompletableFuture> getRandomPosition(@NotNull OnlineUser onlineUser, - @NotNull String... args) { - return getRandomLocation(onlineUser.getPosition().world, args).thenApply(location -> - location.map(position -> new Position(position, onlineUser.getPosition().server))); - } - - /** - * Returns a random {@link Location} on this server from the cache, only generating if necessary - * - * @param world the {@link World} to search for a random {@link Location}. Note that ({@code x: 0, z: 0}) will be - * passed as the origin position in the world - * @param args Arguments specified by the random location request. These may be used to alter which locations are - * generated by the randomizer. - * @return a generated {@link Location} if one was found; an {@link Optional#empty()} otherwise - * @since 3.0 - */ - private CompletableFuture> getRandomLocation(@NotNull World world, @NotNull String... args) { - final Optional keyedWorld = cachedPositions.keySet().stream() - .filter(cachedWorld -> cachedWorld.uuid.equals(world.uuid)) - .findFirst(); - if (keyedWorld.isPresent()) { - final Queue cachedWorldLocations = cachedPositions.get(keyedWorld.get()); - if (!cachedWorldLocations.isEmpty()) { - populateCache(keyedWorld.get(), cacheSize); - return CompletableFuture.completedFuture(Optional.of(cachedWorldLocations.remove())); - } else { - populateCache(keyedWorld.get(), cacheSize); - } - } - return generateRandomLocation(new Location(0, 0, 0, world), args) - .orTimeout(5, TimeUnit.SECONDS) - .exceptionally(throwable -> Optional.empty()); + 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); } }