fix(lint,command,scheduler): lpk alias, ReturnCount/IllegalCatch triage, scheduler facade
- command: replace /lp alias with /lpk (LuckPerms conflict, p.144);
parkour alias kept; docs/changelog/javadoc updated
- lint p.169: restructure last 69 void early-returns into if-blocks and
helpers; ReturnCount is now an error gate (0 violations)
- lint p.170: Throwable->RuntimeException on 3 boundaries; narrow 5
catches to concrete types; document 14 intentional boundary catches
- scheduler p.21: add runTimerAsync to the facade (Bukkit + Folia
backends); MetricsCacheStore and duels go through the facade, no
BukkitRunnable/Bukkit.getScheduler outside scheduler/ (archunit
freeze-store emptied); drop the unverified Folia badge from README
- tracker: mark p.26-29/32-33 done (fixed in fea15e6, verified)
This commit is contained in:
parent
8ff02cff18
commit
b6712391fd
79 changed files with 696 additions and 800 deletions
|
|
@ -104,6 +104,7 @@ public final class LoParkour extends JavaPlugin {
|
|||
try {
|
||||
session.onAllPlayersLeft();
|
||||
} catch (Exception e) {
|
||||
// Boundary: one failing session must not abort server shutdown.
|
||||
getLogger().warning("Error cleaning up session: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
|
|
@ -125,7 +126,7 @@ public final class LoParkour extends JavaPlugin {
|
|||
}
|
||||
Storage.close();
|
||||
World.delete();
|
||||
} catch (Throwable t) {
|
||||
} catch (RuntimeException t) {
|
||||
getLogger().log(Level.SEVERE, "Error during plugin shutdown: " + t.getMessage(), t);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ package dev.loki.loparkour.adaptive.core.metrics;
|
|||
|
||||
import dev.loki.loparkour.adaptive.model.PlayerMetrics;
|
||||
import dev.loki.loparkour.adaptive.storage.StatsRepository;
|
||||
import dev.loki.loparkour.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
|
@ -29,7 +30,7 @@ public class MetricsCacheStore {
|
|||
private final StatsRepository repository;
|
||||
private final Map<UUID, PlayerMetrics> metricsCache;
|
||||
|
||||
private BukkitRunnable autoSaveTask;
|
||||
private ScheduledTask autoSaveTask;
|
||||
|
||||
public MetricsCacheStore(@NotNull Plugin plugin, @NotNull StatsRepository repository) {
|
||||
this.plugin = plugin;
|
||||
|
|
@ -81,14 +82,8 @@ public class MetricsCacheStore {
|
|||
autoSaveTask.cancel();
|
||||
}
|
||||
|
||||
autoSaveTask = new BukkitRunnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
saveAll();
|
||||
}
|
||||
};
|
||||
|
||||
autoSaveTask.runTaskTimerAsynchronously(plugin, AUTO_SAVE_INTERVAL_TICKS, AUTO_SAVE_INTERVAL_TICKS);
|
||||
autoSaveTask = Scheduler.get(plugin).runTimerAsync(this::saveAll,
|
||||
AUTO_SAVE_INTERVAL_TICKS, AUTO_SAVE_INTERVAL_TICKS);
|
||||
}
|
||||
|
||||
public void stopAutoSave() {
|
||||
|
|
|
|||
|
|
@ -123,6 +123,7 @@ public final class PluginBootstrap {
|
|||
World.create();
|
||||
plugin.getLogger().info("Parkour world created successfully!");
|
||||
} catch (Exception ex) {
|
||||
// Boundary: world creation must never break enable; provider behavior varies across versions.
|
||||
plugin.getLogger().log(Level.SEVERE, "Failed to create parkour world", ex);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,13 +26,11 @@ public final class ForceJoinExecutor {
|
|||
}
|
||||
if ("everyone".equalsIgnoreCase(target)) {
|
||||
joinEveryone(sender);
|
||||
return;
|
||||
}
|
||||
if ("nearest".equalsIgnoreCase(target)) {
|
||||
} else if ("nearest".equalsIgnoreCase(target)) {
|
||||
joinNearest(sender);
|
||||
return;
|
||||
} else {
|
||||
joinByName(target, sender);
|
||||
}
|
||||
joinByName(target, sender);
|
||||
}
|
||||
|
||||
private void joinEveryone(CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -26,9 +26,9 @@ public final class ForceLeaveExecutor {
|
|||
}
|
||||
if ("everyone".equalsIgnoreCase(target)) {
|
||||
leaveEveryone(sender);
|
||||
return;
|
||||
} else {
|
||||
leaveByName(target, sender);
|
||||
}
|
||||
leaveByName(target, sender);
|
||||
}
|
||||
|
||||
private void leaveEveryone(CommandSender sender) {
|
||||
|
|
@ -38,15 +38,13 @@ public final class ForceLeaveExecutor {
|
|||
|
||||
private void leaveByName(String target, CommandSender sender) {
|
||||
final Player other = Bukkit.getPlayer(target);
|
||||
final ParkourUser user = other == null ? null : ParkourUser.getUser(other);
|
||||
if (other == null) {
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_online"));
|
||||
return;
|
||||
}
|
||||
final ParkourUser user = ParkourUser.getUser(other);
|
||||
if (user == null) {
|
||||
} else if (user == null) {
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_playing"));
|
||||
return;
|
||||
} else {
|
||||
ParkourUser.leave(user);
|
||||
}
|
||||
ParkourUser.leave(user);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,9 +26,9 @@ public final class RecoverInventoryExecutor {
|
|||
final Player other = Bukkit.getPlayer(target);
|
||||
if (other == null) {
|
||||
AdminResponses.send(sender, LoParkour.PREFIX + Locales.getString(sender, "admin.player_not_online"));
|
||||
return;
|
||||
} else {
|
||||
recover(other, sender);
|
||||
}
|
||||
recover(other, sender);
|
||||
}
|
||||
|
||||
private void recover(Player other, CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -29,9 +29,9 @@ public final class ResetExecutor {
|
|||
}
|
||||
if ("everyone".equalsIgnoreCase(target)) {
|
||||
resetEveryone(sender);
|
||||
return;
|
||||
} else {
|
||||
resetPlayer(target, sender);
|
||||
}
|
||||
resetPlayer(target, sender);
|
||||
}
|
||||
|
||||
private void resetEveryone(CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -54,16 +54,13 @@ class CommandRouter {
|
|||
private void handle2(String a1, String a2, CommandSender sender, @Nullable Player p) {
|
||||
if (isAdminCommand(a1)) {
|
||||
admin.handle(a1, a2, sender, p);
|
||||
return;
|
||||
} else if (p != null) {
|
||||
if (canCreateSchematic(a1, p)) {
|
||||
SchematicCommandHandler.handleCreateDifficultyOnly(a2, sender, p, player);
|
||||
} else {
|
||||
handlePlayerSubcommand(a1, a2, sender, p);
|
||||
}
|
||||
}
|
||||
if (p == null) {
|
||||
return;
|
||||
}
|
||||
if (canCreateSchematic(a1, p)) {
|
||||
SchematicCommandHandler.handleCreateDifficultyOnly(a2, sender, p, player);
|
||||
return;
|
||||
}
|
||||
handlePlayerSubcommand(a1, a2, sender, p);
|
||||
}
|
||||
|
||||
private static boolean isAdminCommand(String a1) {
|
||||
|
|
@ -95,32 +92,24 @@ class CommandRouter {
|
|||
}
|
||||
|
||||
private void handle3(String a1, String a2, String a3, CommandSender sender, @Nullable Player p) {
|
||||
if (p == null) {
|
||||
if (p == null || !p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
}
|
||||
if (!p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ("schematic".equalsIgnoreCase(a1)) {
|
||||
if ("create".equalsIgnoreCase(a2)) {
|
||||
SchematicCommandHandler.handleCreateDifficultyOnly(a3, sender, p, player);
|
||||
return;
|
||||
} else {
|
||||
SchematicCommandHandler.handleSubcommandWithName(a2, a3, sender, p);
|
||||
}
|
||||
SchematicCommandHandler.handleSubcommandWithName(a2, a3, sender, p);
|
||||
}
|
||||
}
|
||||
|
||||
private void handle4(String a1, String a2, String a3, String a4, CommandSender sender, @Nullable Player p) {
|
||||
if (p == null) {
|
||||
if (p == null || !p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
}
|
||||
if (!p.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
return;
|
||||
if ("schematic".equalsIgnoreCase(a1) && "create".equalsIgnoreCase(a2)) {
|
||||
SchematicCommandHandler.handleCreateWithDifficulty(a3, a4, sender, p, player);
|
||||
}
|
||||
if (!"schematic".equalsIgnoreCase(a1) || !"create".equalsIgnoreCase(a2)) {
|
||||
return;
|
||||
}
|
||||
SchematicCommandHandler.handleCreateWithDifficulty(a3, a4, sender, p, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ public class LoParkourCommand implements CommandExecutor, TabCompleter {
|
|||
final Player p = sender instanceof Player ? (Player) sender : null;
|
||||
router.dispatch(args, sender, p);
|
||||
return true;
|
||||
} catch (Throwable t) {
|
||||
} catch (RuntimeException t) {
|
||||
LoParkour.getPlugin().getLogger().log(Level.SEVERE,
|
||||
"LoParkour command failed (" + label + " " + String.join(" ", args) + ")", t);
|
||||
Locales.send(sender, "commands.error");
|
||||
|
|
|
|||
|
|
@ -27,23 +27,21 @@ public class JoinCommandExecutor {
|
|||
final Mode mode = Registry.getMode(arg);
|
||||
if (mode != null) {
|
||||
mode.create(p);
|
||||
return;
|
||||
} else {
|
||||
joinPlayingPlayer(arg, sender, p);
|
||||
}
|
||||
joinPlayingPlayer(arg, sender, p);
|
||||
}
|
||||
|
||||
private void joinPlayingPlayer(String arg, CommandSender sender, Player p) {
|
||||
final Player other = Bukkit.getPlayer(arg);
|
||||
final ParkourPlayer pp = other == null ? null : UserRegistry.getPlayer(other);
|
||||
if (other == null) {
|
||||
CommandUtil.send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.unknown_player"));
|
||||
return;
|
||||
}
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(other);
|
||||
if (pp == null) {
|
||||
} else if (pp == null) {
|
||||
CommandUtil.send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.not_playing"));
|
||||
return;
|
||||
} else {
|
||||
joinSession(sender, p, pp.session);
|
||||
}
|
||||
joinSession(sender, p, pp.session);
|
||||
}
|
||||
|
||||
private void joinSession(CommandSender sender, Player p, Session session) {
|
||||
|
|
|
|||
|
|
@ -55,10 +55,9 @@ public class PlayerCommandHandler {
|
|||
switch (lower) {
|
||||
case "join" -> handleJoin(sender, player);
|
||||
case "leave" -> {
|
||||
if (!cooldown(sender, "leave", COOLDOWN_MS)) {
|
||||
return;
|
||||
if (cooldown(sender, "leave", COOLDOWN_MS)) {
|
||||
ParkourUser.leave(player);
|
||||
}
|
||||
ParkourUser.leave(player);
|
||||
}
|
||||
case "play" -> {
|
||||
if (ParkourOption.PLAY.mayPerform(player)) {
|
||||
|
|
@ -71,19 +70,19 @@ public class PlayerCommandHandler {
|
|||
}
|
||||
}
|
||||
case "leaderboard" -> {
|
||||
if (!ParkourOption.LEADERBOARDS.mayPerform(player)) {
|
||||
if (ParkourOption.LEADERBOARDS.mayPerform(player)) {
|
||||
Menus.LEADERBOARDS.open(player);
|
||||
} else {
|
||||
send(sender, Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
}
|
||||
Menus.LEADERBOARDS.open(player);
|
||||
}
|
||||
case "replay" -> new ReplayCommandExecutor().replay(null, sender, player, this);
|
||||
case "schematic" -> {
|
||||
if (!player.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
if (player.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
SchematicCommandHandler.sendHelp(player);
|
||||
} else {
|
||||
send(sender, Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
}
|
||||
SchematicCommandHandler.sendHelp(player);
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
|
|
@ -96,12 +95,9 @@ public class PlayerCommandHandler {
|
|||
}
|
||||
if (!ParkourOption.JOIN.mayPerform(player)) {
|
||||
send(sender, Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
} else if (ParkourUser.getUser(player) == null) {
|
||||
Modes.defaultMode().create(player);
|
||||
}
|
||||
if (ParkourUser.getUser(player) != null) {
|
||||
return;
|
||||
}
|
||||
Modes.defaultMode().create(player);
|
||||
}
|
||||
|
||||
private void handleReload(@NotNull CommandSender sender, @Nullable Player player) {
|
||||
|
|
@ -110,11 +106,11 @@ public class PlayerCommandHandler {
|
|||
}
|
||||
if (!sender.hasPermission(ParkourOption.ADMIN.permission)) {
|
||||
send(sender, Locales.getString(sender, "other.no_do"));
|
||||
return;
|
||||
} else {
|
||||
Config.reload(false);
|
||||
dev.loki.loparkour.adaptive.bootstrap.AdaptiveServices.reload();
|
||||
send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.reload"));
|
||||
}
|
||||
Config.reload(false);
|
||||
dev.loki.loparkour.adaptive.bootstrap.AdaptiveServices.reload();
|
||||
send(sender, LoParkour.PREFIX + Locales.getString(sender, "commands.reload"));
|
||||
}
|
||||
|
||||
public void sendHelp(@NotNull CommandSender sender) {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import org.jetbrains.annotations.Nullable;
|
|||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Handles {@code /lp replay [index]}: plays back a player's recorded ghost runs.
|
||||
* Handles {@code /lpk replay [index]}: plays back a player's recorded ghost runs.
|
||||
*/
|
||||
public class ReplayCommandExecutor {
|
||||
|
||||
|
|
@ -30,14 +30,18 @@ public class ReplayCommandExecutor {
|
|||
final GhostService ghostService = LoParkour.getGhostService();
|
||||
if (ghostService == null || !Config.CONFIG.getBoolean("ghost-mode.enabled")) {
|
||||
CommandUtil.send(sender, Locales.getString(sender, "commands.replay.disabled"));
|
||||
return;
|
||||
} else {
|
||||
startRun(indexArg, sender, p, ghostService);
|
||||
}
|
||||
}
|
||||
|
||||
private static void startRun(@Nullable String indexArg, @NotNull CommandSender sender, @NotNull Player p,
|
||||
@NotNull GhostService ghostService) {
|
||||
final GhostData run = resolveRun(indexArg, sender, p, ghostService);
|
||||
if (run == null) {
|
||||
return;
|
||||
if (run != null) {
|
||||
ghostService.startReplay(p, run);
|
||||
CommandUtil.send(sender, Locales.getString(sender, "commands.replay.starting"));
|
||||
}
|
||||
ghostService.startReplay(p, run);
|
||||
CommandUtil.send(sender, Locales.getString(sender, "commands.replay.starting"));
|
||||
}
|
||||
|
||||
private static GhostData resolveRun(@Nullable String indexArg, @NotNull CommandSender sender,
|
||||
|
|
|
|||
|
|
@ -35,7 +35,15 @@ final class SchematicHandler {
|
|||
SchematicMessenger.send(player, LoParkour.PREFIX + Locales.getString(player, "schematic.selection_incomplete"));
|
||||
return;
|
||||
}
|
||||
createSelected(sel, optionalName, difficultyRaw, player);
|
||||
}
|
||||
|
||||
private static void createSelected(
|
||||
Location[] sel,
|
||||
@Nullable String optionalName,
|
||||
@NotNull String difficultyRaw,
|
||||
Player player
|
||||
) {
|
||||
final double difficulty;
|
||||
try {
|
||||
difficulty = SchematicCreator.parseDifficulty(difficultyRaw);
|
||||
|
|
@ -60,18 +68,17 @@ final class SchematicHandler {
|
|||
static void paste(String name, CommandSender sender, Player player) {
|
||||
if (!isValidSchematicName(name)) {
|
||||
SchematicMessenger.send(player, LoParkour.PREFIX + Locales.getString(player, "schematic.invalid_name"));
|
||||
return;
|
||||
} else {
|
||||
final ParkourSchematic schematic = LoParkour.getSchematicManager().get(name);
|
||||
if (schematic == null) {
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.not_found")
|
||||
.formatted(name));
|
||||
} else {
|
||||
schematic.paste(player.getLocation(), player.getWorld());
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.pasted")
|
||||
.formatted(name));
|
||||
}
|
||||
}
|
||||
|
||||
final ParkourSchematic schematic = LoParkour.getSchematicManager().get(name);
|
||||
if (schematic == null) {
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.not_found")
|
||||
.formatted(name));
|
||||
return;
|
||||
}
|
||||
schematic.paste(player.getLocation(), player.getWorld());
|
||||
SchematicMessenger.send(sender, LoParkour.PREFIX + Locales.getString(sender, "schematic.pasted")
|
||||
.formatted(name));
|
||||
}
|
||||
|
||||
static void posCommand(Player player, Location[] existing, Location loc, int index) {
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ public final class ConfigLoader {
|
|||
ConfigUpdater.update(configFile, resourceStream, "1.0", ignoredSections, plugin.getLogger());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// Boundary: config sync must never break enable/reload; template or disk may be corrupt.
|
||||
plugin.getLogger().log(java.util.logging.Level.SEVERE,
|
||||
"Error while trying to update config file: " + fileName, ex);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ public final class ConfigUpdater {
|
|||
final List<String> merged = new ConfigMergeProcessor().merge(templateStream, configFile, ignoredKeys);
|
||||
Files.write(configFile.toPath(), merged);
|
||||
logger.info("Configuration file synced: " + configFile.getName());
|
||||
} catch (Exception e) {
|
||||
} catch (IOException e) {
|
||||
if (backup != null && backup.exists()) {
|
||||
Files.copy(backup.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
logger.severe("Config sync failed, restored backup: " + e.getMessage());
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ public class LocaleCache {
|
|||
final T result = extractor.apply(config);
|
||||
return result != null ? result : defaultValue;
|
||||
} catch (Exception e) {
|
||||
// Boundary: message formatting must never throw; locale data is arbitrary.
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ public final class LocaleLoader {
|
|||
|
||||
return loadFromDisk(embedded);
|
||||
} catch (Exception ex) {
|
||||
// Boundary: locale loading must never break enable; disk files may be corrupt.
|
||||
plugin.getLogger().severe("Error while loading locale files: " + ex.getMessage());
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -139,7 +139,7 @@ public final class OptionGeneral {
|
|||
goBackLocation.setYaw(Float.parseFloat(axes[1].trim()));
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
} catch (NumberFormatException ex) {
|
||||
LoParkour.getPlugin().getLogger().warning("Invalid bungeecord.go-back-axes, using 0,0");
|
||||
}
|
||||
}
|
||||
|
|
@ -181,7 +181,7 @@ public final class OptionGeneral {
|
|||
}
|
||||
return new Location(world, Double.parseDouble(values[0]),
|
||||
Double.parseDouble(values[1]), Double.parseDouble(values[2]));
|
||||
} catch (Exception ex) {
|
||||
} catch (IllegalArgumentException | IndexOutOfBoundsException ex) {
|
||||
LoParkour.getPlugin().getLogger().warning(
|
||||
"Invalid bungeecord.go-back value '" + location + "'. Falling back to spawn world origin.");
|
||||
final World fallback = Bukkit.getWorlds().isEmpty() ? null : Bukkit.getWorlds().get(0);
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@ package dev.loki.loparkour.duels;
|
|||
import dev.loki.loparkour.LoParkour;
|
||||
import dev.loki.loparkour.config.locale.Locales;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.scheduler.ScheduledTask;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import dev.loki.loparkour.util.text.ColorUtil;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
|
|
@ -35,14 +35,14 @@ final class DuelsCountdown {
|
|||
private static final String DEFAULT_COLOR = "E120";
|
||||
|
||||
private final DuelsGenerator generator;
|
||||
private BukkitTask countdownTask;
|
||||
private ScheduledTask countdownTask;
|
||||
|
||||
DuelsCountdown(@NotNull DuelsGenerator generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
void giveStartItem(@NotNull ParkourPlayer owner) {
|
||||
Bukkit.getScheduler().runTaskLater(LoParkour.getPlugin(), () -> {
|
||||
Scheduler.get(LoParkour.getPlugin()).runLater(() -> {
|
||||
if (owner.player.isOnline()) {
|
||||
owner.player.getInventory().addItem(Locales.getItem(owner.locale(), "play.multi.duels.start").build());
|
||||
}
|
||||
|
|
@ -52,7 +52,7 @@ final class DuelsCountdown {
|
|||
void start() {
|
||||
cancel();
|
||||
final int[] counter = {COUNTDOWN_SECONDS};
|
||||
countdownTask = Bukkit.getScheduler().runTaskTimer(LoParkour.getPlugin(),
|
||||
countdownTask = Scheduler.get(LoParkour.getPlugin()).runTimer(
|
||||
() -> tick(counter), 0L, COUNTDOWN_PERIOD);
|
||||
}
|
||||
|
||||
|
|
@ -66,15 +66,13 @@ final class DuelsCountdown {
|
|||
void tick(@NotNull int[] counter) {
|
||||
if (generator.state.stopped()) {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
final int current = counter[0]--;
|
||||
if (current == 0) {
|
||||
startRace();
|
||||
return;
|
||||
}
|
||||
if (current <= COUNTDOWN_COLOR_START) {
|
||||
sendCountdownTitle(current);
|
||||
} else {
|
||||
final int current = counter[0]--;
|
||||
if (current == 0) {
|
||||
startRace();
|
||||
} else if (current <= COUNTDOWN_COLOR_START) {
|
||||
sendCountdownTitle(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,12 +8,13 @@ import dev.loki.loparkour.generator.core.coordinator.ParkourGenerator;
|
|||
import dev.loki.loparkour.mode.base.Mode;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.scheduler.Scheduler;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.util.text.ColorUtil;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
|
|
@ -87,46 +88,45 @@ public class DuelsGenerator extends ParkourGenerator {
|
|||
}
|
||||
|
||||
public void addPlayer(@NotNull ParkourPlayer pp) {
|
||||
if (!allowJoining || playerGenerators.containsKey(pp)) {
|
||||
return;
|
||||
if (allowJoining && !playerGenerators.containsKey(pp)) {
|
||||
final SingleDuelsGenerator gen = new SingleDuelsGenerator(session);
|
||||
gen.setOwningGenerator(this);
|
||||
gen.setOwnedPlayer(pp);
|
||||
gen.setPlayerIndex(playerGenerators.size());
|
||||
gen.state.setHeading(OptionGeneral.heading().getDirection());
|
||||
placePlayer(pp, gen, session.getSpawnLocation());
|
||||
}
|
||||
final SingleDuelsGenerator gen = new SingleDuelsGenerator(session);
|
||||
gen.setOwningGenerator(this);
|
||||
gen.setOwnedPlayer(pp);
|
||||
gen.setPlayerIndex(playerGenerators.size());
|
||||
gen.state.setHeading(OptionGeneral.heading().getDirection());
|
||||
final Location spawnBase = session.getSpawnLocation();
|
||||
if (spawnBase == null || spawnBase.getWorld() == null) {
|
||||
return;
|
||||
}
|
||||
Location platformCenter = spawnBase;
|
||||
if (pp != owner) {
|
||||
platformCenter = spawnBase.clone().add(0, 0, islandDistance * (double) playerGenerators.size());
|
||||
for (int dx = -PLATFORM_RADIUS; dx <= PLATFORM_RADIUS; dx++) {
|
||||
for (int dz = -PLATFORM_RADIUS; dz <= PLATFORM_RADIUS; dz++) {
|
||||
platformCenter.getBlock().getRelative(dx, 0, dz).setType(Material.STONE);
|
||||
}
|
||||
|
||||
private void placePlayer(@NotNull ParkourPlayer pp, @NotNull SingleDuelsGenerator gen,
|
||||
@Nullable Location spawnBase) {
|
||||
if (spawnBase != null && spawnBase.getWorld() != null) {
|
||||
Location platformCenter = spawnBase;
|
||||
if (pp != owner) {
|
||||
platformCenter = spawnBase.clone().add(0, 0, islandDistance * (double) playerGenerators.size());
|
||||
for (int dx = -PLATFORM_RADIUS; dx <= PLATFORM_RADIUS; dx++) {
|
||||
for (int dz = -PLATFORM_RADIUS; dz <= PLATFORM_RADIUS; dz++) {
|
||||
platformCenter.getBlock().getRelative(dx, 0, dz).setType(Material.STONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
final Location playerSpawn = platformCenter.clone().add(SPAWN_CENTER_OFFSET, 1, SPAWN_CENTER_OFFSET);
|
||||
playerSpawns.put(pp, playerSpawn);
|
||||
playerGenerators.put(pp, gen);
|
||||
pp.player.teleport(playerSpawn);
|
||||
}
|
||||
final Location playerSpawn = platformCenter.clone().add(SPAWN_CENTER_OFFSET, 1, SPAWN_CENTER_OFFSET);
|
||||
playerSpawns.put(pp, playerSpawn);
|
||||
playerGenerators.put(pp, gen);
|
||||
pp.player.teleport(playerSpawn);
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull ParkourPlayer pp) {
|
||||
final SingleDuelsGenerator gen = playerGenerators.remove(pp);
|
||||
if (gen == null) {
|
||||
return;
|
||||
}
|
||||
gen.reset(false);
|
||||
if (pp == owner) {
|
||||
countdown.cancel();
|
||||
returnToLobby();
|
||||
return;
|
||||
}
|
||||
if (playerGenerators.size() == 1) {
|
||||
win(new ArrayList<>(playerGenerators.keySet()).get(0));
|
||||
if (gen != null) {
|
||||
gen.reset(false);
|
||||
if (pp == owner) {
|
||||
countdown.cancel();
|
||||
returnToLobby();
|
||||
} else if (playerGenerators.size() == 1) {
|
||||
win(new ArrayList<>(playerGenerators.keySet()).get(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -150,7 +150,7 @@ public class DuelsGenerator extends ParkourGenerator {
|
|||
pp.player.sendTitle(ColorUtil.color(Locales.getString(pp.locale(),
|
||||
pp == winner ? "play.multi.duels.victory" : "play.multi.duels.loss")), "", VICTORY_FADE_IN, VICTORY_STAY, VICTORY_FADE_OUT);
|
||||
}
|
||||
Bukkit.getScheduler().runTaskLater(LoParkour.getPlugin(), () -> returnToLobby(), WIN_RETURN_DELAY_TICKS);
|
||||
Scheduler.get(LoParkour.getPlugin()).runLater(this::returnToLobby, WIN_RETURN_DELAY_TICKS);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -44,12 +44,9 @@ public class CloseMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof CloseMode) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof CloseMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(CloseGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(CloseGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,19 +28,21 @@ final class ElytraBoost {
|
|||
private int boostedSectionIdx = Integer.MIN_VALUE;
|
||||
|
||||
void tick(Player player, ElytraSection section, int idx) {
|
||||
if (!section.isAscending()) {
|
||||
return;
|
||||
if (section.isAscending()) {
|
||||
boostIfValid(player, section, idx);
|
||||
}
|
||||
}
|
||||
|
||||
private void boostIfValid(Player player, ElytraSection section, int idx) {
|
||||
final Vector pos = player.getLocation().toVector();
|
||||
final Vector direction = section.end().clone().subtract(section.beginning()).normalize();
|
||||
if (direction.lengthSquared() < EPSILON) {
|
||||
return;
|
||||
}
|
||||
if (idx != boostedSectionIdx && section.isNearKnot(pos, 0, NEAR_KNOT_DISTANCE)) {
|
||||
applyInitialBoost(player, idx, direction);
|
||||
}
|
||||
if (pos.getX() >= section.beginning().getX() && pos.getX() < section.end().getX()) {
|
||||
sustain(player, direction);
|
||||
if (direction.lengthSquared() >= EPSILON) {
|
||||
if (idx != boostedSectionIdx && section.isNearKnot(pos, 0, NEAR_KNOT_DISTANCE)) {
|
||||
applyInitialBoost(player, idx, direction);
|
||||
}
|
||||
if (pos.getX() >= section.beginning().getX() && pos.getX() < section.end().getX()) {
|
||||
sustain(player, direction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import org.bukkit.Material;
|
|||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.util.Vector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
|
@ -93,25 +94,27 @@ public class ElytraGenerator extends ParkourGenerator {
|
|||
@Override
|
||||
public void tick() {
|
||||
final Player player = getPlayer();
|
||||
if (player == null || sections.isEmpty()) {
|
||||
return;
|
||||
if (player != null && !sections.isEmpty()) {
|
||||
tickPlayer(player);
|
||||
}
|
||||
}
|
||||
|
||||
private void tickPlayer(@NotNull Player player) {
|
||||
final int idx = sections.keySet().stream().max(Integer::compareTo).orElse(-1);
|
||||
final ElytraSection section = sections.get(idx);
|
||||
if (section == null) {
|
||||
return;
|
||||
}
|
||||
final Vector pos = player.getLocation().toVector();
|
||||
applyScoring(player, pos);
|
||||
blockChanger.check(player, material);
|
||||
removeOldest(player);
|
||||
if (shouldReset(player, pos)) {
|
||||
reset(true);
|
||||
return;
|
||||
}
|
||||
boost.tick(player, section, idx);
|
||||
if (section.isNearKnot(pos, 2, GENERATE_DISTANCE)) {
|
||||
generate();
|
||||
if (section != null) {
|
||||
final Vector pos = player.getLocation().toVector();
|
||||
applyScoring(player, pos);
|
||||
blockChanger.check(player, material);
|
||||
removeOldest(player);
|
||||
if (shouldReset(player, pos)) {
|
||||
reset(true);
|
||||
} else {
|
||||
boost.tick(player, section, idx);
|
||||
if (section.isNearKnot(pos, 2, GENERATE_DISTANCE)) {
|
||||
generate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -44,12 +44,9 @@ public class ElytraMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof ElytraMode) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof ElytraMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(ElytraGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(ElytraGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,12 +44,9 @@ public class MinSpeedMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof MinSpeedMode) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof MinSpeedMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(MinSpeedGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(MinSpeedGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,15 +46,11 @@ public class ObstacleGenerator extends ElytraGenerator {
|
|||
private void generateObstacle(int idx, ElytraSection section, int knotIdx) {
|
||||
final Obstacle obstacle = Obstacle.values()[ThreadLocalRandom.current().nextInt(Obstacle.values().length)];
|
||||
final List<Vector> points = obstacle.getPoints(section.getKnot(knotIdx), radius());
|
||||
if (points.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
final Player player = getPlayer();
|
||||
if (player == null) {
|
||||
return;
|
||||
if (!points.isEmpty() && player != null) {
|
||||
blockChanger.sendNow(player, points, Material.YELLOW_CONCRETE);
|
||||
obstacles.computeIfAbsent(idx, key -> new ArrayList<>()).addAll(points);
|
||||
}
|
||||
blockChanger.sendNow(player, points, Material.YELLOW_CONCRETE);
|
||||
obstacles.computeIfAbsent(idx, key -> new ArrayList<>()).addAll(points);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -44,12 +44,9 @@ public class ObstacleMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof ObstacleMode) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof ObstacleMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(ObstacleGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(ObstacleGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,12 +44,9 @@ public class SpeedDemonMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof SpeedDemonMode) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof SpeedDemonMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(SpeedDemonGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(SpeedDemonGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,12 +44,9 @@ public class TimeTrialMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof TimeTrialMode) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof TimeTrialMode)) {
|
||||
player.closeInventory();
|
||||
Session.create(TimeTrialGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(TimeTrialGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -170,8 +170,8 @@ public class GeneratorProfileManager {
|
|||
}
|
||||
|
||||
normalizeMap(generator.state.specialChances);
|
||||
} catch (Exception ignored) {
|
||||
// special blocks config optional
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// special blocks config optional: bad numbers/materials only disable specials
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ public class JumpValidator {
|
|||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// Mock blocks in tests cannot be inspected; fall back to no adjustment
|
||||
// Boundary: block inspection may fail on mocks or across versions; fall back to no adjustment.
|
||||
}
|
||||
return 0.0; // No adjustment for full blocks
|
||||
}
|
||||
|
|
@ -82,44 +82,31 @@ public class JumpValidator {
|
|||
final double dy = to.getY() - from.getY();
|
||||
final double dz = to.getZ() - from.getZ();
|
||||
|
||||
// Check if same location (no jump)
|
||||
// Same-location check (no jump)
|
||||
final double horizontalDistance = Math.sqrt(dx * dx + dz * dz);
|
||||
if (horizontalDistance < SAME_LOCATION_EPSILON && Math.abs(dy) < SAME_LOCATION_EPSILON) {
|
||||
return false; // Same location
|
||||
}
|
||||
|
||||
// Check horizontal distance limit
|
||||
if (horizontalDistance > maxHorizontal) {
|
||||
return false;
|
||||
}
|
||||
final boolean sameLocation = horizontalDistance < SAME_LOCATION_EPSILON && Math.abs(dy) < SAME_LOCATION_EPSILON;
|
||||
|
||||
// Adjust vertical limits based on slab height
|
||||
double adjustedMaxVerticalUp = maxVerticalUp;
|
||||
double adjustedMaxVerticalDown = maxVerticalDown;
|
||||
final double adjustedMaxVerticalUp = heightAdjustment < 0
|
||||
? maxVerticalUp + heightAdjustment
|
||||
: maxVerticalUp;
|
||||
final double adjustedMaxVerticalDown = heightAdjustment < 0
|
||||
? maxVerticalDown - heightAdjustment
|
||||
: maxVerticalDown;
|
||||
|
||||
if (heightAdjustment < 0) {
|
||||
// Player is lower (bottom slab), reduce upward jump capability
|
||||
adjustedMaxVerticalUp = maxVerticalUp + heightAdjustment; // Reduce max up jump
|
||||
adjustedMaxVerticalDown = maxVerticalDown - heightAdjustment; // Increase max down jump
|
||||
}
|
||||
// For upward jumps, reduce max horizontal distance (player can't jump as far when jumping up)
|
||||
final double effectiveMaxHorizontal = dy > 0
|
||||
? maxHorizontal - (dy * VERTICAL_REDUCTION_FACTOR)
|
||||
: maxHorizontal;
|
||||
|
||||
// Check vertical limits with adjustment
|
||||
if (dy > adjustedMaxVerticalUp || dy < -adjustedMaxVerticalDown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// For upward jumps, reduce max horizontal distance
|
||||
// Player can't jump as far when jumping up
|
||||
if (dy > 0) {
|
||||
final double adjustedMaxHorizontal = maxHorizontal - (dy * VERTICAL_REDUCTION_FACTOR); // Reduce by 0.5 blocks per block up
|
||||
if (horizontalDistance > adjustedMaxHorizontal) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check total distance
|
||||
final boolean verticalOk = dy <= adjustedMaxVerticalUp && dy >= -adjustedMaxVerticalDown;
|
||||
final double totalDistance = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
return totalDistance <= maxDistance;
|
||||
|
||||
return !sameLocation
|
||||
&& horizontalDistance <= maxHorizontal
|
||||
&& verticalOk
|
||||
&& horizontalDistance <= effectiveMaxHorizontal
|
||||
&& totalDistance <= maxDistance;
|
||||
}
|
||||
|
||||
// Check if jump is possible: sqrt(dx² + dy² + dz²) <= maxDistance
|
||||
|
|
|
|||
|
|
@ -95,32 +95,27 @@ public class BlockPlacer {
|
|||
|
||||
final boolean tall = targetSelector.isTallMaterial(blockData.getMaterial());
|
||||
final List<Block> blocks = tall ? targetSelector.selectBlocks(-1) : targetSelector.selectBlocks();
|
||||
if (blocks.isEmpty()) {
|
||||
return;
|
||||
if (!blocks.isEmpty()) {
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, blockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
}
|
||||
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, blockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
}
|
||||
|
||||
private void placeSpecialBlock() {
|
||||
final BlockData specialBlockData = Probs.random(generator.state.specialChances);
|
||||
if (specialBlockData == null) {
|
||||
placeNormalBlock();
|
||||
return;
|
||||
} else {
|
||||
final boolean tall = targetSelector.isTallMaterial(specialBlockData.getMaterial());
|
||||
final List<Block> blocks = tall ? targetSelector.selectBlocks(-1) : targetSelector.selectBlocks();
|
||||
if (!blocks.isEmpty()) {
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, specialBlockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
}
|
||||
}
|
||||
|
||||
final boolean tall = targetSelector.isTallMaterial(specialBlockData.getMaterial());
|
||||
final List<Block> blocks = tall ? targetSelector.selectBlocks(-1) : targetSelector.selectBlocks();
|
||||
if (blocks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Block selectedBlock = blocks.get(0);
|
||||
worldPlacer.place(selectedBlock, specialBlockData);
|
||||
generator.state.history.add(selectedBlock);
|
||||
generator.state.addGeneratedBlocks(1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -88,18 +88,15 @@ public class LifecycleEventManager {
|
|||
}
|
||||
|
||||
private void applyOneTimeRewards(@NotNull ParkourPlayer player, @NotNull Mode mode, int score) {
|
||||
if (!Rewards.oneTimeRewards().containsKey(score)) {
|
||||
return;
|
||||
}
|
||||
final String rewardKey = String.valueOf(score);
|
||||
if (player.settings().collectedRewards().contains(rewardKey)) {
|
||||
return;
|
||||
if (Rewards.oneTimeRewards().containsKey(score)
|
||||
&& !player.settings().collectedRewards().contains(rewardKey)) {
|
||||
for (final Reward reward : Rewards.oneTimeRewards().get(score)) {
|
||||
reward.execute(player, mode);
|
||||
}
|
||||
player.settings().collectedRewards().add(rewardKey);
|
||||
player.save(false);
|
||||
}
|
||||
for (final Reward reward : Rewards.oneTimeRewards().get(score)) {
|
||||
reward.execute(player, mode);
|
||||
}
|
||||
player.settings().collectedRewards().add(rewardKey);
|
||||
player.save(false);
|
||||
}
|
||||
|
||||
private void processFall() {
|
||||
|
|
|
|||
|
|
@ -39,17 +39,13 @@ public class GeneratorCleanup {
|
|||
}
|
||||
|
||||
final int minStandingIndex = findMinStandingIndex();
|
||||
if (minStandingIndex == Integer.MAX_VALUE) {
|
||||
return;
|
||||
if (minStandingIndex != Integer.MAX_VALUE) {
|
||||
final int keepBehind = Math.max(0, OptionGeneration.trailKeepBehind());
|
||||
final int removeCount = minStandingIndex - keepBehind;
|
||||
if (removeCount > 0) {
|
||||
clearHistoryHead(history, removeCount);
|
||||
}
|
||||
}
|
||||
|
||||
final int keepBehind = Math.max(0, OptionGeneration.trailKeepBehind());
|
||||
final int removeCount = minStandingIndex - keepBehind;
|
||||
if (removeCount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearHistoryHead(history, removeCount);
|
||||
}
|
||||
|
||||
private int findMinStandingIndex() {
|
||||
|
|
|
|||
|
|
@ -105,12 +105,11 @@ public class GhostManager {
|
|||
final File file = new File(playerFolder, data.getTimestamp() + FILE_EXTENSION);
|
||||
try {
|
||||
data.saveToFile(file);
|
||||
evictOldRuns(playerFolder);
|
||||
} catch (IOException e) {
|
||||
LoParkour.getPlugin().getLogger().severe(
|
||||
"Failed to save ghost run for " + data.getPlayerName() + ": " + e.getMessage());
|
||||
return;
|
||||
}
|
||||
evictOldRuns(playerFolder);
|
||||
}
|
||||
|
||||
/** Max runs kept per player; read from config each call so reloads apply. */
|
||||
|
|
|
|||
|
|
@ -37,16 +37,11 @@ public class GhostRecorder {
|
|||
}
|
||||
|
||||
public void recordFrame(@NotNull Location currentLocation) {
|
||||
if (!recording) {
|
||||
return;
|
||||
if (recording && lastLocation.distance(currentLocation) >= MIN_MOVEMENT) {
|
||||
final long timestamp = System.currentTimeMillis() - startTime;
|
||||
frames.add(new GhostFrame(timestamp, currentLocation.clone()));
|
||||
lastLocation = currentLocation.clone();
|
||||
}
|
||||
if (lastLocation.distance(currentLocation) < MIN_MOVEMENT) {
|
||||
return;
|
||||
}
|
||||
|
||||
final long timestamp = System.currentTimeMillis() - startTime;
|
||||
frames.add(new GhostFrame(timestamp, currentLocation.clone()));
|
||||
lastLocation = currentLocation.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -57,24 +57,24 @@ public class GhostReplay {
|
|||
public void start() {
|
||||
if (run.getFrames().isEmpty()) {
|
||||
onFinish.run();
|
||||
return;
|
||||
} else {
|
||||
final ParkourUser user = ParkourUser.getUser(viewer);
|
||||
if (user != null) {
|
||||
ParkourUser.leave(viewer);
|
||||
}
|
||||
final Location start = run.getFrames().get(FIRST_FRAME).toLocation(world);
|
||||
viewer.teleport(start);
|
||||
moved = true;
|
||||
ghost = new PlayerGhost(viewer, run.getPlayerName());
|
||||
if (ghost.spawn(start)) {
|
||||
startTime = System.currentTimeMillis();
|
||||
frameIndex = FIRST_FRAME;
|
||||
current = start;
|
||||
task = Scheduler.get(LoParkour.getPlugin()).runTimer(this::tick, TICK_DELAY, TICK_PERIOD);
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
final ParkourUser user = ParkourUser.getUser(viewer);
|
||||
if (user != null) {
|
||||
ParkourUser.leave(viewer);
|
||||
}
|
||||
final Location start = run.getFrames().get(FIRST_FRAME).toLocation(world);
|
||||
viewer.teleport(start);
|
||||
moved = true;
|
||||
ghost = new PlayerGhost(viewer, run.getPlayerName());
|
||||
if (!ghost.spawn(start)) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
startTime = System.currentTimeMillis();
|
||||
frameIndex = FIRST_FRAME;
|
||||
current = start;
|
||||
task = Scheduler.get(LoParkour.getPlugin()).runTimer(this::tick, TICK_DELAY, TICK_PERIOD);
|
||||
}
|
||||
|
||||
private void tick() {
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ public final class HoloHook {
|
|||
public static void init() {
|
||||
try {
|
||||
Class.forName("me.filoghost.holographicdisplays.api.HolographicDisplaysAPI");
|
||||
} catch (Exception ex) {
|
||||
} catch (ClassNotFoundException | LinkageError ex) {
|
||||
LoParkour.getPlugin().getLogger().warning("##");
|
||||
LoParkour.getPlugin().getLogger().warning("## LoParkour only supports Holographic Displays v3.0.0 or higher!");
|
||||
LoParkour.getPlugin().getLogger().warning("## This hook will now be disabled.");
|
||||
|
|
@ -30,50 +30,47 @@ public final class HoloHook {
|
|||
return;
|
||||
}
|
||||
|
||||
HolographicDisplaysAPI.get(LoParkour.getPlugin()).registerGlobalPlaceholder("ip_leaderboard", PLACEHOLDER_REFRESH_TICKS, argument -> {
|
||||
HolographicDisplaysAPI.get(LoParkour.getPlugin())
|
||||
.registerGlobalPlaceholder("ip_leaderboard", PLACEHOLDER_REFRESH_TICKS, HoloHook::resolveLeaderboard);
|
||||
}
|
||||
|
||||
if (argument == null) {
|
||||
return "?";
|
||||
}
|
||||
/** Resolves the {@code {ip_leaderboard: mode, type, #rank}} global placeholder. */
|
||||
private static String resolveLeaderboard(String argument) {
|
||||
if (argument == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
// {ip_leaderboard: default, score, #1}
|
||||
final String[] split = argument.replace(" ", "").split(",");
|
||||
// {ip_leaderboard: default, score, #1}
|
||||
final String[] split = argument.replace(" ", "").split(",");
|
||||
final Mode mode = Registry.getMode(split[0].toLowerCase());
|
||||
final Leaderboard leaderboard = mode == null ? null : mode.getLeaderboard();
|
||||
if (leaderboard == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
final Mode mode = Registry.getMode(split[0].toLowerCase());
|
||||
final String type = split[1].toLowerCase();
|
||||
final String rank = split[2].replace("#", "");
|
||||
final Score score = lookupScore(leaderboard, rank);
|
||||
if (score == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
if (mode == null) {
|
||||
return "?";
|
||||
}
|
||||
return switch (type) {
|
||||
case "score" -> Integer.toString(score.score());
|
||||
case "name" -> score.name();
|
||||
case "time" -> score.time();
|
||||
case "difficulty" -> score.difficulty();
|
||||
case "difficulty_string" -> parseDifficulty(score.difficulty());
|
||||
default -> "?";
|
||||
};
|
||||
}
|
||||
|
||||
final Leaderboard leaderboard = mode.getLeaderboard();
|
||||
|
||||
if (leaderboard == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
final String type = split[1].toLowerCase();
|
||||
final String rank = split[2].replace("#", "");
|
||||
|
||||
final Score score;
|
||||
try {
|
||||
score = leaderboard.getScoreAtRank(Integer.parseInt(rank));
|
||||
} catch (NumberFormatException e) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
if (score == null) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
return switch (type) {
|
||||
case "score" -> Integer.toString(score.score());
|
||||
case "name" -> score.name();
|
||||
case "time" -> score.time();
|
||||
case "difficulty" -> score.difficulty();
|
||||
case "difficulty_string" -> parseDifficulty(score.difficulty());
|
||||
default -> "?";
|
||||
};
|
||||
});
|
||||
private static Score lookupScore(Leaderboard leaderboard, String rank) {
|
||||
try {
|
||||
return leaderboard.getScoreAtRank(Integer.parseInt(rank));
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String parseDifficulty(String string) {
|
||||
|
|
|
|||
|
|
@ -4,11 +4,23 @@ import dev.loki.loparkour.LoParkour;
|
|||
import dev.loki.loparkour.leaderboard.model.Score;
|
||||
import dev.loki.loparkour.mode.base.Modes;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class GlobalPlaceholderResolver {
|
||||
|
||||
private final ScoreRankResolver rankResolver = new ScoreRankResolver();
|
||||
private final PlaceholderFormatters formatters = new PlaceholderFormatters();
|
||||
|
||||
/** Maps a placeholder token to the value extracted from the ranked {@link Score} (checked in declaration order). */
|
||||
private final List<RankedMapping> rankedMappings = List.of(
|
||||
new RankedMapping("player_rank_", Score::name),
|
||||
new RankedMapping("score_rank_", Score::score),
|
||||
new RankedMapping("time_rank_", Score::time),
|
||||
new RankedMapping("difficulty_rank_", Score::difficulty),
|
||||
new RankedMapping("difficulty_string_rank_", formatters::difficultyString)
|
||||
);
|
||||
|
||||
public String resolve(String params) {
|
||||
final String value = resolveStatic(params);
|
||||
if (value != null) {
|
||||
|
|
@ -37,22 +49,14 @@ public class GlobalPlaceholderResolver {
|
|||
}
|
||||
|
||||
private String resolveRanked(String params) {
|
||||
if (params.contains("player_rank_")) {
|
||||
return rankResolver.resolve(params.replace("player_rank_", ""), Score::name);
|
||||
}
|
||||
if (params.contains("score_rank_")) {
|
||||
return rankResolver.resolve(params.replace("score_rank_", ""), Score::score);
|
||||
}
|
||||
if (params.contains("time_rank_")) {
|
||||
return rankResolver.resolve(params.replace("time_rank_", ""), Score::time);
|
||||
}
|
||||
if (params.contains("difficulty_rank_")) {
|
||||
return rankResolver.resolve(params.replace("difficulty_rank_", ""), Score::difficulty);
|
||||
}
|
||||
if (params.contains("difficulty_string_rank_")) {
|
||||
return rankResolver.resolve(params.replace("difficulty_string_rank_", ""),
|
||||
formatters::difficultyString);
|
||||
for (final RankedMapping mapping : rankedMappings) {
|
||||
if (params.contains(mapping.token())) {
|
||||
return rankResolver.resolve(params.replace(mapping.token(), ""), mapping.extractor());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private record RankedMapping(String token, Function<Score, ?> extractor) {
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,10 +6,29 @@ import dev.loki.loparkour.player.core.ParkourUser;
|
|||
import dev.loki.loparkour.player.spectator.ParkourSpectator;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class PlayerPlaceholderResolver {
|
||||
|
||||
private final PlaceholderFormatters formatters = new PlaceholderFormatters();
|
||||
|
||||
/** In-session placeholders resolved straight from the player's generator/settings. */
|
||||
private final Map<String, Function<ParkourPlayer, String>> generatorPlaceholders = Map.ofEntries(
|
||||
Map.entry("score", PlayerPlaceholderResolver::currentScore),
|
||||
Map.entry("current_score", PlayerPlaceholderResolver::currentScore),
|
||||
Map.entry("time", PlayerPlaceholderResolver::currentTime),
|
||||
Map.entry("current_time", PlayerPlaceholderResolver::currentTime),
|
||||
Map.entry("blocklead", pp -> Integer.toString(pp.settings().blockLead())),
|
||||
Map.entry("lead", pp -> Integer.toString(pp.settings().blockLead())),
|
||||
Map.entry("style", pp -> pp.settings().style()),
|
||||
Map.entry("time_pref", pp -> Integer.toString(pp.settings().selectedTime())),
|
||||
Map.entry("time_preference", pp -> Integer.toString(pp.settings().selectedTime())),
|
||||
Map.entry("scoreboard", pp -> pp.settings().showScoreboard().toString()),
|
||||
Map.entry("difficulty", pp -> Double.toString(pp.settings().schematicDifficulty())),
|
||||
Map.entry("difficulty_string", pp -> formatters.parseDifficulty(pp.settings().schematicDifficulty()))
|
||||
);
|
||||
|
||||
public String resolve(Player player, String params) {
|
||||
final String value = resolveLeaderboard(player, params);
|
||||
if (value != null) {
|
||||
|
|
@ -55,35 +74,19 @@ public class PlayerPlaceholderResolver {
|
|||
}
|
||||
|
||||
private String resolveGenerator(ParkourPlayer pp, String params) {
|
||||
switch (params) {
|
||||
case "score", "current_score" -> {
|
||||
return Integer.toString(pp.session.generator().state.score());
|
||||
}
|
||||
case "time", "current_time" -> {
|
||||
return pp.session.generator().getFormattedTime();
|
||||
}
|
||||
case "blocklead", "lead" -> {
|
||||
return Integer.toString(pp.settings().blockLead());
|
||||
}
|
||||
case "style" -> {
|
||||
return pp.settings().style();
|
||||
}
|
||||
case "time_pref", "time_preference" -> {
|
||||
return Integer.toString(pp.settings().selectedTime());
|
||||
}
|
||||
case "scoreboard" -> {
|
||||
return pp.settings().showScoreboard().toString();
|
||||
}
|
||||
case "difficulty" -> {
|
||||
return Double.toString(pp.settings().schematicDifficulty());
|
||||
}
|
||||
case "difficulty_string" -> {
|
||||
return formatters.parseDifficulty(pp.settings().schematicDifficulty());
|
||||
}
|
||||
default -> {
|
||||
return resolveScoreUntil(pp, params);
|
||||
}
|
||||
final Function<ParkourPlayer, String> handler = generatorPlaceholders.get(params);
|
||||
if (handler != null) {
|
||||
return handler.apply(pp);
|
||||
}
|
||||
return resolveScoreUntil(pp, params);
|
||||
}
|
||||
|
||||
private static String currentScore(ParkourPlayer pp) {
|
||||
return Integer.toString(pp.session.generator().state.score());
|
||||
}
|
||||
|
||||
private static String currentTime(ParkourPlayer pp) {
|
||||
return pp.session.generator().getFormattedTime();
|
||||
}
|
||||
|
||||
private String resolveScoreUntil(ParkourPlayer pp, String params) {
|
||||
|
|
|
|||
|
|
@ -24,16 +24,20 @@ public final class VaultHook {
|
|||
}
|
||||
|
||||
if (economy == null) {
|
||||
final RegisteredServiceProvider<Economy> service = Bukkit.getServicesManager().getRegistration(Economy.class);
|
||||
|
||||
if (service == null) {
|
||||
LoParkour.getPlugin().getLogger().severe("Error while trying to fetch the Vault economy - No economy found");
|
||||
return;
|
||||
}
|
||||
|
||||
economy = service.getProvider();
|
||||
economy = resolveEconomy();
|
||||
}
|
||||
|
||||
economy.depositPlayer(player, amount);
|
||||
if (economy != null) {
|
||||
economy.depositPlayer(player, amount);
|
||||
}
|
||||
}
|
||||
|
||||
private static Economy resolveEconomy() {
|
||||
final RegisteredServiceProvider<Economy> service = Bukkit.getServicesManager().getRegistration(Economy.class);
|
||||
if (service == null) {
|
||||
LoParkour.getPlugin().getLogger().severe("Error while trying to fetch the Vault economy - No economy found");
|
||||
return null;
|
||||
}
|
||||
return service.getProvider();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import dev.loki.loparkour.menu.core.Menus;
|
|||
import dev.loki.loparkour.menu.core.screen.ParkourOption;
|
||||
import dev.loki.loparkour.player.core.ParkourPlayer;
|
||||
import dev.loki.loparkour.player.core.ParkourUser;
|
||||
import dev.loki.loparkour.session.core.Session;
|
||||
import dev.loki.loparkour.player.service.UserRegistry;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
|
|
@ -27,53 +26,38 @@ import org.bukkit.event.player.PlayerTeleportEvent;
|
|||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Hotbar interactions, chat routing, focus mode and general restrictions for parkour players. */
|
||||
public class ParkourRestrictionListener implements Listener {
|
||||
|
||||
@EventHandler
|
||||
public void onChat(AsyncPlayerChatEvent event) {
|
||||
if (!OptionGeneral.optionsEnabled().getOrDefault(ParkourOption.CHAT, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Player player = event.getPlayer();
|
||||
final ParkourUser user = ParkourUser.getUser(player);
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Session session = user.session;
|
||||
if (session.isMuted(user)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.setCancelled(true);
|
||||
switch (user.chatType()) {
|
||||
case LOBBY_ONLY -> session.getUsers().forEach(
|
||||
u -> u.sendTranslated("settings.chat.formats.lobby", player.getName(), event.getMessage()));
|
||||
case PLAYERS_ONLY -> session.getPlayers().forEach(
|
||||
u -> u.sendTranslated("settings.chat.formats.players", player.getName(), event.getMessage()));
|
||||
default -> event.setCancelled(false);
|
||||
if (OptionGeneral.optionsEnabled().getOrDefault(ParkourOption.CHAT, true)
|
||||
&& user != null && !user.session.isMuted(user)) {
|
||||
event.setCancelled(true);
|
||||
switch (user.chatType()) {
|
||||
case LOBBY_ONLY -> user.session.getUsers().forEach(
|
||||
u -> u.sendTranslated("settings.chat.formats.lobby", player.getName(), event.getMessage()));
|
||||
case PLAYERS_ONLY -> user.session.getPlayers().forEach(
|
||||
u -> u.sendTranslated("settings.chat.formats.players", player.getName(), event.getMessage()));
|
||||
default -> event.setCancelled(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onCommand(PlayerCommandPreprocessEvent event) {
|
||||
if (!Config.CONFIG.getBoolean("focus-mode.enabled")) {
|
||||
return;
|
||||
}
|
||||
final ParkourUser user = ParkourUser.getUser(event.getPlayer());
|
||||
if (user == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String cmd = event.getMessage().toLowerCase();
|
||||
if (Config.CONFIG.getStringList("focus-mode.whitelist").stream().anyMatch(cmd::contains)) {
|
||||
return;
|
||||
if (Config.CONFIG.getBoolean("focus-mode.enabled")
|
||||
&& user != null
|
||||
&& Config.CONFIG.getStringList("focus-mode.whitelist").stream().noneMatch(cmd::contains)) {
|
||||
user.sendTranslated("other.no_do");
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
user.sendTranslated("other.no_do");
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
|
|
@ -93,59 +77,57 @@ public class ParkourRestrictionListener implements Listener {
|
|||
&& isContainer && event.getHand() == org.bukkit.inventory.EquipmentSlot.HAND) {
|
||||
event.setCancelled(true);
|
||||
player.closeInventory();
|
||||
return;
|
||||
} else {
|
||||
handleRightClick(event, player);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleRightClick(PlayerInteractEvent event, Player player) {
|
||||
final boolean isRightClick = (event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_AIR
|
||||
|| event.getAction() == org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK)
|
||||
&& event.getHand() == org.bukkit.inventory.EquipmentSlot.HAND;
|
||||
if (!isRightClick) {
|
||||
return;
|
||||
}
|
||||
final ItemStack held = heldItem(player);
|
||||
event.setCancelled(true);
|
||||
|
||||
if (!openHotbarMenu(player, held) && !Config.CONFIG.getBoolean("options.disable-inventory-blocks")) {
|
||||
event.setCancelled(false);
|
||||
if (isRightClick) {
|
||||
final ItemStack held = heldItem(player);
|
||||
event.setCancelled(true);
|
||||
if (!openHotbarMenu(player, held) && !Config.CONFIG.getBoolean("options.disable-inventory-blocks")) {
|
||||
event.setCancelled(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean openHotbarMenu(Player player, ItemStack held) {
|
||||
if (matchesLocaleHotbar(player, "play.item", held)) {
|
||||
Menus.PLAY.open(player);
|
||||
return true;
|
||||
}
|
||||
if (matchesLocaleHotbar(player, "community.item", held)) {
|
||||
Menus.COMMUNITY.open(player);
|
||||
return true;
|
||||
}
|
||||
if (matchesLocaleHotbar(player, "settings.item", held)) {
|
||||
Menus.SETTINGS.open(player);
|
||||
return true;
|
||||
}
|
||||
if (matchesLocaleHotbar(player, "lobby.item", held)) {
|
||||
Menus.LOBBY.open(player);
|
||||
return true;
|
||||
}
|
||||
if (matchesLocaleHotbar(player, "other.quit", held)) {
|
||||
ParkourUser.leave(player);
|
||||
return true;
|
||||
for (final HotbarAction action : HOTBAR_ACTIONS) {
|
||||
if (matchesLocaleHotbar(player, action.localeKey(), held)) {
|
||||
action.apply(player);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A hotbar item (matched by locale) and the action it triggers, checked in declaration order. */
|
||||
private record HotbarAction(String localeKey, java.util.function.Consumer<Player> action) {
|
||||
void apply(Player player) {
|
||||
action.accept(player);
|
||||
}
|
||||
}
|
||||
|
||||
private static final List<HotbarAction> HOTBAR_ACTIONS = List.of(
|
||||
new HotbarAction("play.item", p -> Menus.PLAY.open(p)),
|
||||
new HotbarAction("community.item", p -> Menus.COMMUNITY.open(p)),
|
||||
new HotbarAction("settings.item", p -> Menus.SETTINGS.open(p)),
|
||||
new HotbarAction("lobby.item", p -> Menus.LOBBY.open(p)),
|
||||
new HotbarAction("other.quit", ParkourUser::leave)
|
||||
);
|
||||
|
||||
@EventHandler(priority = EventPriority.LOW)
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
if (event.getWhoClicked() instanceof Player player) {
|
||||
final InventoryType type = event.getInventory().getType();
|
||||
if (type != InventoryType.CHEST && type != InventoryType.CRAFTING) {
|
||||
restrict(player, event);
|
||||
}
|
||||
}
|
||||
if (event.getInventory().getType() == InventoryType.CHEST) {
|
||||
return; // menu GUI
|
||||
}
|
||||
if (event.getInventory().getType() == InventoryType.CRAFTING) {
|
||||
return; // own inv
|
||||
}
|
||||
restrict(player, event);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
|
|
|
|||
|
|
@ -34,24 +34,22 @@ public class PlayerConnectionListener implements Listener {
|
|||
|
||||
if (Config.CONFIG.getBoolean("bungeecord.enabled")) {
|
||||
Modes.defaultMode().create(player);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!player.getWorld().equals(World.getWorld())) {
|
||||
return;
|
||||
} else if (player.getWorld().equals(World.getWorld())) {
|
||||
teleportOutOfParkourWorld(player);
|
||||
}
|
||||
}
|
||||
|
||||
private void teleportOutOfParkourWorld(Player player) {
|
||||
final org.bukkit.World fallback = Bukkit.getWorld(Config.CONFIG.getString("world.fall-back"));
|
||||
if (fallback != null) {
|
||||
PaperLib.teleportAsync(player, fallback.getSpawnLocation(), PlayerTeleportEvent.TeleportCause.PLUGIN);
|
||||
return;
|
||||
} else {
|
||||
PaperLib.teleportAsync(player, Bukkit.getWorlds().stream()
|
||||
.filter(w -> !w.equals(World.getWorld()))
|
||||
.findAny()
|
||||
.orElseThrow(() -> new NoSuchElementException("No fallback world found!"))
|
||||
.getSpawnLocation());
|
||||
}
|
||||
|
||||
PaperLib.teleportAsync(player, Bukkit.getWorlds().stream()
|
||||
.filter(w -> !w.equals(World.getWorld()))
|
||||
.findAny()
|
||||
.orElseThrow(() -> new NoSuchElementException("No fallback world found!"))
|
||||
.getSpawnLocation());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
|
|
|
|||
|
|
@ -23,18 +23,11 @@ public class SchematicWandListener implements Listener {
|
|||
|
||||
@EventHandler(ignoreCancelled = true)
|
||||
public void onInteract(@NotNull PlayerInteractEvent event) {
|
||||
if (event.getHand() != EquipmentSlot.HAND) {
|
||||
return;
|
||||
}
|
||||
if (!SchematicCommandHandler.isWand(event.getItem())) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Action action = event.getAction();
|
||||
if (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK) {
|
||||
return;
|
||||
}
|
||||
if (event.getClickedBlock() == null) {
|
||||
if (event.getHand() != EquipmentSlot.HAND
|
||||
|| !SchematicCommandHandler.isWand(event.getItem())
|
||||
|| (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK)
|
||||
|| event.getClickedBlock() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -107,17 +107,16 @@ public class SingleLeaderboardMenu extends LPMenu {
|
|||
|
||||
private void applySkullOwner(@NotNull Player player, @NotNull ItemStack skull,
|
||||
@NotNull UUID id, int rank) {
|
||||
if (rank > SKULL_RANK_LIMIT || ParkourUser.isBedrockPlayer(player)) {
|
||||
return;
|
||||
}
|
||||
final OfflinePlayer op = org.bukkit.Bukkit.getOfflinePlayer(id);
|
||||
if (op.getName() == null || op.getName().startsWith(".")) {
|
||||
return;
|
||||
}
|
||||
final SkullMeta meta = (SkullMeta) skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(op);
|
||||
skull.setItemMeta(meta);
|
||||
if (rank <= SKULL_RANK_LIMIT
|
||||
&& !ParkourUser.isBedrockPlayer(player)
|
||||
&& op.getName() != null
|
||||
&& !op.getName().startsWith(".")) {
|
||||
final SkullMeta meta = (SkullMeta) skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(op);
|
||||
skull.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,26 +39,22 @@ public final class GuiManager implements Listener {
|
|||
|
||||
@EventHandler
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) {
|
||||
return;
|
||||
if (event.getWhoClicked() instanceof Player player) {
|
||||
final OpenGui open = ACTIVE.get(player.getUniqueId());
|
||||
if (open != null && open.inventory().equals(event.getInventory())) {
|
||||
open.gui().handleClick(event);
|
||||
}
|
||||
}
|
||||
final OpenGui open = ACTIVE.get(player.getUniqueId());
|
||||
if (open == null || !open.inventory().equals(event.getInventory())) {
|
||||
return;
|
||||
}
|
||||
open.gui().handleClick(event);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryClose(InventoryCloseEvent event) {
|
||||
if (!(event.getPlayer() instanceof Player player)) {
|
||||
return;
|
||||
if (event.getPlayer() instanceof Player player) {
|
||||
final OpenGui open = ACTIVE.get(player.getUniqueId());
|
||||
if (open != null && open.inventory().equals(event.getInventory())) {
|
||||
ACTIVE.remove(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
final OpenGui open = ACTIVE.get(player.getUniqueId());
|
||||
if (open == null || !open.inventory().equals(event.getInventory())) {
|
||||
return;
|
||||
}
|
||||
ACTIVE.remove(player.getUniqueId());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
|
|
|
|||
|
|
@ -108,16 +108,13 @@ public class DuelsMenu extends LPMenu {
|
|||
}
|
||||
|
||||
private void applySkullOwner(@NotNull Player player, @NotNull ItemStack skull, @NotNull ParkourUser owner) {
|
||||
if (ParkourUser.isBedrockPlayer(player)) {
|
||||
return;
|
||||
}
|
||||
if (owner.getName() == null || owner.getName().startsWith(".")) {
|
||||
return;
|
||||
}
|
||||
final SkullMeta meta = (SkullMeta) skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(owner.player);
|
||||
skull.setItemMeta(meta);
|
||||
final String name = owner.getName();
|
||||
if (!ParkourUser.isBedrockPlayer(player) && name != null && !name.startsWith(".")) {
|
||||
final SkullMeta meta = (SkullMeta) skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(owner.player);
|
||||
skull.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -84,16 +84,13 @@ public class SpectatorMenu extends LPMenu {
|
|||
}
|
||||
|
||||
private void applySkullOwner(@NotNull Player player, @NotNull ItemStack skull, @NotNull ParkourUser pp) {
|
||||
if (ParkourUser.isBedrockPlayer(player)) {
|
||||
return;
|
||||
}
|
||||
if (pp.getName() == null || pp.getName().startsWith(".")) {
|
||||
return;
|
||||
}
|
||||
final SkullMeta meta = (SkullMeta) skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(pp.player);
|
||||
skull.setItemMeta(meta);
|
||||
final String name = pp.getName();
|
||||
if (!ParkourUser.isBedrockPlayer(player) && name != null && !name.startsWith(".")) {
|
||||
final SkullMeta meta = (SkullMeta) skull.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setOwningPlayer(pp.player);
|
||||
skull.setItemMeta(meta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,11 +41,9 @@ public class InvisibleBarrierMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() instanceof BarrierGenerator) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() instanceof BarrierGenerator)) {
|
||||
player.closeInventory();
|
||||
Session.create(session -> new BarrierGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
Session.create(session -> new BarrierGenerator(session), null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,37 +53,29 @@ public class CoopMode implements MultiMode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() instanceof CoopGenerator) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() instanceof CoopGenerator)) {
|
||||
player.closeInventory();
|
||||
Session.create(CoopGenerator::new,
|
||||
session -> session.getPlayers().size() < getMaxPlayers(),
|
||||
null,
|
||||
player);
|
||||
Menus.LOBBY.open(player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
Session.create(CoopGenerator::new,
|
||||
session -> session.getPlayers().size() < getMaxPlayers(),
|
||||
null,
|
||||
player);
|
||||
Menus.LOBBY.open(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void join(Player joiningPlayer, Session session) {
|
||||
if (!ModeMessages.checkJoiningEnabled(joiningPlayer)) {
|
||||
return;
|
||||
}
|
||||
if (ModeMessages.checkJoiningEnabled(joiningPlayer) && session.generator() != null) {
|
||||
final ParkourPlayer pp = ParkourUser.register(joiningPlayer, session);
|
||||
session.addPlayers(pp);
|
||||
pp.updateGeneratorSettings(session.generator());
|
||||
if (session.generator() instanceof CoopGenerator coopGenerator) {
|
||||
coopGenerator.onPlayerJoin(pp);
|
||||
}
|
||||
|
||||
if (session.generator() == null) {
|
||||
return;
|
||||
session.getPlayers().forEach(p ->
|
||||
p.sendTranslated("modes.coop.player_joined", joiningPlayer.getName()));
|
||||
}
|
||||
|
||||
final ParkourPlayer pp = ParkourUser.register(joiningPlayer, session);
|
||||
session.addPlayers(pp);
|
||||
pp.updateGeneratorSettings(session.generator());
|
||||
if (session.generator() instanceof CoopGenerator coopGenerator) {
|
||||
coopGenerator.onPlayerJoin(pp);
|
||||
}
|
||||
|
||||
session.getPlayers().forEach(p ->
|
||||
p.sendTranslated("modes.coop.player_joined", joiningPlayer.getName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -66,12 +66,10 @@ public class RaceMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() instanceof RaceGenerator) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() instanceof RaceGenerator)) {
|
||||
player.closeInventory();
|
||||
Session.create(session -> new RaceGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
Session.create(session -> new RaceGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
// ── RaceGenerator ─────────────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -45,23 +45,18 @@ public class SpectatorMode implements Mode {
|
|||
}
|
||||
if (!ParkourOption.SPECTATOR.mayPerform(player)) {
|
||||
player.sendMessage(Locales.getString(player, "other.no_do"));
|
||||
return;
|
||||
} else if (!session.getPlayers().isEmpty()) {
|
||||
final ParkourUser user = ParkourUser.getUser(player);
|
||||
final ParkourSpectator spectator;
|
||||
|
||||
if (user != null) {
|
||||
ParkourUser.unregister(user, false, false, false);
|
||||
spectator = new ParkourSpectator(player, session, user.previousData());
|
||||
} else {
|
||||
spectator = new ParkourSpectator(player, session, null);
|
||||
}
|
||||
|
||||
session.addSpectators(spectator);
|
||||
}
|
||||
|
||||
final ParkourUser user = ParkourUser.getUser(player);
|
||||
final ParkourSpectator spectator;
|
||||
|
||||
if (session.getPlayers().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (user != null) {
|
||||
ParkourUser.unregister(user, false, false, false);
|
||||
spectator = new ParkourSpectator(player, session, user.previousData());
|
||||
} else {
|
||||
spectator = new ParkourSpectator(player, session, null);
|
||||
}
|
||||
|
||||
session.addSpectators(spectator);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,12 +45,11 @@ public class DefaultMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() != null && pp.session.generator().getMode() instanceof DefaultMode) {
|
||||
return;
|
||||
final boolean alreadyPlaying = pp != null && pp.session.generator() != null
|
||||
&& pp.session.generator().getMode() instanceof DefaultMode;
|
||||
if (!alreadyPlaying) {
|
||||
player.closeInventory();
|
||||
Session.create(ParkourGenerator::new, null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
|
||||
Session.create(ParkourGenerator::new, null, null, player);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,12 +58,10 @@ public class GravityShiftMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() instanceof GravityShiftGenerator) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() instanceof GravityShiftGenerator)) {
|
||||
player.closeInventory();
|
||||
Session.create(session -> new GravityShiftGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
Session.create(session -> new GravityShiftGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
// ── GravityShiftGenerator ─────────────────────────────────────────────────
|
||||
|
|
|
|||
|
|
@ -69,12 +69,10 @@ public class SpeedrunMode implements Mode {
|
|||
}
|
||||
|
||||
final ParkourPlayer pp = UserRegistry.getPlayer(player);
|
||||
if (pp != null && pp.session.generator() instanceof SpeedrunGenerator) {
|
||||
return;
|
||||
if (!(pp != null && pp.session.generator() instanceof SpeedrunGenerator)) {
|
||||
player.closeInventory();
|
||||
Session.create(session -> new SpeedrunGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
player.closeInventory();
|
||||
Session.create(session -> new SpeedrunGenerator(session), null, null, player);
|
||||
}
|
||||
|
||||
// ── SpeedrunGenerator ─────────────────────────────────────────────────────
|
||||
|
|
@ -106,19 +104,12 @@ public class SpeedrunMode implements Mode {
|
|||
// The block the player just landed on is the previous-to-last in history
|
||||
// (history.size()-1 is the leading block, size()-2 is where player stands)
|
||||
final int histSize = state.history.size();
|
||||
if (histSize < 2) {
|
||||
return;
|
||||
if (histSize >= 2) {
|
||||
final Block stepped = state.history.get(histSize - 2);
|
||||
if (stepped.getType() != Material.AIR && !scheduledTasks.containsKey(stepped)) {
|
||||
scheduleBlockRemoval(stepped);
|
||||
}
|
||||
}
|
||||
|
||||
final Block stepped = state.history.get(histSize - 2);
|
||||
if (stepped.getType() == Material.AIR) {
|
||||
return;
|
||||
}
|
||||
if (scheduledTasks.containsKey(stepped)) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleBlockRemoval(stepped);
|
||||
}
|
||||
|
||||
private void scheduleBlockRemoval(@NotNull Block block) {
|
||||
|
|
|
|||
|
|
@ -57,24 +57,30 @@ public class InventoryData {
|
|||
}
|
||||
|
||||
private void loadFile(Consumer<@Nullable InventoryData> onFinish) {
|
||||
if (!tryLoadYaml(onFinish)) {
|
||||
if (file.length() == 0) {
|
||||
onFinish.accept(null);
|
||||
} else {
|
||||
loadLegacy(onFinish);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Attempts to load modern YAML data, invoking {@code onFinish} and returning {@code true} on success. */
|
||||
private boolean tryLoadYaml(Consumer<@Nullable InventoryData> onFinish) {
|
||||
try {
|
||||
final YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file);
|
||||
if (!yaml.getKeys(false).isEmpty()) {
|
||||
loadFromYaml(yaml);
|
||||
onFinish.accept(this);
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// Boundary: corrupt player data falls back to legacy format, never breaks join.
|
||||
LoParkour.getPlugin().getLogger().warning(
|
||||
"YAML inventory parse failed for %s, trying legacy format: %s".formatted(file.getName(), ex.getMessage()));
|
||||
}
|
||||
|
||||
if (file.length() == 0) {
|
||||
onFinish.accept(null);
|
||||
return;
|
||||
}
|
||||
|
||||
loadLegacy(onFinish);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void loadFromYaml(YamlConfiguration yaml) {
|
||||
|
|
|
|||
|
|
@ -85,7 +85,8 @@ public class PreviousData {
|
|||
player.resetPlayerWeather();
|
||||
player.setVelocity(new Vector(0, 0, 0));
|
||||
player.setFallDistance(0f);
|
||||
} catch (Exception ex) { // not the best way to do this... too bad!
|
||||
} catch (Exception ex) {
|
||||
// Boundary: stat restore must never throw; Bukkit behavior varies across 1.19-26.x.
|
||||
LoParkour.getPlugin().getLogger().severe("Error while recovering stats of %s".formatted(player.getName()) + " - " + ex.getMessage());
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -75,15 +75,13 @@ public final class UserRegistry {
|
|||
user.unregister();
|
||||
resetScoreboard(user);
|
||||
} catch (Exception ex) {
|
||||
// Boundary: listener/scoreboard failures must not break the leave path.
|
||||
handleUnregisterError(user, ex);
|
||||
}
|
||||
|
||||
if (restorePreviousData && shouldKickToBungee(kickIfBungee)) {
|
||||
BungeeUtil.sendPlayerToServer(user.player, Config.CONFIG.getString("bungeecord.return_server"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (restorePreviousData) {
|
||||
} else if (restorePreviousData) {
|
||||
restorePreviousState(user, urgent);
|
||||
}
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -134,6 +134,7 @@ public class ScoreboardManager {
|
|||
try {
|
||||
return me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, text);
|
||||
} catch (Exception e) {
|
||||
// Boundary: external PlaceholderAPI may throw on version skew; scoreboard must survive.
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,23 +81,17 @@ public class ParkourSpectator extends ParkourUser {
|
|||
player.setGameMode(GameMode.SPECTATOR);
|
||||
updateScoreboard(session.generator());
|
||||
|
||||
// spectator is still being teleported to world
|
||||
if (closest.getLocation().getWorld() != player.getLocation().getWorld()) {
|
||||
return;
|
||||
// spectator is still being teleported to world (same world) and far enough from the followed player
|
||||
final boolean sameWorld = closest.getLocation().getWorld() == player.getLocation().getWorld();
|
||||
final boolean farEnough = closest.getLocation().distanceSquared(player.getLocation())
|
||||
>= TELEPORT_THRESHOLD * TELEPORT_THRESHOLD; // avoid sqrt
|
||||
if (sameWorld && farEnough) {
|
||||
teleport(closest.getLocation());
|
||||
if (player.getGameMode() == GameMode.SPECTATOR) { // if player is a spectator
|
||||
player.setSpectatorTarget(null);
|
||||
player.setSpectatorTarget(player.getSpectatorTarget());
|
||||
}
|
||||
}
|
||||
|
||||
if (closest.getLocation().distanceSquared(player.getLocation()) < TELEPORT_THRESHOLD * TELEPORT_THRESHOLD) { // avoid sqrt
|
||||
return;
|
||||
}
|
||||
|
||||
teleport(closest.getLocation());
|
||||
if (player.getGameMode() != GameMode.SPECTATOR) { // if player isn't in spectator or is a bedrock player
|
||||
return;
|
||||
}
|
||||
|
||||
// if player is a spectator
|
||||
player.setSpectatorTarget(null);
|
||||
player.setSpectatorTarget(player.getSpectatorTarget());
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -26,41 +26,34 @@ public record Reward(@NotNull String string) {
|
|||
return;
|
||||
}
|
||||
|
||||
String command = this.string;
|
||||
|
||||
final Mode rewardMode = Registry.getModes().stream()
|
||||
.filter(m -> this.string.contains("%s:".formatted(m.getName().toLowerCase())))
|
||||
.findFirst()
|
||||
.orElse(Modes.defaultMode());
|
||||
|
||||
if (mode != rewardMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
command = command.replaceFirst("%s:".formatted(rewardMode.getName().toLowerCase()), "");
|
||||
|
||||
// check for placeholders
|
||||
if (command.toLowerCase().contains("%player%")) {
|
||||
command = command.replaceAll("%player%", player.getName());
|
||||
if (mode == rewardMode) {
|
||||
String command = string.replaceFirst("%s:".formatted(rewardMode.getName().toLowerCase()), "");
|
||||
if (command.toLowerCase().contains("%player%")) {
|
||||
command = command.replaceAll("%player%", player.getName());
|
||||
}
|
||||
applyCommand(player, command);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyCommand(@NotNull ParkourPlayer player, String command) {
|
||||
// check for extra data
|
||||
if (command.toLowerCase().contains("leave:")) { // leave:
|
||||
command = command.replaceFirst("leave:", "");
|
||||
player.previousData().onLeave.add(new Reward(command));
|
||||
player.previousData().onLeave.add(new Reward(command.replaceFirst("leave:", "")));
|
||||
return;
|
||||
}
|
||||
|
||||
// check for things to perform
|
||||
if (command.toLowerCase().contains("send:")) {
|
||||
command = command.replaceFirst("send:", "");
|
||||
|
||||
player.send(command);
|
||||
player.send(command.replaceFirst("send:", ""));
|
||||
} else if (command.toLowerCase().contains("vault:")) {
|
||||
command = command.replaceFirst("vault:", "");
|
||||
|
||||
final String amount = command.replaceFirst("vault:", "");
|
||||
try {
|
||||
VaultHook.deposit(player.player, Double.parseDouble(command));
|
||||
VaultHook.deposit(player.player, Double.parseDouble(amount));
|
||||
} catch (NumberFormatException ex) {
|
||||
LoParkour.getPlugin().getLogger().severe(
|
||||
"Error while trying to process Vault reward - check your rewards file for incorrect numbers - "
|
||||
|
|
|
|||
|
|
@ -33,4 +33,9 @@ final class BukkitBackend implements Scheduler.Backend {
|
|||
public ScheduledTask runTimer(Runnable task, long delayTicks, long periodTicks) {
|
||||
return Bukkit.getScheduler().runTaskTimer(plugin, task, delayTicks, periodTicks)::cancel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledTask runTimerAsync(Runnable task, long delayTicks, long periodTicks) {
|
||||
return Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, task, delayTicks, periodTicks)::cancel;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ final class FoliaBackend implements Scheduler.Backend {
|
|||
private final Method globalRunDelayed;
|
||||
private final Method globalRunAtFixedRate;
|
||||
private final Method asyncRunNow;
|
||||
private final Method asyncRunAtFixedRate;
|
||||
private final Method taskCancel;
|
||||
|
||||
FoliaBackend(Plugin plugin) throws ReflectiveOperationException {
|
||||
|
|
@ -40,6 +41,8 @@ final class FoliaBackend implements Scheduler.Backend {
|
|||
this.globalRunAtFixedRate = method(GLOBAL_SCHEDULER_CLASS, "runAtFixedRate",
|
||||
Plugin.class, Consumer.class, long.class, long.class);
|
||||
this.asyncRunNow = method(ASYNC_SCHEDULER_CLASS, "runNow", Plugin.class, Consumer.class);
|
||||
this.asyncRunAtFixedRate = method(ASYNC_SCHEDULER_CLASS, "runAtFixedRate",
|
||||
Plugin.class, Consumer.class, long.class, long.class);
|
||||
this.taskCancel = Class.forName(SCHEDULER_PACKAGE + "ScheduledTask").getMethod("cancel");
|
||||
}
|
||||
|
||||
|
|
@ -64,6 +67,12 @@ final class FoliaBackend implements Scheduler.Backend {
|
|||
consumer(task), delayTicks, periodTicks));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduledTask runTimerAsync(Runnable task, long delayTicks, long periodTicks) {
|
||||
return wrap(invoke(asyncRunAtFixedRate, asyncScheduler, plugin,
|
||||
consumer(task), delayTicks, periodTicks));
|
||||
}
|
||||
|
||||
private static Object scheduler(String bukkitGetter) throws ReflectiveOperationException {
|
||||
return Bukkit.class.getMethod(bukkitGetter).invoke(null);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,6 +87,18 @@ public final class Scheduler {
|
|||
return backend.runTimer(task, delayTicks, periodTicks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the task repeatedly on a worker thread after the given delay.
|
||||
*
|
||||
* @param task the task to run
|
||||
* @param delayTicks first run delay in ticks
|
||||
* @param periodTicks period between runs in ticks
|
||||
* @return a handle used to cancel the task
|
||||
*/
|
||||
public ScheduledTask runTimerAsync(Runnable task, long delayTicks, long periodTicks) {
|
||||
return backend.runTimerAsync(task, delayTicks, periodTicks);
|
||||
}
|
||||
|
||||
private static Backend createBackend(Plugin plugin) {
|
||||
if (FOLIA) {
|
||||
try {
|
||||
|
|
@ -118,5 +130,7 @@ public final class Scheduler {
|
|||
ScheduledTask runLater(Runnable task, long delayTicks);
|
||||
|
||||
ScheduledTask runTimer(Runnable task, long delayTicks, long periodTicks);
|
||||
|
||||
ScheduledTask runTimerAsync(Runnable task, long delayTicks, long periodTicks);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ public class SessionStateManager {
|
|||
if (LoParkour.getGhostService() != null) {
|
||||
LoParkour.getGhostService().recordPlayers(session.generator());
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
} catch (RuntimeException t) {
|
||||
session.generator().session.getPlayers().forEach(p ->
|
||||
p.player.sendMessage("§c[LoParkour] Tick error: " + t.getMessage()));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,11 +102,10 @@ public final class StorageDisk {
|
|||
LoParkour.getPlugin().getLogger().warning(
|
||||
"Player data file for %s is empty or corrupted, using defaults".formatted(player.getName()));
|
||||
PlayerSettingsManager.applyDefaults(player);
|
||||
return;
|
||||
} else {
|
||||
normalizeLegacyKeys(settings);
|
||||
PlayerSettingsManager.applySettings(player, settings);
|
||||
}
|
||||
|
||||
normalizeLegacyKeys(settings);
|
||||
PlayerSettingsManager.applySettings(player, settings);
|
||||
} catch (IOException ex) {
|
||||
LoParkour.getPlugin().getLogger().severe(
|
||||
"Error while trying to read disk data of %s".formatted(player.getName()) + " - " + ex.getMessage());
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ public class SQLConnectionManager {
|
|||
|
||||
executeCallbacks();
|
||||
} catch (Exception ex) {
|
||||
// Boundary: pool failure taxonomy is not public API; connect must never break enable.
|
||||
handleConnectionError(ex);
|
||||
}
|
||||
}
|
||||
|
|
@ -103,6 +104,7 @@ public class SQLConnectionManager {
|
|||
try {
|
||||
cb.run();
|
||||
} catch (Exception e) {
|
||||
// Boundary: one failing callback must not block the remaining on-connect callbacks.
|
||||
LoParkour.getPlugin().getLogger().severe("Error in SQL onConnect callback: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import org.jetbrains.annotations.NotNull;
|
|||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Parses {@link Material} names from config (modern IDs, registry, legacy aliases).
|
||||
|
|
@ -27,46 +28,33 @@ public final class Materials {
|
|||
return null;
|
||||
}
|
||||
final String key = raw.toLowerCase(Locale.ROOT).replace(' ', '_');
|
||||
|
||||
Material m = Material.matchMaterial(key, false);
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
|
||||
m = fromRegistry(key);
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
|
||||
m = Material.matchMaterial(raw.toUpperCase(Locale.ROOT), false);
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
|
||||
final int colon = key.indexOf(':');
|
||||
if (colon >= 0) {
|
||||
final String id = key.substring(colon + 1);
|
||||
m = Material.matchMaterial(id, false);
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
m = fromRegistry(id);
|
||||
final String colonId = colon >= 0 ? key.substring(colon + 1) : null;
|
||||
|
||||
return firstNonNull(
|
||||
() -> Material.matchMaterial(key, false),
|
||||
() -> fromRegistry(key),
|
||||
() -> Material.matchMaterial(raw.toUpperCase(Locale.ROOT), false),
|
||||
() -> colonId == null ? null : firstNonNull(
|
||||
() -> Material.matchMaterial(colonId, false),
|
||||
() -> fromRegistry(colonId)),
|
||||
() -> coloredSlabFallback(key),
|
||||
() -> Material.matchMaterial(key, true),
|
||||
() -> Material.getMaterial(raw.toUpperCase(Locale.ROOT))
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns the first non-null result produced by the candidates, evaluated in order. */
|
||||
@Nullable
|
||||
@SafeVarargs
|
||||
private static Material firstNonNull(Supplier<Material>... candidates) {
|
||||
for (final Supplier<Material> candidate : candidates) {
|
||||
final Material m = candidate.get();
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
m = coloredSlabFallback(key);
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
|
||||
m = Material.matchMaterial(key, true);
|
||||
if (m != null) {
|
||||
return m;
|
||||
}
|
||||
|
||||
return Material.getMaterial(raw.toUpperCase(Locale.ROOT));
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
|
|
|||
|
|
@ -40,10 +40,12 @@ public final class World {
|
|||
|
||||
final var existingWorld = Bukkit.getWorld(name);
|
||||
|
||||
if (!Config.CONFIG.getBoolean("joining")) {
|
||||
return;
|
||||
if (Config.CONFIG.getBoolean("joining")) {
|
||||
createOrReuse(existingWorld);
|
||||
}
|
||||
}
|
||||
|
||||
private static void createOrReuse(org.bukkit.World existingWorld) {
|
||||
if (existingWorld != null) {
|
||||
LoParkour.getPlugin().getLogger().warning(
|
||||
"Crash detected! The parkour world loading twice is not usual behaviour. " +
|
||||
|
|
@ -134,10 +136,12 @@ public final class World {
|
|||
LoParkour.log("Deleting Spigot world");
|
||||
|
||||
final File folder = worldFolder();
|
||||
if (!folder.exists()) {
|
||||
return;
|
||||
if (folder.exists()) {
|
||||
deleteWorldFolder(folder);
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteWorldFolder(File folder) {
|
||||
try {
|
||||
Bukkit.unloadWorld(name, false);
|
||||
} catch (UnsupportedOperationException ex) {
|
||||
|
|
|
|||
|
|
@ -25,28 +25,28 @@ Player setting **0.25 (easy)** → only structures with difficulty ≤ 0.25.
|
|||
|
||||
## Creating schematics in-game (admin)
|
||||
|
||||
1. Get the wand: `/lp schematic wand`
|
||||
2. **Left-click** = position 1, **right-click** = position 2 (or use `/lp schematic pos1` / `pos2`)
|
||||
1. Get the wand: `/lpk schematic wand`
|
||||
2. **Left-click** = position 1, **right-click** = position 2 (or use `/lpk schematic pos1` / `pos2`)
|
||||
3. Save and register:
|
||||
- `/lp create <difficulty>` — auto name `parkour-<hash>.schem` + YAML entry
|
||||
- `/lp schematic create <difficulty>` — same
|
||||
- `/lp schematic create <name> <difficulty>` — custom name (letters, numbers, `-`, `_`)
|
||||
- `/lpk create <difficulty>` — auto name `parkour-<hash>.schem` + YAML entry
|
||||
- `/lpk schematic create <difficulty>` — same
|
||||
- `/lpk schematic create <name> <difficulty>` — custom name (letters, numbers, `-`, `_`)
|
||||
|
||||
Difficulty examples: `0.25`, `0.5`, `0.75`, `1.0` (must be between 0 and 1).
|
||||
|
||||
4. `/lp schematic reload` — reload files without restart
|
||||
4. `/lpk schematic reload` — reload files without restart
|
||||
|
||||
## Admin commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `/lp schematic wand` | Selection wand |
|
||||
| `/lp schematic pos1` / `pos2` | Set corners at your feet |
|
||||
| `/lp create <difficulty>` | Save selection → `.schem` + YAML |
|
||||
| `/lp schematic create <name> <difficulty>` | Save with custom name |
|
||||
| `/lp schematic list` | List loaded structures |
|
||||
| `/lp schematic paste <name>` | Test-paste at your location |
|
||||
| `/lp schematic reload` | Reload disk files |
|
||||
| `/lpk schematic wand` | Selection wand |
|
||||
| `/lpk schematic pos1` / `pos2` | Set corners at your feet |
|
||||
| `/lpk create <difficulty>` | Save selection → `.schem` + YAML |
|
||||
| `/lpk schematic create <name> <difficulty>` | Save with custom name |
|
||||
| `/lpk schematic list` | List loaded structures |
|
||||
| `/lpk schematic paste <name>` | Test-paste at your location |
|
||||
| `/lpk schematic reload` | Reload disk files |
|
||||
|
||||
## Flow (runtime)
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,6 @@ main: dev.loki.loparkour.LoParkour
|
|||
softdepend: [floodgate, Vault, PlaceholderAPI, Multiverse-Core]
|
||||
commands:
|
||||
loparkour:
|
||||
aliases: [parkour, lp]
|
||||
aliases: [parkour, lpk]
|
||||
usage: /<command> [arguments]
|
||||
description: Main command for LoParkour
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# -------- Structure difficulty --------
|
||||
# plugins/LoParkour/schematics/
|
||||
# .nbt — structure block export
|
||||
# .schem / .schematic — WorldEdit or /lp create
|
||||
# In-game: /lp schematic wand → select → /lp create <difficulty>
|
||||
# .schem / .schematic — WorldEdit or /lpk create
|
||||
# In-game: /lpk schematic wand → select → /lpk create <difficulty>
|
||||
# Docs: plugins/LoParkour/docs/SCHEMATICS.md
|
||||
|
||||
# -------- The difficulty of schematics --------
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
Class <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore$1> extends class <org.bukkit.scheduler.BukkitRunnable> in (MetricsCacheStore.java:0)
|
||||
Constructor <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore$1.<init>(dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore)> calls constructor <org.bukkit.scheduler.BukkitRunnable.<init>()> in (MetricsCacheStore.java:84)
|
||||
Field <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore.autoSaveTask> has type <org.bukkit.scheduler.BukkitRunnable> in (MetricsCacheStore.java:0)
|
||||
Method <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore.startAutoSave()> calls constructor <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore$1.<init>(dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore)> in (MetricsCacheStore.java:84)
|
||||
Method <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore.startAutoSave()> calls method <org.bukkit.scheduler.BukkitRunnable.cancel()> in (MetricsCacheStore.java:81)
|
||||
Method <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore.startAutoSave()> calls method <org.bukkit.scheduler.BukkitRunnable.runTaskTimerAsynchronously(org.bukkit.plugin.Plugin, long, long)> in (MetricsCacheStore.java:91)
|
||||
Method <dev.loki.loparkour.adaptive.core.metrics.MetricsCacheStore.stopAutoSave()> calls method <org.bukkit.scheduler.BukkitRunnable.cancel()> in (MetricsCacheStore.java:96)
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
Method <dev.loki.loparkour.duels.DuelsCountdown.giveStartItem(dev.loki.loparkour.player.core.ParkourPlayer)> calls method <org.bukkit.Bukkit.getScheduler()> in (DuelsCountdown.java:45)
|
||||
Method <dev.loki.loparkour.duels.DuelsCountdown.start()> calls method <org.bukkit.Bukkit.getScheduler()> in (DuelsCountdown.java:55)
|
||||
Method <dev.loki.loparkour.duels.DuelsGenerator.win(dev.loki.loparkour.player.core.ParkourPlayer)> calls method <org.bukkit.Bukkit.getScheduler()> in (DuelsGenerator.java:137)
|
||||
Loading…
Add table
Add a link
Reference in a new issue