diff --git a/doc/COMBAT_RESTRUCTURE_NOTES.md b/doc/COMBAT_RESTRUCTURE_NOTES.md index acd131fd..750b333b 100644 --- a/doc/COMBAT_RESTRUCTURE_NOTES.md +++ b/doc/COMBAT_RESTRUCTURE_NOTES.md @@ -25,7 +25,9 @@ Update this file in the same pull request whenever something here stops being tr | 4.1 Formulas in `combat.yml` | Done (#387) | | 4.2 Stat snapshots | Done (#385) | | 4.2b Vanilla Thorns | Done (#384) | -| 4.3 and 5 | Next: 4.3 | +| 4.3a New event surface, `DIVINITY_` inside a request | Done (#389) | +| 4.3b Fabled: Physical Damage trigger and immediate buffs on `DivinityHitEvent.Result` | Next | +| 5. Clean-up | Not started | ## Rules for every pull request @@ -160,6 +162,33 @@ lift the cap in the test and restore it. roll fails or succeeds, the invulnerability reduction read, and resistance counting toward the absorption cap. Only `VanillaDamageBridgeTest` catches them, so keep that test when the bridge changes. +## The new event surface (4.3a) + +- **`DivinityHitEvent.Prepare` and `.Result`** are the supported events. `Prepare` is fired by + `VanillaWrapperListener` after Codex scaling and before `Start`. `Result` is fired by `DamageManager` after + the per-type loop and before the fully-mitigated check, so a listener that changes the numbers changes the + `BASE` written, the post-hit effects, `Exit` and the combat log. `DivinityHitEventTest` pins the order and + what each change does. +- **They extend Bukkit's `Event`, not Codex's `IEvent`.** `IEvent` has one static `HandlerList` shared by every + Codex event, so every listener of every such event is offered every one of them. Give any new event its own + `HandlerList`. +- **`DamageMeta` carries what the events report:** `origin`, `weaponStatsMode` (what Divinity did, not what the + request asked) and `requestedAmounts`. `VanillaWrapperListener#describe` sets them before the first event + fires. A meta built elsewhere has none; `DivinityHitEvent` then falls back to the inferred origin and `ADD`. +- **The old events are deprecated but still drive Divinity.** The calculation is a `Start` listener, and the + durability and stats-refresh listeners are on `Exit`. Do not move them to the new events without a decision: + `Exit` skips `IGNORE` hits and `Result` does not. +- **`DIVINITY_` inside an open request.** `DamageManager#dealDamage` used to open its own `REPLACE` request, + which Codex's `claim` (newest unclaimed first) handed out in place of the dealer's. The dealer's request then + stayed open and unclaimed, so the next hit on the target inside the same scope claimed it. Now, when + `DamageContexts.isAnnounced(target)`, `dealDamage` opens a `TypedDeals.Deal` instead of a request, and the + listener claims both. `RAW` leaves the hit alone, `IGNORE` uses only the typed amount and is exempt, anything + else is `REPLACE` as before. Codex has no way to read an open request without claiming it; if it gains one, + `TypedDeals` could go. `TypedDamageInsideRequestTest` pins all of this; four of its tests fail without the fix. +- **Fabled's real call path for a `DIVINITY_` skill was not checked** (Fabled is outside this repository's + scope and the published snapshots predate fabled#1919). The fix assumes what the task described: Fabled's + scope is open on the target while it calls `DamageRegistry.dealDamage`. Check this in 4.3b. + ## Formulas in `combat.yml` (4.1) - **Where things are.** `config/CombatCfg` loads and migrates the file and holds what is in force. diff --git a/doc/COMBAT_RESTRUCTURE_PLAN.md b/doc/COMBAT_RESTRUCTURE_PLAN.md index d3110dc9..2cabab42 100644 --- a/doc/COMBAT_RESTRUCTURE_PLAN.md +++ b/doc/COMBAT_RESTRUCTURE_PLAN.md @@ -92,7 +92,8 @@ still treated as swings and are left for a follow-up. Not a bug after all: `DivinityDamageEvent.Exit` does not fire for `ignore-divinity` skill damage. Firing it would make those hits start costing weapon and armor durability, which is a behaviour change. It is -left as it is and revisited with the new event surface in Phase 4. +left as it is and revisited with the new event surface in Phase 4. In 4.3a it stays that way; +`DivinityHitEvent.Result` does fire for those hits. ## Target design @@ -197,7 +198,7 @@ These must keep working unchanged: classifiers such as `skill_defense_default`. Any key clean-up is alias-only. - The `ignore-divinity` skill setting, with its current behaviour. - `DivinityDamageEvent.BeforeScale`, `Start`, `Pre`, `Dodge` and `Exit`, as deprecated shims, for at - least one release after 2.0. + least one release after 2.0. Deprecated in 4.3a in favour of `DivinityHitEvent.Prepare` and `.Result`. - `DamageTypeProvider.dealDamage`, delegating to the new request API. - Existing `engine.yml` combat options, migrated where they move. @@ -260,12 +261,17 @@ Rules for every pull request: | 4.1 | Divinity | Formulas move to `combat.yml` | Config layout | | 4.2 | Divinity | Stat snapshots. Done | Projectile timing | | 4.2b | Divinity | Stop treating hits that are not swings as swings: vanilla Thorns first (cause `THORNS` on every version, the damage type on 1.20.4+). Uses the origin from the damage request where there is one | Thorns damage | -| 4.3 | Divinity and Fabled | New event and API surface. Fabled stops mutating `BASE` when Divinity is present. The Physical Damage trigger and immediate buffs act on Divinity's final numbers | Yes | +| 4.3a | Divinity | New event and API surface (`DivinityHitEvent.Prepare` and `.Result`); the old events become deprecated shims. A `DIVINITY_` hit dealt inside a dealer's open request honours that request's weapon-stats mode. Done (#389) | `DIVINITY_` inside an `IGNORE` or `RAW` request | +| 4.3b | Fabled | Fabled stops mutating `BASE` when Divinity is present. The Physical Damage trigger and immediate buffs act on Divinity's final numbers through `DivinityHitEvent.Result` | Yes | ### Phase 5: clean-up Remove the shims and dead paths after a release or two. Publish documentation for plugin authors. +`DivinityDamageEvent.Dodge` has no replacement in the new surface yet (4.3a). Do not remove it before one +exists. `ItemDurabilityListener` and `EntityManager` listen to `Exit`; moving them to `Result` would make +hits that ignore weapon stats cost durability, so they need their own decision before `Exit` goes. + ## Still to verify - That Fabled's `PhysicalDamageEvent` really runs before Divinity's calculation in practice. This is diff --git a/src/main/java/studio/magemonkey/divinity/api/event/DivinityDamageEvent.java b/src/main/java/studio/magemonkey/divinity/api/event/DivinityDamageEvent.java index fe2d9d7c..4d82b4e7 100644 --- a/src/main/java/studio/magemonkey/divinity/api/event/DivinityDamageEvent.java +++ b/src/main/java/studio/magemonkey/divinity/api/event/DivinityDamageEvent.java @@ -23,6 +23,14 @@ import java.util.Map; import java.util.function.DoubleUnaryOperator; +/** + * The damage events Divinity fired before 2.0. + * + * @deprecated Use {@link DivinityHitEvent.Prepare} and {@link DivinityHitEvent.Result}. These events still fire at + * the same points with the same behaviour, and will be removed in a later 2.x release (not before + * {@link Dodge} has a replacement). See each subclass for the closest replacement. + */ +@Deprecated public abstract class DivinityDamageEvent extends ICancellableEvent { protected LivingEntity victim; @@ -193,9 +201,13 @@ public final EntityStats getDamagerStats() { } /** - * Called at the start of Damage Event, before ANY calculations. - * This is the first QuantumDamageEvent instance. + * Called after Codex scaling, before any calculation. Divinity's own calculation listens to this event at + * {@code HIGHEST}. + * + * @deprecated Use {@link DivinityHitEvent.Prepare}, which fires just before this event with the same damage + * and defense maps. */ + @Deprecated public static class Start extends DivinityDamageEvent { public Start( @@ -217,6 +229,13 @@ public Start( } } + /** + * Called before Codex's attributes and buffs scale the damage and defense maps. + * + * @deprecated Use {@link DivinityHitEvent.Prepare}. It fires after the scaling; nothing replaces the point + * before it. + */ + @Deprecated public static class BeforeScale extends DivinityDamageEvent { public BeforeScale( @@ -239,9 +258,12 @@ public BeforeScale( } /** - * Called at the start of Damage Event, before damage calculations. - * This is the second QuantumDamageEvent instance. + * Called after the dodge roll, critical hit, block and PvP or PvE modifiers, before the formula. + * + * @deprecated Use {@link DivinityHitEvent.Prepare} to change the inputs, or {@link DivinityHitEvent.Result} + * to cancel the hit once critical hit and block are known. */ + @Deprecated public static class Pre extends DivinityDamageEvent { public Pre( @@ -255,6 +277,13 @@ public Pre( } } + /** + * Called when the victim dodges. Cancelling it makes the hit land. + * + * @deprecated No replacement yet. It keeps firing and will not be removed before one exists. A dodged hit + * fires {@link DivinityHitEvent.Prepare} but no {@link DivinityHitEvent.Result}. + */ + @Deprecated public static class Dodge extends DivinityDamageEvent { public Dodge( @@ -275,9 +304,14 @@ public void setCancelled(boolean cancelled) { } /** - * Called at the end of Damage Event, before return the damage value. - * This is the latest QuantumDamageEvent instance. + * Called at the end of the calculation, after the damage is written and the post-hit effects have run. Not + * called for hits that ignore Divinity's weapon stats. + * + * @deprecated Use {@link DivinityHitEvent.Result} for the final numbers (it fires for every calculated hit, + * those ignoring weapon stats included), or the Bukkit damage event at {@code MONITOR} for "after the hit + * landed". */ + @Deprecated public static class Exit extends DivinityDamageEvent { public Exit( diff --git a/src/main/java/studio/magemonkey/divinity/api/event/DivinityHitEvent.java b/src/main/java/studio/magemonkey/divinity/api/event/DivinityHitEvent.java new file mode 100644 index 00000000..e0f1f5fe --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/api/event/DivinityHitEvent.java @@ -0,0 +1,455 @@ +package studio.magemonkey.divinity.api.event; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import studio.magemonkey.codex.api.damage.DamageOrigin; +import studio.magemonkey.codex.api.damage.DamageRequest; +import studio.magemonkey.codex.api.damage.WeaponStatsMode; +import studio.magemonkey.divinity.manager.damage.DamageMeta; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; +import studio.magemonkey.divinity.stats.items.attributes.DefenseAttribute; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A hit Divinity calculates, at the two points where other plugins can see or change it. + *

+ * Listen to {@link Prepare} or {@link Result}. This base class has no handler list of its own. + *

Order

+ * Both events are fired from Divinity's {@code EntityDamageEvent} handler, at priority {@code HIGHEST}, on the + * server thread: + *
    + *
  1. {@link Prepare}: the damage and defense per type are known, Codex's attributes and buffs have been + * applied, and nothing has been calculated yet. It fires just before the deprecated + * {@code DivinityDamageEvent.Start}.
  2. + *
  3. The dodge roll (a dodged hit ends here), critical hit, block, PvP or PvE modifiers, and the formula + * for each damage type, defenses included.
  4. + *
  5. {@link Result}: Divinity's final numbers per type, before anything is written to the Bukkit event. + * What listeners leave here is what the target takes and what vampirism, bleeding, thornmail, area + * damage and the deprecated {@code DivinityDamageEvent.Exit} see.
  6. + *
+ * Neither event fires for a hit Divinity leaves alone: a request with {@link WeaponStatsMode#RAW}, + * vanilla-only damage handling, a target that is not a living entity, or a hit another listener cancelled + * before Divinity's handler ran. + *

Cancelling

+ * Cancelling either event cancels the Bukkit event, and un-cancelling it un-cancels the Bukkit event, as the + * deprecated events do. After a cancelled {@link Prepare} nothing more is calculated. After a cancelled + * {@link Result} nothing is written to the Bukkit event and no post-hit effect runs. + */ +public abstract class DivinityHitEvent extends Event implements Cancellable { + + private final LivingEntity victim; + private final LivingEntity attacker; + private final Projectile projectile; + private final EntityDamageEvent original; + private final DamageMeta meta; + private final DamageOrigin origin; + private final WeaponStatsMode weaponStats; + private final Map requestedAmounts; + private boolean cancelled; + + protected DivinityHitEvent(@NotNull LivingEntity victim, + @Nullable LivingEntity attacker, + @Nullable Projectile projectile, + @NotNull EntityDamageEvent original, + @NotNull DamageMeta meta) { + this.victim = victim; + this.attacker = attacker; + this.projectile = projectile; + this.original = original; + this.meta = meta; + // A damage meta that did not come from Divinity's own listener (a plugin firing a deprecated event by + // hand) has neither, so they are worked out here the same way + this.origin = meta.getOrigin() != null ? meta.getOrigin() : inferOrigin(projectile, attacker, false); + this.weaponStats = meta.getWeaponStatsMode() != null ? meta.getWeaponStatsMode() : WeaponStatsMode.ADD; + this.requestedAmounts = Collections.unmodifiableMap(new LinkedHashMap<>(meta.getRequestedAmounts())); + } + + @NotNull + public LivingEntity getVictim() { + return victim; + } + + /** + * @return the living entity the hit is attributed to: the swinging entity, the projectile's shooter, or + * the source of a hit dealt through Divinity. Null if there is none + */ + @Nullable + public LivingEntity getAttacker() { + return attacker; + } + + @Nullable + public Projectile getProjectile() { + return projectile; + } + + /** + * @return the weapon whose stats took part in the hit: the item in the attacker's main hand, or the item a + * projectile was launched from. Null if there is none + */ + @Nullable + public ItemStack getWeapon() { + return meta.getWeapon(); + } + + @NotNull + public DamageCause getCause() { + return original.getCause(); + } + + /** + * @return the Bukkit event of the hit. Do not change its damage directly: Divinity writes it after + * {@link Result} + */ + @NotNull + public EntityDamageEvent getOriginalEvent() { + return original; + } + + /** + * @return how the dealer described this hit through Codex, or null if it did not. For a + * {@code DIVINITY_} hit dealt through Codex's {@code DamageRegistry} while the dealer's own request + * was open on the target, this is the dealer's request + */ + @Nullable + public DamageRequest getRequest() { + return meta.getRequest(); + } + + /** + * @return whether the hit was described by a request, so that {@link #getOrigin()} is the dealer's word + * rather than Divinity's guess + */ + public boolean isDescribed() { + return getRequest() != null; + } + + /** + * What kind of thing dealt the hit. With a request, its origin. Without one, Divinity's best guess: + * {@link DamageOrigin#WEAPON_PROJECTILE} for a projectile, {@link DamageOrigin#EFFECT} for vanilla Thorns, + * {@link DamageOrigin#WEAPON_MELEE} when there is a living attacker, and {@link DamageOrigin#ENVIRONMENT} + * otherwise. A plugin's {@code damage(amount, player)} without a request cannot be told from a swing, so it + * is guessed as {@link DamageOrigin#WEAPON_MELEE}. + */ + @NotNull + public DamageOrigin getOrigin() { + return origin; + } + + /** + * How Divinity handled the attacker's equipment for this hit. This is what Divinity did, which can differ + * from what the request asked for: {@link WeaponStatsMode#ADD} without a request, + * {@link WeaponStatsMode#IGNORE} for Fabled's ignore-divinity setting, and {@link WeaponStatsMode#REPLACE} + * (or {@link WeaponStatsMode#IGNORE} when the request asked for that) for a {@code DIVINITY_} hit. + * Never {@link WeaponStatsMode#RAW}, since no event is fired for such a hit. + */ + @NotNull + public WeaponStatsMode getWeaponStatsMode() { + return weaponStats; + } + + /** + * @return the typed amounts the hit was described with, by damage type as the dealer wrote it + * ({@code DIVINITY_fire}, {@code default}, ...). For a {@code DIVINITY_} hit, that type and its + * amount. Empty if there are none. Cannot be changed + */ + @NotNull + public Map getRequestedAmounts() { + return requestedAmounts; + } + + @NotNull + protected DamageMeta getMeta() { + return meta; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + this.original.setCancelled(cancelled); + } + + /** + * Divinity's guess at the origin of a hit no request describes. See {@link #getOrigin()}. + */ + @NotNull + public static DamageOrigin inferOrigin(@Nullable Projectile projectile, + @Nullable LivingEntity attacker, + boolean vanillaThorns) { + if (vanillaThorns) return DamageOrigin.EFFECT; + if (projectile != null) return DamageOrigin.WEAPON_PROJECTILE; + if (attacker != null) return DamageOrigin.WEAPON_MELEE; + return DamageOrigin.ENVIRONMENT; + } + + @Nullable + static DamageAttribute damageType(@NotNull String id) { + return ItemStats.getDamageById(id); + } + + @Nullable + static DefenseAttribute defenseType(@NotNull String id) { + return ItemStats.getDefenseById(id); + } + + private static double amount(double value) { + return Double.isNaN(value) ? 0D : Math.max(0D, value); + } + + /** + * The inputs of a hit, before Divinity calculates anything. The damage and defense per type can be + * changed. A damage type set to 0 is removed. + */ + public static class Prepare extends DivinityHitEvent { + private static final HandlerList HANDLERS = new HandlerList(); + + private final Map damages; + private final Map defenses; + + public Prepare(@NotNull LivingEntity victim, + @Nullable LivingEntity attacker, + @Nullable Projectile projectile, + @NotNull EntityDamageEvent original, + @NotNull DamageMeta meta, + @NotNull Map damages, + @NotNull Map defenses) { + super(victim, attacker, projectile, original, meta); + this.damages = damages; + this.defenses = defenses; + } + + /** + * @return the damage per type, which cannot be changed through this map. Use + * {@link #setDamage(DamageAttribute, double)} + */ + @NotNull + public Map getDamages() { + return Collections.unmodifiableMap(damages); + } + + public double getDamage(@NotNull DamageAttribute type) { + return damages.getOrDefault(type, 0D); + } + + /** + * @return the damage of the type with this id, 0 if the hit has none or there is no such type + */ + public double getDamage(@NotNull String type) { + DamageAttribute attribute = damageType(type); + return attribute == null ? 0D : getDamage(attribute); + } + + /** + * Sets the damage of one type, before defenses. A value of 0 or less removes the type from the hit. + */ + public void setDamage(@NotNull DamageAttribute type, double amount) { + double value = amount(amount); + if (value == 0D) damages.remove(type); + else damages.put(type, value); + } + + /** + * @return false if there is no damage type with this id + */ + public boolean setDamage(@NotNull String type, double amount) { + DamageAttribute attribute = damageType(type); + if (attribute == null) return false; + setDamage(attribute, amount); + return true; + } + + /** + * @return the victim's defense per type, which cannot be changed through this map. Use + * {@link #setDefense(DefenseAttribute, double)} + */ + @NotNull + public Map getDefenses() { + return Collections.unmodifiableMap(defenses); + } + + public double getDefense(@NotNull DefenseAttribute type) { + return defenses.getOrDefault(type, 0D); + } + + public double getDefense(@NotNull String type) { + DefenseAttribute attribute = defenseType(type); + return attribute == null ? 0D : getDefense(attribute); + } + + /** + * Sets the victim's value of one defense for this hit. Defense applies to the damage types it is + * attached to. Unlike damage, a defense may be negative. + */ + public void setDefense(@NotNull DefenseAttribute type, double value) { + defenses.put(type, Double.isNaN(value) ? 0D : value); + } + + /** + * @return false if there is no defense type with this id + */ + public boolean setDefense(@NotNull String type, double value) { + DefenseAttribute attribute = defenseType(type); + if (attribute == null) return false; + setDefense(attribute, value); + return true; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } + } + + /** + * Divinity's final damage per type, after defenses, before it is written to the Bukkit event. The damage + * can be changed; whatever listeners leave is what the victim takes. + *

+ * Divinity writes the sum of the types, less the vanilla invulnerability reduction and rounded to two + * decimals, as the Bukkit event's base damage. If the hit then comes to nothing, it is cancelled. + */ + public static class Result extends DivinityHitEvent { + private static final HandlerList HANDLERS = new HandlerList(); + + private final Map incoming; + + public Result(@NotNull LivingEntity victim, + @Nullable LivingEntity attacker, + @Nullable Projectile projectile, + @NotNull EntityDamageEvent original, + @NotNull DamageMeta meta, + @NotNull Map incoming) { + super(victim, attacker, projectile, original, meta); + this.incoming = Collections.unmodifiableMap(new LinkedHashMap<>(incoming)); + } + + /** + * @return the damage per type that went into the formula, before defenses. Cannot be changed + */ + @NotNull + public Map getIncomingDamages() { + return incoming; + } + + /** + * @return the final damage per type, which cannot be changed through this map. Use + * {@link #setDamage(DamageAttribute, double)} + */ + @NotNull + public Map getDamages() { + return Collections.unmodifiableMap(getMeta().getDamages()); + } + + /** + * @return a copy of the final damage per type, by damage type id + */ + @NotNull + public Map getDamagesById() { + Map byId = new LinkedHashMap<>(); + getMeta().getDamages().forEach((type, amount) -> byId.put(type.getId(), amount)); + return byId; + } + + public double getDamage(@NotNull DamageAttribute type) { + return getMeta().getDamage(type); + } + + public double getDamage(@NotNull String type) { + DamageAttribute attribute = damageType(type); + return attribute == null ? 0D : getDamage(attribute); + } + + /** + * Sets the final damage of one type. Negative values count as 0. A type the hit did not have is added. + */ + public void setDamage(@NotNull DamageAttribute type, double amount) { + getMeta().setDamage(type, amount(amount)); + } + + /** + * @return false if there is no damage type with this id + */ + public boolean setDamage(@NotNull String type, double amount) { + DamageAttribute attribute = damageType(type); + if (attribute == null) return false; + setDamage(attribute, amount); + return true; + } + + /** + * @return the sum of the final damage of every type, not rounded + */ + public double getTotalDamage() { + double total = 0D; + for (double amount : getMeta().getDamages().values()) total += amount; + return total; + } + + /** + * Sets the total damage, scaling every type by the same factor so their shares stay the same. If every + * type is at 0, the whole amount goes to the default damage type. Negative values count as 0. + */ + public void setTotalDamage(double total) { + double target = amount(total); + double current = getTotalDamage(); + Map damages = getMeta().getDamages(); + if (current > 0D) { + double factor = target / current; + damages.replaceAll((type, amount) -> amount * factor); + return; + } + if (target == 0D) return; + DamageAttribute fallback = ItemStats.getDamageByDefault(); + damages.replaceAll((type, amount) -> 0D); + getMeta().setDamage(fallback, target); + } + + /** + * @return how much of the type the victim's defense absorbed. 0 if no defense applied + */ + public double getDefended(@NotNull DamageAttribute type) { + return getMeta().getDefendedDamage(type); + } + + public boolean isCritical() { + return getMeta().isCritical(); + } + + public boolean isBlocked() { + return getMeta().isBlocked(); + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } + } +} diff --git a/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java b/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java index 01c1c95b..e709aa0e 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java +++ b/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java @@ -209,6 +209,7 @@ public void onStatsSprintPacketDuplicator(PlayerToggleSprintEvent e) { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + @SuppressWarnings("deprecation") public void onStatsDamagePacketDuplicator(DivinityDamageEvent.Exit e) { LivingEntity victim = e.getVictim(); this.addDuplicatorFixer(victim); diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/DamageManager.java b/src/main/java/studio/magemonkey/divinity/manager/damage/DamageManager.java index 3493b156..c045344a 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/damage/DamageManager.java +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/DamageManager.java @@ -34,6 +34,7 @@ import studio.magemonkey.divinity.Divinity; import studio.magemonkey.divinity.api.PartyAPI; import studio.magemonkey.divinity.api.event.DivinityDamageEvent; +import studio.magemonkey.divinity.api.event.DivinityHitEvent; import studio.magemonkey.divinity.config.EngineCfg; import studio.magemonkey.divinity.hooks.EHook; import studio.magemonkey.divinity.hooks.external.FabledHook; @@ -295,6 +296,11 @@ public void onDamageRPGStart(@NotNull DivinityDamageEvent.Start e) { } } + DivinityHitEvent.Result result = + new DivinityHitEvent.Result(victim, damager, projectile, orig, meta, e.getDamageMap()); + plugin.getPluginManager().callEvent(result); + if (result.isCancelled()) return; + VanillaDamageBridge vanilla = new VanillaDamageBridge(orig); double modifiedDamage = meta.getTotalDamage(); @@ -567,6 +573,17 @@ public boolean dealDamage(@NotNull LivingEntity entity, // The request cannot carry a negative amount or one that is not a number. The Bukkit call below still // gets the amount as it was given. double requested = Double.isNaN(amount) ? 0D : Math.max(0D, amount); + + // Inside a dealer's own request (a Fabled skill with a DIVINITY_ classifier), a request of ours + // would be claimed in its place and the dealer's weapon-stats mode and origin would be lost. Let the + // listener claim the dealer's request and take the typed amount from here instead. + if (DamageContexts.isAnnounced(entity)) { + try (TypedDeals.Deal deal = TypedDeals.open(entity, damageType, requested)) { + entity.damage(amount, damager); + return deal.isClaimed(); + } + } + DamageRequest request = DamageRequest.builder() .origin(DamageOrigin.EXTERNAL) .source(damager) diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/DamageMeta.java b/src/main/java/studio/magemonkey/divinity/manager/damage/DamageMeta.java index 39b32a81..bfc03932 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/damage/DamageMeta.java +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/DamageMeta.java @@ -7,13 +7,17 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import studio.magemonkey.codex.api.damage.DamageOrigin; import studio.magemonkey.codex.api.damage.DamageRequest; +import studio.magemonkey.codex.api.damage.WeaponStatsMode; import studio.magemonkey.divinity.modules.list.arrows.ArrowManager.QArrow; import studio.magemonkey.divinity.stats.EntityStats; import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; import studio.magemonkey.divinity.stats.items.attributes.DefenseAttribute; +import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; @@ -42,6 +46,20 @@ public class DamageMeta { @Setter @Nullable private DamageRequest request; + /** What dealt the hit: the request's origin, or Divinity's guess without one. Set before any event fires. */ + @Getter + @Setter + @Nullable + private DamageOrigin origin; + /** How Divinity handled the attacker's equipment for this hit. Set before any event fires. */ + @Getter + @Setter + @Nullable + private WeaponStatsMode weaponStatsMode; + /** The typed amounts the hit was described with, by type as the dealer wrote it. */ + @Getter + @NotNull + private Map requestedAmounts = Collections.emptyMap(); private String entityName; private String damagerName; @@ -62,6 +80,10 @@ public DamageMeta( this.combatStartTime = System.currentTimeMillis(); } + public void setRequestedAmounts(@NotNull Map amounts) { + this.requestedAmounts = Collections.unmodifiableMap(new LinkedHashMap<>(amounts)); + } + public void setArrow(@Nullable QArrow arrow, int arrowLevel) { this.arrow = arrow; this.arrowLevel = arrowLevel; diff --git a/src/main/java/studio/magemonkey/divinity/manager/damage/TypedDeals.java b/src/main/java/studio/magemonkey/divinity/manager/damage/TypedDeals.java new file mode 100644 index 00000000..91449cee --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/manager/damage/TypedDeals.java @@ -0,0 +1,97 @@ +package studio.magemonkey.divinity.manager.damage; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.bukkit.entity.Entity; +import org.bukkit.event.entity.EntityDamageEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +/** + * The typed amount of a {@code DIVINITY_} hit that {@link DamageManager#dealDamage} deals while a dealer's + * Codex request is already open on the target, as a Fabled skill with a {@code DIVINITY_} classifier does. + *

+ * Opening a request of Divinity's own there would hide the dealer's, and with it the weapon-stats mode the + * dealer chose. So instead the damage listener claims the dealer's request as usual and takes the typed amount + * from here. A deal is claimed by the same rule as a Codex request: the first damage event of the target that + * asks takes the newest deal not yet taken, and asking again with that event returns the same deal. + *

+ * Not thread safe. Server thread only, like Codex's {@code DamageContexts}. + */ +public final class TypedDeals { + private static final Map> OPEN = new HashMap<>(); + + private TypedDeals() {} + + /** + * Announces a typed hit on the target. Close the returned deal when the call to {@code damage()} returns. + * + * @param type the damage type exactly as the dealer named it, such as {@code DIVINITY_fire} + * @param amount the amount, 0 or more + */ + @NotNull + static Deal open(@NotNull Entity target, @NotNull String type, double amount) { + Deal deal = new Deal(target.getUniqueId(), type, amount); + OPEN.computeIfAbsent(deal.target, id -> new ArrayDeque<>()).push(deal); + return deal; + } + + /** + * @return the typed hit this event is, or null if it is not one + */ + @Nullable + public static Deal claim(@NotNull EntityDamageEvent event) { + Deque deals = OPEN.get(event.getEntity().getUniqueId()); + if (deals == null) return null; + for (Deal deal : deals) { + if (deal.claimedBy == event) return deal; + } + for (Deal deal : deals) { + if (deal.claimedBy == null) { + deal.claimedBy = event; + return deal; + } + } + return null; + } + + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) + public static final class Deal implements AutoCloseable { + private final UUID target; + /** The damage type exactly as the dealer named it. */ + @Getter + @NotNull + private final String type; + @Getter + private final double amount; + private EntityDamageEvent claimedBy; + private boolean closed; + + public boolean isClaimed() { + return claimedBy != null; + } + + @Override + public void close() { + if (closed) return; + closed = true; + Deque deals = OPEN.get(target); + if (deals == null) return; + for (Iterator it = deals.iterator(); it.hasNext(); ) { + if (it.next() == this) { + it.remove(); + break; + } + } + if (deals.isEmpty()) OPEN.remove(target); + } + } +} diff --git a/src/main/java/studio/magemonkey/divinity/manager/listener/object/ItemDurabilityListener.java b/src/main/java/studio/magemonkey/divinity/manager/listener/object/ItemDurabilityListener.java index e9637e4d..b8118ab3 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/listener/object/ItemDurabilityListener.java +++ b/src/main/java/studio/magemonkey/divinity/manager/listener/object/ItemDurabilityListener.java @@ -60,6 +60,9 @@ public void onDuraFish(PlayerFishEvent e) { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + // Stays on the deprecated Exit on purpose: Exit is not fired for hits that ignore weapon stats, which must + // cost no durability + @SuppressWarnings("deprecation") public void onDuraDamageWeapon(DivinityDamageEvent.Exit e) { // Reduce durability of victim's armor LivingEntity victim = e.getVictim(); diff --git a/src/main/java/studio/magemonkey/divinity/manager/listener/object/VanillaWrapperListener.java b/src/main/java/studio/magemonkey/divinity/manager/listener/object/VanillaWrapperListener.java index 8eb4a0cc..8ccc3904 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/listener/object/VanillaWrapperListener.java +++ b/src/main/java/studio/magemonkey/divinity/manager/listener/object/VanillaWrapperListener.java @@ -28,6 +28,7 @@ import studio.magemonkey.codex.util.ItemUT; import studio.magemonkey.divinity.Divinity; import studio.magemonkey.divinity.api.event.DivinityDamageEvent; +import studio.magemonkey.divinity.api.event.DivinityHitEvent; import studio.magemonkey.divinity.api.event.DivinityProjectileLaunchEvent; import studio.magemonkey.divinity.config.EngineCfg; import studio.magemonkey.divinity.hooks.EHook; @@ -38,6 +39,7 @@ import studio.magemonkey.codex.api.damage.WeaponStatsMode; import studio.magemonkey.codex.api.items.PrefixHelper; import studio.magemonkey.divinity.manager.damage.DamageMeta; +import studio.magemonkey.divinity.manager.damage.TypedDeals; import studio.magemonkey.divinity.manager.damage.VanillaDamageBridge; import studio.magemonkey.divinity.modules.list.arrows.ArrowManager; import studio.magemonkey.divinity.modules.list.arrows.ArrowManager.QArrow; @@ -52,6 +54,7 @@ import studio.magemonkey.divinity.stats.items.attributes.api.SimpleStat; import studio.magemonkey.divinity.utils.ItemUtils; +import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -192,10 +195,10 @@ private static void adjustWeaponDamage(Map damages, Dam */ private void replaceDamage(Map damages, Map defenses, - DamageRequest request) { + Map amounts) { String namespace = plugin.getName().toUpperCase(Locale.US); damages.clear(); - request.getAmounts().forEach((type, amount) -> { + amounts.forEach((type, amount) -> { DamageAttribute dmgAtt = ItemStats.getDamageById(PrefixHelper.stripPrefix(namespace, type)); if (dmgAtt == null) return; damages.merge(dmgAtt, amount, Double::sum); @@ -223,6 +226,10 @@ public void onVanillaDamage(EntityDamageEvent e) { // How the dealer described this hit, if it did. Fabled's throwaway events never get this far, so // they cannot take a request away from the real hit. DamageRequest request = DamageContexts.claim(e); + // A DIVINITY_ hit dealt through DamageRegistry inside the dealer's own request: the request says + // how to treat the weapon, the deal says what the damage is. Claimed before any early return, so a + // nested hit on the same target cannot pick it up. + TypedDeals.Deal typed = TypedDeals.claim(e); if (request != null && request.getWeaponStats() == WeaponStatsMode.RAW) return; // Disable vanilla armor effect. @@ -247,6 +254,7 @@ public void onVanillaDamage(EntityDamageEvent e) { statsVictim.setLastDamageMeta(meta); boolean isFullDamage = false; + boolean thornsHit = false; // The vanilla damage type, read at most once per event. It is read for the Thorns check on a hit with // no request, and reused by the attached-damage-types fallback below. @@ -277,6 +285,7 @@ public void onVanillaDamage(EntityDamageEvent e) { vanillaTypeKnown = true; } if (isThornsHit(cause, vanillaType)) { + thornsHit = true; break labelFullDamage; } } @@ -350,6 +359,7 @@ public void onVanillaDamage(EntityDamageEvent e) { if (request != null && request.getWeaponStats() == WeaponStatsMode.IGNORE && damager != null) { skillShouldIgnore = true; } + describe(meta, request, typed, projectile, damager, thornsHit, skillShouldIgnore); // +----------------------------------------------------+ // | Get all DamageAttribute values of the damager. | @@ -450,8 +460,10 @@ public void onVanillaDamage(EntityDamageEvent e) { .forEach((dmgAtt) -> damages.compute(dmgAtt, (dmgKey, dmgVal) -> (dmgVal != null ? dmgVal : 0) + damageStart2)); - if (request != null && request.getWeaponStats() == WeaponStatsMode.REPLACE) { - replaceDamage(damages, defenses, request); + if (typed != null) { + replaceDamage(damages, defenses, Collections.singletonMap(typed.getType(), typed.getAmount())); + } else if (request != null && request.getWeaponStats() == WeaponStatsMode.REPLACE) { + replaceDamage(damages, defenses, request.getAmounts()); } DivinityDamageEvent.BeforeScale beforeScale = new DivinityDamageEvent.BeforeScale(victim, @@ -471,6 +483,14 @@ public void onVanillaDamage(EntityDamageEvent e) { scaleValuesWithCore(damager, projectile, damages, defenses, victim); + DivinityHitEvent.Prepare prepare = + new DivinityHitEvent.Prepare(victim, damager, projectile, e, meta, damages, defenses); + plugin.getPluginManager().callEvent(prepare); + if (prepare.isCancelled()) { + clearArrowBonus(statsDamager, statsVictim); + return; + } + DivinityDamageEvent.Start eventStart = new DivinityDamageEvent.Start(victim, damager, projectile, @@ -500,6 +520,36 @@ public void onVanillaDamage(EntityDamageEvent e) { // Divinity.getInstance().info("event took: " + (System.currentTimeMillis() - l1) + " millis"); } + /** + * Records on the damage meta what {@link DivinityHitEvent} reports about the hit: its origin, how the + * weapon was treated, and the typed amounts it was described with. + */ + private static void describe(@NotNull DamageMeta meta, + @Nullable DamageRequest request, + @Nullable TypedDeals.Deal typed, + @Nullable Projectile projectile, + @Nullable LivingEntity damager, + boolean thornsHit, + boolean ignored) { + meta.setOrigin(request != null + ? request.getOrigin() + : DivinityHitEvent.inferOrigin(projectile, damager, thornsHit)); + + WeaponStatsMode asked = request != null ? request.getWeaponStats() : null; + WeaponStatsMode handled; + if (ignored) handled = WeaponStatsMode.IGNORE; + else if (typed != null) handled = asked == WeaponStatsMode.IGNORE ? WeaponStatsMode.IGNORE : WeaponStatsMode.REPLACE; + else if (asked != null) handled = asked; + else handled = WeaponStatsMode.ADD; + meta.setWeaponStatsMode(handled); + + if (typed != null) { + meta.setRequestedAmounts(Collections.singletonMap(typed.getType(), typed.getAmount())); + } else if (request != null) { + meta.setRequestedAmounts(request.getAmounts()); + } + } + /** * Whether this is the damage vanilla Thorns deals back to an attacker: cause {@code THORNS} on every * version, or, where the server has vanilla damage types (1.20.4 and newer), the type diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/CombatTestBase.java b/src/test/java/studio/magemonkey/divinity/manager/damage/CombatTestBase.java new file mode 100644 index 00000000..d3f1ccad --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/CombatTestBase.java @@ -0,0 +1,231 @@ +package studio.magemonkey.divinity.manager.damage; + +import com.google.common.base.Function; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.mockbukkit.mockbukkit.ServerMock; +import org.mockbukkit.mockbukkit.entity.PlayerMock; +import org.mockito.MockedStatic; +import studio.magemonkey.codex.compat.VersionManager; +import studio.magemonkey.codex.hooks.NHook; +import studio.magemonkey.codex.util.EffectUT; +import studio.magemonkey.divinity.config.EngineCfg; +import studio.magemonkey.divinity.hooks.EHook; +import studio.magemonkey.divinity.hooks.external.FabledHook; +import studio.magemonkey.divinity.stats.EntityStats; +import studio.magemonkey.divinity.stats.bonus.StatBonus; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.attributes.api.SimpleStat; +import studio.magemonkey.divinity.stats.items.attributes.api.TypedStat; +import studio.magemonkey.divinity.testutil.MockedTest; + +import java.lang.reflect.Field; +import java.util.*; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mockStatic; + +/** + * The setup the combat tests written after the characterization tests share: an attacker, a victim that + * fires real damage events, and helpers to build Divinity items. {@code CombatCharacterizationTest} keeps + * its own copy of these on purpose, so that it is not touched by changes here. + */ +abstract class CombatTestBase extends MockedTest { + protected static final double DELTA = 1e-6; + protected static final double VANILLA_SWORD_DAMAGE = 6D; + + private final Map originalCaps = new EnumMap<>(TypedStat.Type.class); + + protected PlayerMock attacker; + protected FiringPlayer victim; + + @BeforeEach + void setupCombat() { + attacker = new TickSafePlayer(server, "Attacker"); + server.addPlayer(attacker); + players.add(attacker); + victim = new FiringPlayer(server, "Victim"); + server.addPlayer(victim); + players.add(victim); + + EngineCfg.VANILLA_ONLY_ITEM_STATS = true; + doAnswer(ans -> isIronSword(ans.getArgument(0)) ? VANILLA_SWORD_DAMAGE : 0D) + .when(VersionManager.getNms()).getDefaultDamage(any()); + doAnswer(ans -> isIronSword(ans.getArgument(0))) + .when(VersionManager.getNms()).isWeapon(any()); + doAnswer(ans -> Registry.ATTRIBUTE.get(NamespacedKey.minecraft(((String) ans.getArgument(0)).toLowerCase( + Locale.US)))).when(VersionManager.getNms()).getAttribute(anyString()); + } + + @AfterEach + void tearDownCombat() { + int offset = 0; + for (PlayerMock player : players) { + player.teleport(player.getLocation().add(10_000 + 100 * offset++, 0, 0)); + } + try (MockedStatic ignored = mockStatic(EffectUT.class)) { + server.getScheduler().performOneTick(); + } + players.forEach(EntityStats::purge); + EngineCfg.VANILLA_ONLY_ITEM_STATS = false; + originalCaps.forEach((type, cap) -> ItemStats.getStat(type).setCapability(cap)); + originalCaps.clear(); + } + + private static boolean isIronSword(@Nullable ItemStack item) { + return item != null && item.getType() == Material.IRON_SWORD; + } + + protected void refresh(LivingEntity entity) { + EntityStats.purge(entity); + EntityStats.get(entity).updateAll(); + } + + protected Map damagesOf(LivingEntity target) { + return ids(Objects.requireNonNull(EntityStats.get(target).getLastDamageMeta())); + } + + protected static Map ids(DamageMeta meta) { + Map damages = new HashMap<>(); + meta.getDamages().forEach((attribute, amount) -> damages.put(attribute.getId(), amount)); + return damages; + } + + protected static Map rounded(Map values) { + Map rounded = new HashMap<>(); + values.forEach((key, value) -> rounded.put(key, Math.round(value * 1e6) / 1e6)); + return rounded; + } + + protected static Map modifiers(double base) { + Map modifiers = new EnumMap<>(DamageModifier.class); + modifiers.put(DamageModifier.BASE, base); + return modifiers; + } + + protected static Map> functions(Map modifiers) { + Map> functions = new EnumMap<>(DamageModifier.class); + modifiers.forEach((modifier, value) -> functions.put(modifier, d -> value)); + return functions; + } + + protected EntityDamageByEntityEvent meleeEvent(Entity damager, Entity target, double eventDamage) { + return new EntityDamageByEntityEvent(damager, + target, + DamageCause.ENTITY_ATTACK, + modifiers(eventDamage), + functions(modifiers(eventDamage))); + } + + protected ItemStack weapon(Map damages) { + ItemStack item = new ItemStack(Material.IRON_SWORD); + damages.forEach((id, value) -> Objects.requireNonNull(ItemStats.getDamageById(id)) + .add(item, new StatBonus(new double[]{value}, false, null), -1)); + return item; + } + + protected ItemStack armor(Map defenses) { + ItemStack item = new ItemStack(Material.IRON_CHESTPLATE); + defenses.forEach((id, value) -> Objects.requireNonNull(ItemStats.getDefenseById(id)) + .add(item, new StatBonus(new double[]{value}, false, null), -1)); + return item; + } + + protected void stat(ItemStack item, TypedStat.Type type, double value) { + ((SimpleStat) Objects.requireNonNull(ItemStats.getStat(type), type.name() + " is not enabled")) + .add(item, new StatBonus(new double[]{value}, false, null), -1); + } + + protected void liftCap(TypedStat.Type type) { + TypedStat stat = Objects.requireNonNull(ItemStats.getStat(type), type.name() + " is not enabled"); + originalCaps.putIfAbsent(type, stat.getCapability()); + stat.setCapability(-1); + } + + /** + * Registers a Fabled hook by hand, since Fabled is not loaded in the tests. + */ + protected FabledHook installFabledHook() throws Exception { + FabledHook hook = new FabledHook(plugin); + Field field = NHook.class.getDeclaredField("pluginName"); + field.setAccessible(true); + field.set(hook, EHook.SKILL_API); + plugin.getHooks().getHooks(plugin).add(hook); + return hook; + } + + protected void removeFabledHook(FabledHook hook) { + plugin.getHooks().getHooks(plugin).remove(hook); + } + + static class TickSafePlayer extends PlayerMock { + TickSafePlayer(@NotNull ServerMock server, @NotNull String name) { + super(server, name, UUID.randomUUID()); + } + + @Override + public float getAttackCooldown() { + return 1F; + } + } + + /** + * Fires the damage event a real server would for {@code damage(amount, source)}, and remembers it. + */ + static class FiringPlayer extends TickSafePlayer { + final List events = new ArrayList<>(); + private final Map cooldowns = new EnumMap<>(Material.class); + EntityDamageEvent lastEvent; + + FiringPlayer(@NotNull ServerMock server, @NotNull String name) { + super(server, name); + } + + @Override + public void damage(double amount, @Nullable Entity source) { + if (source == null) { + lastEvent = new EntityDamageEvent(this, + DamageCause.CUSTOM, + modifiers(amount), + functions(modifiers(amount))); + } else { + lastEvent = new EntityDamageByEntityEvent(source, + this, + DamageCause.ENTITY_ATTACK, + modifiers(amount), + functions(modifiers(amount))); + } + events.add(lastEvent); + server.getPluginManager().callEvent(lastEvent); + } + + @Override + public void damage(double amount) { + damage(amount, (Entity) null); + } + + @Override + public int getCooldown(@NotNull Material material) { + return cooldowns.getOrDefault(material, 0); + } + + @Override + public void setCooldown(@NotNull Material material, int ticks) { + cooldowns.put(material, ticks); + } + } +} diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/DivinityHitEventTest.java b/src/test/java/studio/magemonkey/divinity/manager/damage/DivinityHitEventTest.java new file mode 100644 index 00000000..c996110b --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/DivinityHitEventTest.java @@ -0,0 +1,390 @@ +package studio.magemonkey.divinity.manager.damage; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.inventory.ItemStack; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import studio.magemonkey.codex.api.damage.DamageContexts; +import studio.magemonkey.codex.api.damage.DamageOrigin; +import studio.magemonkey.codex.api.damage.DamageRequest; +import studio.magemonkey.codex.api.damage.DamageScope; +import studio.magemonkey.codex.api.damage.WeaponStatsMode; +import studio.magemonkey.divinity.api.event.DivinityDamageEvent; +import studio.magemonkey.divinity.api.event.DivinityHitEvent; +import studio.magemonkey.divinity.hooks.external.FabledHook; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.attributes.api.TypedStat; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * The new damage event surface (Combat 4.3a): when {@link DivinityHitEvent.Prepare} and + * {@link DivinityHitEvent.Result} fire relative to the deprecated events, what they report, and what changing + * or cancelling them does. + */ +@SuppressWarnings("deprecation") +class DivinityHitEventTest extends CombatTestBase { + private final List fired = new ArrayList<>(); + private final List hits = new ArrayList<>(); + private Consumer onPrepare = e -> {}; + private Consumer onResult = e -> {}; + private Listener recorder; + + @BeforeEach + void listen() { + recorder = new Listener() { + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.BeforeScale e) {fired.add("BeforeScale");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Start e) {fired.add("Start");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Dodge e) {fired.add("Dodge");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Pre e) {fired.add("Pre");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Exit e) {fired.add("Exit");} + + @EventHandler + public void on(DivinityHitEvent.Prepare e) { + fired.add("Prepare"); + hits.add(e); + onPrepare.accept(e); + } + + @EventHandler + public void on(DivinityHitEvent.Result e) { + fired.add("Result"); + hits.add(e); + onResult.accept(e); + } + }; + server.getPluginManager().registerEvents(recorder, plugin); + } + + @AfterEach + void stopListening() { + HandlerList.unregisterAll(recorder); + fired.clear(); + hits.clear(); + onPrepare = e -> {}; + onResult = e -> {}; + } + + private EntityDamageByEntityEvent swing(ItemStack weapon, double eventDamage) { + attacker.getInventory().setItemInMainHand(weapon); + refresh(attacker); + refresh(victim); + fired.clear(); + hits.clear(); + EntityDamageByEntityEvent event = meleeEvent(attacker, victim, eventDamage); + server.getPluginManager().callEvent(event); + return event; + } + + private DivinityHitEvent.Result result() { + return (DivinityHitEvent.Result) hits.stream() + .filter(hit -> hit instanceof DivinityHitEvent.Result) + .findFirst() + .orElseThrow(() -> new AssertionError("No Result fired: " + fired)); + } + + // ------------------------------------------------------------------ // + // Order + // ------------------------------------------------------------------ // + + @Test + void firesBetweenTheDeprecatedEvents() { + swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertEquals(List.of("BeforeScale", "Prepare", "Start", "Pre", "Result", "Exit"), fired); + } + + @Test + void eachEventHasItsOwnHandlerList() { + assertNotSame(DivinityHitEvent.Prepare.getHandlerList(), DivinityHitEvent.Result.getHandlerList()); + } + + @Test + void dodgedHit_firesPrepareButNoResult() { + liftCap(TypedStat.Type.DODGE_RATE); + ItemStack chest = armor(Map.of()); + stat(chest, TypedStat.Type.DODGE_RATE, 100); + victim.getInventory().setChestplate(chest); + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertEquals(List.of("BeforeScale", "Prepare", "Start", "Dodge"), fired); + assertTrue(event.isCancelled()); + } + + @Test + void rawRequest_firesNothing() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(attacker); + refresh(victim); + + try (DamageScope ignored = DamageContexts.open(victim, + DamageRequest.builder().source(attacker).weaponStats(WeaponStatsMode.RAW).build())) { + victim.damage(7, attacker); + } + + assertEquals(List.of(), fired); + } + + // ------------------------------------------------------------------ // + // What the hit is + // ------------------------------------------------------------------ // + + @Test + void undescribedSwing_isAWeaponMeleeHitManagedAsAdd() { + swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + for (DivinityHitEvent hit : hits) { + assertFalse(hit.isDescribed()); + assertNull(hit.getRequest()); + assertEquals(DamageOrigin.WEAPON_MELEE, hit.getOrigin()); + assertEquals(WeaponStatsMode.ADD, hit.getWeaponStatsMode()); + assertEquals(Map.of(), hit.getRequestedAmounts()); + assertSame(attacker, hit.getAttacker()); + assertSame(victim, hit.getVictim()); + assertNotNull(hit.getWeapon()); + } + } + + @Test + void environmentalDamage_isAnEnvironmentHit() { + refresh(victim); + victim.damage(4); + + assertEquals(DamageOrigin.ENVIRONMENT, result().getOrigin()); + assertNull(result().getAttacker()); + assertEquals(Map.of("physical", 4D), result().getDamagesById()); + } + + @Test + void describedHit_reportsTheRequest() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(attacker); + refresh(victim); + DamageRequest request = DamageRequest.builder() + .origin(DamageOrigin.SKILL) + .source(attacker) + .weaponStats(WeaponStatsMode.REPLACE) + .amount("DIVINITY_fire", 4) + .build(); + + try (DamageScope ignored = DamageContexts.open(victim, request)) { + victim.damage(4, attacker); + } + + DivinityHitEvent.Result result = result(); + assertTrue(result.isDescribed()); + assertSame(request, result.getRequest()); + assertEquals(DamageOrigin.SKILL, result.getOrigin()); + assertEquals(WeaponStatsMode.REPLACE, result.getWeaponStatsMode()); + assertEquals(Map.of("DIVINITY_fire", 4D), result.getRequestedAmounts()); + assertEquals(Map.of("fire", 4D), result.getDamagesById()); + } + + @Test + void legacyIgnoreDivinity_isReportedAsIgnore_andStillGetsAResult() throws Exception { + FabledHook hook = installFabledHook(); + try { + hook.ignoreDivinity(attacker, true); + swing(weapon(Map.of("physical", 20D)), 7); + } finally { + hook.ignoreDivinity(attacker, false); + removeFabledHook(hook); + } + + assertEquals(WeaponStatsMode.IGNORE, result().getWeaponStatsMode()); + assertEquals(List.of("BeforeScale", "Prepare", "Start", "Pre", "Result"), fired, + "Result fires for an IGNORE hit; Exit still does not"); + } + + // ------------------------------------------------------------------ // + // Prepare + // ------------------------------------------------------------------ // + + @Test + void prepare_changingTheDamageChangesTheHit() { + onPrepare = e -> { + assertEquals(20D, e.getDamage("physical"), DELTA); + e.setDamage("physical", 10); + assertTrue(e.setDamage("fire", 5)); + assertFalse(e.setDamage("not_a_type", 5)); + }; + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertEquals(Map.of("physical", 10D, "fire", 5D), damagesOf(victim)); + assertEquals(15D, event.getFinalDamage(), DELTA); + } + + @Test + void prepare_damageSetToZeroLeavesTheHit() { + onPrepare = e -> e.setDamage("fire", 0); + + swing(weapon(Map.of("physical", 20D, "fire", 10D)), VANILLA_SWORD_DAMAGE); + + assertEquals(Map.of("physical", 20D), damagesOf(victim)); + } + + @Test + void prepare_changingTheDefenseChangesTheHit() { + victim.getInventory().setChestplate(armor(Map.of("physical", 10D))); + onPrepare = e -> { + assertEquals(10D, e.getDefense("physical"), DELTA); + e.setDefense("physical", 0); + }; + + swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertEquals(Map.of("physical", 20D), damagesOf(victim)); + } + + @Test + void prepare_seenByStartListeners() { + List seenAtStart = new ArrayList<>(); + Listener start = new Listener() { + @EventHandler(priority = EventPriority.NORMAL) + public void on(DivinityDamageEvent.Start e) { + seenAtStart.add(e.getDamageMap().get(ItemStats.getDamageById("physical"))); + } + }; + server.getPluginManager().registerEvents(start, plugin); + onPrepare = e -> e.setDamage("physical", 3); + try { + swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + } finally { + HandlerList.unregisterAll(start); + } + + assertEquals(List.of(3D), seenAtStart); + } + + @Test + void prepare_cancelled_stopsTheHit() { + onPrepare = e -> e.setCancelled(true); + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertTrue(event.isCancelled()); + assertEquals(List.of("BeforeScale", "Prepare"), fired); + } + + // ------------------------------------------------------------------ // + // Result + // ------------------------------------------------------------------ // + + @Test + void result_reportsTheNumbersAfterDefense() { + victim.getInventory().setChestplate(armor(Map.of("physical", 10D))); + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + DivinityHitEvent.Result result = result(); + // As in CombatCharacterizationTest#defense_currentFormula + double physical = damagesOf(victim).get("physical"); + assertTrue(physical < 20D); + assertEquals(physical, result.getDamage("physical"), DELTA); + assertEquals(physical, result.getTotalDamage(), DELTA); + assertEquals(20D - physical, result.getDefended(ItemStats.getDamageById("physical")), DELTA); + assertEquals(Map.of(ItemStats.getDamageById("physical"), 20D), result.getIncomingDamages()); + assertEquals(physical, event.getFinalDamage(), 0.01); + assertFalse(result.isCritical()); + assertFalse(result.isBlocked()); + } + + @Test + void result_changingTheDamageIsWhatTheVictimTakes_andWhatPostEffectsSee() { + liftCap(TypedStat.Type.VAMPIRISM); + ItemStack sword = weapon(Map.of("physical", 20D)); + stat(sword, TypedStat.Type.VAMPIRISM, 50); + attacker.setHealth(10D); + List seenAtExit = new ArrayList<>(); + Listener exit = new Listener() { + @EventHandler + public void on(DivinityDamageEvent.Exit e) {seenAtExit.add(e.getDamageMeta().getTotalDamage());} + }; + server.getPluginManager().registerEvents(exit, plugin); + onResult = e -> e.setDamage("physical", 4); + EntityDamageByEntityEvent event; + try { + event = swing(sword, VANILLA_SWORD_DAMAGE); + } finally { + HandlerList.unregisterAll(exit); + } + + assertEquals(4D, event.getFinalDamage(), DELTA); + assertEquals(Map.of("physical", 4D), damagesOf(victim)); + assertEquals(List.of(4D), seenAtExit); + assertEquals(12D, attacker.getHealth(), DELTA, "Vampirism heals half of the changed damage"); + } + + @Test + void result_setTotalDamage_keepsEachTypesShare() { + onResult = e -> { + assertEquals(30D, e.getTotalDamage(), DELTA); + e.setTotalDamage(15); + }; + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D, "fire", 10D)), 0); + + assertEquals(Map.of("physical", 10D, "fire", 5D), rounded(damagesOf(victim))); + assertEquals(15D, event.getFinalDamage(), DELTA); + } + + @Test + void result_setTotalDamage_withNothingLeft_goesToTheDefaultType() { + onResult = e -> { + e.setDamage("physical", 0); + e.setTotalDamage(5); + }; + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertEquals(5D, event.getFinalDamage(), DELTA); + assertEquals(5D, damagesOf(victim).get(ItemStats.getDamageByDefault().getId()), DELTA); + } + + @Test + void result_damageTakenToNothing_cancelsTheHitAsAFullyMitigatedOne() { + onResult = e -> e.setTotalDamage(0); + + EntityDamageByEntityEvent event = swing(weapon(Map.of("physical", 20D)), VANILLA_SWORD_DAMAGE); + + assertTrue(event.isCancelled()); + assertFalse(fired.contains("Exit")); + } + + @Test + void result_cancelled_writesNothingAndSkipsPostEffects() { + liftCap(TypedStat.Type.VAMPIRISM); + ItemStack sword = weapon(Map.of("physical", 20D)); + stat(sword, TypedStat.Type.VAMPIRISM, 50); + attacker.setHealth(10D); + onResult = e -> e.setCancelled(true); + + EntityDamageByEntityEvent event = swing(sword, VANILLA_SWORD_DAMAGE); + + assertTrue(event.isCancelled()); + assertEquals(VANILLA_SWORD_DAMAGE, event.getDamage(), DELTA, "BASE is left as the event had it"); + assertEquals(List.of("BeforeScale", "Prepare", "Start", "Pre", "Result"), fired); + assertEquals(10D, attacker.getHealth(), DELTA); + } +} diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/TypedDamageInsideRequestTest.java b/src/test/java/studio/magemonkey/divinity/manager/damage/TypedDamageInsideRequestTest.java new file mode 100644 index 00000000..a097d5e2 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/TypedDamageInsideRequestTest.java @@ -0,0 +1,199 @@ +package studio.magemonkey.divinity.manager.damage; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import studio.magemonkey.codex.api.damage.DamageContexts; +import studio.magemonkey.codex.api.damage.DamageOrigin; +import studio.magemonkey.codex.api.damage.DamageRequest; +import studio.magemonkey.codex.api.damage.DamageScope; +import studio.magemonkey.codex.api.damage.WeaponStatsMode; +import studio.magemonkey.codex.registry.DamageRegistry; +import studio.magemonkey.divinity.api.event.DivinityDamageEvent; +import studio.magemonkey.divinity.api.event.DivinityHitEvent; +import studio.magemonkey.divinity.stats.EntityStats; +import studio.magemonkey.divinity.stats.items.attributes.api.TypedStat; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * A skill whose damage classifier is {@code DIVINITY_} goes through {@code DamageRegistry.dealDamage}, + * and so through {@link DamageManager#dealDamage}, while the skill's own request is open on the target. These + * pin what Divinity does with the two together (Combat 4.3a). + */ +@SuppressWarnings("deprecation") +class TypedDamageInsideRequestTest extends CombatTestBase { + private static final List FULL_PIPELINE = List.of("BeforeScale", "Start", "Pre", "Exit"); + private static final List EXEMPT = List.of("BeforeScale", "Start", "Pre"); + + private final List fired = new ArrayList<>(); + private final List results = new ArrayList<>(); + private Listener recorder; + + @BeforeEach + void listen() { + recorder = new Listener() { + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.BeforeScale e) {fired.add("BeforeScale");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Start e) {fired.add("Start");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Pre e) {fired.add("Pre");} + + @EventHandler(priority = EventPriority.LOWEST) + public void on(DivinityDamageEvent.Exit e) {fired.add("Exit");} + + @EventHandler(priority = EventPriority.MONITOR) + public void on(DivinityHitEvent.Result e) {results.add(e);} + }; + server.getPluginManager().registerEvents(recorder, plugin); + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + victim.getInventory().setChestplate(armor(Map.of("fire", 10D))); + refresh(attacker); + refresh(victim); + } + + @AfterEach + void stopListening() { + HandlerList.unregisterAll(recorder); + fired.clear(); + results.clear(); + } + + private DamageRequest outer(WeaponStatsMode mode) { + return DamageRequest.builder() + .origin(DamageOrigin.SKILL) + .source(attacker) + .amount("DIVINITY_fire", 4) + .weaponStats(mode) + .build(); + } + + @Test + void outerIgnore_usesOnlyTheTypedAmount_andTheHitIsExempt() { + armAttackerWith(TypedStat.Type.VAMPIRISM); + DamageRequest request = outer(WeaponStatsMode.IGNORE); + + try (DamageScope scope = DamageContexts.open(victim, request)) { + assertTrue(DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker)); + assertTrue(scope.isClaimed(), "The skill's own request is the one the hit used"); + } + + // Fire 4 against fire defense 10, as in damageRegistry_divinityType_isReducedByMatchingDefense + assertEquals(Map.of("fire", 2.72D), rounded(damagesOf(victim))); + assertEquals(EXEMPT, fired, "No Exit, as for ignore-divinity: no durability cost"); + assertEquals(10D, attacker.getHealth(), DELTA, "No on-hit effects: vampirism did not heal"); + assertSame(request, EntityStats.get(victim).getLastDamageMeta().getRequest()); + assertEquals(1, results.size()); + assertEquals(WeaponStatsMode.IGNORE, results.get(0).getWeaponStatsMode()); + assertEquals(DamageOrigin.SKILL, results.get(0).getOrigin()); + assertEquals(Map.of("DIVINITY_fire", 4D), results.get(0).getRequestedAmounts()); + } + + @Test + void outerRaw_leavesTheEventAlone() { + try (DamageScope scope = DamageContexts.open(victim, outer(WeaponStatsMode.RAW))) { + assertTrue(DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker)); + assertTrue(scope.isClaimed()); + } + + assertEquals(List.of(), fired, "None of Divinity's damage events fire"); + assertEquals(List.of(), results); + assertEquals(4D, victim.lastEvent.getFinalDamage(), DELTA, "The fire defense is not applied"); + } + + @Test + void outerAdd_replacesWithTheTypedAmount_asWithoutARequest() { + DamageRequest request = outer(WeaponStatsMode.ADD); + + try (DamageScope scope = DamageContexts.open(victim, request)) { + assertTrue(DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker)); + assertTrue(scope.isClaimed()); + } + + assertEquals(Map.of("fire", 2.72D), rounded(damagesOf(victim))); + assertEquals(2.72D, victim.lastEvent.getFinalDamage(), DELTA); + assertEquals(FULL_PIPELINE, fired); + assertSame(request, EntityStats.get(victim).getLastDamageMeta().getRequest()); + assertEquals(WeaponStatsMode.REPLACE, results.get(0).getWeaponStatsMode()); + assertEquals(DamageOrigin.SKILL, results.get(0).getOrigin(), "The dealer's origin, not EXTERNAL"); + } + + @Test + void outerReplace_replacesWithTheTypedAmount() { + try (DamageScope ignored = DamageContexts.open(victim, outer(WeaponStatsMode.REPLACE))) { + DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker); + } + + assertEquals(Map.of("fire", 2.72D), rounded(damagesOf(victim))); + assertEquals(FULL_PIPELINE, fired); + } + + @Test + void typedAmountIsTheOneDealt_notTheOneInTheRequest() { + try (DamageScope ignored = DamageContexts.open(victim, DamageRequest.builder() + .source(attacker) + .amount("DIVINITY_fire", 100) + .weaponStats(WeaponStatsMode.IGNORE) + .build())) { + DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker); + } + + assertEquals(Map.of("fire", 2.72D), rounded(damagesOf(victim))); + } + + @Test + void aSecondHitInsideTheSameRequest_isAnOrdinarySwing() { + try (DamageScope ignored = DamageContexts.open(victim, outer(WeaponStatsMode.IGNORE))) { + DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker); + fired.clear(); + + victim.damage(VANILLA_SWORD_DAMAGE, attacker); + } + + assertEquals(Map.of("physical", 20D), damagesOf(victim)); + assertEquals(FULL_PIPELINE, fired); + assertNull(EntityStats.get(victim).getLastDamageMeta().getRequest()); + } + + @Test + void unknownType_dealsNothing_andLeavesTheRequestOpen() { + try (DamageScope scope = DamageContexts.open(victim, outer(WeaponStatsMode.IGNORE))) { + assertFalse(DamageRegistry.dealDamage(victim, 4, "DIVINITY_not_a_type", attacker)); + assertFalse(scope.isClaimed()); + } + + assertNull(victim.lastEvent); + } + + @Test + void withoutAnOuterRequest_nothingChanges() { + DamageRegistry.dealDamage(victim, 4, "DIVINITY_fire", attacker); + + assertEquals(Map.of("fire", 2.72D), rounded(damagesOf(victim))); + assertEquals(FULL_PIPELINE, fired); + DamageRequest inner = EntityStats.get(victim).getLastDamageMeta().getRequest(); + assertNotNull(inner); + assertEquals(DamageOrigin.EXTERNAL, inner.getOrigin()); + assertEquals(WeaponStatsMode.REPLACE, inner.getWeaponStats()); + } + + /** Gives the attacker's sword a certain stat, so an on-hit effect would be visible. */ + private void armAttackerWith(TypedStat.Type type) { + org.bukkit.inventory.ItemStack sword = weapon(Map.of("physical", 20D)); + stat(sword, type, 100); + attacker.getInventory().setItemInMainHand(sword); + attacker.setHealth(10D); + refresh(attacker); + } +}