377 lines
21 KiB
Java
377 lines
21 KiB
Java
package games.dmg.fantasystick.ability;
|
|
|
|
import games.dmg.fantasystick.items.CharacterSheets;
|
|
import games.dmg.fantasystick.items.TailBooks;
|
|
import games.dmg.fantasystick.persistence.CharacterRecord;
|
|
import games.dmg.fantasystick.persistence.CharacterStorage;
|
|
import games.dmg.fantasystick.persistence.RevivalStore;
|
|
import games.dmg.fantasystick.progression.Stat;
|
|
import games.dmg.fantasystick.session.ControlInput;
|
|
import java.math.BigDecimal;
|
|
import java.math.BigInteger;
|
|
import java.time.Clock;
|
|
import java.time.Duration;
|
|
import java.time.Instant;
|
|
import java.time.temporal.ChronoUnit;
|
|
import java.util.ArrayList;
|
|
import java.util.IdentityHashMap;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Objects;
|
|
import java.util.UUID;
|
|
import java.util.concurrent.CompletableFuture;
|
|
import java.util.function.Consumer;
|
|
import net.kyori.adventure.text.Component;
|
|
import org.bukkit.Location;
|
|
import org.bukkit.Material;
|
|
import org.bukkit.entity.Entity;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.event.EventHandler;
|
|
import org.bukkit.event.EventPriority;
|
|
import org.bukkit.event.Listener;
|
|
import org.bukkit.inventory.Inventory;
|
|
import org.bukkit.inventory.ItemStack;
|
|
|
|
/** Revive target selection, contained popup and proof-based Tail conversion. */
|
|
public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
|
public interface PopupFactory { Inventory create(int size, Component title); }
|
|
private static final Duration DEATH_AGE = Duration.ofHours(24);
|
|
private static final Duration VIEW_TIME = Duration.ofMinutes(5);
|
|
private static final double RANGE = 12;
|
|
private record Candidate(int slot, ItemStack captured, TailBooks.Identity identity) { }
|
|
private record Choice(Candidate candidate, CharacterRecord record) { }
|
|
|
|
private final CharacterStorage characters;
|
|
private final RevivalStore reservations;
|
|
private final Clock clock;
|
|
private final Consumer<Runnable> nextTick;
|
|
private final PopupFactory popups;
|
|
private final Consumer<Throwable> failures;
|
|
private final TailBooks tails = new TailBooks();
|
|
private final CharacterSheets sheets = new CharacterSheets();
|
|
private final Map<Inventory, View> inventories = new IdentityHashMap<>();
|
|
private final Map<UUID, View> targets = new LinkedHashMap<>();
|
|
private boolean closed;
|
|
|
|
private final class View implements AutoCloseable {
|
|
final AbilityExecution execution;
|
|
final Player target;
|
|
final Inventory inventory;
|
|
final Map<Integer, Choice> choices;
|
|
boolean selecting;
|
|
boolean finished;
|
|
View(AbilityExecution execution, Player target, Inventory inventory, Map<Integer, Choice> choices) {
|
|
this.execution = execution; this.target = target; this.inventory = inventory; this.choices = choices;
|
|
}
|
|
@Override public void close() {
|
|
if (finished) return;
|
|
finished = true;
|
|
inventories.remove(inventory, this); targets.remove(target.getUniqueId(), this);
|
|
inventory.clear();
|
|
try { target.closeInventory(); } catch (RuntimeException failure) { report(failure); }
|
|
}
|
|
}
|
|
|
|
public Revive(CharacterStorage characters, RevivalStore reservations, Clock clock, Consumer<Runnable> nextTick,
|
|
PopupFactory popups, Consumer<Throwable> failures) {
|
|
this.characters = Objects.requireNonNull(characters); this.reservations = Objects.requireNonNull(reservations);
|
|
this.clock = Objects.requireNonNull(clock); this.nextTick = Objects.requireNonNull(nextTick);
|
|
this.popups = Objects.requireNonNull(popups); this.failures = Objects.requireNonNull(failures);
|
|
}
|
|
|
|
public AbilityDefinition definition() {
|
|
return new AbilityDefinition("revive", "Revive", Material.ECHO_SHARD,
|
|
List.of("Let another player continue one fallen character.", "A valid cast spends the daily opportunity."),
|
|
"Use the equipped shard while aiming at another player within 12 blocks.",
|
|
Map.of(Stat.WIS, BigInteger.valueOf(30), Stat.CHR, BigInteger.valueOf(24), Stat.CON, BigInteger.valueOf(12)),
|
|
BigInteger.ONE, AbilityDefinition.Activation.SELECTION, ControlInput.Gesture.USE, Duration.ofHours(24),
|
|
Map.of("range", BigDecimal.valueOf(12), "selection-time", BigDecimal.valueOf(300),
|
|
"death-age", BigDecimal.valueOf(86400)),
|
|
AbilityDefinition.TargetPolicy.EXCEPTIONAL_NONCOMBAT_SELECTION, this);
|
|
}
|
|
|
|
@Override public boolean accepts(ControlInput input) { return !closed && target(input) != null; }
|
|
|
|
@Override public void activate(AbilityExecution execution) {
|
|
if (closed || !execution.stillCurrent()) { execution.finish(); return; }
|
|
Player target = target(execution.input());
|
|
if (target == null) {
|
|
execution.input().player().sendMessage("Revive found no eligible player within 12 blocks and line of sight.");
|
|
execution.finish(); return;
|
|
}
|
|
var captured = candidates(target);
|
|
if (captured.isEmpty()) {
|
|
execution.input().player().sendMessage("That player has no direct-inventory Tail eligible for Revive.");
|
|
execution.finish(); return;
|
|
}
|
|
var loads = captured.stream().map(candidate -> characters.find(candidate.identity().characterId())).toList();
|
|
CompletableFuture.allOf(loads.toArray(CompletableFuture[]::new)).whenComplete((ignored, failure) -> schedule(() -> {
|
|
if (failure != null) { report(failure); execution.input().player().sendMessage("Revive could not inspect those Tails safely."); execution.finish(); return; }
|
|
if (closed || !execution.stillCurrent() || !target.isOnline()) { execution.finish(); return; }
|
|
var eligible = new ArrayList<Choice>();
|
|
Instant now = clock.instant();
|
|
for (int index = 0; index < captured.size(); index++) {
|
|
var found = loads.get(index).join();
|
|
if (found.isEmpty()) continue;
|
|
var record = found.orElseThrow();
|
|
var candidate = captured.get(index);
|
|
if (eligible(record, candidate.identity(), now) && unchanged(target, candidate)) eligible.add(new Choice(candidate, record));
|
|
}
|
|
if (eligible.isEmpty()) {
|
|
execution.input().player().sendMessage("That player has no current Tail younger than 24 hours.");
|
|
execution.finish(); return;
|
|
}
|
|
open(execution, target, eligible, now);
|
|
}));
|
|
}
|
|
|
|
private Player target(ControlInput input) {
|
|
Player caster = input.player();
|
|
Entity supplied = input.target();
|
|
Player selected = supplied instanceof Player player ? player : null;
|
|
if (selected == null) {
|
|
Location eye = caster.getEyeLocation();
|
|
var hit = caster.getWorld().rayTraceEntities(eye, eye.getDirection(), RANGE,
|
|
entity -> entity instanceof Player && entity != caster);
|
|
if (hit != null && hit.getHitEntity() instanceof Player player) selected = player;
|
|
}
|
|
if (selected == null || selected == caster || !selected.isOnline() || selected.getWorld() != caster.getWorld()
|
|
|| selected.getLocation().distanceSquared(caster.getLocation()) > RANGE * RANGE
|
|
|| !caster.hasLineOfSight(selected)) return null;
|
|
return selected;
|
|
}
|
|
|
|
private List<Candidate> candidates(Player target) {
|
|
var result = new ArrayList<Candidate>();
|
|
for (int slot = 0; slot <= 40; slot++) {
|
|
if (slot > 35 && slot != 40) continue;
|
|
ItemStack item = target.getInventory().getItem(slot);
|
|
if (item == null || item.isEmpty()) continue;
|
|
var identity = tails.identify(item);
|
|
if (identity.isPresent()) result.add(new Candidate(slot, item.clone(), identity.orElseThrow()));
|
|
}
|
|
return List.copyOf(result);
|
|
}
|
|
|
|
private boolean eligible(CharacterRecord record, TailBooks.Identity identity, Instant now) {
|
|
if (!record.dead() || !record.id().equals(identity.characterId()) || !Objects.equals(record.deathId(), identity.deathId())) return false;
|
|
Duration age = Duration.between(record.diedAt(), now);
|
|
return !age.isNegative() && age.compareTo(DEATH_AGE) < 0;
|
|
}
|
|
|
|
private boolean unchanged(Player target, Candidate candidate) {
|
|
ItemStack current = target.getInventory().getItem(candidate.slot());
|
|
return current != null && current.equals(candidate.captured());
|
|
}
|
|
|
|
private void open(AbilityExecution execution, Player target, List<Choice> eligible, Instant now) {
|
|
View old = targets.get(target.getUniqueId()); if (old != null) old.execution.finish();
|
|
int size = Math.min(54, Math.max(9, ((eligible.size() + 8) / 9) * 9));
|
|
Inventory inventory = popups.create(size, Component.text("Choose a Tail to Revive"));
|
|
var choices = new LinkedHashMap<Integer, Choice>();
|
|
for (int index = 0; index < eligible.size() && index < size; index++) {
|
|
Choice choice = eligible.get(index); ItemStack display = choice.candidate().captured().clone(); display.setAmount(1);
|
|
var meta = display.getItemMeta();
|
|
long seconds = Math.max(0, Duration.between(now, choice.record().diedAt().plus(DEATH_AGE)).toSeconds());
|
|
meta.lore(List.of(Component.text("Level " + choice.record().level()),
|
|
Component.text("Eligible for " + seconds + " more seconds"), Component.text("Click to continue this character")));
|
|
display.setItemMeta(meta); inventory.setItem(index, display); choices.put(index, choice);
|
|
}
|
|
var view = new View(execution, target, inventory, Map.copyOf(choices));
|
|
inventories.put(inventory, view); targets.put(target.getUniqueId(), view); execution.own(view);
|
|
target.openInventory(inventory);
|
|
execution.later(VIEW_TIME, execution::finish);
|
|
}
|
|
|
|
@EventHandler(priority = EventPriority.HIGHEST)
|
|
public void click(org.bukkit.event.inventory.InventoryClickEvent event) {
|
|
var view = inventories.get(event.getView().getTopInventory());
|
|
if (view == null) return;
|
|
event.setCancelled(true);
|
|
if (event.getWhoClicked() != view.target || event.getRawSlot() < 0 || event.getRawSlot() >= view.inventory.getSize()) return;
|
|
Choice choice = view.choices.get(event.getRawSlot());
|
|
if (choice == null || view.selecting) return;
|
|
view.selecting = true; inventories.remove(view.inventory, view); targets.remove(view.target.getUniqueId(), view);
|
|
view.inventory.clear(); view.target.closeInventory();
|
|
confirm(view, choice);
|
|
}
|
|
|
|
@EventHandler(priority = EventPriority.HIGHEST)
|
|
public void drag(org.bukkit.event.inventory.InventoryDragEvent event) {
|
|
var view = inventories.get(event.getView().getTopInventory());
|
|
if (view != null && event.getRawSlots().stream().anyMatch(slot -> slot < view.inventory.getSize())) event.setCancelled(true);
|
|
}
|
|
|
|
@EventHandler(priority = EventPriority.MONITOR)
|
|
public void close(org.bukkit.event.inventory.InventoryCloseEvent event) {
|
|
var view = inventories.get(event.getView().getTopInventory());
|
|
if (view != null && !view.selecting) view.execution.finish();
|
|
}
|
|
|
|
@EventHandler(priority = EventPriority.MONITOR)
|
|
public void quit(org.bukkit.event.player.PlayerQuitEvent event) {
|
|
var targetView = targets.get(event.getPlayer().getUniqueId()); if (targetView != null) targetView.execution.finish();
|
|
for (var view : List.copyOf(inventories.values())) {
|
|
if (view.execution.input().player() == event.getPlayer()) view.execution.finish();
|
|
}
|
|
}
|
|
|
|
@EventHandler(priority = EventPriority.MONITOR)
|
|
public void join(org.bukkit.event.player.PlayerJoinEvent event) { reconcile(event.getPlayer()); }
|
|
|
|
private void confirm(View view, Choice choice) {
|
|
if (closed || !view.execution.stillCurrent() || !view.target.isOnline() || !unchanged(view.target, choice.candidate())) {
|
|
view.execution.finish(); return;
|
|
}
|
|
characters.find(choice.record().id()).whenComplete((found, failure) -> schedule(() -> {
|
|
if (failure != null) { report(failure); view.execution.input().player().sendMessage("Revive could not recheck that Tail; no item changed."); view.execution.finish(); return; }
|
|
if (closed || !view.execution.stillCurrent() || !view.target.isOnline() || found.isEmpty()
|
|
|| !eligible(found.orElseThrow(), choice.candidate().identity(), clock.instant())
|
|
|| !unchanged(view.target, choice.candidate())) {
|
|
view.execution.input().player().sendMessage("That Tail is no longer eligible; no item changed.");
|
|
view.execution.finish(); return;
|
|
}
|
|
reserve(view, choice.candidate(), found.orElseThrow());
|
|
}));
|
|
}
|
|
|
|
private void reserve(View view, Candidate candidate, CharacterRecord dead) {
|
|
ItemStack source = view.target.getInventory().getItem(candidate.slot());
|
|
int destination = source.getAmount() == 1 ? -1 : emptyDirectSlot(view.target, candidate.slot());
|
|
if (source.getAmount() > 1 && destination < 0) {
|
|
view.target.sendMessage("Revive needs one empty direct inventory slot to preserve the copied Tails.");
|
|
view.execution.finish(); return;
|
|
}
|
|
var reservation = new RevivalStore.Reservation(UUID.randomUUID(), view.execution.character().id(),
|
|
view.target.getUniqueId(), dead.id(), dead.deathId(), clock.instant().truncatedTo(ChronoUnit.SECONDS),
|
|
candidate.slot(), source.getAmount(), destination);
|
|
reservations.reserve(reservation).whenComplete((reserved, failure) -> schedule(() -> {
|
|
if (failure != null) { report(failure); view.execution.input().player().sendMessage("Revive reservation could not be saved; no Tail changed."); view.execution.finish(); return; }
|
|
if (reserved.isEmpty() || closed || !view.execution.stillCurrent() || !view.target.isOnline()
|
|
|| !unchanged(view.target, candidate)) {
|
|
view.execution.input().player().sendMessage("Revive selection became stale after reservation; no Tail was changed.");
|
|
view.execution.finish(); return;
|
|
}
|
|
deliver(view, dead, reservation);
|
|
}));
|
|
}
|
|
|
|
private int emptyDirectSlot(Player target, int source) {
|
|
for (int slot = 0; slot <= 40; slot++) {
|
|
if (slot > 35 && slot != 40 || slot == source) continue;
|
|
ItemStack item = target.getInventory().getItem(slot);
|
|
if (item == null || item.isEmpty()) return slot;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
private void deliver(View view, CharacterRecord dead, RevivalStore.Reservation reservation) {
|
|
try {
|
|
var provisional = new CharacterRecord(dead.id(), dead.name(), dead.revision(), dead.stats(), dead.level(), dead.experience(),
|
|
dead.unspentPoints(), dead.maximumHealth(), dead.learned(), dead.loadout(), dead.cooldowns(), dead.restrictedKills(),
|
|
false, dead.deathId(), dead.diedAt());
|
|
ItemStack sheet = sheets.create(provisional);
|
|
ItemStack source = view.target.getInventory().getItem(reservation.sourceSlot());
|
|
if (reservation.sourceAmount() == 1) view.target.getInventory().setItem(reservation.sourceSlot(), sheet);
|
|
else {
|
|
view.target.getInventory().setItem(reservation.destinationSlot(), sheet);
|
|
var remaining = source.clone(); remaining.setAmount(reservation.sourceAmount() - 1);
|
|
view.target.getInventory().setItem(reservation.sourceSlot(), remaining);
|
|
}
|
|
view.target.updateInventory();
|
|
} catch (RuntimeException uncertain) {
|
|
report(uncertain); view.target.sendMessage("Revive item delivery is uncertain; retained proof requires recovery.");
|
|
view.execution.finish(); return;
|
|
}
|
|
var nativeLimit = games.dmg.fantasystick.session.NativeHealthLimit.read();
|
|
characters.restoreDeathRecord(reservation.character(), reservation.death(), nativeLimit)
|
|
.whenComplete((restored, failure) -> schedule(() -> {
|
|
if (failure != null || restored.isEmpty()) {
|
|
if (failure != null) report(failure);
|
|
view.target.sendMessage("The Tail changed, but character restoration is pending recovery; do not move the sheet.");
|
|
view.execution.finish(); return;
|
|
}
|
|
if (installFinalSheet(view.target, restored.orElseThrow())) {
|
|
reservations.clear(reservation.character(), reservation.id()).exceptionally(failure2 -> { report(failure2); return false; });
|
|
view.target.sendMessage("Restored character sheet: " + restored.orElseThrow().name() + ".");
|
|
view.execution.input().player().sendMessage("Revive restored " + restored.orElseThrow().name() + ".");
|
|
} else view.target.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");
|
|
view.execution.finish();
|
|
}));
|
|
}
|
|
|
|
private boolean installFinalSheet(Player target, CharacterRecord record) {
|
|
int slot = uniqueSheetSlot(target, record.id());
|
|
if (slot < 0) return false;
|
|
target.getInventory().setItem(slot, sheets.create(record)); target.updateInventory(); return true;
|
|
}
|
|
|
|
private int uniqueSheetSlot(Player target, UUID character) {
|
|
int found = -1;
|
|
for (int slot = 0; slot <= 40; slot++) {
|
|
if (slot > 35 && slot != 40) continue;
|
|
if (sheets.identify(target.getInventory().getItem(slot)).filter(character::equals).isEmpty()) continue;
|
|
if (found >= 0) return -2;
|
|
found = slot;
|
|
}
|
|
return found;
|
|
}
|
|
|
|
public void reconcile(Player target) {
|
|
if (closed || !target.isOnline()) return;
|
|
reservations.target(target.getUniqueId()).whenComplete((found, failure) -> {
|
|
if (failure != null) { report(failure); return; }
|
|
for (var reservation : found) characters.find(reservation.character()).whenComplete((record, loadFailure) -> schedule(() -> {
|
|
if (loadFailure != null) { report(loadFailure); return; }
|
|
if (closed || !target.isOnline() || record.isEmpty()) return;
|
|
reconcile(target, reservation, record.orElseThrow());
|
|
}));
|
|
});
|
|
}
|
|
|
|
private void reconcile(Player target, RevivalStore.Reservation reservation, CharacterRecord record) {
|
|
int foundSheet = uniqueSheetSlot(target, reservation.character());
|
|
boolean hasSheet = foundSheet >= 0;
|
|
ItemStack source = target.getInventory().getItem(reservation.sourceSlot());
|
|
boolean unchangedTail = source != null && source.getAmount() == reservation.sourceAmount()
|
|
&& tails.identify(source).filter(id -> id.characterId().equals(reservation.character()) && id.deathId().equals(reservation.death())).isPresent();
|
|
boolean consumedTail = reservation.sourceAmount() == 1 ? hasSheet
|
|
: source != null && source.getAmount() == reservation.sourceAmount() - 1
|
|
&& tails.identify(source).filter(id -> id.deathId().equals(reservation.death())).isPresent();
|
|
if (!record.dead() && hasSheet && installFinalSheet(target, record)) {
|
|
reservations.clear(reservation.character(), reservation.id()); return;
|
|
}
|
|
if (record.dead() && unchangedTail && !hasSheet) {
|
|
reservations.clear(reservation.character(), reservation.id()); return;
|
|
}
|
|
if (record.dead() && hasSheet && (consumedTail || unchangedTail && reservation.sourceAmount() > 1)) {
|
|
if (unchangedTail && reservation.sourceAmount() > 1) {
|
|
var remaining = source.clone(); remaining.setAmount(source.getAmount() - 1);
|
|
target.getInventory().setItem(reservation.sourceSlot(), remaining); target.updateInventory();
|
|
}
|
|
var nativeLimit = games.dmg.fantasystick.session.NativeHealthLimit.read();
|
|
(reservation.administrative()
|
|
? characters.restoreDeathRecordAdministratively(reservation.character(), reservation.death(), nativeLimit)
|
|
: characters.restoreDeathRecord(reservation.character(), reservation.death(), nativeLimit))
|
|
.whenComplete((restored, failure) -> schedule(() -> {
|
|
if (failure != null) { report(failure); return; }
|
|
if (restored.isPresent() && installFinalSheet(target, restored.orElseThrow())) {
|
|
reservations.clear(reservation.character(), reservation.id());
|
|
}
|
|
}));
|
|
}
|
|
}
|
|
|
|
private void schedule(Runnable action) {
|
|
try { nextTick.accept(action); } catch (RuntimeException rejected) { report(rejected); }
|
|
}
|
|
private void report(Throwable failure) { try { failures.accept(failure); } catch (RuntimeException ignored) { } }
|
|
|
|
@Override public void close() {
|
|
if (closed) return; closed = true;
|
|
for (var view : List.copyOf(inventories.values())) view.execution.finish();
|
|
inventories.clear(); targets.clear();
|
|
}
|
|
}
|