diff --git a/doc/COMBAT_OPEN_QUESTIONS.md b/doc/COMBAT_OPEN_QUESTIONS.md new file mode 100644 index 00000000..ab205cb7 --- /dev/null +++ b/doc/COMBAT_OPEN_QUESTIONS.md @@ -0,0 +1,214 @@ +# Combat: hits that may wrongly be treated as weapon swings + +Decision note for the combat restructure. Nothing here changes behaviour: each case is pinned by a +characterization test (`NonSwingHitsCharacterizationTest`) and the options are for the maintainers to choose from. +Background: [`COMBAT_RESTRUCTURE_PLAN.md`](COMBAT_RESTRUCTURE_PLAN.md) (vanilla Thorns, the first such case, was +fixed in 4.2b) and [`COMBAT_RESTRUCTURE_NOTES.md`](COMBAT_RESTRUCTURE_NOTES.md). Real-server checks for the +doubtful parts are in [`COMBAT_SERVER_TEST_CHECKLIST.md`](COMBAT_SERVER_TEST_CHECKLIST.md), section Q. + +## The root cause + +`VanillaWrapperListener.onVanillaDamage` decides "this is the attacker's attack" from **who** the damager is, not +**what** hit. A hit with no Codex request becomes a full attack (`isFullDamage`, `VanillaWrapperListener.java:354`) +when its damager is a living entity (`:293-307`) or a projectile with a living shooter (`:309-351`). Then: + +- the attacker's stats are read: damage types from gear (the thrown item standing in for the main hand, + `EntityStats.java:1082-1100`), critical, vampirism, bleed, area damage and the rest (`DamageManager.java:339-426`, + `:452-521`); +- the event's own damage stops being the damage and is only a flat bonus on top (`VanillaWrapperListener.java:414-453`). + +A hit that fails both tests takes the environment path: the event's damage, typed by vanilla damage type, then cause, +then the default type (`:384-396`), defenses applied, no attacker. + +An attacker with **no stats** hides all of this, because with no damage types the event's damage is used anyway. +So every case below has two outcomes: a bare attacker (looks fine) and one with a stat on any worn item (does not). +The tests use a chestplate with 5 physical damage, a certain critical hit (tripled) and 50% vampirism. + +## What was checked, and against what + +The cause and damager Bukkit gives were read from **Paper 1.21.11**: `CraftEventFactory.handleEntityDamageEvent` +(from the dev bundle) and the bytecode of the vanilla 1.21.11 server jar (with Mojang's mappings) for the damage +source and amount each entity uses. Rule: the Bukkit damager is the damage source's *direct* entity; the cause is +`MAGIC` for a thrown potion, `PROJECTILE` for any other projectile, `ENTITY_EXPLOSION` for an explosion tagged +`is_explosion`, `ENTITY_ATTACK` otherwise (and `MAGIC` only for the plain `magic` type). + +**Not checked: 1.16.5 and other old versions.** There, from memory of CraftBukkit, the same rule holds for potions +and projectiles, there are no damage types (so no `attached-damage-types`), no wind charge or breeze, and ownerless +evoker fangs probably fire no damager. The checklist asks for these to be confirmed. + +## Summary + +Attacker-with-stats column: does the hit read the attacker's gear stats, critical, vampirism and the rest? + +| Case (1.21.11) | Cause / damager | Bare attacker | Attacker with stats | Origin reported | Weapon durability | +|---|---|---|---|---|---| +| Splash potion, direct hit | `MAGIC` / the potion | `magical`, event damage | **yes**, armor damage replaces the potion's | `WEAPON_PROJECTILE` | none (projectile) | +| Lingering potion / cloud | `ENTITY_ATTACK` / the cloud | `physical`, event damage | no | `ENVIRONMENT` | none | +| Wind charge, player | `PROJECTILE` / the charge | `physical` 1 | **yes** | `WEAPON_PROJECTILE` | none | +| Wind charge, breeze | `PROJECTILE` / the charge | `physical` 1, mob is damager | mob's stats | `WEAPON_PROJECTILE` | none | +| Fireball, plugin-launched by a player | `PROJECTILE` / the fireball | `physical` | **yes**, and **twice** (hit + explosion) | `WEAPON_PROJECTILE` | none | +| Fireball, dispenser | `PROJECTILE` / the fireball | `physical`, no damager | no | `WEAPON_PROJECTILE` (!) | none | +| Ghast / blaze fireball | `PROJECTILE` / the fireball | `physical`, mob is damager | mob's stats | `WEAPON_PROJECTILE` | none | +| Snowball, egg | `PROJECTILE` / the ball | **cancelled** (0 damage) | **yes**, real damage | `WEAPON_PROJECTILE` | none | +| Llama spit, shulker bullet | `PROJECTILE` / the bullet | `physical`, mob is damager | mob's stats | `WEAPON_PROJECTILE` | none | +| Evoker fangs | `ENTITY_ATTACK` (owned) or `MAGIC` / the fangs | `physical` / `magical` | no | `ENVIRONMENT` | none | +| Trident (thrown) | `PROJECTILE` / the trident | its item's stats | its item's stats plus worn gear | `WEAPON_PROJECTILE` | none | + +Durability: the victim's armor wears on every hit that reaches `Exit`; the attacker's weapon only wears when there +is a damager and the hit is not a projectile (`ItemDurabilityListener.java:88`). So no case here wears a weapon, and +a cancelled hit (snowball) wears nothing. + +## Q1. Splash and lingering potions, area effect clouds + +**Today.** +- A splash potion that hits is a projectile with a living shooter, so it takes the full-attack path + (`VanillaWrapperListener.java:309-351`). The launch handler stores the held potion as its source weapon + (`:114-149`), so no weapon damage is added, but every other worn item's damage applies. With none, the event's + 6 is typed `magical` by the `MAGIC` cause (`damage.yml:36-45`). +- A lingering potion does no harm itself; its **cloud** applies harming. The cloud is an `AreaEffectCloud` damager: + neither living nor a projectile, so it takes the environment path. Cause `ENTITY_ATTACK` is attached to no type, so + the default type (`physical`) is used. +- `DivinityHitEvent.inferOrigin` says `WEAPON_PROJECTILE` for the splash potion and `ENVIRONMENT` for the cloud + (`DivinityHitEvent.java:193-200`). + +**Plausibly wrong?** Yes, twice. (a) With one damage stat on any worn item, a harming potion stops being 6 magical +and becomes 15 physical, critical and vampiric (5 x 3), which no potion thrown by an ungeared player does. +(b) The same effect is `magical` thrown directly and `physical` from a cloud. + +**Options.** +1. Leave it, and document that gear stats apply to thrown potions. +2. Take the non-swing path for potion hits, as 4.2b did for Thorns: the event's damage typed by cause, defenses + applied, no thrower stats. Detect a `ThrownPotion` damager (every version) or damage type `indirect_magic` + with a potion or cloud as direct entity (1.20.4+). +3. Keep the thrower as attacker but skip weapon damage and on-hit effects (the `IGNORE` mode), so critical and + PvP/PvE modifiers still apply. + +For the type mismatch, independently: add `minecraft:indirect_magic` to `magical`'s `attached-damage-types` +(config only, 1.20.4+; older versions keep `physical`). + +**Recommendation.** Option 2 (it matches vanilla expectations and the Thorns precedent), plus the config line in +the 2.0 window because it changes the default numbers. Option 3 if servers want the thrower's critical hit. + +**Pinned by.** `splashPotion_thrownByAnAttackerWithNoStats_...`, `splashPotion_thrownByAnAttackerWithStats_...`, +`areaEffectCloud_isNeverASwing_andIsPhysicalNotMagical`. + +## Q2. Wind charges (1.20.5+ / 1.21) + +**Today.** A wind charge deals 1 damage, damage type `wind_charge`, cause `PROJECTILE`; its explosion deals none +(`SimpleExplosionDamageCalculator(true, false, ...)` in the vanilla class). A player's charge has the player as +shooter and takes the full-attack path (the same as a potion: 15 for the geared attacker). A breeze's charge is a +mob projectile and is the mob's attack. The shipped config has a `wind` damage type and a `wind` defense, but +nothing is attached to either (`damage.yml:100-110`), so no wind charge is ever `wind` damage. + +**Plausibly wrong?** The player case, yes: it is a movement tool that does 1 damage, and a geared player's does 15 +with a critical hit. The breeze case is fine: a mob's projectile is the mob's attack, as an arrow is. + +**Options.** +1. Leave it. +2. Player-thrown charge takes the non-swing path (as Q1 option 2); a breeze's stays a mob projectile. +3. As 2, plus attach `minecraft:wind_charge` to `wind` in `damage.yml` so it is typed and defended as wind, which + is probably why the type exists. + +**Recommendation.** Option 3; the attachment goes in with the other config changes in 2.0. + +**Pinned by.** `windCharge_thrownByAnAttackerWithNoStats_...`, `windCharge_thrownByAnAttackerWithStats_...`, +`windCharge_shotByAMob_...`, `windDamageType_existsButNothingIsAttachedToIt`. + +## Q3. Fireballs and fire charges + +**Today.** +- A fireball that hits an entity deals `fireball` damage (6; a small one 5): cause `PROJECTILE`, damager the + fireball. It then **explodes**: a second hit with cause `ENTITY_EXPLOSION`, damager still the fireball. Both go + through the full-attack path, so a player-owned fireball (a plugin's `launchProjectile`) hits a geared attacker's + stats twice: 33 and 33 in the test. +- A dispenser-fired fire charge or fireball has a block as shooter. No damager is set (`:313-315`), so nothing of + the attacker is read, yet the event reports **`WEAPON_PROJECTILE`** with no attacker, because `projectile` is set + before the shooter is looked at (`DivinityHitEvent.java:197`). +- A ghast's or blaze's fireball is a mob projectile, the mob's attack. + +**Plausibly wrong?** The dispenser origin, yes, though only what the event reports. The two-hit behaviour is +vanilla's. Plugin-launched fireballs are third-party damage, which the plan says stays managed. + +**Options.** +1. Leave it. +2. Report-only: `inferOrigin` says `WEAPON_PROJECTILE` only when the projectile has a living shooter; otherwise + `ENVIRONMENT` (or `EXTERNAL`). Changes what `DivinityHitEvent.getOrigin()` returns, nothing Divinity computes. +3. Also treat player-owned fireballs as non-swings. + +**Recommendation.** Option 2 now, no change to the numbers; leave player-owned fireballs managed. + +**Pinned by.** `fireball_launchedByAnAttackerWithNoStats_...`, `fireballExplosion_isTreatedLikeTheDirectHit`, +`fireball_fromADispenser_isEnvironmentLike`, `smallFireball_shotByAMob_...`. + +## Q4. Other projectiles: snowballs, eggs, llama spit, shulker bullets, evoker fangs, tridents + +**Today.** +- **Snowball and egg** deal 0 damage (3 to a blaze). Paper fires the event even for a player (it removes the + vanilla "0 damage, no hit" return). With no stats the total is 0, and Divinity **cancels** a hit under 0.001 + (`DamageManager.java:311-317`), so the push is believed lost. With a stat on any worn item the same snowball + does 15, critically, with vampirism. `ProjectileStats.canDealDamage` already says snowballs and eggs are "not + fired for their damage" (`ProjectileStats.java:90-96`) but the wrapper does not use it. +- **Llama spit** (1) and **shulker bullet** (4) are mob projectiles, the mob's attack. +- **Evoker fangs** are the damager, neither living nor a projectile: environment path. Owned fangs deal + `indirect_magic` with cause `ENTITY_ATTACK`, so `physical`; unowned ones deal `magic`, so `magical`. +- **Trident**: a real weapon. `getSrcWeapon` reads the entity's item (`ProjectileStats.java:63-65`). Fine. + +**Plausibly wrong?** The snowball and egg: yes, on both counts. Fangs: only the type. Spit, bullet, trident: no. + +**Options.** +1. Leave it. +2. Projectiles that are not `canDealDamage` take the non-swing path (as Q1 option 2), and a hit that arrived with + 0 damage is not cancelled, so vanilla's push survives. +3. Only stop cancelling a hit that arrived with 0 damage; leave gear stats on snowballs. + +For fangs: attach `indirect_magic` to `magical` (config, 1.20.4+). + +**Recommendation.** Option 2. The uncancel is worth doing on its own even if nothing else is, but note it also +affects 0-damage hits from other plugins, so it needs the server check (checklist Q4) first. + +**Pinned by.** `snowballAndEgg_withNoStats_areCancelledAsZeroDamage`, `snowballAndEgg_thrownByAnAttackerWithStats_...`, +`llamaSpitAndShulkerBullet_shotByAMob_...`, `evokerFangs_areNeverASwing_...`, `trident_thrownByAnAttacker_...`. + +## Q5. True damage + +**Today.** Divinity has no true damage. +- Nothing in `src/main` is named or documented as such. `DamageRequest` has no flag for it, and the Codex builder + offers only origin, source, cause, typed amounts, weapon scale and bonus, weapon-stats mode and knockback. +- The "direct damage" part of the formula was meant to skip the defense and is switched off: the modifier is the + constant 0 (`DamageManager.java:386`), its stat is commented out (`TypedStat.java:49`), and the `direct-damage` + expression in `combat.yml` multiplies by it. +- A damage type with **no defense attached** skips the defense formula (`DamageManager.java:277-278`). The shipped + `_vanilla_generic` is that, and is attached to void, starvation, suffocation, drowning, suicide and Thorns + (`damage.yml:7-17`). Dealing it by hand works: `DamageRegistry.dealDamage(target, 4, "DIVINITY__vanilla_generic", src)` + is a request (origin `EXTERNAL`, mode `REPLACE`) that no defense reduces. +- `IGNORE` is not true damage: defenses, PvP/PvE modifiers and enchant protection still apply. `RAW` hands the hit + back to vanilla, which keeps its own armor rules. + +Hits **not described by a request**: all vanilla damage (void, starvation, suffocation, drowning, fire, fall, every +case above) and any third-party `damage(x, source)`. Even `_vanilla_generic` damage still has the PvP/PvE modifier, +enchant protection, the dodge roll and vanilla absorption and resistance applied to it, so it is not truly true. + +**Plausibly wrong?** Not a bug: a missing feature. The risk is Fabled adding "true damage" and reaching for +`_vanilla_generic` by accident. + +**Options.** +1. Document `_vanilla_generic` as the stand-in and leave it. +2. Add a `DamageRequest` flag (a Codex change) that skips the defense stage, read by the calculator. +3. Add a dedicated `true` damage type with no defense to the shipped `damage.yml`. + +**Recommendation.** Option 1 now. Decide on option 2 when Fabled actually asks for it; option 3 would add a +user-visible item stat type, which is a larger decision. + +**Pinned by.** `damageRequest_hasNoTrueDamageOrBypassDefenseFlag` (fails if Codex adds one), +`genericDamageType_hasNoDefenseAttached_soDefensesDoNotReduceIt`, `dealtGenericType_isDescribedByARequest_...`, +`directDamage_isNeverSet`. + +## Not testable under MockBukkit + +- Whether the push really is lost when Divinity cancels a snowball hit (Q4): needs a real server. +- Entities were built by hand with the cause, damager and damage source read from the 1.21.11 server; the tests + cannot prove the server builds them that way, only that Divinity treats them so. +- The breeze is stood in for by a zombie shooter (Divinity only sees a living shooter). `Trident` is a Mockito + stand-in because MockBukkit's throws `UnimplementedOperationException` when its item is used. +- `DivinityProjectileLaunchEvent` cannot be built under MockBukkit, so projectiles get the shooter, held item and + power that `onVanillaProjLaunch` would give them, set by hand. diff --git a/doc/COMBAT_RESTRUCTURE_NOTES.md b/doc/COMBAT_RESTRUCTURE_NOTES.md index 750b333b..a234ca19 100644 --- a/doc/COMBAT_RESTRUCTURE_NOTES.md +++ b/doc/COMBAT_RESTRUCTURE_NOTES.md @@ -13,6 +13,10 @@ Update this file in the same pull request whenever something here stops being tr `Combat .`, in the repository it lands in. The sub-issue states the scope, what must not change, and how it is proven. - **Safety net:** `CombatCharacterizationTest` in Divinity. It pins what the damage pipeline produces. +- **Hits that may wrongly count as swings:** `doc/COMBAT_OPEN_QUESTIONS.md` has the cases, the options and a + recommendation for each; `NonSwingHitsCharacterizationTest` pins today's behaviour for them. Nothing there is + decided: read it before changing how `VanillaWrapperListener` chooses the full-attack path. +- **Before a release:** `doc/COMBAT_SERVER_TEST_CHECKLIST.md`, the manual plan for a real Paper or Spigot server. ## Status @@ -27,6 +31,7 @@ Update this file in the same pull request whenever something here stops being tr | 4.2b Vanilla Thorns | Done (#384) | | 4.3a New event surface, `DIVINITY_` inside a request | Done (#389) | | 4.3b Fabled: Physical Damage trigger and immediate buffs on `DivinityHitEvent.Result` | Next | +| Open questions on non-swing hits, and the server checklist | Written (docs and tests only); decisions pending | | 5. Clean-up | Not started | ## Rules for every pull request @@ -114,6 +119,11 @@ differently from a real server: - **Particles are not implemented.** A bleed tick plays them; mock `EffectUT` around the tick. - **Effects live on the `EntityStats` object.** `EntityStats.purge` drops them, so refreshing an entity that way mid-test ends its bleed. Call `updateAll()` without purging. +- **Entities other than players are limited.** `world.spawn` works for splash potions, area effect clouds, wind + charges, fireballs, snowballs, eggs, llama spit, shulker bullets and evoker fangs, but MockBukkit's `Trident` + throws `UnimplementedOperationException` when its item is used (`NonSwingHitsCharacterizationTest` uses a Mockito + stand-in), and a `ZombieMock` stands in for any mob shooter. A `Projectile` is not given a shooter or a source weapon + by a launch event under MockBukkit: set them by hand, as `onVanillaProjLaunch` would. - **Fabled, MythicMobs and Citizens are not loaded.** Fabled's classes are on the test classpath, so its events can be constructed and its statics mocked, but its listeners do not run. diff --git a/doc/COMBAT_RESTRUCTURE_PLAN.md b/doc/COMBAT_RESTRUCTURE_PLAN.md index 2cabab42..aa858220 100644 --- a/doc/COMBAT_RESTRUCTURE_PLAN.md +++ b/doc/COMBAT_RESTRUCTURE_PLAN.md @@ -88,7 +88,10 @@ newer), takes the non-swing path environmental damage takes: the event's own dam `attached-damage-types`, `attached-damage-causes` or the default type, with the defender's defenses applied. A hit that carries a request is decided by the request's origin, as before. Divinity's own Thornmail stat is not affected; it deals damage through a request with no attacker. Other causes that may be non-swings are -still treated as swings and are left for a follow-up. +still treated as swings and are left for a follow-up. That follow-up is investigated, not decided, in +[`COMBAT_OPEN_QUESTIONS.md`](COMBAT_OPEN_QUESTIONS.md): potions and area effect clouds, wind charges, fireballs, +snowballs and eggs, the other projectiles, and true damage, each with its options, a recommendation and the test +that pins today's behaviour (`NonSwingHitsCharacterizationTest`). 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 @@ -272,6 +275,12 @@ Remove the shims and dead paths after a release or two. Publish documentation fo 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. +## Before release + +Codex 1.3.0, Divinity 2.0.0 and Fabled are tested by hand on a real server first, with the plan in +[`COMBAT_SERVER_TEST_CHECKLIST.md`](COMBAT_SERVER_TEST_CHECKLIST.md). It marks what the automated tests already +cover, so the time goes to the rest. + ## Still to verify - That Fabled's `PhysicalDamageEvent` really runs before Divinity's calculation in practice. This is diff --git a/doc/COMBAT_SERVER_TEST_CHECKLIST.md b/doc/COMBAT_SERVER_TEST_CHECKLIST.md new file mode 100644 index 00000000..383b6b8b --- /dev/null +++ b/doc/COMBAT_SERVER_TEST_CHECKLIST.md @@ -0,0 +1,248 @@ +# Combat: real-server test checklist + +A manual test plan for a real Paper or Spigot server, to run before releasing **Codex 1.3.0, Divinity 2.0.0 and +Fabled**. The automated tests run on MockBukkit, which cannot model a real server's events, timing, entities or +chunk loading (the gaps are listed in [`COMBAT_RESTRUCTURE_NOTES.md`](COMBAT_RESTRUCTURE_NOTES.md)). This list is +for what they cannot show. Design: [`COMBAT_RESTRUCTURE_PLAN.md`](COMBAT_RESTRUCTURE_PLAN.md). Open questions this +list helps answer: [`COMBAT_OPEN_QUESTIONS.md`](COMBAT_OPEN_QUESTIONS.md) (section Q below). + +## How to use it + +Each item has steps, the expected result and a coverage mark that says where to spend your time: + +| Mark | Meaning | What to do | +|---|---|---| +| ✅ | The automated tests cover the numbers well | One quick smoke check that the feature is live | +| ◐ | The tests cover the logic but not the real trigger, timing or version | Run it fully | +| ⬜ | Not covered | Run it fully, and run it first | + +Anything that behaves differently from "Expected" is a finding even if it looks harmless: the release promise is +that the default configuration reproduces today's numbers. + +## Setup + +- **Servers:** the newest Paper 1.21.x you support, and Spigot or Paper 1.16.5. Run every item on both unless it says + otherwise. Divinity 2.0.0, Codex 1.3.0 and the Fabled build under test on both. +- **Players and mobs:** two players, A (attacker) and B (victim), both survival, with permission to use the items; + a zombie and a skeleton; one test-only plugin (see item 11). +- **Items:** Divinity items you can read the numbers off: a sword with a single fixed physical damage (no range), a + bow with the same, armor with a single physical defense and a single fire defense, a shield, an item with each of + critical rate 100%, vampirism, bleed, dodge 100%, block rate 100%. Make a copy of everything with the stat + set so the numbers are not luck. +- **Reading the numbers:** turn on the combat log module and read its breakdown, or run with the debug option you + normally use. Note the damage per type and the victim's health lost. +- **Before each item** put A and B at full health, remove potion effects, and stand them on flat ground away from + other mobs. Set chance stats to 0% or 100% by lifting the cap in `engine.yml` where it caps them (dodge 45%, + accuracy 30% by default) and put the cap back afterwards. +- Record the server version, the three plugin versions and any config you changed for every run. + +## 1. Melee with Divinity items + +1. A holds the single-damage sword (damage D, vanilla damage V). B wears no armor. +2. A hits B once with a full cooldown, then once at the start of the cooldown. +3. Repeat with B wearing the physical-defense armor. + +**Expected:** a full-cooldown hit deals D; a rushed hit deals D times the attack-power modifier. With defense, the +damage drops by the default formula's amount (see `CombatCharacterizationTest#defense_currentFormula`). The sword +loses durability; B's armor loses durability. A sweep attack behaves as set in `engine.yml`. +**Coverage:** ✅ numbers and formulas (`CombatCharacterizationTest`, `DamageCalculatorTest`). ◐ attack cooldown and +sweep on a real server. + +## 2. Projectiles with Divinity items + +1. A shoots B with the Divinity bow, fully drawn; then half drawn. +2. Shoot B with a vanilla bow and with a Divinity crossbow. Throw a trident (Divinity item) at B. +3. Shoot with a custom arrow if the arrow module has one. +4. On 1.20.4 to 1.21.3 specifically, compare the fully drawn damage with 1.21.4+ and with 1.16.5. + +**Expected:** a full draw deals the bow's damage; a half draw scales with the launch power. The custom arrow's +bonus applies to the victim and to the shooter for that hit only. **The full-draw damage is the same on every +version** (`VanillaWrapperListener` divides the force by 3 on 1.20.4 to 1.21.3 only). The bow loses durability once +per shot, not per hit. +**Coverage:** ◐ scaling and snapshots (`CombatCharacterizationTest#projectile_*`, `ProjectileLaunchSnapshotTest`). +⬜ real force values per version, crossbow, trident, custom arrows. + +## 3. Skills: weapon-stats modes and `DIVINITY_` + +Make one Fabled damage skill and run it with each setting. A holds the Divinity sword (damage D). The skill's raw +damage is S. Fabled's "Ignore Divinity" option is the old name for `IGNORE`, and Fabled 3.2 turns it into a +weapon-stats choice. If your editor build only has the old checkbox, test three of the modes as unchecked (ADD), +checked (IGNORE) and a `DIVINITY_` classifier (REPLACE), and write down how `RAW` is reached in your build. + +| Mode | Expected damage | On-hit effects (vampirism, bleed) and durability | +|---|---|---| +| `ADD` | The sword's types plus whatever S exceeds the sword's vanilla damage by (as for any plugin's hit) | Apply | +| `REPLACE` / classifier `DIVINITY_` | Exactly S, as that type, defended by that type's defense | Apply, as for a swing | +| `IGNORE` | S, typed by cause, no sword damage; crit and defenses still apply | Do **not** apply, and the hit costs no durability | +| `RAW` | Divinity does not touch the event: vanilla armor and rules apply | Divinity does nothing, so none | + +Then: use `DIVINITY_fire` on a victim with fire defense; use a classifier inside another skill's damage (a skill +that deals `DIVINITY_` while a `IGNORE` or `RAW` skill is the outer hit); cancel a skill hit (dodge or an +ally check) and then **swing with the sword**: the swing must deal full damage; cast an AoE skill with several +targets. +**Expected for the cancelled hit:** the next swing is a normal swing (a Phase 0 fix). +**Coverage:** ✅ the numbers for each mode (`request_*`, `damageRegistry_*`, `ignoreDivinity_*`, +`TypedDamageInsideRequestTest`). ⬜ Fabled's real call path (`DIVINITY_` inside an open scope was never +checked against Fabled itself), the editor mapping, the Physical Damage trigger and immediate buffs ordering +(`PhysicalDamageEvent` before Divinity's calculation is inferred, not tested), AoE with real targets. + +## 4. Shields + +1. B blocks with a vanilla shield; A hits from the front. Then from behind. +2. B has a block-rate-100% item and blocks; then with block rate 0%. +3. B holds a Fabled shield mechanic and a mob (zombie) hits B; then A hits B. +4. B is hit by fire and fall damage while blocking. + +**Expected:** a frontal block uses the configured shield bonus rate and damage modifier, puts the shield on +cooldown and costs shield durability; from behind it does not block. Block rate 100% reduces by the block-damage stat +only while blocking. The Fabled shield absorbs a mob's hit as well as A's. Environmental damage is not offered to the +shield. +**Coverage:** ✅ logic (`block_*`, `codexScaling_shield*`). ◐ real facing, cooldown and the shield item. + +## 5. Vanilla Thorns + +1. B wears armor with Thorns III; A wears Divinity gear with a physical damage, 100% critical and vampirism. +2. A hits B until Thorns triggers. Repeat on 1.16.5. +3. Give B Divinity's Thornmail stat and hit it. + +**Expected:** the reflected damage is the vanilla 1 to 4, typed by cause, **not** A's weapon damage, not critical, and +A is not healed. Divinity's Thornmail returns a share of the hit with no attacker stats involved. 1.16.5 relies on +the `THORNS` cause alone and 1.20.4+ also on the damage type; both must behave the same. +**Coverage:** ✅ `thorns_*`. ◐ the real Thorns trigger on both versions. + +## 6. Stat snapshots + +1. **Arrow, then swap.** A shoots a long arrow flight at B with a strong bow; before it lands A swaps to a weak + item and takes off the armor with the damage stats. **Expected:** the hit uses the bow and the gear A had when + the arrow left. +2. **Unloaded chunk.** A shoots an arrow far enough that it passes through chunks that unload (or move A away + and let chunks unload while it flies), then lets it land. **Expected:** the arrow still hits with its launch + stats; nothing logs an error. An arrow that despawns frees its snapshot (no growth in memory over a few + hundred arrows). +3. **Equipment change.** A swings, swaps the sword, swings again. **Expected:** the second swing uses the new sword + at once, with no stale damage. Do the same with armor, a Fabled class change and a profile buff. +4. **Effects.** Give A a stat-adjusting effect with one charge; hit twice. **Expected:** the charge is used on one + hit only. A launched arrow that misses spends no charge. +5. **Cache off.** Set `performance.entity-stats.snapshot-max-age: 0`, reload, and repeat 1 and 3. **Expected:** the + same results. If a bug appears only with the cache on, it is the cache. +6. **Reload.** Reload the plugin with arrows in flight. **Expected:** no errors; those arrows are read at impact as + before. + +**Coverage:** ✅ the cache logic (`EntityStatSnapshotTest`, 39 tests). ◐ projectile snapshots +(`ProjectileLaunchSnapshotTest`). ⬜ real chunk unloading and long flights (the tests simulate the chunk check), +equipment changes by other plugins (Fabled levels have no event: they count from the next refresh). + +## 7. `combat.yml` + +1. **Default.** Fresh install: `combat.yml` is written with `preset: default`. Repeat items 1 and 3 and compare + with the 1.x numbers you recorded. **Expected:** identical. +2. **Legacy migration.** Start a server whose `engine.yml` has `legacy-combat: true`. **Expected:** `combat.yml` is + created with `preset: legacy`, the old key is ignored afterwards, and the numbers match the old legacy formula. +3. **Legacy preset.** Set `preset: legacy`, reload. **Expected:** the old defense formula's numbers. +4. **An override.** Uncomment `damage-scaling` and remove `critical` from it; reload. **Expected:** critical hits + no longer multiply, nothing else changes. +5. **A broken override.** Write an expression with an unknown variable, one with a syntax error, one with + `2^-1`, and one that divides by zero on some hit. **Expected:** one console message at load for each of the first three, and that expression falls back to the + preset's. The division by zero cannot be seen at load: on the hit where it happens the preset's result is used. + Combat never stops. +6. **Reload.** Edit the file and run Divinity's reload (not a restart); then break the file and reload. + **Expected:** edits apply at once; a broken file never leaves combat without formulas. +7. **Hand edit survives.** Restart: `combat.yml` is not overwritten. + +**Coverage:** ✅ parsing, fallbacks, migration (`CombatCfgTest`, `CombatFormulasTest`, `CombatReloadTest`). ◐ the +real reload command and console output. ⬜ the performance cost with real load (about 15 times slower per hit +than the old Java in the calculator alone; read the PR notes before judging). + +## 8. Dodge, critical, block, PvP and PvE + +1. Dodge 100% on B, accuracy 0: A hits B. Then give A accuracy 100%. +2. Critical rate 100%, critical damage 2 on A; then 0%. +3. A hits B (PvP), then a zombie (PvE), with and without a PvP damage / PvE damage stat on A and PvP / PvE + defense on B. +4. Hit with a dodge-100% victim using a skill (Fabled) as well. + +**Expected:** a dodge cancels the hit entirely (no damage, no knockback) and the next hit is normal; accuracy +cancels dodge. A critical hit multiplies by 1 + critical damage. PvP and PvE modifiers apply only to their kind of +fight. +**Coverage:** ✅ `dodge_*`, `accuracy_*`, `criticalHit_*`, `pvpDamage_*`, `pveDamage_*`. ◐ real knockback and hurt +animation on a dodge. + +## 9. Durability + +1. A swings a Divinity sword 10 times. **Expected:** it loses 10. +2. A shoots 10 arrows. **Expected:** the bow loses 10 (per shot, not per hit); the sword is untouched. +3. B wears Divinity armor and is hit 10 times by any attacker. **Expected:** each armor piece loses 10. +4. A uses an `IGNORE` skill on B 10 times, then a `RAW` skill, then a `REPLACE` skill. **Expected:** `IGNORE` and + `RAW` cost no durability at all (no weapon, no armor: `Exit` does not fire for them). `REPLACE` costs the sword + and B's armor 10 each, as a swing does. +5. B blocks 10 hits. **Expected:** the shield loses 10. +6. Hit a target dummy or armor stand. + +**Coverage:** ◐ which hits reach `Exit` is covered (`CombatCharacterizationTest`, `DivinityHitEventTest`); the +durability amounts themselves are ⬜ (no test reads item wear). + +## 10. A third-party plugin's damage + +1. With a plugin that calls `entity.damage(x, player)` (a simple command plugin, an ability plugin or MythicMobs + skill damage), damage B "from" A, holding the Divinity sword. +2. Repeat with the plugin damaging a mob. +3. With a plugin that damages with no source. + +**Expected:** with a source, Divinity manages it like a swing: the sword's damage types plus the amount's excess +over the sword's vanilla damage, with on-hit effects (stays so by decision). With no source, the amount is typed by +cause and defended. No Codex request is involved, so `DivinityHitEvent#getOrigin` says `WEAPON_MELEE` for the first +and `ENVIRONMENT` for the last. +**Coverage:** ✅ `pluginDamageAttributedToAPlayer_*`. ⬜ any real plugin, including a plugin that sets +`damageCause` metadata or relies on `custom-cooldown`. + +## 11. `DivinityHitEvent` listeners + +Write a throwaway plugin that logs `DivinityHitEvent.Prepare` and `.Result` (origin, weapon-stats mode, attacker, +projectile, damages), and the deprecated `DivinityDamageEvent` ones. Then: + +1. Melee, projectile, skill (each mode), environment (fall), Thorns, a bleed tick. +2. Cancel `Prepare`; cancel `Result`; change a damage in each. +3. Hit with a dodge-100% victim; with a `RAW` skill. + +**Expected:** order is `BeforeScale`, `Prepare`, `Start`, `Pre`, `Result`, `Exit`; origins match the hit (melee +`WEAPON_MELEE`, arrow `WEAPON_PROJECTILE`, fall `ENVIRONMENT`, Thorns `EFFECT`, a skill `SKILL`); a change in +`Result` is what the victim takes and what vampirism sees; cancelling stops the hit. A dodge fires `Prepare` and no +`Result`. A `RAW` skill fires none. The deprecated events still fire, and `Exit` does not fire for `IGNORE`. +**Coverage:** ✅ `DivinityHitEventTest` (19 tests). ◐ a listener in a separate plugin (class loading, priority). + +## 12. Old version (1.16.5) against 1.21 + +Run items 1 to 11 on both. Specifically expect and check these differences: + +| Area | 1.16.5 | 1.21 | +|---|---|---| +| Vanilla damage types | None: `attached-damage-types` does nothing | Read from the event; finer than the cause | +| Thorns | Detected by the `THORNS` cause only | Cause and `minecraft:thorns` type | +| Skill damage | Dealt without a real damage source (cause and death message by metadata) | Real damage source where Codex's adapter supports it | +| Bow force | Used as is | Divided by 3 on 1.20.4 to 1.21.3 (`VanillaWrapperListener` line 81) | +| Wind charge, breeze | Do not exist | Present: see section Q | +| Death message of a skill kill | Read it: it should name the skill's caster | Read it: it should name the skill's caster | + +**Expected:** the same numbers for the same Divinity setup; only the items in the table differ. Anything else is a +finding. +**Coverage:** ⬜ (MockBukkit runs 1.21 only). + +## Q. Open-question cases (observe and record) + +These are the hits in [`COMBAT_OPEN_QUESTIONS.md`](COMBAT_OPEN_QUESTIONS.md). The tests pin what Divinity does with +the event it is given; this section checks that the server gives that event. Record the result for each rather than +pass or fail. + +| # | Do this | Record | +|---|---|---| +| Q1a | A (no damage stats on any item) throws a splash potion of Harming at B. Then A puts on armor with one damage stat and throws again | Cause, damager, damage type, and the damage per type each time. Expected today: magical 6, then a stat-scaled physical hit with critical and vampirism | +| Q1b | A throws a lingering potion of Harming; B stands in the cloud | Same. Expected: the damager is the cloud, damage physical, nothing of A's applies | +| Q2 | A throws a wind charge at B (1.21 only), with and without the stat armor. A breeze shoots B | Damage, whether A is healed or critical. Expected: 1 physical, then 15 with the stat armor | +| Q3a | A plugin launches a fireball from A. Ghast and blaze fire at B | The two hits (direct and explosion) and their numbers | +| Q3b | A dispenser fires a fireball and a fire charge at B | `DivinityHitEvent#getOrigin` (expected today: `WEAPON_PROJECTILE`, no attacker) | +| Q4a | A (no stats) throws a snowball and an egg at B, a zombie and a blaze | **Does the target get pushed?** Expected today: no push, since Divinity cancels the hit. This is the one to confirm | +| Q4b | The same with the stat armor | Damage, critical, vampirism | +| Q4c | Llama spit, a shulker bullet, an evoker's fangs (with an owner, and from a spawned-in fang with none), a thrown Divinity trident | Cause and numbers | +| Q5 | Void, starvation, drowning on B wearing 50 physical defense; then a skill with `DIVINITY__vanilla_generic` | Whether defense reduces them. Expected: it does not | + +Also record, on 1.16.5, the cause and damager of each of the above; the open-questions note only verified 1.21.11. diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/NonSwingHitsCharacterizationTest.java b/src/test/java/studio/magemonkey/divinity/manager/damage/NonSwingHitsCharacterizationTest.java new file mode 100644 index 00000000..e0d969f3 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/NonSwingHitsCharacterizationTest.java @@ -0,0 +1,644 @@ +package studio.magemonkey.divinity.manager.damage; + +import org.bukkit.Material; +import org.bukkit.damage.DamageSource; +import org.bukkit.damage.DamageType; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; +import org.bukkit.projectiles.BlockProjectileSource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockbukkit.mockbukkit.entity.ZombieMock; +import studio.magemonkey.codex.api.damage.DamageOrigin; +import studio.magemonkey.codex.api.damage.DamageRequest; +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.ProjectileStats; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; +import studio.magemonkey.divinity.stats.items.attributes.api.TypedStat; + +import java.lang.reflect.Method; +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Characterization tests for hits that carry no Codex {@link DamageRequest} and are not weapon swings, but that + * {@code VanillaWrapperListener} may still treat as one (see {@code doc/COMBAT_OPEN_QUESTIONS.md}). Vanilla Thorns + * was the first such case and is pinned in {@code CombatCharacterizationTest}; these are the others. + *

