235 lines
13 KiB
Java
235 lines
13 KiB
Java
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.Comparator;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
import java.util.UUID;
|
|
import org.bukkit.Location;
|
|
import org.bukkit.Material;
|
|
import org.bukkit.Particle;
|
|
import org.bukkit.damage.DamageSource;
|
|
import org.bukkit.damage.DamageType;
|
|
import org.bukkit.entity.Entity;
|
|
import org.bukkit.entity.LivingEntity;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.event.EventHandler;
|
|
import org.bukkit.event.EventPriority;
|
|
import org.bukkit.event.Listener;
|
|
import org.bukkit.event.entity.EntityDamageEvent;
|
|
import org.bukkit.potion.PotionEffect;
|
|
import org.bukkit.potion.PotionEffectType;
|
|
|
|
/** Bounded instantaneous Frost Nova damage and ownership-aware Slowness. */
|
|
public final class FrostNova implements AbilityEffect, Listener, AutoCloseable {
|
|
public record Settings(BigInteger baseDamage, Duration cooldown, double radius,
|
|
int slownessAmplifier, Duration slownessDuration) {
|
|
public Settings {
|
|
Objects.requireNonNull(baseDamage); Objects.requireNonNull(cooldown); Objects.requireNonNull(slownessDuration);
|
|
if (baseDamage.signum() < 0 || cooldown.isNegative() || cooldown.compareTo(Duration.ofDays(365)) > 0
|
|
|| !Double.isFinite(radius) || radius <= 0 || radius > 64
|
|
|| slownessAmplifier < 0 || slownessAmplifier > 255
|
|
|| slownessDuration.isNegative() || slownessDuration.isZero()
|
|
|| slownessDuration.compareTo(Duration.ofDays(1)) > 0) {
|
|
throw new IllegalArgumentException("Invalid Frost Nova settings");
|
|
}
|
|
}
|
|
public static Settings defaults() {
|
|
return new Settings(BigInteger.valueOf(5), Duration.ofSeconds(12), 5, 1, Duration.ofSeconds(3));
|
|
}
|
|
}
|
|
|
|
private static final class SlowLease implements AutoCloseable {
|
|
final LivingEntity target; final PotionEffect previous; final PotionEffect applied;
|
|
final long started = System.nanoTime(); boolean owned; boolean closed;
|
|
SlowLease(LivingEntity target, PotionEffect applied) {
|
|
this.target = target; previous = target.getPotionEffect(PotionEffectType.SLOWNESS); this.applied = applied;
|
|
}
|
|
boolean apply() { owned = target.addPotionEffect(applied); return owned; }
|
|
@Override public void close() {
|
|
if (closed) return; closed = true; if (!owned) return;
|
|
var current = target.getPotionEffect(PotionEffectType.SLOWNESS);
|
|
long elapsed = Math.max(0, (System.nanoTime() - started) / 50_000_000L);
|
|
int expected = (int) Math.max(0, (long) applied.getDuration() - elapsed);
|
|
if (current == null || current.getAmplifier() != applied.getAmplifier()
|
|
|| current.getDuration() > expected + 2) return;
|
|
target.removePotionEffect(PotionEffectType.SLOWNESS);
|
|
if (previous != null) {
|
|
int remaining = (int) Math.max(0, (long) previous.getDuration() - elapsed);
|
|
if (remaining > 0) target.addPotionEffect(previous.withDuration(remaining));
|
|
}
|
|
}
|
|
}
|
|
private final class LeaseGroup implements AutoCloseable {
|
|
final AbilityExecution execution; final List<SlowLease> leases = new ArrayList<>(); boolean closed;
|
|
LeaseGroup(AbilityExecution execution) { this.execution = execution; }
|
|
@Override public void close() {
|
|
if (closed) return; closed = true; active.remove(execution, this);
|
|
for (var lease : List.copyOf(leases)) lease.close(); leases.clear();
|
|
}
|
|
}
|
|
private static final class Attempt {
|
|
final AbilityExecution execution; final LivingEntity target; boolean accepted;
|
|
Attempt(AbilityExecution execution, LivingEntity target) { this.execution = execution; this.target = target; }
|
|
}
|
|
|
|
private volatile Settings settings;
|
|
private final EquipmentSessions sessions;
|
|
private final PartyRoster parties;
|
|
private final Map<AbilityExecution, LeaseGroup> active = new java.util.IdentityHashMap<>();
|
|
private Attempt damaging;
|
|
private boolean closed;
|
|
|
|
public FrostNova(Settings settings, EquipmentSessions sessions, PartyRoster parties) {
|
|
this.settings = Objects.requireNonNull(settings); this.sessions = Objects.requireNonNull(sessions);
|
|
this.parties = Objects.requireNonNull(parties);
|
|
}
|
|
public void configure(Settings settings) { this.settings = Objects.requireNonNull(settings); }
|
|
|
|
public AbilityDefinition definition() {
|
|
var current = settings;
|
|
return new AbilityDefinition("frost_nova", "Frost Nova", Material.SNOWBALL,
|
|
List.of("Burst in a " + decimal(BigDecimal.valueOf(current.radius())) + "-block sphere for "
|
|
+ current.baseDamage() + " + INT modifier damage.",
|
|
"Applies Slowness " + level(current.slownessAmplifier()) + " for " + seconds(current.slownessDuration()) + " seconds."),
|
|
"Use to affect exposed enemies; caster, party and ordinary players are excluded.",
|
|
Map.of(Stat.INT, BigInteger.valueOf(16), Stat.DEX, BigInteger.TEN), BigInteger.ONE,
|
|
AbilityDefinition.Activation.DELAYED, ControlInput.Gesture.USE, current.cooldown(),
|
|
Map.of("base-damage", new BigDecimal(current.baseDamage()),
|
|
"radius", BigDecimal.valueOf(current.radius()).stripTrailingZeros(),
|
|
"slowness-amplifier", BigDecimal.valueOf(current.slownessAmplifier()),
|
|
"slowness-duration-seconds", BigDecimal.valueOf(current.slownessDuration().toNanos()).movePointLeft(9)),
|
|
AbilityDefinition.TargetPolicy.AREA, this);
|
|
}
|
|
|
|
public static BigInteger damage(BigInteger intelligence) { return damage(BigInteger.valueOf(5), intelligence); }
|
|
static BigInteger damage(BigInteger base, BigInteger intelligence) {
|
|
Objects.requireNonNull(base); Objects.requireNonNull(intelligence);
|
|
if (base.signum() < 0 || intelligence.signum() < 0) throw new IllegalArgumentException("Invalid Frost Nova damage input");
|
|
var delta = intelligence.subtract(BigInteger.TEN); var divided = delta.divideAndRemainder(BigInteger.TWO);
|
|
var modifier = divided[0]; if (delta.signum() < 0 && divided[1].signum() != 0) modifier = modifier.subtract(BigInteger.ONE);
|
|
return base.add(modifier);
|
|
}
|
|
|
|
@Override public boolean accepts(ControlInput input) { return !closed && input.target() == null; }
|
|
@Override public void activate(AbilityExecution execution) {
|
|
if (closed || !execution.stillCurrent()) return;
|
|
var captured = from(execution.definition()); var source = execution.input().player();
|
|
Location origin = source.getEyeLocation().clone();
|
|
var group = new LeaseGroup(execution); active.put(execution, group); execution.own(group);
|
|
BigInteger exact = damage(captured.baseDamage(), execution.character().stats().get(Stat.INT));
|
|
double amount = exact.bitLength() > 1023 ? Double.MAX_VALUE : exact.doubleValue();
|
|
int affected = 0;
|
|
for (var target : candidates(source, origin, captured.radius())) {
|
|
if (affected == 64 || !execution.stillCurrent()) break;
|
|
if (!eligible(execution, target, origin, captured.radius())) continue;
|
|
var sourceDamage = DamageSource.builder(DamageType.FREEZE).withCausingEntity(source)
|
|
.withDirectEntity(source).withDamageLocation(origin).build();
|
|
var attempt = new Attempt(execution, target); damaging = attempt;
|
|
try { target.damage(amount, sourceDamage); }
|
|
finally { if (damaging == attempt) damaging = null; }
|
|
affected++;
|
|
if (!attempt.accepted || !execution.stillCurrent() || !eligible(execution, target, origin, captured.radius())) continue;
|
|
int ticks = Math.toIntExact(Math.max(1,
|
|
(captured.slownessDuration().toNanos() + 49_999_999L) / 50_000_000L));
|
|
var lease = new SlowLease(target, new PotionEffect(PotionEffectType.SLOWNESS, ticks,
|
|
captured.slownessAmplifier(), false, true, true));
|
|
if (lease.apply()) group.leases.add(lease);
|
|
}
|
|
try { source.getWorld().spawnParticle(Particle.SNOWFLAKE, origin, 32,
|
|
captured.radius() / 2, captured.radius() / 2, captured.radius() / 2, 0.01); }
|
|
catch (RuntimeException ignored) { }
|
|
if (group.leases.isEmpty()) execution.finish();
|
|
else execution.later(captured.slownessDuration(), execution::finish);
|
|
}
|
|
|
|
private List<LivingEntity> candidates(Player source, Location origin, double radius) {
|
|
List<Entity> nearby;
|
|
try { nearby = source.getNearbyEntities(radius, radius, radius); }
|
|
catch (RuntimeException unavailable) { return List.of(); }
|
|
var unique = new LinkedHashMap<UUID, LivingEntity>(); int inspected = 0;
|
|
for (var entity : nearby) {
|
|
if (++inspected > 256) break;
|
|
if (entity instanceof LivingEntity target && target != source) unique.putIfAbsent(target.getUniqueId(), target);
|
|
}
|
|
var result = new ArrayList<>(unique.values());
|
|
result.sort(Comparator.comparingDouble((LivingEntity target) -> distance(origin, target))
|
|
.thenComparing(LivingEntity::getUniqueId));
|
|
return result;
|
|
}
|
|
|
|
private boolean eligible(AbilityExecution execution, LivingEntity target, Location origin, double radius) {
|
|
if (target == execution.input().player() || !inside(origin, target, radius)) return false;
|
|
try {
|
|
if (!execution.input().player().hasLineOfSight(target) || !unobstructed(origin, target)) return false;
|
|
} catch (RuntimeException unavailable) { return false; }
|
|
if (!(target instanceof Player player)) return true;
|
|
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
|
if (active == null) return false;
|
|
var sourceParty = parties.partyOf(execution.input().player().getUniqueId()).orElse(null);
|
|
var targetParty = parties.partyOf(player.getUniqueId()).orElse(null);
|
|
return sourceParty == null || targetParty == null || !sourceParty.id().equals(targetParty.id());
|
|
}
|
|
|
|
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
|
public void acceptedDamage(EntityDamageEvent event) {
|
|
var attempt = damaging;
|
|
if (attempt == null || attempt.accepted || event.getEntity() != attempt.target
|
|
|| event.getCause() != EntityDamageEvent.DamageCause.FREEZE
|
|
|| event.getFinalDamage() <= 0 || !Double.isFinite(event.getFinalDamage())) return;
|
|
attempt.accepted = true;
|
|
attempt.execution.report(AbilityReport.Type.DAMAGE, attempt.target, BigDecimal.valueOf(event.getFinalDamage()));
|
|
}
|
|
|
|
private static boolean unobstructed(Location origin, LivingEntity target) {
|
|
var world = origin.getWorld(); if (world == null) return false;
|
|
var location = target.getLocation(); if (location.getWorld() != world) return false;
|
|
var bounds = target.getBoundingBox();
|
|
var center = bounds == null ? location.toVector().add(new org.bukkit.util.Vector(0, target.getHeight() / 2, 0))
|
|
: bounds.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;
|
|
}
|
|
|
|
private static boolean inside(Location origin, LivingEntity target, double radius) {
|
|
try { var location = target.getLocation(); return origin.getWorld() == location.getWorld()
|
|
&& origin.distanceSquared(location) <= radius * radius; }
|
|
catch (RuntimeException invalid) { return false; }
|
|
}
|
|
private static double distance(Location origin, LivingEntity target) {
|
|
try { var location = target.getLocation(); return origin.getWorld() == location.getWorld()
|
|
? origin.distanceSquared(location) : Double.POSITIVE_INFINITY; }
|
|
catch (RuntimeException invalid) { return Double.POSITIVE_INFINITY; }
|
|
}
|
|
private static Settings from(AbilityDefinition definition) {
|
|
var parameters = definition.parameters();
|
|
return new Settings(parameters.get("base-damage").toBigIntegerExact(), definition.cooldown(),
|
|
parameters.get("radius").doubleValue(), parameters.get("slowness-amplifier").intValueExact(),
|
|
Duration.ofNanos(parameters.get("slowness-duration-seconds").movePointRight(9).longValueExact()));
|
|
}
|
|
private static String decimal(BigDecimal value) { return value.stripTrailingZeros().toPlainString(); }
|
|
private static String seconds(Duration duration) {
|
|
return decimal(BigDecimal.valueOf(duration.toNanos()).movePointLeft(9));
|
|
}
|
|
private static String level(int amplifier) {
|
|
return switch (amplifier + 1) { case 1 -> "I"; case 2 -> "II"; case 3 -> "III"; case 4 -> "IV"; default -> Integer.toString(amplifier + 1); };
|
|
}
|
|
|
|
@Override public void close() {
|
|
if (closed) return; closed = true; damaging = null;
|
|
for (var group : List.copyOf(active.values())) { group.close(); group.execution.finish(); }
|
|
active.clear();
|
|
}
|
|
}
|