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 2998d34b..ea1e464b 100644 --- a/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java +++ b/common/src/main/java/net/william278/huskhomes/api/BaseHuskHomesAPI.java @@ -190,12 +190,14 @@ public abstract class BaseHuskHomesAPI { * @param user The {@link OnlineUser} to teleport * @param timedTeleport Whether the teleport should be timed or not (requiring a warmup where they must stand still * for a period of time) + * @param rtpArgs Arguments that will be passed to the implementing {@link RandomTeleportEngine} * @return A {@link CompletableFuture} that will complete with a {@link TeleportResult} indicating the result of * completing the teleport. If the teleport was successful, the {@link TeleportResult#successful} will be {@code true}. * @since 3.0 */ - public final CompletableFuture randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport) { - return CompletableFuture.supplyAsync(() -> plugin.getRandomTeleportEngine().getRandomPosition(user.getPosition()) + public final CompletableFuture randomlyTeleportPlayer(@NotNull OnlineUser user, boolean timedTeleport, + @NotNull String... rtpArgs) { + return CompletableFuture.supplyAsync(() -> plugin.getRandomTeleportEngine().getRandomPosition(user.getPosition(), rtpArgs) .thenApply(position -> { if (position.isPresent()) { return teleportPlayer(user, position.get(), timedTeleport).join(); 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 4d778456..6f831261 100644 --- a/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java +++ b/common/src/main/java/net/william278/huskhomes/command/RtpCommand.java @@ -6,6 +6,7 @@ import net.william278.huskhomes.player.OnlineUser; import net.william278.huskhomes.player.UserData; import net.william278.huskhomes.position.Position; import net.william278.huskhomes.util.Permission; +import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.NotNull; import java.time.Instant; @@ -23,7 +24,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { @Override public void onExecute(@NotNull OnlineUser onlineUser, @NotNull String[] args) { OnlineUser target = onlineUser; - if (args.length == 1) { + if (args.length >= 1) { if (!onlineUser.hasPermission(Permission.COMMAND_RTP_OTHER.node)) { plugin.getLocales().getLocale("error_no_permission").ifPresent(onlineUser::sendMessage); return; @@ -35,12 +36,9 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { return; } target = foundUser.get(); - } else if (args.length > 1) { - plugin.getLocales().getLocale("error_invalid_syntax", "/rtp [player]") - .ifPresent(onlineUser::sendMessage); - return; } final Position userPosition = target.getPosition(); + final String[] rtpArguments = args.length >= 1 ? ArrayUtils.subarray(args, 1, args.length) : args; if (plugin.getSettings().rtpRestrictedWorlds.stream() .anyMatch(worldName -> worldName.equals(userPosition.world.name))) { plugin.getLocales().getLocale("error_rtp_restricted_world") @@ -72,7 +70,7 @@ public class RtpCommand extends CommandBase implements ConsoleExecutable { } // Get a random position and teleport - plugin.getRandomTeleportEngine().getRandomPosition(userPosition) + plugin.getRandomTeleportEngine().getRandomPosition(userPosition, rtpArguments) .thenAccept(position -> { if (position.isEmpty()) { plugin.getLocales().getLocale("error_rtp_randomization_timeout") @@ -107,7 +105,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().getPosition()).thenAccept(position -> { + plugin.getRandomTeleportEngine().getRandomPosition(foundUser.get().getPosition(), 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 67c9fca1..411c962d 100644 --- a/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/NormalDistributionEngine.java @@ -15,18 +15,23 @@ import java.util.concurrent.TimeUnit; 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; public NormalDistributionEngine(@NotNull HuskHomes implementor) { super(implementor, "Normal Distribution"); + this.radius = implementor.getSettings().rtpRadius; + this.spawnRadius = implementor.getSettings().rtpSpawnRadius; this.mean = implementor.getSettings().rtpDistributionMean; this.standardDeviation = implementor.getSettings().rtpDistributionStandardDeviation; this.plugin = implementor; } @Override - protected @NotNull CompletableFuture> generateRandomPosition(@NotNull Location origin) { + protected @NotNull CompletableFuture> generateRandomLocation(@NotNull Location origin, + @NotNull String... args) { return CompletableFuture.supplyAsync(() -> plugin.getSafeGroundLocation(generateLocation(origin, mean, standardDeviation, spawnRadius, radius)).join()) .orTimeout(5, TimeUnit.SECONDS) 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 8cb8fb21..42eceffc 100644 --- a/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java +++ b/common/src/main/java/net/william278/huskhomes/random/RandomTeleportEngine.java @@ -13,24 +13,42 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** - * An engine for random teleportation, that generates and caches random points + * 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; - protected final int radius; - protected final int spawnRadius; + /** + * Number of random positions to cache on each world + */ protected final int cacheSize; + /** + * {@link World}s to serve random positions in + */ @NotNull private final List worlds; + /** + * The cache of random positions for each world + */ @NotNull private final Map> cachedRandomLocations; + /** + * (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 + */ protected RandomTeleportEngine(@NotNull HuskHomes implementor, @NotNull String name) { this.name = name; - this.radius = implementor.getSettings().rtpRadius; - this.spawnRadius = implementor.getSettings().rtpSpawnRadius; this.cacheSize = implementor.getSettings().rtpLocationCacheSize; this.worlds = implementor.getWorlds().stream() .filter(world -> world.environment != World.Environment.NETHER) @@ -39,18 +57,28 @@ public abstract class RandomTeleportEngine { this.cachedRandomLocations = new HashMap<>(); } - //todo better API for this? - protected RandomTeleportEngine(@NotNull String name, int radius, int spawnRadius, int cacheSize, @NotNull List worlds) { + /** + * Create a new random teleport engine + * + * @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 + */ + @SuppressWarnings("unused") + protected RandomTeleportEngine(@NotNull String name, @NotNull List worlds) { this.name = name; - this.radius = radius; - this.spawnRadius = spawnRadius; - this.cacheSize = cacheSize; + this.cacheSize = 10; this.worlds = worlds; this.cachedRandomLocations = new HashMap<>(); } /** - * Initializes the RTP engine, populating the cache. This is to be called after the engine has been created. + * Initializes the RTP engine, populating the cache with random positons for each world. + * This is called after the engine is registered. + * + * @since 3.0 */ public void initialize() { CompletableFuture.runAsync(() -> { @@ -62,36 +90,64 @@ public abstract class RandomTeleportEngine { } /** - * Populates the cache with new random locations + * Populates the cache with new random locations, by calling {@link #generateRandomLocation(Location, String...)} * * @param world The world to populate the cache for * @param cacheSize The size of the cache + * @since 3.0 */ private void populateCache(@NotNull World world, final int cacheSize) { final int amountToPopulate = Math.max(1, cacheSize) - cachedRandomLocations.get(world).size(); for (final AtomicInteger i = new AtomicInteger(); i.get() < amountToPopulate; i.getAndIncrement()) { - generateRandomPosition(new Location(0, 0, 0, 0f, 0f, world)).join() + generateRandomLocation(new Location(0, 0, 0, 0f, 0f, world)).join() .ifPresentOrElse(location -> cachedRandomLocations.get(world).add(location), i::getAndDecrement); } } /** - * Generates a new random position within the radius of the origin position. + * 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 two 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(Position, 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 position - * @return A generated location + * @param origin The origin {@link Location} to generate a random position around (i.e. 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> generateRandomPosition(@NotNull Location origin); + protected abstract CompletableFuture> generateRandomLocation(@NotNull Location origin, + @NotNull String... args); /** - * Returns a random {@link Position} from the cache, generating only if needed + * Returns a random {@link Position} from the cache, generating if the cache is empty * - * @param userPosition The user's position - * @return A random {@link Position} + * @param userPosition The {@link Position} of the requesting user + * @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 Position userPosition) { - return getRandomLocation(userPosition.world).thenApply(location -> { + public CompletableFuture> getRandomPosition(@NotNull Position userPosition, + @NotNull String... args) { + return getRandomLocation(userPosition.world, args).thenApply(location -> { if (location.isEmpty()) { return Optional.empty(); } @@ -104,10 +160,12 @@ public abstract class RandomTeleportEngine { * 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} - * @return a {@link CompletableFuture} containing an {@link Optional} containing a {@link Location} if one was found; - * an {@link Optional#empty()} otherwise + * @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) { + private CompletableFuture> getRandomLocation(@NotNull World world, @NotNull String... args) { return CompletableFuture.supplyAsync(() -> { final Optional keyedWorld = cachedRandomLocations.keySet().stream() .filter(cachedWorld -> cachedWorld.uuid.equals(world.uuid)).findFirst(); @@ -120,7 +178,7 @@ public abstract class RandomTeleportEngine { populateCache(keyedWorld.get(), cacheSize); } } - return generateRandomPosition(new Location(0, 0, 0, 0f, 0f, world)).join(); + return generateRandomLocation(new Location(0, 0, 0, 0f, 0f, world), args).join(); }).orTimeout(5, TimeUnit.SECONDS).exceptionally(throwable -> Optional.empty()); }