feat(ability): add rallying cry
Release / release (push) Successful in 7m59s

This commit is contained in:
dmg committed 2026-09-20 17:49:12 -04:00
1 parent cc6c1a7f44
commit c80c088945
10 files changed
+1048 -2

No files matched your search

@@ -74,6 +74,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
private games.dmg.fantasystick.persistence.PurifySettings purifySettings;
private games.dmg.fantasystick.ability.GuardianBond guardianBond;
private games.dmg.fantasystick.persistence.GuardianBondSettings guardianBondSettings;
private games.dmg.fantasystick.ability.OutgoingDamageBonus outgoingDamageBonus;
private games.dmg.fantasystick.ability.RallyingCry rallyingCry;
private games.dmg.fantasystick.persistence.RallyingCrySettings rallyingCrySettings;
private games.dmg.fantasystick.persistence.HexSettings hexSettings;
private games.dmg.fantasystick.persistence.ShieldBashSettings shieldBashSettings;
private games.dmg.fantasystick.persistence.StoneSkinSettings stoneSkinSettings;
@@ -146,6 +149,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
var purifyInitial = games.dmg.fantasystick.persistence.PurifySettings.parse(purifyConfiguration);
var guardianBondConfiguration = guardianBondConfiguration();
var guardianBondInitial = games.dmg.fantasystick.persistence.GuardianBondSettings.parse(guardianBondConfiguration);
var rallyingCryConfiguration = rallyingCryConfiguration();
var rallyingCryInitial = games.dmg.fantasystick.persistence.RallyingCrySettings.parse(rallyingCryConfiguration);
var adminReviveTimeout = games.dmg.fantasystick.persistence.AdminReviveSettings.parse(
getConfig().get(games.dmg.fantasystick.persistence.AdminReviveSettings.KEY));
var factory = new CharacterFactory();
@@ -248,6 +253,12 @@ public final class FantasyStickPlugin extends JavaPlugin {
getDataFolder().toPath(), guardianBondConfiguration);
guardianBond = new games.dmg.fantasystick.ability.GuardianBond(guardianBondInitial, sessions, parties,
support -> combatExperience.support(support.target(), support.supportingCharacter(), support.aided(), support.amount()));
outgoingDamageBonus = new games.dmg.fantasystick.ability.OutgoingDamageBonus(sessions, parties,
support -> combatExperience.support(support.target(), support.supportingCharacter(), support.aided(), support.amount()));
rallyingCrySettings = new games.dmg.fantasystick.persistence.RallyingCrySettings(
getDataFolder().toPath(), rallyingCryConfiguration);
rallyingCry = new games.dmg.fantasystick.ability.RallyingCry(
rallyingCryInitial, sessions, parties, outgoingDamageBonus);
greatSword = new games.dmg.fantasystick.ability.GreatSword(greatSwordSettings);
revivals = new games.dmg.fantasystick.persistence.RevivalStore(getDataFolder().toPath());
revive = new games.dmg.fantasystick.ability.Revive(characters, revivals, Clock.systemUTC(), nextTick,
@@ -265,6 +276,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
abilityRegistry.register(mendingLight.definition());
abilityRegistry.register(purify.definition());
abilityRegistry.register(guardianBond.definition());
abilityRegistry.register(rallyingCry.definition());
abilityRegistry.register(greatSword.definition());
abilityRegistry.register(revive.definition());
sessions.attachAbilityRegistry(abilityRegistry);
@@ -310,6 +322,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
admin.attachMendingLight(mendingLightSettings, mendingLight);
admin.attachPurify(purifySettings, purify);
admin.attachGuardianBond(guardianBondSettings, guardianBond);
admin.attachRallyingCry(rallyingCrySettings, rallyingCry);
admin.attachAdminRevival(adminRevival, adminReviveSettings);
admin.attachExperienceGrant(new games.dmg.fantasystick.session.AdminExperienceGrant(
characters, rules, sessions, nextTick, getServer()::getPlayer,
@@ -345,6 +358,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
guardianBond.install(this);
getServer().getPluginManager().registerEvents(shieldBash, this);
getServer().getPluginManager().registerEvents(outgoingDamageMitigation, this);
getServer().getPluginManager().registerEvents(outgoingDamageBonus, this);
rallyingCry.install(this);
getServer().getPluginManager().registerEvents(temporaryHealth, this);
getServer().getPluginManager().registerEvents(greatSword, this);
getServer().getPluginManager().registerEvents(revive, this);
@@ -417,6 +432,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
var closingPurifySettings = purifySettings; purifySettings = null;
var closingGuardianBond = guardianBond; guardianBond = null;
var closingGuardianBondSettings = guardianBondSettings; guardianBondSettings = null;
var closingRallyingCry = rallyingCry; rallyingCry = null;
var closingRallyingCrySettings = rallyingCrySettings; rallyingCrySettings = null;
var closingOutgoingDamageBonus = outgoingDamageBonus; outgoingDamageBonus = null;
var closingAdminRevival = adminRevival; adminRevival = null;
var closingAdminReviveSettings = adminReviveSettings; adminReviveSettings = null;
var closingSwitchDelaySettings = switchDelaySettings; switchDelaySettings = null;
@@ -453,6 +471,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
if (closingPurifySettings != null) cleanup("Purify configuration", closingPurifySettings::close);
if (closingGuardianBond != null) cleanup("Guardian Bond", closingGuardianBond::close);
if (closingGuardianBondSettings != null) cleanup("Guardian Bond configuration", closingGuardianBondSettings::close);
if (closingRallyingCry != null) cleanup("Rallying Cry", closingRallyingCry::close);
if (closingRallyingCrySettings != null) cleanup("Rallying Cry configuration", closingRallyingCrySettings::close);
if (closingOutgoingDamageBonus != null) cleanup("outgoing damage bonuses", closingOutgoingDamageBonus::close);
if (closingAdminReviveSettings != null) cleanup("admin revival configuration", closingAdminReviveSettings::close);
if (closingSwitchDelaySettings != null) cleanup("switch delay configuration", closingSwitchDelaySettings::close);
if (closingRoleplaySettings != null) cleanup("roleplay configuration", closingRoleplaySettings::close);
@@ -484,6 +505,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
: closingPurifySettings.drained().toCompletableFuture(),
closingGuardianBondSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
: closingGuardianBondSettings.drained().toCompletableFuture(),
closingRallyingCrySettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
: closingRallyingCrySettings.drained().toCompletableFuture(),
closingAdminReviveSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
: closingAdminReviveSettings.drained().toCompletableFuture(),
closingSwitchDelaySettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
@@ -714,6 +737,16 @@ public final class FantasyStickPlugin extends JavaPlugin {
return java.util.Map.copyOf(values);
}
private java.util.Map<String, String> rallyingCryConfiguration() {
var values = new java.util.LinkedHashMap<String, String>();
for (String key : games.dmg.fantasystick.persistence.RallyingCrySettings.keys()) {
values.put(key, getConfig().getString(key,
games.dmg.fantasystick.persistence.RallyingCrySettings.defaultValue(key)));
}
games.dmg.fantasystick.persistence.RallyingCrySettings.parse(values);
return java.util.Map.copyOf(values);
}
private games.dmg.fantasystick.ability.GreatSword.Settings greatSwordSettings() {
try {
var base = new java.math.BigInteger(getConfig().getString("great-sword-base-damage", "7"));
@@ -0,0 +1,114 @@
package games.dmg.fantasystick.ability;
import games.dmg.fantasystick.party.PartyRoster;
import games.dmg.fantasystick.session.EquipmentSessions;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.projectiles.ProjectileSource;
/** Strongest deterministic Fantasy Stick outgoing combat bonus stage. */
public final class OutgoingDamageBonus implements Listener, AutoCloseable {
public record Support(UUID target, UUID supportingCharacter, EquipmentSessions.Active aided, BigDecimal amount) { }
private final class Grant implements AutoCloseable {
final long sequence; final AbilityExecution execution; final Player recipient;
final BigDecimal percent; final BooleanSupplier current; boolean closed;
Grant(AbilityExecution execution, Player recipient, BigDecimal percent, BooleanSupplier current) {
sequence = ++sequences; this.execution = execution; this.recipient = recipient;
this.percent = percent; this.current = current;
}
boolean valid() {
try { return !closed && execution.stillCurrent() && current.getAsBoolean(); }
catch (RuntimeException invalid) { return false; }
}
@Override public void close() {
if (closed) return; closed = true;
var owned = grants.get(recipient.getUniqueId());
if (owned != null) { owned.remove(this); if (owned.isEmpty()) grants.remove(recipient.getUniqueId()); }
}
}
private record Used(Grant grant, Entity target, BigDecimal amount) { }
private final EquipmentSessions sessions;
private final PartyRoster parties;
private final Consumer<Support> supports;
private final Map<UUID, List<Grant>> grants = new java.util.HashMap<>();
private final Map<EntityDamageEvent, Used> pending = new IdentityHashMap<>();
private long sequences;
private boolean closed;
public OutgoingDamageBonus(EquipmentSessions sessions, PartyRoster parties, Consumer<Support> supports) {
this.sessions = Objects.requireNonNull(sessions); this.parties = Objects.requireNonNull(parties);
this.supports = Objects.requireNonNull(supports);
}
public AutoCloseable grant(AbilityExecution execution, Player recipient, BigDecimal percent, BooleanSupplier current) {
Objects.requireNonNull(execution); Objects.requireNonNull(recipient);
Objects.requireNonNull(percent); Objects.requireNonNull(current);
if (closed || percent.signum() < 0 || percent.compareTo(BigDecimal.valueOf(1000)) > 0) {
throw new IllegalArgumentException("Invalid outgoing damage bonus");
}
var grant = new Grant(execution, recipient, percent, current);
grants.computeIfAbsent(recipient.getUniqueId(), ignored -> new ArrayList<>()).add(grant); return grant;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void increase(EntityDamageByEntityEvent event) {
if (closed || GuardianBond.redirectedDamage()) return;
Entity attacker = attacker(event); if (!(attacker instanceof Player player)) return;
var owned = grants.get(player.getUniqueId()); if (owned == null) return;
Grant strongest = null;
for (var grant : List.copyOf(owned)) {
if (grant.recipient != player || !grant.valid()) continue;
if (strongest == null || grant.percent.compareTo(strongest.percent) > 0
|| grant.percent.compareTo(strongest.percent) == 0 && grant.sequence < strongest.sequence) strongest = grant;
}
double original = event.getDamage();
if (strongest == null || !Double.isFinite(original) || original <= 0) return;
BigDecimal added = BigDecimal.valueOf(original).multiply(strongest.percent.movePointLeft(2));
double increased = BigDecimal.valueOf(original).add(added).doubleValue();
if (!Double.isFinite(increased) || increased < 0 || added.signum() <= 0) return;
event.setDamage(increased); pending.put(event, new Used(strongest, event.getEntity(), added));
}
@EventHandler(priority = EventPriority.MONITOR)
public void accepted(EntityDamageEvent event) {
var used = pending.remove(event);
if (used == null || event.isCancelled() || event.getFinalDamage() <= 0 || !used.grant.valid()) return;
used.grant.execution.report(AbilityReport.Type.BOOST_USED, used.target, used.amount);
var aided = sessions.active(used.grant.recipient.getUniqueId()).filter(sessions::current).orElse(null);
if (aided == null || aided.character().equals(used.grant.execution.input().session().character())) return;
var sourceParty = parties.partyOf(used.grant.execution.input().player().getUniqueId()).orElse(null);
var aidedParty = parties.partyOf(used.grant.recipient.getUniqueId()).orElse(null);
if (sourceParty == null || aidedParty == null || !sourceParty.id().equals(aidedParty.id())) return;
supports.accept(new Support(used.target.getUniqueId(), used.grant.execution.input().session().character(), aided, used.amount));
}
private static Entity attacker(EntityDamageByEntityEvent event) {
Entity causing = event.getDamageSource().getCausingEntity(); if (causing != null) return causing;
if (event.getDamager() instanceof Projectile projectile) {
ProjectileSource shooter = projectile.getShooter(); if (shooter instanceof Entity entity) return entity;
}
return event.getDamager();
}
@Override public void close() {
if (closed) return; closed = true;
for (var owned : List.copyOf(grants.values())) for (var grant : List.copyOf(owned)) grant.close();
grants.clear(); pending.clear();
}
}
@@ -0,0 +1,227 @@
package games.dmg.fantasystick.ability;
import games.dmg.fantasystick.party.PartyRoster;
import games.dmg.fantasystick.progression.Stat;
import games.dmg.fantasystick.session.ControlInput;
import games.dmg.fantasystick.session.EquipmentSessions;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
/** Dynamic owned party sphere for Rallying Cry movement and outgoing damage benefits. */
public final class RallyingCry implements AbilityEffect, AutoCloseable {
public record Settings(Duration cooldown, double radius, Duration duration,
int speedAmplifier, BigDecimal damageBonusPercent) {
public Settings {
Objects.requireNonNull(cooldown); Objects.requireNonNull(duration); Objects.requireNonNull(damageBonusPercent);
if (cooldown.isNegative() || cooldown.compareTo(Duration.ofDays(365)) > 0
|| !Double.isFinite(radius) || radius <= 0 || radius > 64
|| duration.isNegative() || duration.isZero() || duration.compareTo(Duration.ofDays(1)) > 0
|| speedAmplifier < 0 || speedAmplifier > 255
|| damageBonusPercent.signum() < 0 || damageBonusPercent.compareTo(BigDecimal.valueOf(100)) > 0) {
throw new IllegalArgumentException("Invalid Rallying Cry settings");
}
}
public static Settings defaults() {
return new Settings(Duration.ofSeconds(25), 8, Duration.ofSeconds(6), 0, BigDecimal.valueOf(20));
}
}
private final class Area implements AutoCloseable {
final long sequence; final AbilityExecution execution; final Player source; final Settings settings;
final Map<UUID, Benefit> recipients = new java.util.HashMap<>(); boolean closed;
Area(AbilityExecution execution, Settings settings) {
sequence = ++sequences; this.execution = execution; source = execution.input().player(); this.settings = settings;
}
void refresh() {
if (closed) return;
if (!sourceCurrent()) { breakArea(this); return; }
var eligible = candidates();
for (var entry : List.copyOf(recipients.entrySet())) {
if (!eligible.containsKey(entry.getKey())) entry.getValue().close();
}
for (var entry : eligible.entrySet()) {
if (!recipients.containsKey(entry.getKey())) {
var benefit = new Benefit(this, entry.getValue()); recipients.put(entry.getKey(), benefit);
}
}
}
boolean sourceCurrent() {
return execution.stillCurrent() && sessions.active(source.getUniqueId())
.filter(active -> active.equals(execution.input().session()) && sessions.current(active)).isPresent();
}
boolean eligible(Player player) {
if (!sourceCurrent()) return false;
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
if (active == null || !inside(source, player, settings.radius())) return false;
if (player == source) return active.equals(execution.input().session());
var sourceParty = parties.partyOf(source.getUniqueId()).orElse(null);
var recipientParty = parties.partyOf(player.getUniqueId()).orElse(null);
return sourceParty != null && recipientParty != null && sourceParty.id().equals(recipientParty.id());
}
Map<UUID, Player> candidates() {
var result = new LinkedHashMap<UUID, Player>();
if (eligible(source)) result.put(source.getUniqueId(), source);
List<Entity> nearby;
try { nearby = source.getNearbyEntities(settings.radius(), settings.radius(), settings.radius()); }
catch (RuntimeException unavailable) { nearby = List.of(); }
int inspected = 0;
for (var entity : nearby) {
if (++inspected > 256 || result.size() == 64) break;
if (entity instanceof Player player && eligible(player)) result.putIfAbsent(player.getUniqueId(), player);
}
return result;
}
@Override public void close() {
if (closed) return; closed = true; areas.remove(sequence, this);
for (var benefit : List.copyOf(recipients.values())) benefit.close(); recipients.clear();
}
}
private final class Benefit implements AutoCloseable {
final Area area; final Player player; final AutoCloseable speed; final AutoCloseable bonus; boolean closed;
Benefit(Area area, Player player) {
this.area = area; this.player = player;
speed = speed(player, area.settings.speedAmplifier());
bonus = bonuses.grant(area.execution, player, area.settings.damageBonusPercent(), () -> !closed && area.eligible(player));
}
@Override public void close() {
if (closed) return; closed = true; area.recipients.remove(player.getUniqueId(), this);
closeResource(bonus); closeResource(speed);
}
}
private final class SpeedGrant implements AutoCloseable {
final SpeedState state; final long sequence; final int amplifier; boolean closed;
SpeedGrant(SpeedState state, int amplifier) { this.state = state; sequence = ++speedSequences; this.amplifier = amplifier; }
@Override public void close() { if (closed) return; closed = true; state.grants.remove(this); state.refresh(); }
}
private final class SpeedState {
final Player player; final List<SpeedGrant> grants = new ArrayList<>(); PotionEffect owned;
SpeedState(Player player) { this.player = player; }
void refresh() {
PotionEffect current;
try { current = player.getPotionEffect(PotionEffectType.SPEED); }
catch (RuntimeException unavailable) { return; }
if (owned != null && !same(current, owned)) owned = null;
SpeedGrant strongest = null;
for (var grant : List.copyOf(grants)) if (!grant.closed && (strongest == null
|| grant.amplifier > strongest.amplifier
|| grant.amplifier == strongest.amplifier && grant.sequence < strongest.sequence)) strongest = grant;
if (strongest == null) {
if (owned != null && same(current, owned) && !removeOwned()) return;
owned = null; speeds.remove(player.getUniqueId(), this); return;
}
if (owned != null && same(current, owned) && owned.getAmplifier() != strongest.amplifier) {
if (!removeOwned()) return;
current = null;
}
if (current != null && current.getAmplifier() >= strongest.amplifier) return;
var effect = new PotionEffect(PotionEffectType.SPEED, PotionEffect.INFINITE_DURATION,
strongest.amplifier, false, false, true);
try { if (player.addPotionEffect(effect, true)) owned = effect; }
catch (RuntimeException ignored) { owned = null; }
}
boolean removeOwned() {
try {
player.removePotionEffect(PotionEffectType.SPEED);
if (same(player.getPotionEffect(PotionEffectType.SPEED), owned)) return false;
} catch (RuntimeException failure) { return false; }
owned = null; return true;
}
}
private volatile Settings settings;
private final EquipmentSessions sessions;
private final PartyRoster parties;
private final OutgoingDamageBonus bonuses;
private final Map<Long, Area> areas = new java.util.HashMap<>();
private final Map<UUID, SpeedState> speeds = new java.util.HashMap<>();
private long sequences; private long speedSequences;
private org.bukkit.scheduler.BukkitTask sweepTask;
private boolean closed;
public RallyingCry(Settings settings, EquipmentSessions sessions, PartyRoster parties, OutgoingDamageBonus bonuses) {
this.settings = Objects.requireNonNull(settings); this.sessions = Objects.requireNonNull(sessions);
this.parties = Objects.requireNonNull(parties); this.bonuses = Objects.requireNonNull(bonuses);
}
public void configure(Settings settings) { this.settings = Objects.requireNonNull(settings); }
public void install(org.bukkit.plugin.Plugin plugin) {
Objects.requireNonNull(plugin);
if (closed || sweepTask != null) throw new IllegalStateException("Rallying Cry sweep already installed or closed");
sweepTask = plugin.getServer().getScheduler().runTaskTimer(plugin, this::sweep, 1, 1);
}
public void sweep() {
if (closed) return; int checked = 0;
for (var area : List.copyOf(areas.values())) { area.refresh(); if (++checked == 64) break; }
for (var state : List.copyOf(speeds.values())) state.refresh();
}
public AbilityDefinition definition() {
var current = settings;
return new AbilityDefinition("rallying_cry", "Rallying Cry", Material.GOAT_HORN,
List.of("Grant nearby active party members Speed " + (current.speedAmplifier() + 1)
+ " and " + decimal(current.damageBonusPercent()) + "% combat damage.",
"A " + decimal(BigDecimal.valueOf(current.radius())) + "-block sphere lasting " + seconds(current.duration()) + " seconds."),
"Use to rally yourself and nearby active party members; copies do not stack.",
Map.of(Stat.CHR, BigInteger.valueOf(16), Stat.CON, BigInteger.valueOf(12)), BigInteger.ONE,
AbilityDefinition.Activation.DELAYED, ControlInput.Gesture.USE, current.cooldown(),
Map.of("radius", BigDecimal.valueOf(current.radius()).stripTrailingZeros(),
"duration-seconds", BigDecimal.valueOf(current.duration().toNanos()).movePointLeft(9),
"speed-amplifier", BigDecimal.valueOf(current.speedAmplifier()),
"damage-bonus-percent", current.damageBonusPercent()), AbilityDefinition.TargetPolicy.AREA, this);
}
@Override public boolean accepts(ControlInput input) { return !closed && input.target() == null; }
@Override public void activate(AbilityExecution execution) {
if (closed || !execution.stillCurrent()) return;
var area = new Area(execution, from(execution.definition())); areas.put(area.sequence, area);
execution.own(area); area.refresh(); execution.later(area.settings.duration(), execution::finish);
}
private AutoCloseable speed(Player player, int amplifier) {
var state = speeds.computeIfAbsent(player.getUniqueId(), ignored -> new SpeedState(player));
var grant = new SpeedGrant(state, amplifier); state.grants.add(grant); state.refresh(); return grant;
}
private void breakArea(Area area) { area.close(); area.execution.finish(); }
private static boolean inside(Player source, Player target, double radius) {
try { var a = source.getLocation(); var b = target.getLocation();
return a.getWorld() == b.getWorld() && a.distanceSquared(b) <= radius * radius;
} catch (RuntimeException invalid) { return false; }
}
private static boolean same(PotionEffect first, PotionEffect second) {
return first != null && second != null && first.getType().equals(second.getType())
&& first.getAmplifier() == second.getAmplifier() && first.isInfinite() && second.isInfinite();
}
private static void closeResource(AutoCloseable resource) {
try { resource.close(); } catch (Exception impossible) { throw new IllegalStateException(impossible); }
}
private static Settings from(AbilityDefinition definition) {
var parameters = definition.parameters();
return new Settings(definition.cooldown(), parameters.get("radius").doubleValue(),
Duration.ofNanos(parameters.get("duration-seconds").movePointRight(9).longValueExact()),
parameters.get("speed-amplifier").intValueExact(), parameters.get("damage-bonus-percent"));
}
private static String decimal(BigDecimal value) { return value.stripTrailingZeros().toPlainString(); }
private static String seconds(Duration duration) {
return decimal(BigDecimal.valueOf(duration.toNanos()).movePointLeft(9));
}
@Override public void close() {
if (closed) return; closed = true; if (sweepTask != null) sweepTask.cancel();
for (var area : List.copyOf(areas.values())) area.execution.finish(); areas.clear();
for (var state : List.copyOf(speeds.values())) { state.grants.clear(); state.refresh(); }
speeds.clear();
}
}
@@ -0,0 +1,172 @@
package games.dmg.fantasystick.persistence;
import games.dmg.fantasystick.ability.RallyingCry;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.OverlappingFileLockException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/** Serialized durable Rallying Cry settings; publication remains a server-thread caller decision. */
public final class RallyingCrySettings implements AutoCloseable {
private static final int MAX_BYTES = 1_048_576;
public static final String COOLDOWN = "rallying-cry-cooldown-seconds";
public static final String RADIUS = "rallying-cry-radius-blocks";
public static final String DURATION = "rallying-cry-duration-seconds";
public static final String SPEED = "rallying-cry-speed-amplifier";
public static final String BONUS = "rallying-cry-damage-bonus-percent";
private static final List<String> KEYS = List.of(COOLDOWN, BONUS, DURATION, RADIUS, SPEED);
private static final Map<String, String> DEFAULTS = Map.of(
COOLDOWN, "25", RADIUS, "8", DURATION, "6", SPEED, "0", BONUS, "20");
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
public record Update(String key, String value, RallyingCry.Settings settings, Map<String, String> values, long sequence) {
public Update { values = Map.copyOf(values); }
}
private final Path directory;
private final Replacement replacement;
private final java.util.concurrent.ExecutorService worker = Executors.newSingleThreadExecutor(
task -> new Thread(task, "fantasy-rallying-cry-configuration"));
private volatile Map<String, String> effectiveValues;
private Map<String, String> persistedValues;
private long persistedSequence;
private long publishedSequence;
private boolean closed;
private int pending;
private final CompletableFuture<Void> drained = new CompletableFuture<>();
public RallyingCrySettings(Path directory, Map<String, String> initial) {
this(directory, initial, (from, to) -> Files.move(from, to,
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING));
}
RallyingCrySettings(Path directory, Map<String, String> initial, Replacement replacement) {
this.directory = Objects.requireNonNull(directory).toAbsolutePath(); this.replacement = Objects.requireNonNull(replacement);
var copy = new LinkedHashMap<String, String>();
for (String key : KEYS) copy.put(key, Objects.requireNonNull(initial.get(key)));
parse(copy); effectiveValues = Map.copyOf(copy); persistedValues = Map.copyOf(copy);
}
public static List<String> keys() { return KEYS; }
public static String defaultValue(String key) { return DEFAULTS.get(key); }
public String value(String key) { return effectiveValues.get(key); }
public RallyingCry.Settings settings() { return parse(effectiveValues); }
public synchronized void publish(Update update) {
Objects.requireNonNull(update);
if (update.sequence() <= publishedSequence) return;
parse(update.values()); effectiveValues = update.values(); publishedSequence = update.sequence();
}
public CompletionStage<Update> set(String key, String value) {
Objects.requireNonNull(key); Objects.requireNonNull(value);
if (!KEYS.contains(key)) return CompletableFuture.failedStage(new IllegalArgumentException("Unknown setting"));
String accepted = canonical(value); var preview = new LinkedHashMap<>(effectiveValues);
preview.put(key, accepted); parse(preview);
synchronized (this) {
if (closed) return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
pending++;
}
try {
return CompletableFuture.supplyAsync(() -> {
try {
var next = new LinkedHashMap<>(persistedValues); next.put(key, accepted);
var parsed = parse(next); save(key, accepted); persistedValues = Map.copyOf(next);
return new Update(key, accepted, parsed, persistedValues, ++persistedSequence);
} catch (IOException | RuntimeException failure) {
throw new java.util.concurrent.CompletionException(failure instanceof IllegalArgumentException
? failure : new IOException("Rallying Cry configuration save refused or failed; effective settings unchanged"));
} finally { finished(); }
}, worker).minimalCompletionStage();
} catch (RejectedExecutionException rejected) {
finished(); return CompletableFuture.failedStage(new IOException("Configuration store is closed"));
}
}
private static String canonical(String raw) {
try { return new BigDecimal(raw).stripTrailingZeros().toPlainString(); }
catch (NumberFormatException invalid) { throw new IllegalArgumentException("Invalid value", invalid); }
}
public static RallyingCry.Settings parse(Map<String, String> values) {
try { return new RallyingCry.Settings(seconds(values.get(COOLDOWN)), finite(values.get(RADIUS)),
seconds(values.get(DURATION)), new BigDecimal(values.get(SPEED)).intValueExact(),
new BigDecimal(values.get(BONUS))); }
catch (ArithmeticException | NumberFormatException | NullPointerException invalid) {
throw new IllegalArgumentException("Rallying Cry settings must use supported numeric values", invalid);
}
}
private static Duration seconds(String value) {
var nanos = new BigDecimal(value).movePointRight(9).toBigIntegerExact().longValueExact();
return Duration.ofNanos(nanos);
}
private static double finite(String value) {
double result = new BigDecimal(value).doubleValue();
if (!Double.isFinite(result)) throw new IllegalArgumentException("Setting is not finite");
return result;
}
private void save(String key, String value) throws IOException {
Files.createDirectories(directory);
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe directory");
var file = directory.resolve("config.yml"); var lockFile = directory.resolve(".config.lock");
if (Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS) && !Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Unsafe lock");
}
try (var channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
LinkOption.NOFOLLOW_LINKS); var lock = channel.tryLock()) {
if (lock == null) throw new IOException("Configuration busy");
var options = new LoaderOptions(); options.setAllowDuplicateKeys(false);
options.setMaxAliasesForCollections(20); options.setCodePointLimit(MAX_BYTES);
var yaml = new Yaml(new SafeConstructor(options)); Map<String, Object> document = new LinkedHashMap<>();
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe configuration");
byte[] bytes;
try (var input = Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS)) { bytes = input.readNBytes(MAX_BYTES + 1); }
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
Object loaded = yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());
if (loaded != null) {
if (!(loaded instanceof Map<?, ?> map)) throw new IOException("Invalid configuration root");
for (var entry : map.entrySet()) {
if (!(entry.getKey() instanceof String savedKey)) throw new IOException("Invalid configuration key");
document.put(savedKey, entry.getValue());
}
}
}
document.put(key, value); byte[] bytes = yaml.dump(document).getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_BYTES) throw new IOException("Configuration too large");
Path temporary = Files.createTempFile(directory, ".config-", ".tmp");
try {
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
var buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) output.write(buffer); output.force(true);
}
replacement.move(temporary, file);
} finally { Files.deleteIfExists(temporary); }
} catch (OverlappingFileLockException busy) { throw new IOException("Configuration busy"); }
}
private synchronized void finished() { pending--; if (closed && pending == 0) drained.complete(null); }
public CompletionStage<Void> drained() { return drained.minimalCompletionStage(); }
@Override public synchronized void close() { closed = true; worker.shutdown(); if (pending == 0) drained.complete(null); }
}
@@ -45,6 +45,8 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
private games.dmg.fantasystick.ability.Purify purify;
private games.dmg.fantasystick.persistence.GuardianBondSettings guardianBondSettings;
private games.dmg.fantasystick.ability.GuardianBond guardianBond;
private games.dmg.fantasystick.persistence.RallyingCrySettings rallyingCrySettings;
private games.dmg.fantasystick.ability.RallyingCry rallyingCry;
private AdminCharacterIssuer characterIssuer;
private AdminRevival adminRevival;
private AdminExperienceGrant experienceGrant;
@@ -241,6 +243,12 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
guardianBondSettings = Objects.requireNonNull(settings); guardianBond = Objects.requireNonNull(effect);
}
public void attachRallyingCry(games.dmg.fantasystick.persistence.RallyingCrySettings settings,
games.dmg.fantasystick.ability.RallyingCry effect) {
if (closed || rallyingCrySettings != null) throw new IllegalStateException("Rallying Cry already attached or command closed");
rallyingCrySettings = Objects.requireNonNull(settings); rallyingCry = Objects.requireNonNull(effect);
}
public void attachSwitchDelay(games.dmg.fantasystick.persistence.SwitchDelaySettings settings){if(closed||switchDelaySettings!=null)throw new IllegalStateException("Switch delay already attached or command closed");switchDelaySettings=Objects.requireNonNull(settings);}
public void attachRoleplaySettings(games.dmg.fantasystick.persistence.RoleplaySettings settings){if(closed||roleplaySettings!=null)throw new IllegalStateException("Roleplay settings already attached or command closed");roleplaySettings=Objects.requireNonNull(settings);}
public void attachPartySettings(games.dmg.fantasystick.persistence.PartySettings settings){if(closed||partySettings!=null)throw new IllegalStateException("Party settings already attached or command closed");partySettings=Objects.requireNonNull(settings);}
@@ -453,6 +461,9 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
if (guardianBondSettings != null && games.dmg.fantasystick.persistence.GuardianBondSettings.keys().contains(args[1])) {
guardianBondConfiguration(sender, args); return;
}
if (rallyingCrySettings != null && games.dmg.fantasystick.persistence.RallyingCrySettings.keys().contains(args[1])) {
rallyingCryConfiguration(sender, args); return;
}
if (frostSettings == null || !games.dmg.fantasystick.persistence.FrostShardSettings.keys().contains(args[1])) {
configurationUsage(sender); return;
}
@@ -634,6 +645,33 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
});
}
private void rallyingCryConfiguration(CommandSender sender, String[] args) {
String key = args[1];
if (args.length == 2) {
sender.sendMessage(key + "=" + rallyingCrySettings.value(key) + " (applies to future Rallying Cry casts only)"); return;
}
java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.RallyingCrySettings.Update> operation;
try { operation = rallyingCrySettings.set(key, args[2]); }
catch (IllegalArgumentException invalid) {
sender.sendMessage("Rallying Cry setting is invalid; the effective value is unchanged."); return;
}
operation.whenComplete((saved, failure) -> {
if (failure != null) report(null, "config-" + key, failure);
if (closed) return;
try { nextTick.accept(() -> {
if (closed) return;
if (failure == null) {
rallyingCry.configure(saved.settings()); abilities.replace(rallyingCry.definition()); rallyingCrySettings.publish(saved);
}
if (!sender.hasPermission(PERMISSION)
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
sender.sendMessage(failure == null
? "Saved " + key + "=" + saved.value() + " for future Rallying Cry casts; active cries and deadlines are unchanged."
: "Rallying Cry configuration save failed; the effective setting is unchanged.");
}); } catch (RuntimeException rejected) { report(null, "config-response", rejected); }
});
}
private void hexConfiguration(CommandSender sender, String[] args) {
String key=args[1];if(args.length==2){sender.sendMessage(key+"="+hexSettings.value(key)+" (applies to future Hex casts only)");return;}
java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.HexSettings.Update> operation;
@@ -791,6 +829,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
keys.addAll(games.dmg.fantasystick.persistence.MendingLightSettings.keys());
keys.addAll(games.dmg.fantasystick.persistence.PurifySettings.keys());
keys.addAll(games.dmg.fantasystick.persistence.GuardianBondSettings.keys());
keys.addAll(games.dmg.fantasystick.persistence.RallyingCrySettings.keys());
return matching(keys, args[1]);
}
if (args.length == 3 && args[0].equals("config")) {
@@ -851,6 +890,12 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
String defaults = games.dmg.fantasystick.persistence.GuardianBondSettings.defaultValue(args[1]);
return matching(current.equals(defaults) ? List.of(current) : List.of(current, defaults), args[2]);
}
if (rallyingCrySettings != null
&& games.dmg.fantasystick.persistence.RallyingCrySettings.keys().contains(args[1])) {
String current = rallyingCrySettings.value(args[1]);
String defaults = games.dmg.fantasystick.persistence.RallyingCrySettings.defaultValue(args[1]);
return matching(current.equals(defaults) ? List.of(current) : List.of(current, defaults), args[2]);
}
}
return List.of();
}