Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java
T
dmg 6ac4c4bfde
CI / build (push) Failing after 4m43s
Release / release (push) Failing after 4m45s
feat(sessions): complete native health and fantasy defeat
2026-09-19 12:37:20 -04:00

265 lines
16 KiB
Java

package games.dmg.fantasystick;
import com.comphenix.protocol.ProtocolLibrary;
import games.dmg.fantasystick.presentation.CharacterPresentation;
import games.dmg.fantasystick.presentation.CharacterChatNames;
import games.dmg.fantasystick.presentation.ProtocolPresentation;
import games.dmg.fantasystick.crafting.CharacterFactory;
import games.dmg.fantasystick.crafting.CharacterAnvilNames;
import games.dmg.fantasystick.crafting.ManualCraftingController;
import games.dmg.fantasystick.crafting.ManualCraftingGuard;
import games.dmg.fantasystick.crafting.PlayerSheetDrops;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.persistence.CharacterStorage;
import games.dmg.fantasystick.persistence.EquipmentSessionStore;
import games.dmg.fantasystick.session.EquipmentAdminCommand;
import games.dmg.fantasystick.session.EquipmentSessionEvents;
import games.dmg.fantasystick.session.EquipmentSessions;
import games.dmg.fantasystick.persistence.YamlCharacterRepository;
import games.dmg.fantasystick.progression.ProgressionRules;
import java.time.Clock;
import java.util.logging.Level;
import org.bukkit.plugin.java.JavaPlugin;
/** Crafting, native fantasy sessions, books, parties and names; progression actions and spells remain separate. */
public final class FantasyStickPlugin extends JavaPlugin {
private CharacterStorage characters;
private ManualCraftingController crafting;
private ManualCraftingGuard guard;
private CharacterAnvilNames anvilNames;
private boolean recipeRegistered;
private EquipmentSessionStore receipts;
private EquipmentSessions sessions;
private EquipmentSessionEvents sessionEvents;
private games.dmg.fantasystick.book.CharacterBookController books;
private games.dmg.fantasystick.party.PartyRoster parties;
private games.dmg.fantasystick.party.PartyEvents partyEvents;
private games.dmg.fantasystick.party.PartyCombat partyCombat;
private EquipmentAdminCommand admin;
private volatile Object lifetime;
private CharacterPresentation presentation;
private ProtocolPresentation protocolPresentation;
private CharacterChatNames chatNames;
private games.dmg.fantasystick.persistence.AdventureSettings adventureSettings;
private games.dmg.fantasystick.session.AdventureModeLease gameModes;
private games.dmg.fantasystick.session.SessionVitals vitals;
private games.dmg.fantasystick.session.SessionVisuals sessionVisuals;
private java.util.concurrent.CompletionStage<Void> configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null);
@Override public void onEnable() {
try {
Object generation = new Object();
lifetime = generation;
if (!configurationDrain.toCompletableFuture().isDone()) {
configurationDrain.whenComplete((ignored, failure) -> {
if (lifetime != generation) return;
try {
getServer().getScheduler().runTask(this, () -> {
if (lifetime == generation && isEnabled()) onEnable();
});
} catch (RuntimeException rejected) {
getLogger().log(Level.WARNING, "Configuration startup continuation unavailable", rejected);
}
});
return;
}
reloadConfig();
var adventure = games.dmg.fantasystick.persistence.AdventureSettings.validate(getConfig().get("adventure-mode"));
adventureSettings = new games.dmg.fantasystick.persistence.AdventureSettings(getDataFolder().toPath(), adventure);
var switchDelay = switchDelay();
var defaults = ProgressionRules.defaults();
var rules = new ProgressionRules(new java.math.BigInteger(getConfig().getString("starting-points", "40")),
defaults.xpPerLevel(), defaults.maximumLevel());
var factory = new CharacterFactory();
characters = new CharacterStorage(new YamlCharacterRepository(getDataFolder().toPath()), Clock.systemUTC());
crafting = new ManualCraftingController(characters, () -> factory.create(rules),
task -> getServer().getScheduler().runTask(this, task),
player -> new PlayerSheetDrops(player, event -> getServer().getPluginManager().callEvent(event)),
problem -> getLogger().log(Level.WARNING, "Character craft " + problem.operation() + " for player "
+ problem.player() + "; character records " + problem.characters(), problem.cause()));
java.util.function.Consumer<Runnable> nextTick = task -> getServer().getScheduler().runTask(this, task);
java.util.function.Consumer<Throwable> presentationFailures = problem ->
getLogger().log(Level.WARNING, "Character presentation failed", problem);
// This supplier belongs to one enable, never the mutable plugin field after re-enable.
var localPresentation = new java.util.concurrent.atomic.AtomicReference<CharacterPresentation>();
var installationFailure = new java.util.concurrent.atomic.AtomicReference<Throwable>();
protocolPresentation = new ProtocolPresentation(this, ProtocolLibrary.getProtocolManager(),
() -> localPresentation.get().snapshot(), problem -> {
installationFailure.compareAndSet(null, problem);
presentationFailures.accept(problem);
});
presentation = new CharacterPresentation(protocolPresentation, nextTick,
() -> getServer().isPrimaryThread(), presentationFailures, characters::find);
localPresentation.set(presentation);
chatNames = new CharacterChatNames(presentation::name);
protocolPresentation.install();
if (installationFailure.get() != null) {
throw new IllegalStateException("Could not install character presentation", installationFailure.get());
}
guard = new ManualCraftingGuard();
anvilNames = new CharacterAnvilNames(characters,
problem -> getLogger().log(Level.WARNING, "Character name update was refused or failed for player "
+ problem.player() + "; character " + problem.character(), problem.cause()), getServer().getItemFactory(),
presentation::acknowledged);
receipts = new EquipmentSessionStore(getDataFolder().toPath(), Clock.systemUTC());
java.util.function.Consumer<EquipmentSessions.Failure> diagnostics = problem ->
getLogger().log(Level.WARNING, "Equipment transition/recovery for player " + problem.player()
+ "; session " + problem.session(), problem.cause());
gameModes = new games.dmg.fantasystick.session.AdventureModeLease();
sessions = new EquipmentSessions(characters, receipts, switchDelay, Clock.systemUTC(), nextTick,
notice -> notifyPlayer(generation, notice), diagnostics, presentation, adventureSettings::enabled, gameModes);
vitals = new games.dmg.fantasystick.session.SessionVitals();
sessions.attachVitals(vitals);
parties = new games.dmg.fantasystick.party.PartyRoster(Clock.systemUTC(), id -> {
var player = getServer().getPlayer(id);
return player != null && player.isOnline();
});
partyEvents = new games.dmg.fantasystick.party.PartyEvents(parties);
partyCombat = new games.dmg.fantasystick.party.PartyCombat(parties, sessions);
books = new games.dmg.fantasystick.book.CharacterBookController(characters, rules, nextTick,
problem -> getLogger().log(Level.WARNING, "Character book failed for player " + problem.player()
+ "; character " + problem.character(), problem.cause()), parties, getServer(), id -> {
String name = localPresentation.get().name(id);
var player = getServer().getPlayer(id);
return net.kyori.adventure.text.Component.text(name != null ? name : player == null ? id.toString() : player.getName());
});
sessionEvents = new EquipmentSessionEvents(sessions, nextTick, diagnostics, books);
admin = new EquipmentAdminCommand(receipts, sessions, getServer(), nextTick,
problem -> getLogger().log(Level.WARNING, "Equipment admin " + problem.operation()
+ " for player " + problem.player(), problem.cause()), adventureSettings);
var command = java.util.Objects.requireNonNull(getCommand("fantasystick"), "Missing packaged fantasystick command");
command.setExecutor(admin);
command.setTabCompleter(admin);
getServer().getPluginManager().registerEvents(crafting, this);
getServer().getPluginManager().registerEvents(guard, this);
getServer().getPluginManager().registerEvents(anvilNames, this);
getServer().getPluginManager().registerEvents(sessionEvents, this);
getServer().getPluginManager().registerEvents(chatNames, this);
getServer().getPluginManager().registerEvents(partyEvents, this);
getServer().getPluginManager().registerEvents(partyCombat, this);
partyCombat.install(this);
getServer().getPluginManager().registerEvents(books, this);
getServer().getPluginManager().registerEvents(gameModes, this);
sessionVisuals = new games.dmg.fantasystick.session.SessionVisuals(sessions,
failure -> getLogger().log(Level.WARNING, "Fantasy session particle delivery failed", failure));
sessionVisuals.install(this);
recipeRegistered = getServer().addRecipe(new CharacterSheets().recipe());
if (!recipeRegistered) throw new IllegalStateException("Character-sheet recipe key is already registered");
for (var player : getServer().getOnlinePlayers()) sessions.arrive(player);
} catch (RuntimeException | LinkageError failure) {
try { onDisable(); }
catch (RuntimeException | LinkageError cleanupFailure) { failure.addSuppressed(cleanupFailure); }
throw failure;
}
}
@Override public void onDisable() {
lifetime = null;
// Detach this enable's resources before any native callback can reenter disable.
var closingPresentation = presentation; presentation = null;
var closingProtocol = protocolPresentation; protocolPresentation = null;
var closingChat = chatNames; chatNames = null;
var closingAdmin = admin; admin = null;
var closingEvents = sessionEvents; sessionEvents = null;
var closingBooks = books; books = null;
var closingPartyEvents = partyEvents; partyEvents = null;
var closingPartyCombat = partyCombat; partyCombat = null;
var closingParties = parties; parties = null;
var closingCrafting = crafting; crafting = null;
var closingGuard = guard; guard = null;
var closingAnvil = anvilNames; anvilNames = null;
var closingSessions = sessions; sessions = null;
var closingReceipts = receipts; receipts = null;
var closingCharacters = characters; characters = null;
var closingSettings = adventureSettings; adventureSettings = null;
var closingModes = gameModes; gameModes = null;
var closingVitals = vitals; vitals = null;
var closingVisuals = sessionVisuals; sessionVisuals = null;
// Retire client resources independently of successful ordinary-equipment restoration.
if (closingPresentation != null) cleanup("presentation", closingPresentation::close);
if (closingProtocol != null) cleanup("protocol presentation", closingProtocol::close);
if (closingAdmin != null) cleanup("admin command", closingAdmin::close);
if (closingSettings != null) {
configurationDrain = closingSettings.drained();
cleanup("configuration", closingSettings::close);
}
if (closingBooks != null) cleanup("character book", closingBooks::close);
if (closingVisuals != null) cleanup("session particles", closingVisuals::close);
if (closingParties != null) cleanup("parties", closingParties::close);
if (closingPartyCombat != null) cleanup("party combat", closingPartyCombat::close);
if (closingEvents != null) cleanup("session events", closingEvents::close);
if (closingCrafting != null) cleanup("craft attempts", closingCrafting::close);
if (closingSessions != null) cleanup("equipment sessions", closingSessions::close);
if (closingVitals != null) cleanup("native health hooks", closingVitals::close);
unregister(closingModes);
unregister(closingChat);
unregister(closingPartyEvents);
unregister(closingPartyCombat);
unregister(closingBooks);
unregister(closingEvents);
unregister(closingCrafting);
unregister(closingGuard);
unregister(closingAnvil);
if (recipeRegistered) cleanup("character-sheet recipe", () -> {
getServer().removeRecipe(CharacterSheets.RECIPE);
recipeRegistered = false; // Retain ownership for a later retry if removal failed.
});
if (closingCharacters != null) cleanup("character storage", closingCharacters::close);
// Never await IO on the server thread or close receipts ahead of accepted preparations.
if (closingReceipts != null) cleanup("equipment receipt drain", () -> {
if (closingSessions == null) closingReceipts.close();
else closingSessions.drained().whenComplete((ignored, failure) -> closingReceipts.close());
});
}
private void unregister(org.bukkit.event.Listener listener) {
if (listener != null) cleanup("listener " + listener.getClass().getSimpleName(),
() -> org.bukkit.event.HandlerList.unregisterAll(listener));
}
private void cleanup(String resource, Runnable action) {
try { action.run(); }
catch (RuntimeException | LinkageError failure) {
try { getLogger().log(Level.WARNING, "Could not close " + resource + "; continuing shutdown cleanup", failure); }
catch (RuntimeException | LinkageError ignored) { /* Diagnostics must not prevent remaining cleanup. */ }
}
}
private java.time.Duration switchDelay() {
Object configured = getConfig().get("character-swap-cooldown-seconds", 900);
String value = String.valueOf(configured);
if (!value.matches("[0-9]+")) {
throw new IllegalArgumentException("character-swap-cooldown-seconds must be a nonnegative integer");
}
try {
var delay = java.time.Duration.ofSeconds(new java.math.BigInteger(value).longValueExact());
var deadline = java.time.Instant.now().plus(delay);
if (deadline.atOffset(java.time.ZoneOffset.UTC).getYear() > 9999) {
throw new IllegalArgumentException("character-swap-cooldown-seconds exceeds the persisted UTC timestamp range");
}
return delay;
} catch (ArithmeticException | java.time.DateTimeException invalid) {
throw new IllegalArgumentException("character-swap-cooldown-seconds exceeds the supported duration range", invalid);
}
}
private void notifyPlayer(Object generation, EquipmentSessions.Notice notice) {
Runnable delivery = () -> {
if (lifetime != generation) return;
var player = getServer().getPlayer(notice.player());
if (player == null || !player.isOnline()) return;
String message = switch (notice.code()) {
case "NO_SPACE" -> "Equipment entry refused: free one slot in your main inventory for the Fantasy Storage Box.";
case "INELIGIBLE_EQUIPMENT" -> "Equipment entry refused: a hotbar or armor item cannot fit in a vanilla shulker box. Move it before retrying.";
default -> notice.message();
};
player.sendMessage(message);
if (notice.code().equals("DEFEAT")) games.dmg.fantasystick.session.SessionVisuals.burst(player, org.bukkit.Color.RED, 12);
else player.spawnParticle(org.bukkit.Particle.ANGRY_VILLAGER, player.getLocation().add(0, 1, 0), 8, 0.3, 0.4, 0.3, 0);
};
if (lifetime != generation) return;
if (getServer().isPrimaryThread()) delivery.run();
else getServer().getScheduler().runTask(this, delivery);
}
}