+ * They record what happens today. Nothing here says the result is right; where it is doubtful the + * assertion message says so, and the open-questions note has the options. If a change makes one of these fail, + * that change altered behaviour and needs the decision in that note first. + *

+ * Each event is built the way the server builds it: the cause, the damager entity and the damage source were read + * from Paper's {@code CraftEventFactory} and from the vanilla 1.21.11 entity classes (see the note for how). A + * projectile is given the shooter and the source weapon that {@code VanillaWrapperListener#onVanillaProjLaunch} + * gives it, because {@code DivinityProjectileLaunchEvent} cannot be constructed under MockBukkit. + *

+ * Two probes tell a swing from anything else. The attacker's chestplate carries a stat each: 5 physical damage, a + * certain critical hit (damage tripled) and 50% vampirism. A hit that reads the attacker's stats shows those; one + * that does not, shows none of them. Without the chestplate the attacker has no stats at all. + */ +@SuppressWarnings("deprecation") +class NonSwingHitsCharacterizationTest extends CombatTestBase { + private final List spawned = new ArrayList<>(); + private final List seen = new ArrayList<>(); + private Listener probe; + private ZombieMock mob; + + /** What the new and the old events reported for one hit. */ + private static final class Seen { + DamageOrigin origin; + WeaponStatsMode mode; + LivingEntity attacker; + Entity projectile; + boolean exited; + LivingEntity exitDamager; + boolean exitProjectile; + } + + @BeforeEach + void listen() { + mob = new ZombieMock(server, UUID.randomUUID()); + probe = new Listener() { + @EventHandler + public void on(DivinityHitEvent.Result e) { + Seen s = new Seen(); + s.origin = e.getOrigin(); + s.mode = e.getWeaponStatsMode(); + s.attacker = e.getAttacker(); + s.projectile = e.getProjectile(); + seen.add(s); + } + + @EventHandler + public void on(DivinityDamageEvent.Exit e) { + // ItemDurabilityListener reads exactly these two: the attacker's weapon only loses durability + // when there is a damager and the hit is not a projectile + Seen s = seen.get(seen.size() - 1); + s.exited = true; + s.exitDamager = e.getDamager(); + s.exitProjectile = e.isProjectile(); + } + }; + server.getPluginManager().registerEvents(probe, plugin); + } + + @AfterEach + void cleanUp() { + HandlerList.unregisterAll(probe); + seen.clear(); + spawned.forEach(Entity::remove); + spawned.clear(); + EntityStats.purge(mob); + } + + // ------------------------------------------------------------------ // + // Building blocks + // ------------------------------------------------------------------ // + + private T spawn(Class type) { + T entity = victim.getWorld().spawn(victim.getLocation(), type); + spawned.add(entity); + return entity; + } + + /** + * What gives an attacker's hit away as read from the attacker's stats: 5 physical damage, a certain + * critical hit that triples it, and 50% vampirism. All on the chestplate, so no weapon is involved. + */ + private void wearStatChestplate() { + liftCap(TypedStat.Type.VAMPIRISM); + ItemStack chest = armor(Map.of()); + Objects.requireNonNull(ItemStats.getDamageById("physical")) + .add(chest, new studio.magemonkey.divinity.stats.bonus.StatBonus(new double[]{5}, false, null), -1); + stat(chest, TypedStat.Type.CRITICAL_RATE, 100); + stat(chest, TypedStat.Type.CRITICAL_DAMAGE, 2); + stat(chest, TypedStat.Type.VAMPIRISM, 50); + attacker.getInventory().setChestplate(chest); + } + + /** What {@code onVanillaProjLaunch} does for a living shooter: the shooter, the held item and full power. */ + private void launch(Projectile projectile, LivingEntity shooter, ItemStack held) { + projectile.setShooter(shooter); + if (held != null) ProjectileStats.setSrcWeapon(projectile, held); + ProjectileStats.setPower(projectile, 1D); + } + + private EntityDamageByEntityEvent hitBy(Entity direct, + DamageCause cause, + DamageType type, + Entity causing, + double amount) { + DamageSource.Builder source = DamageSource.builder(type).withDirectEntity(direct); + if (causing != null) source.withCausingEntity(causing); + return new EntityDamageByEntityEvent(direct, + victim, + cause, + source.build(), + modifiers(amount), + functions(modifiers(amount))); + } + + private EntityDamageByEntityEvent fire(EntityDamageByEntityEvent event) { + attacker.setHealth(10D); + refresh(attacker); + refresh(victim); + seen.clear(); + server.getPluginManager().callEvent(event); + return event; + } + + private Map damages() { + return rounded(damagesOf(victim)); + } + + private DamageMeta meta() { + return Objects.requireNonNull(EntityStats.get(victim).getLastDamageMeta()); + } + + private Seen reported() { + assertEquals(1, seen.size(), "Expected exactly one DivinityHitEvent.Result"); + return seen.get(0); + } + + /** The probes say the hit read the attacker's stats: 5 physical tripled by a critical hit, and vampirism. */ + private void assertReadAttackerStats(EntityDamageByEntityEvent event, double expectedPhysical) { + assertEquals(Map.of("physical", expectedPhysical), damages()); + assertSame(attacker, meta().getDamager()); + assertTrue(meta().isCritical(), "The attacker's certain critical hit applied"); + assertEquals(Math.min(20D, 10D + expectedPhysical / 2), + attacker.getHealth(), + 1e-6, + "50% vampirism healed the attacker (up to their 20 maximum health)"); + assertEquals(expectedPhysical, event.getFinalDamage(), 1e-6); + } + + /** The probes say none of the attacker's stats applied: only the event's own damage, no critical, no healing. */ + private void assertNoStatsApplied(EntityDamageByEntityEvent event, Map expected) { + assertEquals(expected, damages()); + assertFalse(meta().isCritical()); + assertEquals(10D, attacker.getHealth(), 1e-6, "No vampirism"); + assertEquals(expected.values().stream().mapToDouble(Double::doubleValue).sum(), event.getFinalDamage(), 1e-6); + } + + /** As {@link #assertNoStatsApplied}, and Divinity did not even take the shooter as the hit's damager. */ + private void assertTakenAsEnvironmental(EntityDamageByEntityEvent event, Map expected) { + assertNoStatsApplied(event, expected); + assertNull(meta().getDamager(), "Same as environmental damage: no damager stats are read"); + } + + // ------------------------------------------------------------------ // + // 1. Splash potions and area effect clouds + // ------------------------------------------------------------------ // + + /** + * Server: cause {@code MAGIC}, damager the {@code ThrownPotion} (damage type {@code indirect_magic}, direct + * entity the potion, causing entity the thrower). The thrower has no stats, so the event's own damage is + * typed by the cause, and the hit is still reported as a weapon projectile. + */ + @Test + void splashPotion_thrownByAnAttackerWithNoStats_isMagicalDamageReportedAsAWeaponProjectile() { + attacker.getInventory().setItemInMainHand(new ItemStack(Material.SPLASH_POTION)); + SplashPotion potion = spawn(SplashPotion.class); + launch(potion, attacker, new ItemStack(Material.SPLASH_POTION)); + + EntityDamageByEntityEvent event = + fire(hitBy(potion, DamageCause.MAGIC, DamageType.INDIRECT_MAGIC, attacker, 6)); + + assertEquals("magical", ItemStats.getDamageByCause(DamageCause.MAGIC).getId(), "Test setup"); + assertNoStatsApplied(event, Map.of("magical", 6D)); + assertSame(attacker, meta().getDamager(), "The thrower is the damager, who happens to have no stats"); + Seen s = reported(); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, s.origin, "A potion is guessed to be a weapon projectile"); + assertEquals(WeaponStatsMode.ADD, s.mode); + assertSame(potion, s.projectile); + assertSame(attacker, s.attacker); + assertTrue(s.exited); + assertSame(attacker, s.exitDamager); + assertTrue(s.exitProjectile, "Projectile hits cost the attacker's weapon no durability"); + } + + /** + * With a stat on the thrower's armor, the potion's 6 is no longer what counts: the armor's damage is, with the + * thrower's critical hit and vampirism. The potion is handled as a projectile that takes its shooter's stats. + */ + @Test + void splashPotion_thrownByAnAttackerWithStats_takesTheAttackersStatsInPlaceOfItsOwnDamage() { + wearStatChestplate(); + attacker.getInventory().setItemInMainHand(new ItemStack(Material.SPLASH_POTION)); + SplashPotion potion = spawn(SplashPotion.class); + launch(potion, attacker, new ItemStack(Material.SPLASH_POTION)); + + EntityDamageByEntityEvent event = + fire(hitBy(potion, DamageCause.MAGIC, DamageType.INDIRECT_MAGIC, attacker, 6)); + + // Plausibly wrong: the harming potion's 6 magical damage is gone, replaced by 5 physical x 3 + assertReadAttackerStats(event, 15D); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + /** + * Server: the cloud applies the instant effect itself, so the damager is the {@code AreaEffectCloud}, which is + * not a projectile. The cause stays {@code ENTITY_ATTACK}: Paper only turns {@code MAGIC} into a cause for + * a thrown potion or the plain {@code magic} damage type, not for {@code indirect_magic}. Divinity sees neither + * a living damager nor a projectile, so it takes the non-swing path, typed by that cause: physical, whereas + * the same potion thrown directly is magical. + */ + @Test + void areaEffectCloud_isNeverASwing_andIsPhysicalNotMagical() { + for (boolean geared : new boolean[]{false, true}) { + if (geared) wearStatChestplate(); + AreaEffectCloud cloud = spawn(AreaEffectCloud.class); + cloud.setSource(attacker); + + // Harming I, scaled by 0.5 for a cloud: (int) (0.5 * 6 + 0.5) = 3 + EntityDamageByEntityEvent event = + fire(hitBy(cloud, DamageCause.ENTITY_ATTACK, DamageType.INDIRECT_MAGIC, attacker, 3)); + + assertNull(ItemStats.getDamageByCause(DamageCause.ENTITY_ATTACK), + "Test setup: ENTITY_ATTACK is attached to no type, so the default type (physical) is used"); + assertTakenAsEnvironmental(event, Map.of("physical", 3D)); + Seen s = reported(); + assertEquals(DamageOrigin.ENVIRONMENT, s.origin, "geared=" + geared); + assertNull(s.attacker); + assertNull(s.projectile); + assertNull(s.exitDamager, "Nothing reads the weapon, so no durability and no on-hit effects"); + } + } + + // ------------------------------------------------------------------ // + // 2. Wind charges + // ------------------------------------------------------------------ // + + /** + * Server (1.21): cause {@code PROJECTILE}, damager the {@code WindCharge}, damage type {@code wind_charge}, + * 1 damage. Its explosion does no damage ({@code SimpleExplosionDamageCalculator(true, false, ...)}). A player + * throwing it holds it, so the wind charge item is the source weapon. + */ + @Test + void windCharge_thrownByAnAttackerWithNoStats_isOnePhysicalDamageReportedAsAWeaponProjectile() { + attacker.getInventory().setItemInMainHand(new ItemStack(Material.WIND_CHARGE)); + WindCharge charge = spawn(WindCharge.class); + launch(charge, attacker, new ItemStack(Material.WIND_CHARGE)); + + EntityDamageByEntityEvent event = + fire(hitBy(charge, DamageCause.PROJECTILE, DamageType.WIND_CHARGE, attacker, 1)); + + assertNoStatsApplied(event, Map.of("physical", 1D)); + assertSame(attacker, meta().getDamager()); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + assertTrue(reported().exitProjectile); + } + + @Test + void windCharge_thrownByAnAttackerWithStats_takesTheAttackersStatsInPlaceOfItsOwnDamage() { + wearStatChestplate(); + attacker.getInventory().setItemInMainHand(new ItemStack(Material.WIND_CHARGE)); + WindCharge charge = spawn(WindCharge.class); + launch(charge, attacker, new ItemStack(Material.WIND_CHARGE)); + + EntityDamageByEntityEvent event = + fire(hitBy(charge, DamageCause.PROJECTILE, DamageType.WIND_CHARGE, attacker, 1)); + + // Plausibly wrong: a hit meant to push (1 damage) becomes 15 with a critical hit and vampirism + assertReadAttackerStats(event, 15D); + } + + /** + * A breeze's charge. A zombie stands in for the breeze: Divinity only sees a {@code LivingEntity} shooter. + * With no stats on the mob, it is the event's own 1 damage as physical, attributed to the mob. + */ + @Test + void windCharge_shotByAMob_isAWeaponProjectileOfTheMob() { + BreezeWindCharge charge = spawn(BreezeWindCharge.class); + charge.setShooter(mob); + + EntityDamageByEntityEvent event = fire(hitBy(charge, DamageCause.PROJECTILE, DamageType.WIND_CHARGE, mob, 1)); + + assertEquals(Map.of("physical", 1D), damages()); + assertSame(mob, meta().getDamager()); + assertEquals(1D, event.getFinalDamage(), 1e-6); + Seen s = reported(); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, s.origin); + assertSame(mob, s.attacker); + assertSame(charge, s.projectile); + } + + /** The shipped config has a wind damage type and a wind defense, but nothing is attached to them. */ + @Test + void windDamageType_existsButNothingIsAttachedToIt() { + DamageAttribute wind = Objects.requireNonNull(ItemStats.getDamageById("wind")); + + assertTrue(wind.getAttachedDamageTypes().isEmpty()); + assertNull(ItemStats.getDamageByVanillaType("minecraft:wind_charge")); + assertNull(ItemStats.getDamageByVanillaType("wind_charge")); + assertNotNull(wind.getAttachedDefense(), "Test setup: there is a wind defense to go with it"); + } + + // ------------------------------------------------------------------ // + // 3. Fire charges and fireballs + // ------------------------------------------------------------------ // + + /** + * Server: a fireball that hits an entity deals {@code fireball} damage (6): cause {@code PROJECTILE}, damager + * the fireball. The damage type is not an explosion, so Paper does not call it one. The fireball then + * explodes, which is a second hit (below). + */ + @Test + void fireball_launchedByAnAttackerWithNoStats_isTheEventsDamageAsPhysical() { + LargeFireball ball = spawn(LargeFireball.class); + launch(ball, attacker, new ItemStack(Material.AIR)); + + EntityDamageByEntityEvent event = fire(hitBy(ball, DamageCause.PROJECTILE, DamageType.FIREBALL, attacker, 6)); + + assertNull(ItemStats.getDamageByCause(DamageCause.PROJECTILE), "Test setup: PROJECTILE is attached to no type"); + assertNoStatsApplied(event, Map.of("physical", 6D)); + assertSame(attacker, meta().getDamager()); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + /** + * Server: the explosion of a ghast's fireball. Cause {@code ENTITY_EXPLOSION} and damager the fireball (it is + * not TNT), damage type {@code player_explosion} when the fireball has an owner. Divinity treats it exactly like + * the direct hit: a projectile of its shooter. + */ + @Test + void fireballExplosion_isTreatedLikeTheDirectHit() { + wearStatChestplate(); + LargeFireball ball = spawn(LargeFireball.class); + launch(ball, attacker, new ItemStack(Material.AIR)); + + EntityDamageByEntityEvent direct = + fire(hitBy(ball, DamageCause.PROJECTILE, DamageType.FIREBALL, attacker, 6)); + // (5 from the chestplate + the event's 6, which an empty hand does not deduct) x 3 + assertReadAttackerStats(direct, 33D); + + EntityDamageByEntityEvent explosion = + fire(hitBy(ball, DamageCause.ENTITY_EXPLOSION, DamageType.PLAYER_EXPLOSION, attacker, 6)); + assertReadAttackerStats(explosion, 33D); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + /** + * A fireball from a dispenser has a block as its shooter, which is not a living entity: no damager, so it + * is handled like environmental damage and no stats are read. {@code DivinityHitEvent} still calls it a weapon + * projectile, because the projectile is set before the shooter is looked at: origin and handling disagree. + * A fireball a plugin launches from a player has the player as its shooter and is the case above. + */ + @Test + void fireball_fromADispenser_isEnvironmentLike() { + wearStatChestplate(); + LargeFireball ball = spawn(LargeFireball.class); + ball.setShooter(mock(BlockProjectileSource.class)); + + EntityDamageByEntityEvent event = fire(hitBy(ball, DamageCause.PROJECTILE, DamageType.FIREBALL, null, 6)); + + assertTakenAsEnvironmental(event, Map.of("physical", 6D)); + Seen s = reported(); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, s.origin, "Plausibly wrong: there is no weapon and no attacker"); + assertSame(ball, s.projectile); + assertNull(s.attacker); + assertNull(s.exitDamager); + } + + /** A blaze's small fireball: a mob projectile, 5 damage, attributed to the blaze. */ + @Test + void smallFireball_shotByAMob_isAWeaponProjectileOfTheMob() { + SmallFireball ball = spawn(SmallFireball.class); + ball.setShooter(mob); + + EntityDamageByEntityEvent event = fire(hitBy(ball, DamageCause.PROJECTILE, DamageType.FIREBALL, mob, 5)); + + assertEquals(Map.of("physical", 5D), damages()); + assertSame(mob, meta().getDamager()); + assertEquals(5D, event.getFinalDamage(), 1e-6); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + // ------------------------------------------------------------------ // + // 4. Other projectiles + // ------------------------------------------------------------------ // + + /** + * Server: a snowball and an egg deal 0 damage (a snowball 3 to a blaze), cause {@code PROJECTILE}, damage type + * {@code thrown}, and the event fires for a player too (Paper removes the vanilla "0 damage, no hit" return). + * Divinity cancels a hit whose total is below 0.001, so the push the vanilla hit would give is believed to be + * lost. That last part is not testable here and is on the server checklist. + */ + @Test + void snowballAndEgg_withNoStats_areCancelledAsZeroDamage() { + attacker.getInventory().setItemInMainHand(new ItemStack(Material.SNOWBALL)); + Snowball snowball = spawn(Snowball.class); + launch(snowball, attacker, new ItemStack(Material.SNOWBALL)); + EntityDamageByEntityEvent snow = fire(hitBy(snowball, DamageCause.PROJECTILE, DamageType.THROWN, attacker, 0)); + + assertTrue(snow.isCancelled(), "Plausibly wrong: the knockback-only hit is cancelled"); + assertEquals(Map.of("physical", 0D), damages()); + Seen s = reported(); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, s.origin); + assertFalse(s.exited, "A cancelled hit does not reach Exit"); + + Egg egg = spawn(Egg.class); + launch(egg, attacker, new ItemStack(Material.EGG)); + assertTrue(fire(hitBy(egg, DamageCause.PROJECTILE, DamageType.THROWN, attacker, 0)).isCancelled()); + } + + @Test + void snowballAndEgg_thrownByAnAttackerWithStats_dealRealDamageWithOnHitEffects() { + wearStatChestplate(); + attacker.getInventory().setItemInMainHand(new ItemStack(Material.SNOWBALL)); + Snowball snowball = spawn(Snowball.class); + launch(snowball, attacker, new ItemStack(Material.SNOWBALL)); + + EntityDamageByEntityEvent event = + fire(hitBy(snowball, DamageCause.PROJECTILE, DamageType.THROWN, attacker, 0)); + + // Plausibly wrong: a snowball that pushes and does nothing else now hits for 15, critically, and heals + assertReadAttackerStats(event, 15D); + assertFalse(event.isCancelled()); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + /** Llama spit (1 damage) and a shulker bullet (4): projectiles of a mob shooter, as any arrow is. */ + @Test + void llamaSpitAndShulkerBullet_shotByAMob_areWeaponProjectilesOfTheMob() { + LlamaSpit spit = spawn(LlamaSpit.class); + spit.setShooter(mob); + EntityDamageByEntityEvent spat = fire(hitBy(spit, DamageCause.PROJECTILE, DamageType.SPIT, mob, 1)); + + assertEquals(Map.of("physical", 1D), damages()); + assertSame(mob, meta().getDamager()); + assertEquals(1D, spat.getFinalDamage(), 1e-6); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + + ShulkerBullet bullet = spawn(ShulkerBullet.class); + bullet.setShooter(mob); + EntityDamageByEntityEvent shot = fire(hitBy(bullet, DamageCause.PROJECTILE, DamageType.MOB_PROJECTILE, mob, 4)); + + assertEquals(Map.of("physical", 4D), damages()); + assertSame(mob, meta().getDamager()); + assertEquals(4D, shot.getFinalDamage(), 1e-6); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + /** + * Server: fangs with an owner deal {@code indirect_magic} (6) with the fangs as direct entity, so the damager + * is the {@code EvokerFangs} and the cause {@code ENTITY_ATTACK}. The fangs are neither a living entity nor a + * projectile, so this is the non-swing path: physical, no damager, no on-hit effects. Fangs without an owner + * deal plain {@code magic}, whose cause is {@code MAGIC}: magical. + */ + @Test + void evokerFangs_areNeverASwing_andTheirTypeDependsOnWhetherTheyHaveAnOwner() { + wearStatChestplate(); + EvokerFangs fangs = spawn(EvokerFangs.class); + + EntityDamageByEntityEvent owned = + fire(hitBy(fangs, DamageCause.ENTITY_ATTACK, DamageType.INDIRECT_MAGIC, mob, 6)); + assertTakenAsEnvironmental(owned, Map.of("physical", 6D)); + Seen s = reported(); + assertEquals(DamageOrigin.ENVIRONMENT, s.origin); + assertNull(s.attacker, "The evoker is not Divinity's attacker"); + assertNull(s.exitDamager); + + EntityDamageByEntityEvent unowned = fire(hitBy(fangs, DamageCause.MAGIC, DamageType.MAGIC, null, 6)); + assertTakenAsEnvironmental(unowned, Map.of("magical", 6D)); + assertEquals(DamageOrigin.ENVIRONMENT, reported().origin); + } + + /** + * Server: a thrown trident deals {@code trident} damage (8): cause {@code PROJECTILE}, damager the trident. + * Unlike the others it is a weapon, with Divinity stats on the item: {@code ProjectileStats} reads them from + * the trident entity's item. This is a legitimate weapon projectile and is pinned to show what the stats do. + *

+ * MockBukkit's {@code Trident} cannot be used (its item and shooter calls are not implemented), so this is a + * Mockito stand-in that only answers what Divinity asks of a projectile. + */ + @Test + void trident_thrownByAnAttacker_usesTheTridentItemsStats() { + ItemStack item = new ItemStack(Material.TRIDENT); + Objects.requireNonNull(ItemStats.getDamageById("physical")) + .add(item, new studio.magemonkey.divinity.stats.bonus.StatBonus(new double[]{20}, false, null), -1); + attacker.getInventory().setItemInMainHand(item); + Trident trident = mock(Trident.class); + UUID id = UUID.randomUUID(); + when(trident.getUniqueId()).thenReturn(id); + when(trident.getType()).thenReturn(EntityType.TRIDENT); + when(trident.getShooter()).thenReturn(attacker); + when(trident.getItem()).thenReturn(item); + when(trident.getMetadata(anyString())).thenReturn(List.of()); + when(trident.getLocation()).thenReturn(victim.getLocation()); + when(trident.getWorld()).thenReturn(victim.getWorld()); + + EntityDamageByEntityEvent event = fire(new EntityDamageByEntityEvent(trident, + victim, + DamageCause.PROJECTILE, + modifiers(8), + functions(modifiers(8)))); + + assertEquals(Map.of("physical", 20D), damages()); + assertSame(attacker, meta().getDamager()); + assertEquals(Material.TRIDENT, meta().getWeapon().getType()); + assertEquals(20D, event.getFinalDamage(), 1e-6); + assertEquals(DamageOrigin.WEAPON_PROJECTILE, reported().origin); + } + + // ------------------------------------------------------------------ // + // 5. True damage + // ------------------------------------------------------------------ // + + /** + * There is no flag for it on {@link DamageRequest}: nothing in its builder says to skip defenses. If Codex adds + * one, this fails, which is the cue to decide what Divinity does with it. + */ + @Test + void damageRequest_hasNoTrueDamageOrBypassDefenseFlag() { + List names = new ArrayList<>(); + for (Method method : DamageRequest.Builder.class.getMethods()) names.add(method.getName().toLowerCase()); + for (Method method : DamageRequest.class.getMethods()) names.add(method.getName().toLowerCase()); + + for (String name : names) { + assertFalse(name.contains("true") || name.contains("bypass") || name.contains("pierce") + || name.contains("ignoredefense") || name.contains("unblockable"), + "DamageRequest gained '" + name + "': decide what Divinity does with it (COMBAT_OPEN_QUESTIONS.md)"); + } + } + + /** + * The closest thing Divinity has is a damage type with no defense attached: {@code _vanilla_generic}, which the + * shipped config attaches to void, starvation, suffocation, drowning, suicide and Thorns. The defense formula + * is skipped for it. It is not truly true damage: PvP and PvE modifiers, enchantment protection, the victim's + * dodge and the vanilla invulnerability reduction still apply. + */ + @Test + void genericDamageType_hasNoDefenseAttached_soDefensesDoNotReduceIt() { + victim.getInventory().setChestplate(armor(Map.of("physical", 50D))); + refresh(victim); + DamageAttribute generic = Objects.requireNonNull(ItemStats.getDamageById("_vanilla_generic")); + assertNull(generic.getAttachedDefense()); + for (DamageCause cause : new DamageCause[]{DamageCause.VOID, DamageCause.STARVATION, DamageCause.SUFFOCATION, + DamageCause.DROWNING, DamageCause.SUICIDE}) { + assertSame(generic, ItemStats.getDamageByCause(cause), cause.name()); + } + + victim.damage(4); // CUSTOM environmental damage: the default type, physical, which 50 defense reduces + double reduced = damagesOf(victim).get("physical"); + assertTrue(reduced < 4D, "Physical defense applies to physical damage"); + + server.getPluginManager().callEvent(new org.bukkit.event.entity.EntityDamageEvent(victim, + DamageCause.VOID, + modifiers(4), + functions(modifiers(4)))); + assertEquals(Map.of("_vanilla_generic", 4D), rounded(damagesOf(victim)), "Not reduced by 50 physical defense"); + assertNull(meta().getRequest(), "A vanilla void hit is not described by a request"); + } + + /** + * Typed damage dealt through Codex ({@code DamageTypeProvider.dealDamage}, which is a request with + * {@code REPLACE}) in the generic type is the only way to ask Divinity for "damage that defenses do not + * reduce": described by a request, unreduced. Nothing in the request says so; it is a side effect of the + * type's missing defense. + */ + @Test + void dealtGenericType_isDescribedByARequest_andNotReducedByDefense() { + victim.getInventory().setChestplate(armor(Map.of("physical", 50D))); + refresh(attacker); + refresh(victim); + + boolean handled = DamageRegistry.dealDamage(victim, 4, "DIVINITY__vanilla_generic", attacker); + + assertTrue(handled); + assertEquals(Map.of("_vanilla_generic", 4D), rounded(damagesOf(victim))); + DamageRequest request = Objects.requireNonNull(meta().getRequest()); + assertEquals(DamageOrigin.EXTERNAL, request.getOrigin()); + assertEquals(WeaponStatsMode.REPLACE, request.getWeaponStats()); + } + + /** + * The "direct damage" part of the formula, which was meant to skip defenses, is fixed at 0%: the stat that fed + * it is commented out and the modifier is the constant 0. + */ + @Test + void directDamage_isNeverSet() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + + fire(meleeEvent(attacker, victim, VANILLA_SWORD_DAMAGE)); + + assertEquals(0D, meta().getDirectModifier()); + assertThrows(IllegalArgumentException.class, () -> TypedStat.Type.valueOf("DIRECT_DAMAGE")); + } +}