317 lines
21 KiB
Java
317 lines
21 KiB
Java
package games.dmg.fantasystick.ability;
|
|
|
|
import games.dmg.fantasystick.party.PartyRoster;
|
|
import games.dmg.fantasystick.persistence.CharacterRecord;
|
|
import games.dmg.fantasystick.persistence.CharacterStorage;
|
|
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.Comparator;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
import java.util.UUID;
|
|
import java.util.function.Consumer;
|
|
import java.util.function.Supplier;
|
|
import org.bukkit.Location;
|
|
import org.bukkit.Material;
|
|
import org.bukkit.Particle;
|
|
import org.bukkit.attribute.Attribute;
|
|
import org.bukkit.entity.Entity;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.event.entity.EntityRegainHealthEvent;
|
|
|
|
/** Fixed bounded Sanctuary cylinder with delayed healing pulses and dynamic strongest mitigation. */
|
|
public final class Sanctuary implements AbilityEffect, AutoCloseable {
|
|
public record Settings(Duration cooldown, double radius, double verticalRange, Duration duration,
|
|
Duration pulseInterval, BigDecimal healingPerPulse, BigDecimal damageReductionPercent) {
|
|
public Settings {
|
|
Objects.requireNonNull(cooldown); Objects.requireNonNull(duration); Objects.requireNonNull(pulseInterval);
|
|
Objects.requireNonNull(healingPerPulse); Objects.requireNonNull(damageReductionPercent);
|
|
if (cooldown.isNegative() || cooldown.compareTo(Duration.ofDays(365)) > 0
|
|
|| !Double.isFinite(radius) || radius <= 0 || radius > 64
|
|
|| !Double.isFinite(verticalRange) || verticalRange < 0 || verticalRange > 64
|
|
|| duration.isZero() || duration.isNegative() || duration.compareTo(Duration.ofDays(1)) > 0
|
|
|| pulseInterval.isZero() || pulseInterval.isNegative() || pulseInterval.compareTo(duration) > 0
|
|
|| duration.toNanos() / pulseInterval.toNanos() > 64
|
|
|| healingPerPulse.signum() < 0 || healingPerPulse.compareTo(BigDecimal.valueOf(Double.MAX_VALUE)) > 0
|
|
|| damageReductionPercent.signum() < 0 || damageReductionPercent.compareTo(BigDecimal.valueOf(100)) > 0) {
|
|
throw new IllegalArgumentException("Invalid Sanctuary settings");
|
|
}
|
|
}
|
|
public static Settings defaults() {
|
|
return new Settings(Duration.ofSeconds(45), 6, 3, Duration.ofSeconds(6), Duration.ofSeconds(1),
|
|
BigDecimal.valueOf(2), BigDecimal.valueOf(20));
|
|
}
|
|
}
|
|
private record Target(Player player, EquipmentSessions.Active active, CharacterRecord record) { }
|
|
|
|
private final class State implements AutoCloseable {
|
|
final AbilityExecution execution; final Player source;
|
|
final Location origin; final Settings captured; final Map<UUID, Benefit> mitigation = new LinkedHashMap<>();
|
|
Duration elapsed = Duration.ZERO; Duration nextPulse; final Duration scanPeriod;
|
|
UUID areaApplication; int pulseOrdinal;
|
|
String endReason = "interrupted"; int pending; boolean expired; boolean closed;
|
|
State(AbilityExecution execution, Settings captured) {
|
|
this.execution = execution; this.source = execution.input().player(); this.origin = source.getLocation().clone();
|
|
this.captured = captured; this.nextPulse = captured.pulseInterval();
|
|
long period = Math.max(50_000_000L, (captured.duration().toNanos() + 59) / 60);
|
|
this.scanPeriod = Duration.ofNanos(period);
|
|
}
|
|
void start() {
|
|
states.add(this); execution.own(this);
|
|
areaApplication = execution.effectApplied("sanctuary_area", null,
|
|
Map.of("radius", captured.radius(), "vertical_range", captured.verticalRange(),
|
|
"duration_seconds", seconds(captured.duration()), "area_location", locationData(origin)));
|
|
reconcile(); visual(); schedule();
|
|
}
|
|
void schedule() {
|
|
if (closed || expired) return;
|
|
Duration remaining = captured.duration().minus(elapsed);
|
|
execution.later(remaining.compareTo(scanPeriod) < 0 ? remaining : scanPeriod, this::step);
|
|
}
|
|
void step() {
|
|
if (closed || !execution.stillCurrent()) { execution.resolve("interrupted"); execution.finish(); return; }
|
|
Duration remaining = captured.duration().minus(elapsed);
|
|
elapsed = elapsed.plus(remaining.compareTo(scanPeriod) < 0 ? remaining : scanPeriod);
|
|
reconcile(); visual();
|
|
while (nextPulse.compareTo(elapsed) <= 0 && nextPulse.compareTo(captured.duration()) <= 0) {
|
|
pulse(); nextPulse = nextPulse.plus(captured.pulseInterval());
|
|
}
|
|
if (elapsed.compareTo(captured.duration()) >= 0) {
|
|
expired = true; endReason = "expired"; closeMitigation();
|
|
execution.resolve("expired", Map.of("pulse_count", pulseOrdinal));
|
|
if (pending == 0) execution.finish();
|
|
} else schedule();
|
|
}
|
|
void reconcile() {
|
|
var eligible = recipients();
|
|
for (var entry : List.copyOf(mitigation.entrySet())) {
|
|
if (eligible.stream().noneMatch(player -> player.getUniqueId().equals(entry.getKey()))) {
|
|
entry.getValue().close(); mitigation.remove(entry.getKey());
|
|
}
|
|
}
|
|
for (var player : eligible) mitigation.computeIfAbsent(player.getUniqueId(), ignored -> new Benefit(this, player));
|
|
}
|
|
void pulse() {
|
|
pulseOrdinal++;
|
|
for (var player : recipients()) if (owner(player) == this) heal(player);
|
|
}
|
|
void heal(Player player) {
|
|
var target = target(player); if (target == null) return;
|
|
var attribute = player.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return;
|
|
double current = player.getHealth(), maximum = attribute.getValue(), missing = maximum - current;
|
|
double proposed = Math.min(missing, captured.healingPerPulse().doubleValue());
|
|
if (!Double.isFinite(current) || !Double.isFinite(maximum) || !Double.isFinite(proposed) || proposed <= 0) return;
|
|
var event = new EntityRegainHealthEvent(player, proposed, EntityRegainHealthEvent.RegainReason.CUSTOM);
|
|
healingEvents.accept(event); double accepted = Math.min(proposed, Math.min(missing, event.getAmount()));
|
|
if (event.isCancelled() || !Double.isFinite(accepted) || accepted <= 0) return;
|
|
pending++; var expected = target.record().revision();
|
|
characters.saveHealth(target.record().id(), expected, BigDecimal.valueOf(current + accepted), nativeLimit.get())
|
|
.whenComplete((saved, failure) -> {
|
|
try { nextTick.accept(() -> completeHeal(this, target, expected, accepted, saved, failure)); }
|
|
catch (RuntimeException rejected) { completePending(this); }
|
|
});
|
|
}
|
|
List<Player> recipients() {
|
|
List<Entity> nearby;
|
|
try { nearby = new ArrayList<>(source.getWorld().getNearbyEntities(origin,
|
|
captured.radius(), captured.verticalRange(), captured.radius())); }
|
|
catch (RuntimeException unavailable) { nearby = new ArrayList<>(); }
|
|
nearby.addFirst(source); var unique = new LinkedHashMap<UUID, Player>(); int inspected = 0;
|
|
for (var entity : nearby) {
|
|
if (++inspected > 256) break;
|
|
if (entity instanceof Player player && recipientCurrent(player)) unique.putIfAbsent(player.getUniqueId(), player);
|
|
}
|
|
var result = new ArrayList<>(unique.values());
|
|
result.sort(Comparator.comparingDouble((Player player) -> distance(origin, player)).thenComparing(Player::getUniqueId));
|
|
return result.size() <= 64 ? result : new ArrayList<>(result.subList(0, 64));
|
|
}
|
|
boolean recipientCurrent(Player player) {
|
|
if (closed || !execution.stillCurrent() || !inside(origin, player, captured.radius(), captured.verticalRange())
|
|
|| !unobstructed(origin, player)) return false;
|
|
if (player == source) return sessions.active(player.getUniqueId()).filter(sessions::current)
|
|
.map(active -> active.equals(execution.input().session())).orElse(false);
|
|
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
|
return active != null && sameParty(source, player);
|
|
}
|
|
Target target(Player player) {
|
|
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
|
var record = active == null ? null : sessions.currentRecord(active).orElse(null);
|
|
return record == null ? null : new Target(player, active, record);
|
|
}
|
|
void visual() {
|
|
try { particles.world(Particle.END_ROD, origin, 12,
|
|
captured.radius() / 2, 0.1, captured.radius() / 2, 0); } catch (RuntimeException ignored) { }
|
|
}
|
|
void closeMitigation() {
|
|
for (var grant : List.copyOf(mitigation.values())) grant.close();
|
|
mitigation.clear();
|
|
}
|
|
@Override public void close() {
|
|
if (closed) return; closed = true; expired = true; states.remove(this); closeMitigation();
|
|
if (areaApplication != null) execution.effectEnded(areaApplication, endReason);
|
|
}
|
|
}
|
|
|
|
private final class Benefit implements AutoCloseable {
|
|
final State state; final Player player; final AutoCloseable grant;
|
|
UUID application; boolean closed;
|
|
Benefit(State state, Player player) {
|
|
this.state = state; this.player = player;
|
|
grant = combatMitigation.grant(state.execution, player, state.captured.damageReductionPercent(),
|
|
() -> !closed && state.recipientCurrent(player), (event, amount) -> {
|
|
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
|
var attacker = event.getDamageSource().getCausingEntity();
|
|
if (attacker == null && event instanceof org.bukkit.event.entity.EntityDamageByEntityEvent byEntity)
|
|
attacker = byEntity.getDamager();
|
|
if (active != null && attacker != null && amount > 0)
|
|
state.execution.acceptedPrevention(active, player, attacker,
|
|
event.getDamage() + amount, amount, event.getFinalDamage(), application);
|
|
});
|
|
try {
|
|
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
|
var evidence = new LinkedHashMap<String, Object>();
|
|
evidence.put("damage_reduction_percent", state.captured.damageReductionPercent().toPlainString());
|
|
if (active != null) {
|
|
evidence.put("recipient_character_id", active.character().toString());
|
|
evidence.put("recipient_session_id", active.session().toString());
|
|
}
|
|
application = state.execution.effectApplied("sanctuary_benefit", player, evidence);
|
|
} catch (RuntimeException ignored) { /* Auditing cannot refuse a native mitigation grant. */ }
|
|
}
|
|
@Override public void close() {
|
|
if (closed) return; closed = true;
|
|
try { grant.close(); } catch (Exception ignored) { }
|
|
if (application != null) state.execution.effectEnded(application,
|
|
state.closed || state.expired ? state.endReason : "recipient_eligibility_changed");
|
|
}
|
|
}
|
|
|
|
private volatile Settings settings;
|
|
private final CharacterStorage characters; private final EquipmentSessions sessions; private final PartyRoster parties;
|
|
private final CombatMitigation combatMitigation; private final Consumer<Runnable> nextTick;
|
|
private final Consumer<EntityRegainHealthEvent> healingEvents; private final Supplier<BigDecimal> nativeLimit;
|
|
private final Consumer<MendingLight.Support> supports;
|
|
private final games.dmg.fantasystick.presentation.ParticleDelivery particles;
|
|
private final List<State> states = new ArrayList<>();
|
|
private boolean closed;
|
|
|
|
public Sanctuary(Settings settings, CharacterStorage characters, EquipmentSessions sessions, PartyRoster parties,
|
|
CombatMitigation combatMitigation, Consumer<Runnable> nextTick,
|
|
Consumer<EntityRegainHealthEvent> healingEvents, Supplier<BigDecimal> nativeLimit,
|
|
Consumer<MendingLight.Support> supports) {
|
|
this(settings, characters, sessions, parties, combatMitigation, nextTick, healingEvents, nativeLimit, supports,
|
|
games.dmg.fantasystick.presentation.ParticleDelivery.legacyBroadcast());
|
|
}
|
|
public Sanctuary(Settings settings, CharacterStorage characters, EquipmentSessions sessions, PartyRoster parties,
|
|
CombatMitigation combatMitigation, Consumer<Runnable> nextTick,
|
|
Consumer<EntityRegainHealthEvent> healingEvents, Supplier<BigDecimal> nativeLimit,
|
|
Consumer<MendingLight.Support> supports,
|
|
games.dmg.fantasystick.presentation.ParticleDelivery particles) {
|
|
this.settings = Objects.requireNonNull(settings); this.characters = Objects.requireNonNull(characters);
|
|
this.sessions = Objects.requireNonNull(sessions); this.parties = Objects.requireNonNull(parties);
|
|
this.combatMitigation = Objects.requireNonNull(combatMitigation); this.nextTick = Objects.requireNonNull(nextTick);
|
|
this.healingEvents = Objects.requireNonNull(healingEvents); this.nativeLimit = Objects.requireNonNull(nativeLimit);
|
|
this.supports = Objects.requireNonNull(supports); this.particles = Objects.requireNonNull(particles);
|
|
}
|
|
public void configure(Settings settings) { this.settings = Objects.requireNonNull(settings); }
|
|
public AbilityDefinition definition() {
|
|
var current = settings;
|
|
return new AbilityDefinition("sanctuary", "Sanctuary", Material.SEA_LANTERN,
|
|
List.of("Create a fixed " + decimal(current.radius()) + "-block sanctuary for " + seconds(current.duration()) + " seconds.",
|
|
"Party members inside heal " + decimal(current.healingPerPulse()) + " each second and take "
|
|
+ decimal(current.damageReductionPercent()) + "% less combat damage."),
|
|
"Use to hold exposed ground; healing starts after one second and the area does not follow you.",
|
|
Map.of(Stat.WIS, BigInteger.valueOf(24), Stat.CHR, BigInteger.valueOf(20), Stat.CON, BigInteger.TEN), BigInteger.ONE, AbilityDefinition.Category.HEAL,
|
|
AbilityDefinition.Activation.DELAYED, ControlInput.Gesture.USE, current.cooldown(),
|
|
Map.of("radius", BigDecimal.valueOf(current.radius()).stripTrailingZeros(),
|
|
"vertical-range", BigDecimal.valueOf(current.verticalRange()).stripTrailingZeros(),
|
|
"duration-seconds", nanos(current.duration()), "pulse-interval-seconds", nanos(current.pulseInterval()),
|
|
"healing-per-pulse", current.healingPerPulse(), "damage-reduction-percent", current.damageReductionPercent()),
|
|
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; new State(execution, from(execution.definition())).start();
|
|
}
|
|
|
|
private void completeHeal(State state, Target target, BigInteger expected, double accepted,
|
|
java.util.Optional<CharacterRecord> saved, Throwable failure) {
|
|
try {
|
|
if (failure != null || saved == null || saved.isEmpty() || !state.execution.stillCurrent()
|
|
|| !state.recipientCurrent(target.player())) return;
|
|
var persisted = saved.orElseThrow();
|
|
if (!sessions.acknowledgeProgress(target.active(), expected, persisted)) return;
|
|
var attribute = target.player().getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return;
|
|
double current = target.player().getHealth(), maximum = attribute.getValue();
|
|
double desired = Math.min(maximum, persisted.health().doubleValue()); double restored = Math.min(accepted, desired - current);
|
|
if (!Double.isFinite(current) || !Double.isFinite(maximum) || !Double.isFinite(restored) || restored <= 0) return;
|
|
target.player().setHealth(Math.min(maximum, current + restored));
|
|
double after = target.player().getHealth();
|
|
double actual = after - current;
|
|
if (!Double.isFinite(actual) || actual <= 0) return;
|
|
state.execution.acceptedHeal(target.active(), target.player(), persisted,
|
|
accepted, actual, current, after, maximum);
|
|
state.execution.report(AbilityReport.Type.HEALING, target.player(),
|
|
BigDecimal.valueOf(actual).stripTrailingZeros());
|
|
if (target.player() != state.source) supports.accept(new MendingLight.Support(
|
|
state.execution.input().session().character(), target.active(), BigDecimal.valueOf(actual).stripTrailingZeros()));
|
|
} finally { completePending(state); }
|
|
}
|
|
private static void completePending(State state) {
|
|
if (state.pending > 0) state.pending--; if (state.expired && state.pending == 0) state.execution.finish();
|
|
}
|
|
private State owner(Player player) {
|
|
for (var state : List.copyOf(states)) if (!state.expired
|
|
&& state.mitigation.containsKey(player.getUniqueId())) return state;
|
|
return null;
|
|
}
|
|
private boolean sameParty(Player source, Player target) {
|
|
var party = parties.partyOf(source.getUniqueId()).orElse(null);
|
|
return party != null && party.members().contains(target.getUniqueId());
|
|
}
|
|
private static boolean inside(Location origin, Player player, double radius, double vertical) {
|
|
try { var at = player.getLocation(); if (origin.getWorld() != at.getWorld()) return false;
|
|
double dx = at.getX() - origin.getX(), dz = at.getZ() - origin.getZ();
|
|
return dx * dx + dz * dz <= radius * radius && Math.abs(at.getY() - origin.getY()) <= vertical;
|
|
} catch (RuntimeException invalid) { return false; }
|
|
}
|
|
private static boolean unobstructed(Location origin, Player player) {
|
|
try { var world = origin.getWorld(); if (world == null) return false; var box = player.getBoundingBox();
|
|
var center = box.getCenter(); var offset = center.clone().subtract(origin.toVector()); double distance = offset.length();
|
|
if (!Double.isFinite(distance) || distance == 0) return distance == 0;
|
|
return world.rayTraceBlocks(origin, offset.multiply(1 / distance), distance, org.bukkit.FluidCollisionMode.NEVER, true) == null;
|
|
} catch (RuntimeException invalid) { return false; }
|
|
}
|
|
private static Map<String, Object> locationData(Location location) {
|
|
var world = location == null ? null : location.getWorld();
|
|
if (world == null || world.getUID() == null || world.getName() == null)
|
|
return Map.of("location_status", "unavailable");
|
|
return Map.of("world_id", world.getUID().toString(), "world_name", world.getName(),
|
|
"x", location.getX(), "y", location.getY(), "z", location.getZ());
|
|
}
|
|
private static double distance(Location origin, Player player) {
|
|
try { var at = player.getLocation(); if (origin.getWorld() != at.getWorld()) return Double.POSITIVE_INFINITY;
|
|
double dx = at.getX() - origin.getX(), dz = at.getZ() - origin.getZ(); return dx * dx + dz * dz;
|
|
} catch (RuntimeException invalid) { return Double.POSITIVE_INFINITY; }
|
|
}
|
|
private static Settings from(AbilityDefinition definition) { var p = definition.parameters();
|
|
return new Settings(definition.cooldown(), p.get("radius").doubleValue(), p.get("vertical-range").doubleValue(),
|
|
duration(p.get("duration-seconds")), duration(p.get("pulse-interval-seconds")),
|
|
p.get("healing-per-pulse"), p.get("damage-reduction-percent")); }
|
|
private static Duration duration(BigDecimal seconds) { return Duration.ofNanos(seconds.movePointRight(9).longValueExact()); }
|
|
private static BigDecimal nanos(Duration value) { return BigDecimal.valueOf(value.toNanos()).movePointLeft(9); }
|
|
private static String seconds(Duration value) { return decimal(nanos(value)); }
|
|
private static String decimal(double value) { return decimal(BigDecimal.valueOf(value)); }
|
|
private static String decimal(BigDecimal value) { return value.stripTrailingZeros().toPlainString(); }
|
|
@Override public void close() {
|
|
if (closed) return; closed = true; for (var state : List.copyOf(states)) { state.close(); state.execution.finish(); } states.clear();
|
|
}
|
|
}
|