diff --git a/doc/COMBAT_RESTRUCTURE_NOTES.md b/doc/COMBAT_RESTRUCTURE_NOTES.md index e68501e1..145d2d1a 100644 --- a/doc/COMBAT_RESTRUCTURE_NOTES.md +++ b/doc/COMBAT_RESTRUCTURE_NOTES.md @@ -22,7 +22,8 @@ Update this file in the same pull request whenever something here stops being tr | 1. Extract the calculator (1.1) and the vanilla modifier bridge (1.2) | Done | | 2. The shared contract | Done with 2.2c, which adds the `attached-damage-types` key | | 3. Fabled migration | Next | -| 4 and 5 | Not started | +| 4.2 Stat snapshots | Done, in this pull request (#372). 4.1 and 4.3 are not started; 4.2b is next after them | +| 4 (rest) and 5 | Not started | ## Rules for every pull request @@ -153,6 +154,64 @@ 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. +## Stat snapshots (4.2) + +Read this before you touch `EntityStats`, `StatSnapshot`, `ProjectileStats` or the equipment handlers in +`EntityManager`. + +- **What is cached and what is not.** `EntityStats` always cached the equipment list (`inventory`) and the set + and class bonus functions (`bonuses`), and refreshed both in `updateAll()`. A `StatSnapshot` sits on top of + those and is filled in on demand: each damage type's minimum and maximum, each defense, each item stat, each + enchantment protection factor. It stores the value *before* the things that belong to the moment of the hit, + which are applied on every read: the roll (`Rnd.getDouble(min, max)`), the biome, active effects + (`AdjustStatEffect`, which has charges and runs out by itself), and an item stat's cap. The Codex registries + (`scaleValuesWithCore`), attack power, the `custom-cooldown` metadata and the attacker's `ATTACK_DAMAGE` + attribute are read at the hit too. Do not move any of these into the snapshot: effects and rolls would then + need invalidation that cannot be done reliably. +- **Ranges are summed over items, then rolled once.** `RANGE_FULL` adds every item's minimum and maximum before + anything is rolled, so a snapshot holding `{min, max}` per type gives exactly the old distribution. The same + seed gives the same rolls (`EntityStatSnapshotTest#rolls_*`). +- **Anything new that stats read needs an invalidation or a check.** If you add an input to what + `DamageAttribute.get`, `DefenseAttribute.get`, `SimpleStat.get` or `getBonuses` read, either make the code that + changes it call `EntityStats.invalidateSnapshot()` / `updateAll()`, or compare it on each read the way the + vanilla armor and toughness attributes are (`EntityStats#getDefenseValues`, `#getItemStatValue`). The table of + triggers is in the description of the pull request that introduced this. +- **`updateAll()` forces, `refreshAfterHit()` compares.** Every completed hit asks for both fighters' stats to be + read again on the next tick (`EntityManager#onStatsDamagePacketDuplicator`). If that dropped the snapshot, it + would never survive until the next hit. `refreshAfterHit()` drops it only when the equipment or the bonus maps + differ from what the snapshot was built from; wear (vanilla damage and Divinity's durability) does not count. + Callers that change something that is not equipment (a class, a profile, a set) call `updateAll()`. +- **A snapshot copies the items it was built from,** so a stack changed in place is still seen as a change. +- **Profile buffs.** `UserProfile` counts every change to its buffs (`getBuffRevision`) and the snapshot compares + it. The buff sets are handed out for editing: code that edits them directly must call `markBuffsChanged()`, + as `BuffCommand` does. +- **Projectiles.** `VanillaWrapperListener#onProjectileLaunchSnapshot` runs last (MONITOR) on + `DivinityProjectileLaunchEvent`. For a projectile that can deal damage (`ProjectileStats#canDealDamage`: + `AbstractArrow` plus the damaging kinds in `AmmoAttribute.Type`) it stores a frozen snapshot with the weapon in + place of the main hand, the custom arrow's bonus, the active effects, the shooter's biome and the shooter's + UUID. At impact it is ignored if the projectile's shooter is someone else. Effects are captured *without* + using their charges; the hit that lands uses them (`StatSnapshot#rollDamage`, `#itemStats`), so a miss spends + none. The snapshots are kept in `ProjectileStats` by projectile UUID, not as entity metadata: metadata is only + cleared when someone removes it. `EntityStatsTask` sweeps every 100 ticks: an entry goes when the projectile is + dead or cannot be found in a chunk that is loaded, never because its chunk is unloaded, and in any case ten + minutes after launch. A plugin reload clears them (`Divinity#disable`). A projectile with no snapshot is read + at impact, as before. +- **Config.** `performance.entity-stats.snapshot-max-age` (ticks, default 20) bounds how long a snapshot is + reused when nothing announced a change. 0 turns the cache off (nothing is kept and no items are copied), which + is the quickest way to tell whether a stat bug is the cache. +- **Benchmark.** `CombatBenchmark` is off unless asked for: + `mvn -Dtest=CombatBenchmark -Dcombat.benchmark=true -Dcombat.benchmark.out= test`. MockBukkit parses items + slowly, so a run takes about eleven minutes without the cache. To get "before" numbers for a change, check out + the base commit in a worktree and copy the benchmark in. +- **Testing traps found on the way.** + - Joining a player queues a forced refresh for the next tick. In a test that ticks the scheduler, that refresh + drops the snapshot you are looking at. Tick once in `@BeforeEach`, after adding the players. + - `DivinityProjectileLaunchEvent` cannot be constructed under MockBukkit: its constructor calls + `Projectile#setBounce`, which MockBukkit refuses. Build it with Mockito (`CALLS_REAL_METHODS` and stubs for + the getters) and set the weapon and power on the projectile by hand, as the constructor would. + - `PlayerMock` has no armor or toughness attribute until you call `registerAttribute`. + - A seeded test needs `Rnd.rnd.setSeed(...)`. `Rnd` has one shared generator, so re-seed before each sequence. + ## Still open - Whether Fabled's `PhysicalDamageEvent` runs before Divinity's calculation is inferred from plugin load @@ -164,3 +223,8 @@ lift the cap in the test and restore it. which it never is in the tests. So "a throwaway event does not take a damage request away from the real hit" is true by the order of the code in `VanillaWrapperListener`, not by a test. - Environmental damage is not offered to Fabled shields. +- Level changes made by another plugin (Fabled, for example) have no event. An item's level requirement is + decided when the equipment list is rebuilt, as it was before snapshots, so such an item starts counting at the + next refresh. Nothing about that changed in 4.2. +- A projectile hit uses the charges of effects the shooter had at launch, if the effect still exists. An effect + that has gone by impact still adjusts the hit (it was fired with it) and is not charged. diff --git a/doc/COMBAT_RESTRUCTURE_PLAN.md b/doc/COMBAT_RESTRUCTURE_PLAN.md index d387d6b6..ddf3623d 100644 --- a/doc/COMBAT_RESTRUCTURE_PLAN.md +++ b/doc/COMBAT_RESTRUCTURE_PLAN.md @@ -163,6 +163,11 @@ migrated automatically. Cache each entity's minimum and maximum per damage type, invalidate on equipment or effect change, and roll at hit time. Projectiles snapshot the shooter's stats at launch. +As built in 4.2: the snapshot is the part of a stat that gear, sets, classes and profile buffs decide. The roll, +the biome and active effects are applied at the hit and are not cached, because effects carry charges and run +out on their own. A snapshot is dropped by the existing refresh paths, compared after a hit, and bounded by +a maximum age for changes nothing announces. See the notes file for the rules. + ### 6. Improvements on Minecraft 1.20.4 and newer (Codex) Behind one Codex interface that does nothing on older versions: @@ -248,7 +253,7 @@ Rules for every pull request: | PR | Repo | Scope | Breaking | |---|---|---|---| | 4.1 | Divinity | Formulas move to `combat.yml` | Config layout | -| 4.2 | Divinity | Stat snapshots | Projectile timing | +| 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 | diff --git a/src/main/java/studio/magemonkey/divinity/Divinity.java b/src/main/java/studio/magemonkey/divinity/Divinity.java index 9f0df133..9c36d58e 100644 --- a/src/main/java/studio/magemonkey/divinity/Divinity.java +++ b/src/main/java/studio/magemonkey/divinity/Divinity.java @@ -35,6 +35,7 @@ import studio.magemonkey.divinity.modules.ModuleCache; import studio.magemonkey.divinity.nms.engine.PMSManager; 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.requirements.ItemRequirements; import studio.magemonkey.divinity.utils.DivinityProvider; @@ -181,6 +182,8 @@ public void disable() { this.pms.shutdown(); ItemStats.clear(); + // Projectiles in flight hold stats keyed by the stat objects that are being thrown away + ProjectileStats.clear(); ItemRequirements.clear(); List toRemove = new ArrayList<>(EntityStats.getAll()); toRemove.forEach(EntityStats::purge); diff --git a/src/main/java/studio/magemonkey/divinity/command/BuffCommand.java b/src/main/java/studio/magemonkey/divinity/command/BuffCommand.java index 7a9d5515..028d3a42 100644 --- a/src/main/java/studio/magemonkey/divinity/command/BuffCommand.java +++ b/src/main/java/studio/magemonkey/divinity/command/BuffCommand.java @@ -136,6 +136,7 @@ public void perform(@NotNull CommandSender sender, @NotNull String label, @NotNu if (replace) userBuffs.removeIf(buff -> buff.getStatId().equals(statId)); SavedBuff buff = new SavedBuff(stat, amount, isModifier, seconds); userBuffs.add(buff); + user.getActiveProfile().markBuffsChanged(); plugin.lang().Command_Buff_Done .replace("%time%", TimeUT.formatTime(seconds * 1000L)) diff --git a/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java b/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java index 4c0e9a78..84a3f4ac 100644 --- a/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java +++ b/src/main/java/studio/magemonkey/divinity/config/EngineCfg.java @@ -57,6 +57,8 @@ public EngineCfg(@NotNull Divinity plugin) throws InvalidConfigurationException public static double COMBAT_SHIELD_BLOCK_BONUS_DAMAGE_MOD; public static int COMBAT_SHIELD_BLOCK_COOLDOWN; public static boolean LEGACY_COMBAT; + /** Longest time, in ticks, that what was worked out from an entity's gear is reused. 0 turns the cache off. */ + public static int PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 20; public static boolean COMBAT_DISABLE_VANILLA_SWEEP; public static boolean COMBAT_REDUCE_PLAYER_HEALTH_BAR; public static boolean COMBAT_FISHING_HOOK_DO_DAMAGE; @@ -177,6 +179,8 @@ public void setup() { path = "performance."; path = "performance.entity-stats."; + cfg.addMissing(path + "snapshot-max-age", 20); + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = cfg.getInt(path + "snapshot-max-age", 20); // A T T R I B U T E S // path = "attributes."; diff --git a/src/main/java/studio/magemonkey/divinity/data/api/UserProfile.java b/src/main/java/studio/magemonkey/divinity/data/api/UserProfile.java index 3afa415f..6c558a67 100644 --- a/src/main/java/studio/magemonkey/divinity/data/api/UserProfile.java +++ b/src/main/java/studio/magemonkey/divinity/data/api/UserProfile.java @@ -26,6 +26,8 @@ public class UserProfile { private final Set buffDamage; private final Set buffDefense; private final Set buffStats; + /** Counts every change to the buffs, so a cached stat can tell its buffs are no longer the current ones. */ + private volatile int buffRevision; private UserEntityNamesMode namesMode; @Setter @@ -192,16 +194,51 @@ public void removeStatBuff(@NotNull String statId) { } private void validateBuffs(@NotNull Set list) { - list.removeIf(buff -> buff.isExpired()); + if (list.removeIf(buff -> buff.isExpired())) this.markBuffsChanged(); } private void addBuff(@NotNull SavedBuff buff, @NotNull Set to) { this.removeBuff(buff.getStatId(), to); to.add(buff); + this.markBuffsChanged(); } private void removeBuff(@NotNull String statId, @NotNull Set from) { - from.removeIf(buff -> buff.getStatId().equalsIgnoreCase(statId)); + if (from.removeIf(buff -> buff.getStatId().equalsIgnoreCase(statId))) this.markBuffsChanged(); + } + + /** + * A number that is different every time buffs are added, replaced or removed, expired ones included. + */ + public int getBuffRevision() { + return this.buffRevision; + } + + /** + * Tells whoever caches stats that the buffs changed. The buff sets are handed out for editing, so code + * that edits them directly has to call this. + */ + public void markBuffsChanged() { + this.buffRevision++; + } + + /** + * When the first of the buffs that are active now runs out, in epoch milliseconds, or + * {@link Long#MAX_VALUE} if none does. + */ + public long getNextBuffExpiry() { + long next = Long.MAX_VALUE; + try { + for (Set buffs : List.of(this.getDamageBuffs(), this.getDefenseBuffs(), this.getItemStatBuffs())) { + for (SavedBuff buff : buffs) { + next = Math.min(next, buff.getExpireTime()); + } + } + } catch (java.util.ConcurrentModificationException e) { + // Edited on another thread while we looked: say it expires now, so nothing is cached from it + return Long.MIN_VALUE; + } + return next; } public void setClassData(@Nullable UserClassData cData) { diff --git a/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java b/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java index 72a9710c..01c1c95b 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java +++ b/src/main/java/studio/magemonkey/divinity/manager/EntityManager.java @@ -147,17 +147,34 @@ public void onPickup(EntityPickupItemEvent e) { } private final void pushToUpdate(@NotNull LivingEntity entity, double time) { + this.pushToUpdate(entity, time, true); + } + + /** + * @param changed whether something is known to have changed, as it has when equipment or the held item + * did. After a hit nothing is known: the entity's stats are read again and its snapshot is + * kept unless the equipment turns out to be different. + */ + private final void pushToUpdate(@NotNull LivingEntity entity, double time, boolean changed) { if(EngineCfg.VANILLA_ONLY_ENTITY_STATS) return; EntityEquipment equip = new EntityEquipmentSnapshot(entity); previousEquipment.put(entity.getUniqueId(), equip); + Runnable refresh = () -> { + EntityStats stats = EntityStats.get(entity); + if (changed) { + stats.updateAll(); + } else { + stats.refreshAfterHit(); + } + }; if (time <= 0D) { - plugin.getServer().getScheduler().runTask(plugin, () -> EntityStats.get(entity).updateAll()); + plugin.getServer().getScheduler().runTask(plugin, refresh); return; } new BukkitRunnable() { @Override public void run() { - EntityStats.get(entity).updateAll(); + refresh.run(); } }.runTask(Divinity.getInstance()); } @@ -195,12 +212,12 @@ public void onStatsSprintPacketDuplicator(PlayerToggleSprintEvent e) { public void onStatsDamagePacketDuplicator(DivinityDamageEvent.Exit e) { LivingEntity victim = e.getVictim(); this.addDuplicatorFixer(victim); - this.pushToUpdate(victim, 1.5D); + this.pushToUpdate(victim, 1.5D, false); LivingEntity damager = e.getDamager(); if (damager != null) { this.addDuplicatorFixer(damager); - this.pushToUpdate(damager, 1.5D); + this.pushToUpdate(damager, 1.5D, false); } } diff --git a/src/main/java/studio/magemonkey/divinity/manager/effects/main/AdjustStatEffect.java b/src/main/java/studio/magemonkey/divinity/manager/effects/main/AdjustStatEffect.java index 1df925fd..3158ebc5 100644 --- a/src/main/java/studio/magemonkey/divinity/manager/effects/main/AdjustStatEffect.java +++ b/src/main/java/studio/magemonkey/divinity/manager/effects/main/AdjustStatEffect.java @@ -26,6 +26,7 @@ private AdjustStatEffect(@NotNull Builder builder) { @Nullable public DoubleUnaryOperator getAdjust(@NotNull ItemLoreStat stat, boolean safe) { + if (this.functions == null) return null; // Cleared DoubleUnaryOperator operator = this.functions.get(stat); if (operator == null) return null; @@ -49,7 +50,7 @@ public Set> getAdjustedStats() { } public boolean isAdjusted(@NotNull ItemLoreStat stat) { - return this.functions.containsKey(stat); + return this.functions != null && this.functions.containsKey(stat); } @Override 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 4001cb7a..dd9c21e9 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 @@ -44,6 +44,7 @@ import studio.magemonkey.divinity.modules.list.itemgenerator.ItemGeneratorManager; import studio.magemonkey.divinity.stats.EntityStats; import studio.magemonkey.divinity.stats.ProjectileStats; +import studio.magemonkey.divinity.stats.StatSnapshot; import studio.magemonkey.divinity.stats.items.ItemStats; import studio.magemonkey.divinity.stats.items.attributes.AmmoAttribute; import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; @@ -144,6 +145,38 @@ public void onVanillaProjectLaunch(ProjectileLaunchEvent e) { } } + /** + * Records what the shooter's stats are at the moment a projectile leaves, so the hit is worked out from + * those and not from whatever the shooter wears when it lands. This runs last of all the launch handlers, + * so the weapon, the power and the custom arrow have been put on the projectile by then. + *

+ * A projectile that is not launched through {@link DivinityProjectileLaunchEvent} gets no snapshot and + * is worked out at impact, as it always was. + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onProjectileLaunchSnapshot(DivinityProjectileLaunchEvent e) { + if (EngineCfg.VANILLA_ONLY_DAMAGE_HANDLING) return; + if (!(e.getProjectile() instanceof Projectile)) return; + + Projectile pj = (Projectile) e.getProjectile(); + // A pearl, a snowball or a fishing hook is not fired for its damage: leave it to be read as it always was + if (!ProjectileStats.canDealDamage(pj)) return; + + QArrow arrow = null; + int level = 0; + ArrowManager arr = plugin.getModuleCache().getArrowManager(); + if (arr != null) { + arrow = arr.getArrow(pj); + level = arr.getArrowLevel(pj); + } + + StatSnapshot snapshot = EntityStats.get(e.getShooter()) + .snapshotForLaunch(ProjectileStats.getSrcWeapon(pj), arrow, level); + if (snapshot != null) { + ProjectileStats.setSnapshot(pj, snapshot); + } + } + /** * Applies a request's scale and bonus to the damage of the attacker's weapon. A type that ends at 0 or * below is dropped, as a weapon damage type of 0 always is. @@ -198,8 +231,9 @@ public void onVanillaDamage(EntityDamageEvent e) { double damageStart = e.getDamage(); - ItemStack weapon = null; - Projectile projectile = null; + ItemStack weapon = null; + Projectile projectile = null; + StatSnapshot launched = null; LivingEntity damager = null; LivingEntity victim = (LivingEntity) eVictim; @@ -262,6 +296,11 @@ public void onVanillaDamage(EntityDamageEvent e) { statsDamager = EntityStats.get(damager); statsDamager.setLastDamageMeta(meta); weapon = ProjectileStats.getSrcWeapon(projectile); + launched = ProjectileStats.getSnapshot(projectile); + // A projectile that has changed hands since it was launched is not the shooter's snapshot's + if (launched != null && !launched.isShooter(damager.getUniqueId())) { + launched = null; + } // Applying custom arrow object to damage meta, // if it's present, to use additional stats from it. @@ -306,7 +345,9 @@ public void onVanillaDamage(EntityDamageEvent e) { // Pre-cache damager damage types. if (statsDamager != null && !skillShouldIgnore && isFullDamage) { ItemStack statWeapon = projectile != null ? weapon : null; - damages.putAll(statsDamager.getDamageTypes(false, statWeapon)); + damages.putAll(launched != null + ? launched.rollDamage() + : statsDamager.getDamageTypes(false, statWeapon)); if (request != null && request.adjustsWeaponDamage()) { adjustWeaponDamage(damages, request); } @@ -327,7 +368,7 @@ public void onVanillaDamage(EntityDamageEvent e) { if (statsDamager != null) { ItemStack statWeapon = projectile != null ? weapon : null; - stats.putAll(statsDamager.getItemStats(false, statWeapon)); + stats.putAll(launched != null ? launched.itemStats() : statsDamager.getItemStats(false, statWeapon)); } defenses.putAll(statsVictim.getDefenseTypes(false)); diff --git a/src/main/java/studio/magemonkey/divinity/stats/EntityStats.java b/src/main/java/studio/magemonkey/divinity/stats/EntityStats.java index 06f64831..a02bad12 100644 --- a/src/main/java/studio/magemonkey/divinity/stats/EntityStats.java +++ b/src/main/java/studio/magemonkey/divinity/stats/EntityStats.java @@ -57,6 +57,7 @@ import java.util.Map.Entry; import java.util.function.BiFunction; import java.util.function.DoubleUnaryOperator; +import java.util.function.LongSupplier; import java.util.stream.Collectors; import static org.bukkit.attribute.AttributeModifier.Operation; @@ -66,6 +67,18 @@ public class EntityStats { private static final SimpleStat.Type[] ATTRIBUTE_BONUS_STATS; private static final NBTAttribute[] ATTRIBUTE_BONUS_NBT; private static final double DEFAULT_ATTACK_POWER = 1D; + private static final long MILLIS_PER_TICK = 50L; + + /** Where snapshots read the time from. Tests replace it. */ + private static volatile LongSupplier clock = System::currentTimeMillis; + + static void setClock(@NotNull LongSupplier supplier) { + clock = supplier; + } + + static void resetClock() { + clock = System::currentTimeMillis; + } static { STATS = Collections.synchronizedMap(new HashMap<>()); @@ -97,6 +110,14 @@ public class EntityStats { private QArrow arrowBonus; private int arrowLevel; + /** + * What was worked out from this entity's gear, or null when nothing is cached. Everything that can change + * it ends up in {@link #invalidateSnapshot()}, or is checked each time it is used; see {@link StatSnapshot}. + */ + private volatile StatSnapshot snapshot; + /** The bonus maps (sets, classes) behind {@link #bonuses}, so a refresh can tell whether they changed. */ + private final List bonusMaps = new ArrayList<>(); + private double atkPower; private boolean aoeIgnore; @@ -134,6 +155,25 @@ public static void purge(@NotNull LivingEntity entity) { STATS.remove(uuid); } + /** + * Whether stats are being kept for the entity. Stats, and the snapshot on them, are released when a + * player quits, when an entity dies and when an entity is no longer valid (see {@link #getAll()}). + */ + public static boolean isTracked(@NotNull LivingEntity entity) { + return STATS.containsKey(entity.getUniqueId().toString()); + } + + /** + * Drops every entity's snapshot. For changes that affect everyone, such as a reload of the stat config. + */ + public static void invalidateAllSnapshots() { + List all; + synchronized (STATS) { + all = new ArrayList<>(STATS.values()); + } + all.forEach(EntityStats::invalidateSnapshot); + } + @NotNull public synchronized static Collection getAll() { STATS.values().removeIf(stats -> !stats.entity.isValid() || stats.entity.isDead()); @@ -190,10 +230,13 @@ public void handleDeath() { this.inventory.clear(); this.permaEffects.clear(); this.bonuses.clear(); + this.bonusMaps.clear(); this.damageMeta = null; this.aoeIgnore = false; + this.invalidateSnapshot(); this.updateBonusAttributes(); } else { + this.invalidateSnapshot(); this.purge(); } } @@ -445,7 +488,13 @@ private void updateInventory() { } } + /** + * Reads the entity's equipment and bonuses again, and drops the snapshot of its stats whether or not anything + * looks different. This is what to call when something that is not equipment may have changed: a class, + * a profile, a set. + */ public void updateAll() { + this.invalidateSnapshot(); if(EngineCfg.VANILLA_ONLY_ENTITY_STATS) return; if (!EngineCfg.ATTRIBUTES_EFFECTIVE_FOR_MOBS && !this.isPlayer()) { return; @@ -455,28 +504,67 @@ public void updateAll() { this.updateBonus(); } + /** + * Reads the entity's equipment and bonuses again after a hit, and keeps the snapshot if they are what it + * was built from. A hit wears gear down and changes nothing else, and it asks for this on the next tick for + * both fighters, so dropping the snapshot here every time would leave it never used between two hits. + *

+ * A change that has no event of its own, such as a plugin setting a piece of armor, is still seen here: + * the equipment is compared with the copies the snapshot was built from. + */ + public void refreshAfterHit() { + if(EngineCfg.VANILLA_ONLY_ENTITY_STATS) return; + if (!EngineCfg.ATTRIBUTES_EFFECTIVE_FOR_MOBS && !this.isPlayer()) { + return; + } + + this.updateInventory(); + this.updateBonus(); + + StatSnapshot current = this.snapshot; + if (current != null && !current.matches(this.inventory, this.bonusMaps)) { + this.snapshot = null; + } + } + + /** + * Forgets what was worked out from this entity's gear, so the next read does it again. + */ + public void invalidateSnapshot() { + this.snapshot = null; + } + + boolean hasSnapshot() { + return this.snapshot != null; + } + private void addBonus(@NotNull BonusMap bMap) { + this.bonusMaps.add(bMap); bMap.getBonuses() .forEach((stat, func) -> this.bonuses.computeIfAbsent(stat, list -> new ArrayList<>()).add(func)); } @NotNull public List> getBonuses(@NotNull ItemLoreStat stat) { + return this.getBonuses(stat, this.arrowBonus, this.arrowLevel); + } + + @NotNull + private List> getBonuses(@NotNull ItemLoreStat stat, + @Nullable QArrow arrow, + int arrowLevel) { List> bonuses = new ArrayList<>(this.bonuses.computeIfAbsent(stat, list -> new ArrayList<>())); - BonusMap arrowBonus = this.arrowBonus != null ? this.arrowBonus.getBonusMap(this.arrowLevel) : null; + BonusMap arrowBonus = arrow != null ? arrow.getBonusMap(arrowLevel) : null; if (arrowBonus != null) { BiFunction arrowBif = arrowBonus.getBonus(stat); if (arrowBif != null) bonuses.add(arrowBif); } - if (this.isPlayer() && !this.isNPC()) { - DivinityUser user = plugin.getUserManager().getOrLoadUser(this.player); - if (user != null) { - UserProfile prof = user.getActiveProfile(); - bonuses.add(prof.getBuff(stat)); - } + UserProfile prof = this.getActiveProfile(); + if (prof != null) { + bonuses.add(prof.getBuff(stat)); } return bonuses; @@ -484,6 +572,7 @@ public List> getBonuses(@NotNull ItemLoreSta private void updateBonus() { this.bonuses.clear(); + this.bonusMaps.clear(); // Update sets bonuses SetManager set = plugin.getModuleCache().getSetManager(); @@ -656,7 +745,8 @@ public double getDefenseByType(@NotNull DefenseAttribute type) { return this.getDefenseTypes(true).getOrDefault(type, 0D); } - // Damage not cached due to broke of range values + // What is cached is each damage type's minimum and maximum. The roll is made on every call, so ranges + // keep their distribution. @NotNull public Map getDamageTypes(boolean safe) { return this.getDamageTypes(safe, null); @@ -668,9 +758,38 @@ public Map getDamageTypes(boolean safe, @Nullable ItemS return Collections.emptyMap(); } - Map map = new HashMap<>(); - Biome bio = this.entity.getLocation().getBlock().getBiome(); - List equip = this.getEquipmentForStats(mainHandOverride); + Biome bio = this.entity.getLocation().getBlock().getBiome(); + return StatSnapshot.roll(this.getDamageRanges(mainHandOverride), bio, stat -> this.getEffectBonus(stat, safe)); + } + + /** + * Each damage type's minimum and maximum, summed over the equipment. Those are what the gear, sets, + * classes and profile buffs decide; the roll, the biome and the effects come after. + *

+ * Read from the snapshot, except when the answer depends on something that belongs to one hit: a different + * main hand (a projectile's weapon) or a custom arrow's bonus. + */ + @NotNull + private Map getDamageRanges(@Nullable ItemStack mainHandOverride) { + if (mainHandOverride != null || this.arrowBonus != null) { + return this.buildDamageRanges(mainHandOverride, this.arrowBonus, this.arrowLevel); + } + + StatSnapshot current = this.snapshot(); + synchronized (current) { + if (current.damageRanges == null) { + current.damageRanges = this.buildDamageRanges(null, null, 0); + } + return current.damageRanges; + } + } + + @NotNull + private Map buildDamageRanges(@Nullable ItemStack mainHandOverride, + @Nullable QArrow arrow, + int arrowLevel) { + Map ranges = StatSnapshot.newRanges(); + List equip = this.getEquipmentForStats(mainHandOverride); for (DamageAttribute dmgAtt : ItemStats.getDamages()) { List> bonuses = new ArrayList<>(); @@ -685,7 +804,7 @@ public Map getDamageTypes(boolean safe, @Nullable ItemS // value = 1D; // Default hand damage for default damage type. //} - for (BiFunction bonus : this.getBonuses(dmgAtt)) { + for (BiFunction bonus : this.getBonuses(dmgAtt, arrow, arrowLevel)) { bonuses.add((isPercent, input) -> input.length == 2 ? new double[]{ bonus.apply(isPercent, input[0]), @@ -693,34 +812,61 @@ public Map getDamageTypes(boolean safe, @Nullable ItemS : new double[]{ bonus.apply(isPercent, input[0])}); } - double[] range = BonusCalculator.RANGE_FULL.apply(new double[]{0, 0}, bonuses); - double value = Rnd.getDouble(range[0], range[1]); - value *= dmgAtt.getDamageModifierByBiome(bio); // Multiply by Biome - value = this.getEffectBonus(dmgAtt, safe).applyAsDouble(value); + ranges.put(dmgAtt, BonusCalculator.RANGE_FULL.apply(new double[]{0, 0}, bonuses)); + } + return ranges; + } + + @NotNull + public Map getDefenseTypes(boolean safe) { + if (!EngineCfg.ATTRIBUTES_EFFECTIVE_FOR_MOBS && !this.isPlayer()) { + return Collections.emptyMap(); + } + Map map = new HashMap<>(); + for (Map.Entry entry : this.getDefenseValues().entrySet()) { + DefenseAttribute dt = entry.getKey(); + double value = this.getEffectBonus(dt, safe).applyAsDouble(entry.getValue()); if (value > 0D) { - map.put(dmgAtt, value); + map.put(dt, value); } } return map; } + /** + * Each defense type's value from gear, sets, classes and profile buffs, before the active effects. + */ @NotNull - public Map getDefenseTypes(boolean safe) { - if (!EngineCfg.ATTRIBUTES_EFFECTIVE_FOR_MOBS && !this.isPlayer()) { - return Collections.emptyMap(); + private Map getDefenseValues() { + if (this.arrowBonus != null) { + return this.buildDefenseValues(this.arrowBonus, this.arrowLevel); + } + + StatSnapshot current = this.snapshot(); + synchronized (current) { + // The vanilla armor attribute is added to the default defense and has no event of its own + double armor = this.attributeValue("ARMOR", true); + if (current.defenses == null || Double.compare(current.armorKey, armor) != 0) { + current.armorKey = armor; + current.defenses = this.buildDefenseValues(null, 0); + } + return current.defenses; } + } + @NotNull + private Map buildDefenseValues(@Nullable QArrow arrow, int arrowLevel) { List equip = this.getEquipment(); - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); for (DefenseAttribute dt : ItemStats.getDefenses()) { List> bonuses = new ArrayList<>(); for (ItemStack item : equip) { bonuses.addAll(dt.get(item, player)); } - bonuses.addAll(this.getBonuses(dt)); + bonuses.addAll(this.getBonuses(dt, arrow, arrowLevel)); if (dt.isDefault()) { AttributeInstance attribute = entity.getAttribute(VersionManager.getNms().getAttribute("ARMOR")); if (attribute != null) { @@ -728,13 +874,8 @@ public Map getDefenseTypes(boolean safe) { } } - double value = BonusCalculator.SIMPLE_FULL.apply(0D, bonuses); - value = this.getEffectBonus(dt, safe).applyAsDouble(value); - if (value > 0D) { - map.put(dt, value); - } + map.put(dt, BonusCalculator.SIMPLE_FULL.apply(0D, bonuses)); } - return map; } @@ -772,6 +913,42 @@ public double getItemStat(@NotNull SimpleStat.Type type, boolean safe, @Nullable SimpleStat stat = (SimpleStat) ItemStats.getStat(type); if (stat == null) return 0D; + double value = mainHandOverride != null || this.arrowBonus != null + ? this.buildItemStat(type, stat, mainHandOverride, this.arrowBonus, this.arrowLevel) + : this.getItemStatValue(type, stat); + + return StatSnapshot.finish(stat, value, this.getEffectBonus(stat, safe)); + } + + /** + * An item stat's value from gear, sets, classes and profile buffs, before the active effects and the cap. + */ + private double getItemStatValue(@NotNull SimpleStat.Type type, @NotNull SimpleStat stat) { + StatSnapshot current = this.snapshot(); + synchronized (current) { + // The vanilla toughness attribute is added to this stat and has no event of its own + double toughness = type == TypedStat.Type.ARMOR_TOUGHNESS + ? this.attributeValue("ARMOR_TOUGHNESS", false) + : Double.NaN; + Double cached = current.itemStats.get(type); + if (cached != null && type == TypedStat.Type.ARMOR_TOUGHNESS + && Double.compare(current.toughnessKey, toughness) != 0) { + cached = null; + } + if (cached == null) { + current.toughnessKey = type == TypedStat.Type.ARMOR_TOUGHNESS ? toughness : current.toughnessKey; + cached = this.buildItemStat(type, stat, null, null, 0); + current.itemStats.put(type, cached); + } + return cached; + } + } + + private double buildItemStat(@NotNull SimpleStat.Type type, + @NotNull SimpleStat stat, + @Nullable ItemStack mainHandOverride, + @Nullable QArrow arrow, + int arrowLevel) { List equip = this.getEquipmentForStats(mainHandOverride); List> bonuses = new ArrayList<>(); @@ -780,7 +957,7 @@ public double getItemStat(@NotNull SimpleStat.Type type, boolean safe, @Nullable bonuses.addAll(stat.get(item, player)); } - bonuses.addAll(this.getBonuses(stat)); + bonuses.addAll(this.getBonuses(stat, arrow, arrowLevel)); if (type == TypedStat.Type.ARMOR_TOUGHNESS) { AttributeInstance attribute = @@ -791,16 +968,114 @@ public double getItemStat(@NotNull SimpleStat.Type type, boolean safe, @Nullable } // Get Sets bonuses - double value = BonusCalculator.SIMPLE_FULL.apply(type == TypedStat.Type.CRITICAL_DAMAGE ? 1D : 0D, bonuses); - value = this.getEffectBonus(stat, safe).applyAsDouble(value); + return BonusCalculator.SIMPLE_FULL.apply(type == TypedStat.Type.CRITICAL_DAMAGE ? 1D : 0D, bonuses); + } + + /** + * The value of a vanilla attribute that a cached stat adds in, or NaN if the entity has none. It is + * compared with the value a snapshot was built with, because plugins and potions change attributes + * without telling anyone. + */ + private double attributeValue(@NotNull String name, boolean base) { + AttributeInstance attribute = entity.getAttribute(VersionManager.getNms().getAttribute(name)); + if (attribute == null) return Double.NaN; + return base ? attribute.getBaseValue() : attribute.getValue(); + } - if (stat.getCapability() >= 0) { - if (value > stat.getCapability()) { - value = stat.getCapability(); + /** + * Takes what a projectile fired now would carry, so that the stats it hits with are the stats it was fired + * with. Damage ranges and item stats are taken with the weapon in place of the main hand, as they are for + * any projectile hit, and with the custom arrow's bonus. The active effects are taken as well. Their + * charges are not used now: the hit that lands uses them, and a projectile that misses spends none. + * + * @return null if the entity has no stats from items to take + */ + @Nullable + public StatSnapshot snapshotForLaunch(@Nullable ItemStack weapon, @Nullable QArrow arrow, int arrowLevel) { + if (!EngineCfg.ATTRIBUTES_EFFECTIVE_FOR_MOBS && !this.isPlayer()) return null; + + Map, DoubleUnaryOperator> effects = new HashMap<>(); + StatSnapshot frozen = new StatSnapshot(this.entity.getUniqueId(), + this.entity.getLocation().getBlock().getBiome(), + effects); + + Map ranges = this.buildDamageRanges(weapon, arrow, arrowLevel); + frozen.setDamageRanges(ranges); + for (DamageAttribute dmgAtt : ranges.keySet()) { + this.captureEffects(frozen, effects, dmgAtt, true); + } + + for (SimpleStat.Type type : TypedStat.Type.values()) { + if (!type.isGlobal()) continue; + SimpleStat stat = (SimpleStat) ItemStats.getStat(type); + if (stat == null) continue; + + frozen.itemStats.put(type, this.buildItemStat(type, stat, weapon, arrow, arrowLevel)); + this.captureEffects(frozen, effects, stat, false); + } + return frozen; + } + + /** + * Takes the adjustment the active effects make to a stat without using up any charge, and notes which + * effects the hit that lands will have to charge. + */ + private synchronized void captureEffects(@NotNull StatSnapshot frozen, + @NotNull Map, DoubleUnaryOperator> effects, + @NotNull ItemLoreStat stat, + boolean damage) { + effects.put(stat, this.getEffectBonus(stat, true)); + for (IEffect effect : this.getActiveEffects(false)) { + if (effect instanceof AdjustStatEffect && ((AdjustStatEffect) effect).isAdjusted(stat)) { + frozen.addCharge((AdjustStatEffect) effect, stat, damage); } } + } - return value; + /** + * The current snapshot, or a new one if there is none or it is out of date. A snapshot is out of date when + * it is older than {@code performance.entity-stats.snapshot-max-age}, when a profile buff it includes has run + * out, or when the player's profile or its buffs are not what it was built with. A maximum age of 0 turns + * the cache off: every call then works from a snapshot that is thrown away. + */ + @NotNull + private StatSnapshot snapshot() { + long now = clock.getAsLong(); + UserProfile profile = this.getActiveProfile(); + + StatSnapshot current = this.snapshot; + if (current != null && current.isCurrent(now, profile)) { + return current; + } + + long maxAge = Math.max(0, EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE) * MILLIS_PER_TICK; + long validUntil = now + maxAge; + int revision = 0; + if (profile != null) { + // Asking for the next expiry also drops buffs that have already run out + validUntil = Math.min(validUntil, profile.getNextBuffExpiry()); + revision = profile.getBuffRevision(); + } + + if (maxAge <= 0) { + // Off: nothing is kept, so there is nothing to compare against later and nothing to copy now + return new StatSnapshot(validUntil, profile, revision, List.of(), List.of()); + } + + StatSnapshot created = new StatSnapshot(validUntil, + profile, + revision, + StatSnapshot.copyOf(this.inventory), + new ArrayList<>(this.bonusMaps)); + this.snapshot = created; + return created; + } + + @Nullable + private UserProfile getActiveProfile() { + if (!this.isPlayer() || this.isNPC()) return null; + DivinityUser user = plugin.getUserManager().getOrLoadUser(this.player); + return user == null ? null : user.getActiveProfile(); } @NotNull @@ -826,6 +1101,13 @@ private List getEquipmentForStats(@Nullable ItemStack mainHandOverrid } public double getEnchantProtectFactor(@NotNull Enchantment en) { + StatSnapshot current = this.snapshot(); + synchronized (current) { + return current.enchantFactors.computeIfAbsent(en, this::computeEnchantProtectFactor); + } + } + + private double computeEnchantProtectFactor(@NotNull Enchantment en) { int epfPer = 1; // EPF Per each enchantment level if (en == NamespaceResolver.getEnchantment("FIRE_PROTECTION", "PROTECTION_FIRE") || en == NamespaceResolver.getEnchantment("BLAST_PROTECTION", "PROTECTION_EXPLOSION") diff --git a/src/main/java/studio/magemonkey/divinity/stats/EntityStatsTask.java b/src/main/java/studio/magemonkey/divinity/stats/EntityStatsTask.java index 46de928e..addbc1d2 100644 --- a/src/main/java/studio/magemonkey/divinity/stats/EntityStatsTask.java +++ b/src/main/java/studio/magemonkey/divinity/stats/EntityStatsTask.java @@ -36,6 +36,10 @@ public void action() { stats.triggerEffects(); } + if (this.count % 100 == 0) { + ProjectileStats.sweep(); + } + if (this.count++ >= 100) { this.count = 1; } diff --git a/src/main/java/studio/magemonkey/divinity/stats/ProjectileStats.java b/src/main/java/studio/magemonkey/divinity/stats/ProjectileStats.java index e81038e1..e5d7ef52 100644 --- a/src/main/java/studio/magemonkey/divinity/stats/ProjectileStats.java +++ b/src/main/java/studio/magemonkey/divinity/stats/ProjectileStats.java @@ -1,5 +1,9 @@ package studio.magemonkey.divinity.stats; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.AbstractArrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Projectile; import org.bukkit.entity.Trident; @@ -8,6 +12,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import studio.magemonkey.divinity.Divinity; +import studio.magemonkey.divinity.stats.items.attributes.AmmoAttribute; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.LongSupplier; public class ProjectileStats { @@ -17,6 +27,34 @@ public class ProjectileStats { private static final String PROJECTILE_PICKABLE = "QRPG_PJ_PICKABLE"; private static final String PROJECTILE_LAUNCH_POWER = "QRPG_PJ_POWER"; + /** + * The shooter's stats as they were when each projectile was launched. Kept here rather than in entity + * metadata because metadata is only cleared when someone removes it, and these are not small: an entry is + * released by {@link #sweep()} once its projectile is really gone. + */ + private static final Map LAUNCH_SNAPSHOTS = new ConcurrentHashMap<>(); + + /** Longest time a launch snapshot is kept whatever happens to its projectile: 10 minutes. */ + static final long MAX_HELD_MILLIS = 10 * 60 * 1000L; + + private static volatile LongSupplier clock = System::currentTimeMillis; + + private static final class Held { + private final StatSnapshot snapshot; + private final long heldSince; + private final UUID world; + private int chunkX; + private int chunkZ; + + private Held(StatSnapshot snapshot, long heldSince, UUID world, int chunkX, int chunkZ) { + this.snapshot = snapshot; + this.heldSince = heldSince; + this.world = world; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + } + } + public static void setSrcWeapon(@NotNull Projectile pp, @NotNull ItemStack item) { pp.setMetadata(PROJECTILE_SOURCE_WEAPON, new FixedMetadataValue(plugin, item)); } @@ -44,6 +82,88 @@ public static double getPower(@NotNull Projectile e) { return meta.get(0).asDouble(); } + /** + * Whether a projectile is one that can hurt what it hits, and so is worth taking its shooter's stats for. + * Arrows, tridents and the damaging kinds of ammo Divinity can launch are; pearls, snowballs, eggs, bottles + * and fishing hooks are not. + */ + public static boolean canDealDamage(@NotNull Projectile pp) { + if (pp instanceof AbstractArrow) return true; // Arrows, spectral arrows and tridents + for (AmmoAttribute.Type type : AmmoAttribute.Type.values()) { + if (type.dealsDamage() && type.getProjectileClass().isInstance(pp)) return true; + } + return false; + } + + public static void setSnapshot(@NotNull Projectile pp, @NotNull StatSnapshot snapshot) { + Location at = pp.getLocation(); + World w = at.getWorld(); + hold(pp.getUniqueId(), + snapshot, + w == null ? null : w.getUID(), + at.getBlockX() >> 4, + at.getBlockZ() >> 4); + } + + static void hold(@NotNull UUID projectile, @NotNull StatSnapshot snapshot, @Nullable UUID world, int chunkX, int chunkZ) { + LAUNCH_SNAPSHOTS.put(projectile, new Held(snapshot, clock.getAsLong(), world, chunkX, chunkZ)); + } + + /** + * @return the shooter's stats at launch, or null if there are none: the projectile was not launched + * through Divinity's launch event, it cannot deal damage, or its entry was released. + */ + @Nullable + public static StatSnapshot getSnapshot(@NotNull Projectile pp) { + Held held = LAUNCH_SNAPSHOTS.get(pp.getUniqueId()); + return held == null ? null : held.snapshot; + } + + /** + * Releases the snapshots of projectiles that are gone. A projectile is gone when it can no longer be found + * although the chunk it was last seen in is loaded, or when it is found dead. One that cannot be found + * because its chunk is unloaded may come back, so it keeps its snapshot, up to {@link #MAX_HELD_MILLIS} + * after launch, which also bounds anything else this fails to recognise. + */ + public static void sweep() { + long now = clock.getAsLong(); + LAUNCH_SNAPSHOTS.entrySet().removeIf(entry -> { + Held held = entry.getValue(); + if (now - held.heldSince > MAX_HELD_MILLIS) return true; + + Entity entity = Bukkit.getEntity(entry.getKey()); + if (entity != null) { + if (entity.isDead()) return true; + Location at = entity.getLocation(); + held.chunkX = at.getBlockX() >> 4; + held.chunkZ = at.getBlockZ() >> 4; + return false; + } + + World world = held.world == null ? null : Bukkit.getWorld(held.world); + if (world == null) return true; // The world itself is gone + return world.isChunkLoaded(held.chunkX, held.chunkZ); + }); + } + + /** Releases every launch snapshot, for when the stats they were taken with are replaced. */ + public static void clear() { + LAUNCH_SNAPSHOTS.clear(); + } + + static void setClock(@NotNull LongSupplier supplier) { + clock = supplier; + } + + static void resetClock() { + clock = System::currentTimeMillis; + } + + /** How many projectiles have a snapshot held, for diagnostics and tests. */ + public static int snapshotCount() { + return LAUNCH_SNAPSHOTS.size(); + } + public static void setPickable(@NotNull Entity pp, boolean b) { pp.setMetadata(PROJECTILE_PICKABLE, new FixedMetadataValue(plugin, b)); } diff --git a/src/main/java/studio/magemonkey/divinity/stats/StatSnapshot.java b/src/main/java/studio/magemonkey/divinity/stats/StatSnapshot.java new file mode 100644 index 00000000..330e0e73 --- /dev/null +++ b/src/main/java/studio/magemonkey/divinity/stats/StatSnapshot.java @@ -0,0 +1,313 @@ +package studio.magemonkey.divinity.stats; + +import org.bukkit.block.Biome; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.enchantments.Enchantment; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import studio.magemonkey.codex.util.random.Rnd; +import studio.magemonkey.divinity.data.api.UserProfile; +import studio.magemonkey.divinity.manager.effects.main.AdjustStatEffect; +import studio.magemonkey.divinity.stats.bonus.BonusMap; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.api.ItemLoreStat; +import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; +import studio.magemonkey.divinity.stats.items.attributes.DefenseAttribute; +import studio.magemonkey.divinity.stats.items.attributes.api.SimpleStat; +import studio.magemonkey.divinity.stats.items.attributes.api.TypedStat; +import studio.magemonkey.divinity.stats.items.attributes.stats.DurabilityStat; + +import java.util.ArrayList; +import java.util.UUID; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.DoubleUnaryOperator; + +/** + * What {@link EntityStats} worked out from an entity's gear, kept until something that feeds into it changes. + *

+ * There are two kinds, and they differ in who may change them: + *

    + *
  • A live snapshot belongs to an entity and is filled in on demand, one section at a time: + * damage ranges, defenses, item stats and enchantment protection. It holds the part of a stat that only + * gear, sets, classes and profile buffs decide, before anything that is meant to be read at the + * moment of the hit: the roll of a damage range, the biome, and active effects (which carry charges and + * run out by themselves). Those three are applied by the caller each time. {@link EntityStats} drops the + * snapshot when one of its inputs changes; see its {@code invalidateSnapshot}.
  • + *
  • A frozen snapshot is taken when a projectile is launched and never changes. It also holds the + * shooter's effects and biome as they were, so the arrow does the damage it was fired with. It is rolled + * at impact like a live one.
  • + *
+ * A damage type is stored as its minimum and maximum, the sum over every equipped item. The roll happens + * when the hit lands, with the same single call as before, so the distribution of results is unchanged. + */ +public final class StatSnapshot { + private static final DoubleUnaryOperator IDENTITY = value -> value; + + private final long validUntil; + @Nullable + private final UserProfile profile; + private final int profileRevision; + private final List inputItems; + private final List inputBonuses; + private final boolean frozen; + + // Filled in on demand, under the lock of this snapshot + Map damageRanges; + Map defenses; + double armorKey = Double.NaN; + double toughnessKey = Double.NaN; + final Map itemStats = new HashMap<>(); + final Map enchantFactors = new HashMap<>(); + + // Frozen snapshots only + @Nullable + private Map, DoubleUnaryOperator> frozenEffects; + @Nullable + private Biome frozenBiome; + @Nullable + private UUID shooter; + /** The effects whose charges a hit uses, for damage types and for item stats. */ + private final List damageCharges = new ArrayList<>(); + private final List statCharges = new ArrayList<>(); + + /** A live snapshot. */ + StatSnapshot(long validUntil, + @Nullable UserProfile profile, + int profileRevision, + @NotNull List inputItems, + @NotNull List inputBonuses) { + this.validUntil = validUntil; + this.profile = profile; + this.profileRevision = profileRevision; + this.inputItems = inputItems; + this.inputBonuses = inputBonuses; + this.frozen = false; + } + + /** A frozen snapshot, for a projectile. */ + StatSnapshot(@NotNull UUID shooter, + @Nullable Biome biome, + @NotNull Map, DoubleUnaryOperator> effects) { + this.shooter = shooter; + this.validUntil = Long.MAX_VALUE; + this.profile = null; + this.profileRevision = 0; + this.inputItems = List.of(); + this.inputBonuses = List.of(); + this.frozen = true; + this.frozenBiome = biome; + this.frozenEffects = effects; + } + + public boolean isFrozen() { + return this.frozen; + } + + /** + * Whether this launch snapshot is of the given shooter. A projectile that has changed hands since it was + * launched (reflected, re-owned by a plugin) is not the shooter's any more. + */ + public boolean isShooter(@Nullable UUID entity) { + return this.shooter != null && this.shooter.equals(entity); + } + + /** Records that a hit using this snapshot spends a charge of the effect on the stat, if it still has one. */ + void addCharge(@NotNull AdjustStatEffect effect, @NotNull ItemLoreStat stat, boolean damage) { + (damage ? this.damageCharges : this.statCharges).add(new ChargeUse(effect, stat)); + } + + /** + * Effects were captured at launch without using their charges. A hit that lands uses them, once per + * effect and stat, as a hit read at impact always did. An effect that is gone or has no charge for the + * stat any more is left alone; the hit still has the adjustment it was fired with. + */ + private static void spend(@NotNull List uses) { + for (ChargeUse use : uses) { + if (use.effect.isExpired() || !use.effect.isAdjusted(use.stat)) continue; + use.effect.getAdjust(use.stat, false); + } + } + + private static final class ChargeUse { + private final AdjustStatEffect effect; + private final ItemLoreStat stat; + + private ChargeUse(AdjustStatEffect effect, ItemLoreStat stat) { + this.effect = effect; + this.stat = stat; + } + } + + /** + * Whether this snapshot can still be used at {@code now}. A snapshot goes out of date by itself when + * it is older than the configured maximum age, when a profile buff it was built with runs out, and + * when the player's active profile or its buffs are not the ones it was built with. + */ + boolean isCurrent(long now, @Nullable UserProfile activeProfile) { + if (this.frozen) return true; + if (now >= this.validUntil) return false; + if (this.profile != activeProfile) return false; + return this.profile == null || this.profile.getBuffRevision() == this.profileRevision; + } + + /** + * Whether the equipment and bonus maps this snapshot was built from are what an entity has now. Items + * are compared the way a player would see it: wear (vanilla damage and Divinity's durability) is not + * a change, anything else about an item is. + */ + boolean matches(@NotNull List items, @NotNull List bonuses) { + if (this.inputItems.size() != items.size() || this.inputBonuses.size() != bonuses.size()) return false; + for (int i = 0; i < bonuses.size(); i++) { + if (this.inputBonuses.get(i) != bonuses.get(i)) return false; + } + synchronized (items) { + for (int i = 0; i < items.size(); i++) { + if (!sameIgnoringWear(this.inputItems.get(i), items.get(i))) return false; + } + } + return true; + } + + /** + * Copies the items a snapshot is built from. The copies are what a later {@link #matches} compares + * against, so a change made in place to an equipped stack is still seen as a change. + */ + static List copyOf(@NotNull List items) { + synchronized (items) { + List copy = new ArrayList<>(items.size()); + for (ItemStack item : items) copy.add(item == null ? null : item.clone()); + return copy; + } + } + + private static boolean sameIgnoringWear(@Nullable ItemStack a, @Nullable ItemStack b) { + if (a == b) return true; + if (a == null || b == null) return false; + if (a.isSimilar(b)) return true; + if (a.getType() != b.getType()) return false; + + ItemStack unwornA = withoutWear(a); + ItemStack unwornB = withoutWear(b); + return unwornA.isSimilar(unwornB); + } + + /** A copy of the item as it was when new. */ + private static ItemStack withoutWear(@NotNull ItemStack item) { + ItemStack copy = item.clone(); + copy.setAmount(1); + + DurabilityStat durability = ItemStats.getStat(DurabilityStat.class); + if (durability != null) { + double[] raw = durability.getRaw(copy); + if (raw != null && raw.length == 2 && raw[1] > 0) { + if (durability.add(copy, new double[]{raw[1], raw[1]}, -1)) { + durability.syncVanillaBar(copy, raw[1], raw[1]); + } + } + } + + ItemMeta meta = copy.getItemMeta(); + if (meta instanceof Damageable && ((Damageable) meta).hasDamage()) { + ((Damageable) meta).setDamage(0); + copy.setItemMeta(meta); + } + return copy; + } + + // ------------------------------------------------------------------ // + // Rolling and finishing: the part that is done at the moment of the hit + // ------------------------------------------------------------------ // + + /** + * Rolls every damage type's range once. One roll per type, from its summed minimum and maximum, then + * the biome and the effects, in that order. A type that ends at 0 or below is left out. + * + * @param effect the adjusting function of a stat from the active effects + */ + @NotNull + static Map roll(@NotNull Map ranges, + @Nullable Biome biome, + @NotNull Function, DoubleUnaryOperator> effect) { + Map map = new HashMap<>(); + for (Map.Entry entry : ranges.entrySet()) { + DamageAttribute dmgAtt = entry.getKey(); + double[] range = entry.getValue(); + + double value = Rnd.getDouble(range[0], range[1]); + if (biome != null) value *= dmgAtt.getDamageModifierByBiome(biome); // Multiply by Biome + value = effect.apply(dmgAtt).applyAsDouble(value); + + if (value > 0D) { + map.put(dmgAtt, value); + } + } + return map; + } + + /** Applies the effects, then the stat's cap, to an item stat's value from gear. */ + static double finish(@NotNull SimpleStat stat, double value, @NotNull DoubleUnaryOperator effect) { + value = effect.applyAsDouble(value); + if (stat.getCapability() >= 0) { + if (value > stat.getCapability()) { + value = stat.getCapability(); + } + } + return value; + } + + /** + * Rolls the damage the shooter had at launch. Only for a frozen snapshot. + */ + @NotNull + public Map rollDamage() { + if (!this.frozen || this.damageRanges == null) { + throw new IllegalStateException("Only a frozen snapshot holds a launch's damage"); + } + Map, DoubleUnaryOperator> effects = this.frozenEffects; + Map rolled = roll(this.damageRanges, + this.frozenBiome, + stat -> effects == null ? IDENTITY : effects.getOrDefault(stat, IDENTITY)); + spend(this.damageCharges); + return rolled; + } + + /** + * The shooter's item stats at launch. Only for a frozen snapshot. + */ + @NotNull + public Map itemStats() { + if (!this.frozen) { + throw new IllegalStateException("Only a frozen snapshot holds a launch's item stats"); + } + Map, DoubleUnaryOperator> effects = this.frozenEffects; + Map map = new HashMap<>(); + for (SimpleStat.Type type : TypedStat.Type.values()) { + Double raw = this.itemStats.get(type); + if (raw == null) continue; + SimpleStat stat = (SimpleStat) ItemStats.getStat(type); + if (stat == null) continue; + + double value = finish(stat, raw, effects == null ? IDENTITY : effects.getOrDefault(stat, IDENTITY)); + if (value > 0D) { + map.put(type, value); + } + } + spend(this.statCharges); + return map; + } + + /** For {@link EntityStats}, which builds a frozen snapshot. */ + void setDamageRanges(@NotNull Map ranges) { + this.damageRanges = ranges; + } + + static Map newRanges() { + return new LinkedHashMap<>(); + } +} diff --git a/src/main/java/studio/magemonkey/divinity/stats/items/ItemStats.java b/src/main/java/studio/magemonkey/divinity/stats/items/ItemStats.java index 901082fa..a205cf1d 100644 --- a/src/main/java/studio/magemonkey/divinity/stats/items/ItemStats.java +++ b/src/main/java/studio/magemonkey/divinity/stats/items/ItemStats.java @@ -22,6 +22,7 @@ import studio.magemonkey.divinity.Divinity; import studio.magemonkey.divinity.config.EngineCfg; import studio.magemonkey.divinity.modules.api.QModuleDrop; +import studio.magemonkey.divinity.stats.EntityStats; import studio.magemonkey.divinity.stats.items.api.DuplicableItemLoreStat; import studio.magemonkey.divinity.stats.items.api.DynamicStat; import studio.magemonkey.divinity.stats.items.api.ItemLoreStat; @@ -86,6 +87,8 @@ public class ItemStats { // TODO Register logs public static void clear() { + // What was worked out from these stats is no good to anyone once they are gone + EntityStats.invalidateAllSnapshots(); DAMAGES.clear(); DEFENSES.clear(); STATS.clear(); @@ -99,6 +102,7 @@ public static void clear() { } public static void registerDamage(@NotNull DamageAttribute dmg) { + EntityStats.invalidateAllSnapshots(); DAMAGES.put(dmg.getId(), dmg); if (DAMAGE_DEFAULT == null || dmg.getPriority() >= DAMAGE_DEFAULT.getPriority()) { DAMAGE_DEFAULT = dmg; @@ -112,6 +116,7 @@ public static void registerDamage(@NotNull DamageAttribute dmg) { } public static void registerDefense(@NotNull DefenseAttribute def) { + EntityStats.invalidateAllSnapshots(); DEFENSES.put(def.getId(), def); ItemStats.updateDefenseByDefault(); } @@ -119,6 +124,7 @@ public static void registerDefense(@NotNull DefenseAttribute def) { public static void registerStat(@NotNull TypedStat stat) { if (stat.getCapability() == 0) return; // TODO Log + EntityStats.invalidateAllSnapshots(); STATS.put(stat.getType(), stat); } diff --git a/src/main/java/studio/magemonkey/divinity/stats/items/attributes/AmmoAttribute.java b/src/main/java/studio/magemonkey/divinity/stats/items/attributes/AmmoAttribute.java index 0d03284d..f29dfa61 100644 --- a/src/main/java/studio/magemonkey/divinity/stats/items/attributes/AmmoAttribute.java +++ b/src/main/java/studio/magemonkey/divinity/stats/items/attributes/AmmoAttribute.java @@ -42,24 +42,39 @@ public Class getParameterClass() { public static enum Type { - ARROW(Arrow.class, EntityType.ARROW), - SNOWBALL(Snowball.class, EntityType.SNOWBALL), - EGG(Egg.class, EntityType.EGG), - FIREBALL(Fireball.class, EntityType.FIREBALL), - WITHER_SKULL(WitherSkull.class, EntityType.WITHER_SKULL), - SHULKER_BULLET(ShulkerBullet.class, EntityType.SHULKER_BULLET), - LLAMA_SPIT(LlamaSpit.class, EntityType.LLAMA_SPIT), - ENDER_PEARL(EnderPearl.class, EntityType.ENDER_PEARL), + ARROW(Arrow.class, EntityType.ARROW, true), + SNOWBALL(Snowball.class, EntityType.SNOWBALL, false), + EGG(Egg.class, EntityType.EGG, false), + FIREBALL(Fireball.class, EntityType.FIREBALL, true), + WITHER_SKULL(WitherSkull.class, EntityType.WITHER_SKULL, true), + SHULKER_BULLET(ShulkerBullet.class, EntityType.SHULKER_BULLET, true), + LLAMA_SPIT(LlamaSpit.class, EntityType.LLAMA_SPIT, true), + ENDER_PEARL(EnderPearl.class, EntityType.ENDER_PEARL, false), EXP_POTION(ThrownExpBottle.class, - EntityType.fromName("experience_bottle")), // THROWN_EXP_BOTTLE/EXPERIENCE_BOTTLE + EntityType.fromName("experience_bottle"), false), // THROWN_EXP_BOTTLE/EXPERIENCE_BOTTLE ; private Class clazz; private EntityType eType; + private boolean dealsDamage; - private Type(@NotNull Class clazz, @NotNull EntityType eType) { + private Type(@NotNull Class clazz, @NotNull EntityType eType, boolean dealsDamage) { this.clazz = clazz; this.eType = eType; + this.dealsDamage = dealsDamage; + } + + /** + * Whether this kind of projectile hurts what it hits. Pearls, snowballs, eggs and bottles are thrown + * for their other effects, and the damage they cause on impact is not what the ammo's stats are for. + */ + public boolean dealsDamage() { + return this.dealsDamage; + } + + @NotNull + public Class getProjectileClass() { + return this.clazz; } } diff --git a/src/main/resources/engine.yml b/src/main/resources/engine.yml index 72e57b67..85a2eca0 100644 --- a/src/main/resources/engine.yml +++ b/src/main/resources/engine.yml @@ -42,6 +42,14 @@ performance: # Default value: 50 ticks (2.5 seconds). # Recommended: 20 or more (1+ seconds). bonus-update-interval: 50 + # Damage, defense and item stats are worked out from an entity's gear once and reused for hits, instead + # of being read from every item on every hit. Changing equipment, held items, sets, classes, profile buffs + # and dying all make Divinity work them out again. This is the longest time (in ticks) a result is + # reused when nothing told Divinity that something changed, for example gear changed by another plugin. + # Active effects, damage rolls and biome modifiers are never cached. + # Setting this value to 0 turns the cache off. + # Default value: 20 ticks (1 second). + snapshot-max-age: 20 # Item Attributes Settings. attributes: diff --git a/src/test/java/studio/magemonkey/divinity/manager/damage/CombatBenchmark.java b/src/test/java/studio/magemonkey/divinity/manager/damage/CombatBenchmark.java new file mode 100644 index 00000000..1b172039 --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/manager/damage/CombatBenchmark.java @@ -0,0 +1,235 @@ +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.event.entity.EntityDamageByEntityEvent; +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.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +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.util.EffectUT; +import studio.magemonkey.divinity.config.EngineCfg; +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.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mockStatic; + +/** + * Hits per second through the damage pipeline (the listener, which reads stats, and the calculator), for the + * same inputs before and after a change to how stats are read. It measures nothing the suite asserts, so it + * only runs when asked for: + *
+ *   mvn -Dtest=CombatBenchmark -Dcombat.benchmark=true [-Dcombat.benchmark.out=/path/file] test
+ * 
+ * Two situations are timed, because they differ in what a stat cache can save: + *
    + *
  • burst: hits that follow each other with nothing in between, as with area damage or several + * projectiles landing in one tick.
  • + *
  • steady: one hit per tick, with the server tick in between. A hit asks for the stats of both + * fighters to be refreshed on the next tick, so this is what ordinary combat looks like.
  • + *
+ * The fighters carry a weapon with three damage types and four armor pieces with three defenses each, plus + * item stats on all of them, which is about what a geared player has. + */ +@EnabledIfSystemProperty(named = "combat.benchmark", matches = "true") +class CombatBenchmark extends MockedTest { + private static final int WARMUP_HITS = 1500; + private static final int BURST_HITS = 4000; + private static final int STEADY_HITS = 1500; + private static final int ROUNDS = 5; + + private TickSafePlayer attacker; + private TickSafePlayer victim; + + @BeforeEach + void setup() { + useRealAttributes(); + doAnswer(ans -> Registry.ATTRIBUTE.get(NamespacedKey.minecraft(((String) ans.getArgument(0)).toLowerCase( + Locale.US)))).when(VersionManager.getNms()).getAttribute(anyString()); + doAnswer(ans -> 0D).when(VersionManager.getNms()).getDefaultDamage(any()); + doAnswer(ans -> false).when(VersionManager.getNms()).isWeapon(any()); + + EngineCfg.VANILLA_ONLY_ITEM_STATS = true; + + attacker = new TickSafePlayer(server, "BenchAttacker"); + server.addPlayer(attacker); + players.add(attacker); + victim = new TickSafePlayer(server, "BenchVictim"); + server.addPlayer(victim); + players.add(victim); + + attacker.getInventory().setItemInMainHand(weapon()); + attacker.getInventory().setHelmet(armor(Material.IRON_HELMET)); + attacker.getInventory().setChestplate(armor(Material.IRON_CHESTPLATE)); + victim.getInventory().setHelmet(armor(Material.IRON_HELMET)); + victim.getInventory().setChestplate(armor(Material.IRON_CHESTPLATE)); + victim.getInventory().setLeggings(armor(Material.IRON_LEGGINGS)); + victim.getInventory().setBoots(armor(Material.IRON_BOOTS)); + refresh(); + } + + @AfterEach + void tearDown() { + EngineCfg.VANILLA_ONLY_ITEM_STATS = false; + try (MockedStatic ignored = mockStatic(EffectUT.class)) { + attacker.teleport(attacker.getLocation().add(10_000, 0, 0)); + victim.teleport(victim.getLocation().add(10_100, 0, 0)); + server.getScheduler().performOneTick(); + } + players.forEach(EntityStats::purge); + } + + @Test + void hitsPerSecond() throws IOException { + List burst = new ArrayList<>(); + List steady = new ArrayList<>(); + + try (MockedStatic ignored = mockStatic(EffectUT.class)) { + for (int i = 0; i < WARMUP_HITS; i++) { + hit(); + if (i % 10 == 0) server.getScheduler().performOneTick(); + } + for (int round = 0; round < ROUNDS; round++) { + server.getScheduler().performOneTick(); + long start = System.nanoTime(); + for (int i = 0; i < BURST_HITS; i++) hit(); + burst.add(BURST_HITS / ((System.nanoTime() - start) / 1e9)); + + server.getScheduler().performOneTick(); + start = System.nanoTime(); + for (int i = 0; i < STEADY_HITS; i++) { + hit(); + server.getScheduler().performOneTick(); + } + steady.add(STEADY_HITS / ((System.nanoTime() - start) / 1e9)); + } + } + + String report = String.format(Locale.US, + "BENCH burst median=%.0f hits/s (rounds: %s) | steady median=%.0f hits/s (rounds: %s)", + median(burst), format(burst), median(steady), format(steady)); + System.out.println(report); + String out = System.getProperty("combat.benchmark.out"); + if (out != null) { + Path file = Paths.get(out); + Files.write(file, + (report + System.lineSeparator()).getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE, + StandardOpenOption.APPEND); + } + assertTrue(median(burst) > 0 && median(steady) > 0); + } + + private void hit() { + Map modifiers = new EnumMap<>(DamageModifier.class); + modifiers.put(DamageModifier.BASE, 6D); + Map> functions = new EnumMap<>(DamageModifier.class); + functions.put(DamageModifier.BASE, d -> 6D); + server.getPluginManager() + .callEvent(new EntityDamageByEntityEvent((Entity) attacker, + victim, + DamageCause.ENTITY_ATTACK, + modifiers, + functions)); + } + + private void refresh() { + for (PlayerMock player : List.of(attacker, victim)) { + EntityStats.purge(player); + EntityStats.get(player).updateAll(); + } + } + + private ItemStack weapon() { + ItemStack item = new ItemStack(Material.IRON_SWORD); + damage(item, "physical", new double[]{10D, 20D}); + damage(item, "fire", new double[]{4D}); + damage(item, "magical", new double[]{2D, 6D}); + stat(item, TypedStat.Type.PVP_DAMAGE, 10D); + stat(item, TypedStat.Type.PENETRATION, 5D); + stat(item, TypedStat.Type.CRITICAL_DAMAGE, 1.5D); + return item; + } + + private ItemStack armor(Material material) { + ItemStack item = new ItemStack(material); + defense(item, "physical", 6D); + defense(item, "fire", 3D); + defense(item, "magical", 2D); + stat(item, TypedStat.Type.PVP_DEFENSE, 5D); + stat(item, TypedStat.Type.HEALTH_REGEN, 2D); + return item; + } + + private static void damage(ItemStack item, String id, double[] value) { + Objects.requireNonNull(ItemStats.getDamageById(id), id + " damage type is not enabled") + .add(item, new StatBonus(value, false, null), -1); + } + + private static void defense(ItemStack item, String id, double value) { + Objects.requireNonNull(ItemStats.getDefenseById(id), id + " defense type is not enabled") + .add(item, new StatBonus(new double[]{value}, false, null), -1); + } + + private static 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); + } + + private static double median(List values) { + List sorted = new ArrayList<>(values); + sorted.sort(null); + return sorted.get(sorted.size() / 2); + } + + private static String format(List values) { + StringBuilder sb = new StringBuilder(); + values.forEach(v -> sb.append(String.format(Locale.US, "%.0f ", v))); + return sb.toString().trim(); + } + + /** MockBukkit does not implement the attack cooldown, which the server tick reads for every player. */ + private static class TickSafePlayer extends PlayerMock { + TickSafePlayer(@NotNull ServerMock server, @NotNull String name) { + super(server, name, UUID.randomUUID()); + } + + @Override + public float getAttackCooldown() { + return 1F; + } + } +} diff --git a/src/test/java/studio/magemonkey/divinity/stats/EntityStatSnapshotTest.java b/src/test/java/studio/magemonkey/divinity/stats/EntityStatSnapshotTest.java new file mode 100644 index 00000000..d7a7b6db --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/stats/EntityStatSnapshotTest.java @@ -0,0 +1,942 @@ +package studio.magemonkey.divinity.stats; + +import com.google.common.base.Function; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.attribute.Attribute; +import org.bukkit.damage.DamageSource; +import org.bukkit.damage.DamageType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Arrow; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.player.PlayerItemHeldEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockbukkit.mockbukkit.ServerMock; +import org.mockbukkit.mockbukkit.entity.PlayerMock; +import org.mockbukkit.mockbukkit.entity.ZombieMock; +import org.mockito.MockedStatic; +import studio.magemonkey.codex.compat.VersionManager; +import studio.magemonkey.codex.util.EffectUT; +import studio.magemonkey.codex.util.EnumUT; +import studio.magemonkey.codex.util.random.Rnd; +import studio.magemonkey.divinity.api.event.DivinityProjectileLaunchEvent; +import studio.magemonkey.divinity.api.event.EntityEquipmentChangeEvent; +import studio.magemonkey.divinity.config.EngineCfg; +import studio.magemonkey.divinity.data.api.DivinityUser; +import studio.magemonkey.divinity.data.api.UserProfile; +import studio.magemonkey.divinity.manager.damage.DamageMeta; +import studio.magemonkey.divinity.manager.effects.buffs.SavedBuff; +import studio.magemonkey.divinity.manager.effects.main.AdjustStatEffect; +import studio.magemonkey.divinity.modules.ModuleCache; +import studio.magemonkey.divinity.modules.list.sets.SetManager; +import studio.magemonkey.divinity.stats.bonus.BonusMap; +import studio.magemonkey.divinity.stats.bonus.StatBonus; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; +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.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +/** + * Entity stat snapshots (issue #372). A snapshot keeps what was worked out from an entity's gear so a hit does + * not read every item again. What matters is that it never outlives a change: for each way stats can change + * there is a test that warms the cache with a hit, makes the change the way the server would, and checks the + * very next hit. + *

+ * Every damage value is a single number so the results can be asserted exactly. The tests that are about + * rolls seed the generator. + */ +@SuppressWarnings("deprecation") +class EntityStatSnapshotTest extends MockedTest { + private static final double DELTA = 1e-6; + private static final double VANILLA_SWORD_DAMAGE = 6D; + + private TickSafePlayer attacker; + private TickSafePlayer victim; + private int originalMaxAge; + + @BeforeEach + void setup() { + attacker = new TickSafePlayer(server, "Attacker"); + server.addPlayer(attacker); + players.add(attacker); + victim = new TickSafePlayer(server, "Victim"); + server.addPlayer(victim); + players.add(victim); + + originalMaxAge = EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE; + + // Adding a stat to an item also syncs vanilla attribute modifiers onto it, which the mocked NMS layer + // cannot do + 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()); + // Without this an entity's max health reads as 0 and refreshing its stats kills it + doAnswer(ans -> Registry.ATTRIBUTE.get(NamespacedKey.minecraft(((String) ans.getArgument(0)).toLowerCase( + Locale.US)))).when(VersionManager.getNms()).getAttribute(anyString()); + + // Joining asks for a forced refresh on the next tick. Let it run now, or it would run in the middle of a + // test and drop the snapshot the test is looking at + tick(); + } + + @AfterEach + void tearDown() { + EntityStats.resetClock(); + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = originalMaxAge; + EngineCfg.VANILLA_ONLY_ITEM_STATS = false; + EngineCfg.LEGACY_COMBAT = false; + + // The server is shared by every test in this class and entity stats are static: take the players out + // of reach of anything still queued, and let it run + 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); + } + + // ------------------------------------------------------------------ // + // The cache is used, and a hit does not throw it away + // ------------------------------------------------------------------ // + + @Test + void ahitFillsTheSnapshotsOfBothFighters() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertFalse(EntityStats.get(attacker).hasSnapshot()); + + hit(); + + assertTrue(EntityStats.get(attacker).hasSnapshot()); + assertTrue(EntityStats.get(victim).hasSnapshot()); + } + + @Test + void theRefreshAfterAHit_keepsTheSnapshotOfUnchangedGear() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + victim.getInventory().setChestplate(armor(Map.of("physical", 30D))); + refresh(); + hit(); + + tick(); // The hit asked for both fighters' stats to be read again on the next tick + + assertTrue(EntityStats.get(attacker).hasSnapshot(), "A hit changes nothing about the attacker's gear"); + assertTrue(EntityStats.get(victim).hasSnapshot(), "A hit changes nothing about the victim's gear"); + } + + @Test + void wear_isNotAChange() { + ItemStack sword = weapon(Map.of("physical", 20D)); + attacker.getInventory().setItemInMainHand(sword); + refresh(); + hit(); + tick(); + + // Every hit wears the weapon down a little + ItemStack worn = attacker.getInventory().getItemInMainHand(); + ItemMeta meta = worn.getItemMeta(); + ((Damageable) meta).setDamage(5); + worn.setItemMeta(meta); + attacker.getInventory().setItemInMainHand(worn); + hit(); + tick(); + + assertTrue(EntityStats.get(attacker).hasSnapshot(), "Wear should not cost the attacker their snapshot"); + } + + @Test + void anythingElseAboutAnItem_isAChange() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + hit(); + tick(); + + ItemStack enchanted = attacker.getInventory().getItemInMainHand(); + enchanted.addUnsafeEnchantment(Enchantment.SHARPNESS, 1); + attacker.getInventory().setItemInMainHand(enchanted); + hit(); + tick(); + + assertFalse(EntityStats.get(attacker).hasSnapshot()); + } + + // ------------------------------------------------------------------ // + // Invalidation: one test for each way stats change + // ------------------------------------------------------------------ // + + @Test + void heldItemChange_isSeenByTheNextHit() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + tick(); + + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 30D))); + server.getPluginManager().callEvent(new PlayerItemHeldEvent(attacker, 0, 1)); + tick(); + + assertEquals(30D, physicalHit(), DELTA); + } + + @Test + void equipmentChange_isSeenByTheNextHit() { + EngineCfg.LEGACY_COMBAT = true; + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + victim.getInventory().setChestplate(armor(Map.of("physical", 30D))); + refresh(); + assertEquals(15.2D, physicalHit(), DELTA); + tick(); + + victim.getInventory().setChestplate(armor(Map.of("physical", 50D))); + server.getPluginManager().callEvent(new EntityEquipmentChangeEvent(victim)); + tick(); + + assertEquals(12D, physicalHit(), DELTA); // 20 * (1 - 50 * 0.8 * 0.01) + } + + @Test + void anItemChangedInPlace_gemsAndSocketsIncluded_isSeenByTheNextHit() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + tick(); + + // What socketing a gem does to the stack a player is holding: the same item, with different stats on it + ItemStack held = attacker.getInventory().getItemInMainHand(); + Objects.requireNonNull(ItemStats.getDamageById("physical")) + .add(held, new StatBonus(new double[]{30D}, false, null), -1); + attacker.getInventory().setItemInMainHand(held); + server.getPluginManager().callEvent(new EntityEquipmentChangeEvent(attacker)); + tick(); + + assertEquals(30D, physicalHit(), DELTA); + } + + @Test + void gearChangedWithoutAnyEvent_isSeenOnceTheHitsRefreshHasRun() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + + // A plugin sets the weapon and tells no one. This is how it has always been: the hit that follows still + // uses the gear that was read last, and the refresh the hit asks for puts it right + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 30D))); + assertEquals(20D, physicalHit(), DELTA); + tick(); + + assertEquals(30D, physicalHit(), DELTA); + } + + @Test + void aForcedRefresh_dropsTheSnapshotEvenIfNothingLooksDifferent() { + // What classes, profiles and sets ask for when they change something that is not equipment + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + hit(); + assertTrue(EntityStats.get(attacker).hasSnapshot()); + + EntityStats.get(attacker).updateAll(); + + assertFalse(EntityStats.get(attacker).hasSnapshot()); + } + + @Test + void setBonus_isSeenByTheNextHit_whenTheRefreshIsForced() throws Exception { + BonusMap setBonus = physicalDamageBonus(10D); + List active = new ArrayList<>(); + try (SetManagerInstalled ignored = installSetManager(active)) { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + tick(); + + active.add(setBonus); // The last piece of the set goes on + EntityStats.get(attacker).updateAll(); // What SetManager asks for when equipment changes + + assertEquals(30D, physicalHit(), DELTA); + } + } + + @Test + void setBonus_changeIsSeenAfterAHit_withoutAForcedRefresh() throws Exception { + BonusMap setBonus = physicalDamageBonus(10D); + List active = new ArrayList<>(List.of(setBonus)); + try (SetManagerInstalled ignored = installSetManager(active)) { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(30D, physicalHit(), DELTA); + + active.clear(); // A set piece is gone, and the equipment itself looks the same + hit(); + tick(); + + assertEquals(20D, physicalHit(), DELTA); + } + } + + @Test + void effectAdded_isSeenByTheNextHit_andNoLongerOnceRemoved() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + + AdjustStatEffect effect = new AdjustStatEffect.Builder(-1) + .withAdjust(Objects.requireNonNull(ItemStats.getDamageById("physical")), v -> v + 10D) + .build(); + EntityStats.get(attacker).addEffect(effect); + assertEquals(30D, physicalHit(), DELTA); + + EntityStats.get(attacker).removeEffect(effect); + assertEquals(20D, physicalHit(), DELTA); + } + + @Test + void effectThatRunsOut_isNoLongerSeenByTheNextHit() throws Exception { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + AdjustStatEffect effect = new AdjustStatEffect.Builder(0.5) + .withAdjust(Objects.requireNonNull(ItemStats.getDamageById("physical")), v -> v + 10D) + .build(); + EntityStats.get(attacker).addEffect(effect); + assertEquals(30D, physicalHit(), DELTA); + + Thread.sleep(700); + + assertEquals(20D, physicalHit(), DELTA); + } + + @Test + void effectWithOneCharge_isUsedUpByTheFirstHit() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + + EntityStats.get(attacker).addEffect(new AdjustStatEffect.Builder(-1) + .withCharges(1) + .withAdjust(Objects.requireNonNull(ItemStats.getDamageById("physical")), v -> v + 10D) + .build()); + + assertEquals(30D, physicalHit(), DELTA); + assertEquals(20D, physicalHit(), DELTA); + } + + @Test + void profileBuffAdded_isSeenByTheNextHit_andNoLongerOnceRemoved() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + UserProfile profile = profileOf(attacker); + + profile.addDamageBuff(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 60_000L)); + assertEquals(30D, physicalHit(), DELTA); + + profile.removeDamageBuff("physical"); + assertEquals(20D, physicalHit(), DELTA); + } + + @Test + void profileBuffThatRunsOut_isNoLongerSeenByTheNextHit() throws Exception { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + // Long enough that the first hit lands while it is still active, short enough to wait for + profileOf(attacker).addDamageBuff(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 600L)); + assertEquals(30D, physicalHit(), DELTA); + + Thread.sleep(800); + + assertEquals(20D, physicalHit(), DELTA); + } + + @Test + void profileBuffsEditedInPlace_areSeenOnceTheyAreMarkedChanged() { + // What the buff command does: it edits the sets it is handed + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + UserProfile profile = profileOf(attacker); + + profile.getDamageBuffs().add(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 60_000L)); + profile.markBuffsChanged(); + + assertEquals(30D, physicalHit(), DELTA); + } + + @Test + void profileSwitch_isSeenByTheNextHit() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + UserProfile first = profileOf(attacker); + first.addDamageBuff(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 60_000L)); + assertEquals(30D, physicalHit(), DELTA); + + DivinityUser user = Objects.requireNonNull(plugin.getUserManager().getOrLoadUser(attacker)); + assertTrue(user.addProfile("other")); + assertTrue(user.switchProfile("other")); + try { + assertEquals(20D, physicalHit(), DELTA, "The other profile has no buff"); + } finally { + user.switchProfile(first.getIdName()); + } + } + + @Test + void biome_isReadAtTheHit_notCached() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + tick(); + assertTrue(EntityStats.get(attacker).hasSnapshot()); + + String biome = EnumUT.getName(attacker.getLocation().getBlock().getBiome()); + Map modifiers = ItemStats.getDamageById("physical").getBiomeDamageModifiers(); + Double previous = modifiers.put(biome, 1.5D); + try { + assertEquals(30D, physicalHit(), DELTA); + } finally { + if (previous == null) modifiers.remove(biome); + else modifiers.put(biome, previous); + } + assertEquals(20D, physicalHit(), DELTA); + } + + @Test + void vanillaArmorAttribute_isSeenByTheNextHit() { + EngineCfg.LEGACY_COMBAT = true; + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + + // Potions and other plugins change attributes and tell no one + victim.registerAttribute(Attribute.ARMOR); + Objects.requireNonNull(victim.getAttribute(Attribute.ARMOR)).setBaseValue(30D); + + assertEquals(15.2D, physicalHit(), DELTA); + } + + @Test + void vanillaToughnessAttribute_isSeenByTheNextHit() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + victim.getInventory().setChestplate(armor(Map.of("physical", 30D))); + refresh(); + // 1 - max(30 / 5, 30 - 4 * 20 / (toughness 0 + 8)) * protection factor 0.8 * 0.05 = 0.2 + assertEquals(4D, physicalHit(), DELTA); + + victim.registerAttribute(Attribute.ARMOR_TOUGHNESS); + Objects.requireNonNull(victim.getAttribute(Attribute.ARMOR_TOUGHNESS)).setBaseValue(2D); + + // 1 - max(6, 30 - 4 * 20 / (2 + 8)) * 0.04 = 0.12 + assertEquals(2.4D, physicalHit(), DELTA); + } + + @Test + void death_dropsAPlayersSnapshot() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + hit(); + assertTrue(EntityStats.get(attacker).hasSnapshot()); + assertEquals(20D, EntityStats.get(attacker).getDamageByType(physical()), DELTA); + + attacker.getInventory().clear(); // What dying does to the inventory + EntityStats.get(attacker).handleDeath(); + + assertFalse(EntityStats.get(attacker).hasSnapshot()); + assertEquals(0D, EntityStats.get(attacker).getDamageByType(physical()), DELTA); + } + + @Test + void death_releasesAMobsStats() { + ZombieMock zombie = new ZombieMock(server, UUID.randomUUID()); + EntityStats.get(zombie).getEnchantProtectFactor(Enchantment.PROTECTION); // Fills a snapshot + assertTrue(EntityStats.isTracked(zombie)); + + server.getPluginManager() + .callEvent(new EntityDeathEvent(zombie, + DamageSource.builder(DamageType.GENERIC).build(), + new ArrayList<>())); + + assertFalse(EntityStats.isTracked(zombie)); + } + + @Test + void quit_releasesAPlayersStats() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + hit(); + assertTrue(EntityStats.isTracked(attacker)); + + server.getPluginManager().callEvent(new PlayerQuitEvent(attacker, "left")); + + assertFalse(EntityStats.isTracked(attacker)); + } + + @Test + void anEntityThatIsGone_isReleasedBySweep() { + ZombieMock zombie = new ZombieMock(server, UUID.randomUUID()); + EntityStats.get(zombie).getEnchantProtectFactor(Enchantment.PROTECTION); + assertTrue(EntityStats.isTracked(zombie)); + + zombie.remove(); // What unloading or despawning does + EntityStats.getAll(); // What the stats task does every tick + + assertFalse(EntityStats.isTracked(zombie)); + } + + @Test + void invalidatingEveryone_dropsEveryoneSnapshot() { + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + hit(); + assertTrue(EntityStats.get(attacker).hasSnapshot()); + assertTrue(EntityStats.get(victim).hasSnapshot()); + + EntityStats.invalidateAllSnapshots(); // What a reload of the stat config does + + assertFalse(EntityStats.get(attacker).hasSnapshot()); + assertFalse(EntityStats.get(victim).hasSnapshot()); + } + + // ------------------------------------------------------------------ // + // The fallback for changes nothing announces + // ------------------------------------------------------------------ // + + @Test + void aSnapshot_isNotUsedPastItsMaximumAge() { + AtomicLong now = new AtomicLong(1_000_000L); + EntityStats.setClock(now::get); + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 20; // 1 second + + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + UserProfile profile = profileOf(attacker); + // Edited without a word to anyone: nothing here can tell the snapshot + profile.getDamageBuffs().add(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 3_600_000L)); + + now.addAndGet(900); + assertEquals(20D, physicalHit(), DELTA, "Still inside the maximum age: the snapshot is used"); + + now.addAndGet(200); + assertEquals(30D, physicalHit(), DELTA, "Past the maximum age: read again"); + } + + @Test + void aMaximumAgeOfZero_turnsTheCacheOff() { + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 0; + attacker.getInventory().setItemInMainHand(weapon(Map.of("physical", 20D))); + refresh(); + assertEquals(20D, physicalHit(), DELTA); + assertFalse(EntityStats.get(attacker).hasSnapshot()); + + profileOf(attacker).getDamageBuffs() + .add(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 60_000L)); + + assertEquals(30D, physicalHit(), DELTA); + } + + // ------------------------------------------------------------------ // + // Rolls: the range is cached, the roll is not + // ------------------------------------------------------------------ // + + @Test + void aRange_isRolledAtEveryHit_notWhenTheSnapshotIsTaken() { + attacker.getInventory().setItemInMainHand(rangedWeapon(10D, 20D)); + refresh(); + + Set rolls = new HashSet<>(); + for (int i = 0; i < 40; i++) { + double damage = physicalHit(); // No refresh in between: one snapshot serves them all + assertTrue(damage >= 10D && damage <= 20D, "Rolled outside the range: " + damage); + rolls.add(damage); + } + assertTrue(EntityStats.get(attacker).hasSnapshot()); + assertTrue(rolls.size() > 20, "Every hit should roll for itself, but only got " + rolls.size() + " values"); + } + + @Test + void rolls_followTheSameSequenceWhetherOrNotTheSnapshotIsUsed() { + attacker.getInventory().setItemInMainHand(rangedWeapon(10D, 20D)); + refresh(); + + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 20; + List cached = rolls(200, 1234L); + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 0; + List uncached = rolls(200, 1234L); + + assertEquals(uncached, cached, "The same seed should give the same rolls with or without the cache"); + } + + @Test + void rolls_areUniformOverTheRange() { + attacker.getInventory().setItemInMainHand(rangedWeapon(10D, 20D)); + refresh(); + + int n = 20_000; + List rolls = rolls(n, 99L); + + double mean = rolls.stream().mapToDouble(d -> d).average().orElseThrow(); + assertEquals(15D, mean, 0.15D, "The mean of a uniform roll between 10 and 20 is 15"); + int[] bins = new int[10]; + for (double roll : rolls) { + assertTrue(roll >= 10D && roll <= 20D); + bins[Math.min(9, (int) (roll - 10D))]++; + } + double expected = n / 10D; + double chi = 0; + for (int count : bins) chi += (count - expected) * (count - expected) / expected; + assertTrue(chi < 40D, "Rolls are not uniform, chi-square " + chi + " over bins " + java.util.Arrays.toString(bins)); + } + + @Test + void rolls_matchWhatTheCalculatorGaveBeforeSnapshotsExisted() { + // These numbers were produced by the code before snapshots existed, from the same item and seed + attacker.getInventory().setItemInMainHand(rangedWeapon(10D, 20D)); + refresh(); + + List rolls = rolls(5, 1234L); + + double[] before = BEFORE_SNAPSHOTS_SEED_1234; + for (int i = 0; i < before.length; i++) { + assertEquals(before[i], rolls.get(i), 1e-9, "Roll " + i); + } + } + + // Rolled by the code of the base commit (aed8234) for the same item and seed + private static final double[] BEFORE_SNAPSHOTS_SEED_1234 = { + 16.05520825575022D, 17.93004448505456D, 17.417024356698136D, 12.687599526733104D, 17.451704997376304D}; + + // ------------------------------------------------------------------ // + // Projectiles: the shooter's stats at launch + // ------------------------------------------------------------------ // + + @Test + void projectile_usesTheGearItWasFiredWith_notTheGearAtImpact() { + attacker.getInventory().setItemInMainHand(bow(15D)); + attacker.getInventory().setChestplate(damageGear(5D)); + refresh(); + + Arrow arrow = launch(); + // The shooter swaps armor while the arrow is in the air + attacker.getInventory().setChestplate(damageGear(25D)); + EntityStats.get(attacker).updateAll(); + + assertEquals(20D, arrowPhysical(arrow), DELTA, "15 from the bow and 5 from the armor worn at launch"); + } + + @Test + void projectile_notLaunchedThroughDivinity_isReadAtImpactAsItAlwaysWas() { + attacker.getInventory().setItemInMainHand(bow(15D)); + attacker.getInventory().setChestplate(damageGear(5D)); + refresh(); + + Arrow arrow = victim.getWorld().spawn(victim.getLocation(), Arrow.class); + arrow.setShooter(attacker); + ProjectileStats.setSrcWeapon(arrow, bow(15D)); + ProjectileStats.setPower(arrow, 1D); + assertNull(ProjectileStats.getSnapshot(arrow)); + + attacker.getInventory().setChestplate(damageGear(25D)); + EntityStats.get(attacker).updateAll(); + + assertEquals(40D, arrowPhysical(arrow), DELTA); + } + + @Test + void projectile_ignoresABuffGainedAfterItWasFired() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + Arrow arrow = launch(); + + profileOf(attacker).addDamageBuff(new SavedBuff("physical", 10D, false, System.currentTimeMillis() + 60_000L)); + + assertEquals(15D, arrowPhysical(arrow), DELTA); + assertEquals(25D, arrowPhysical(launch()), DELTA, "An arrow fired now has the buff"); + } + + @Test + void projectile_ignoresAnEffectGainedAfterItWasFired() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + Arrow arrow = launch(); + + EntityStats.get(attacker).addEffect(new AdjustStatEffect.Builder(-1) + .withAdjust(physical(), v -> v + 10D) + .build()); + + assertEquals(15D, arrowPhysical(arrow), DELTA); + } + + @Test + void projectile_keepsAnEffectItWasFiredWith_evenIfItIsGoneAtImpact() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + AdjustStatEffect effect = new AdjustStatEffect.Builder(-1).withAdjust(physical(), v -> v + 10D).build(); + EntityStats.get(attacker).addEffect(effect); + Arrow arrow = launch(); + + EntityStats.get(attacker).removeEffect(effect); + + assertEquals(25D, arrowPhysical(arrow), DELTA); + } + + @Test + void projectile_takesTheShootersItemStatsAtLaunchToo() { + ItemStack bow = bow(15D); + stat(bow, TypedStat.Type.PVP_DAMAGE, 50D); // +50% against players + attacker.getInventory().setItemInMainHand(bow); + refresh(); + Arrow arrow = launch(); + + // Gear with a higher PvP bonus goes on while the arrow flies + ItemStack ring = damageGear(0D); + stat(ring, TypedStat.Type.PVP_DAMAGE, 500D); + attacker.getInventory().setChestplate(ring); + EntityStats.get(attacker).updateAll(); + + assertEquals(22.5D, arrowPhysical(arrow), DELTA); + } + + @Test + void projectile_snapshotIsReleasedWhenTheProjectileIsGone() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + Arrow arrow = launch(); + ProjectileStats.sweep(); + assertNotNull(ProjectileStats.getSnapshot(arrow), "A projectile in the air keeps its snapshot"); + int before = ProjectileStats.snapshotCount(); + + arrow.remove(); + // Where it was is loaded, and it is not there any more: gone. (Were the chunk unloaded it would be kept.) + victim.getWorld().loadChunk(arrow.getLocation().getBlockX() >> 4, arrow.getLocation().getBlockZ() >> 4); + ProjectileStats.sweep(); + + assertNull(ProjectileStats.getSnapshot(arrow)); + assertEquals(before - 1, ProjectileStats.snapshotCount()); + } + + // ------------------------------------------------------------------ // + // Helpers + // ------------------------------------------------------------------ // + + private static boolean isIronSword(ItemStack item) { + return item != null && item.getType() == Material.IRON_SWORD; + } + + private DamageAttribute physical() { + return Objects.requireNonNull(ItemStats.getDamageById("physical")); + } + + private void refresh() { + for (PlayerMock player : List.of(attacker, victim)) { + EntityStats.purge(player); + EntityStats.get(player).updateAll(); + } + } + + /** Lets the server run a tick, which is when the refreshes that a hit or an equipment change asks for run. */ + private void tick() { + try (MockedStatic ignored = mockStatic(EffectUT.class)) { + server.getScheduler().performOneTick(); + } + } + + /** Fires a melee hit the way the server would and returns what it did, by damage type. */ + private Map hit() { + server.getPluginManager().callEvent(new EntityDamageByEntityEvent(attacker, + victim, + DamageCause.ENTITY_ATTACK, + modifiers(VANILLA_SWORD_DAMAGE), + functions(modifiers(VANILLA_SWORD_DAMAGE)))); + return damagesOf(EntityStats.get(victim).getLastDamageMeta()); + } + + private double physicalHit() { + return hit().getOrDefault("physical", 0D); + } + + private double arrowPhysical(Arrow arrow) { + return arrowHit(arrow).getOrDefault("physical", 0D); + } + + private Map arrowHit(Arrow arrow) { + server.getPluginManager().callEvent(new EntityDamageByEntityEvent(arrow, + victim, + DamageCause.PROJECTILE, + modifiers(4), + functions(modifiers(4)))); + return damagesOf(EntityStats.get(victim).getLastDamageMeta()); + } + + /** What the server does when the attacker shoots: the launch event, with the bow in hand. */ + private Arrow launch() { + ItemStack bow = attacker.getInventory().getItemInMainHand(); + Arrow arrow = victim.getWorld().spawn(victim.getLocation(), Arrow.class); + arrow.setShooter(attacker); + // The real event cannot be built here: its constructor sets properties MockBukkit refuses to set. What + // it records on the projectile is recorded by hand, as the constructor would. + ProjectileStats.setSrcWeapon(arrow, bow); + ProjectileStats.setPower(arrow, 1D); + DivinityProjectileLaunchEvent event = mock(DivinityProjectileLaunchEvent.class, + withSettings().defaultAnswer(CALLS_REAL_METHODS)); + doReturn(arrow).when(event).getProjectile(); + doReturn(attacker).when(event).getShooter(); + doReturn(bow).when(event).getWeapon(); + doReturn(1D).when(event).getPower(); + doReturn(true).when(event).isBowEvent(); + server.getPluginManager().callEvent(event); + assertNotNull(ProjectileStats.getSnapshot(arrow), "Test setup: the launch should have taken a snapshot"); + return arrow; + } + + private List rolls(int count, long seed) { + Rnd.rnd.setSeed(seed); + EntityStats stats = EntityStats.get(attacker); + List rolls = new ArrayList<>(); + for (int i = 0; i < count; i++) { + rolls.add(stats.getDamageByType(physical())); + } + return rolls; + } + + private UserProfile profileOf(PlayerMock player) { + DivinityUser user = Objects.requireNonNull(plugin.getUserManager().getOrLoadUser(player)); + return user.getActiveProfile(); + } + + private static Map damagesOf(DamageMeta meta) { + Map damages = new HashMap<>(); + Objects.requireNonNull(meta).getDamages().forEach((attribute, amount) -> damages.put(attribute.getId(), amount)); + return damages; + } + + private BonusMap physicalDamageBonus(double flat) { + BonusMap map = new BonusMap(); + map.getBonuses().put(physical(), (isPercent, input) -> isPercent ? input : input + flat); + return map; + } + + /** Stands in for the sets module, which the tests do not configure. */ + private SetManagerInstalled installSetManager(List active) throws Exception { + Field field = ModuleCache.class.getDeclaredField("setManager"); + field.setAccessible(true); + ModuleCache cache = plugin.getModuleCache(); + Object previous = field.get(cache); + + SetManager sets = mock(SetManager.class); + when(sets.getActiveSetBonuses(any())).thenAnswer(ans -> new ArrayList<>(active)); + field.set(cache, sets); + return () -> { + try { + field.set(cache, previous); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + }; + } + + private interface SetManagerInstalled extends AutoCloseable { + @Override + void close(); + } + + private 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; + } + + private ItemStack rangedWeapon(double min, double max) { + ItemStack item = new ItemStack(Material.IRON_SWORD); + physical().add(item, new StatBonus(new double[]{min, max}, false, null), -1); + return item; + } + + private ItemStack bow(double physical) { + ItemStack item = new ItemStack(Material.BOW); + physical().add(item, new StatBonus(new double[]{physical}, false, null), -1); + return item; + } + + /** A chestplate that adds damage, as a piece of gear with a damage stat does. */ + private ItemStack damageGear(double physical) { + ItemStack item = new ItemStack(Material.IRON_CHESTPLATE); + if (physical > 0) physical().add(item, new StatBonus(new double[]{physical}, false, null), -1); + return item; + } + + private 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; + } + + private 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); + } + + private static Map modifiers(double base) { + Map modifiers = new EnumMap<>(DamageModifier.class); + modifiers.put(DamageModifier.BASE, base); + return modifiers; + } + + private static Map> functions(Map modifiers) { + Map> functions = new EnumMap<>(DamageModifier.class); + modifiers.forEach((modifier, value) -> functions.put(modifier, d -> value)); + return functions; + } + + /** MockBukkit does not implement the attack cooldown, which the server tick reads for every player. */ + private static class TickSafePlayer extends PlayerMock { + TickSafePlayer(@NotNull ServerMock server, @NotNull String name) { + super(server, name, UUID.randomUUID()); + } + + @Override + public float getAttackCooldown() { + return 1F; + } + } +} diff --git a/src/test/java/studio/magemonkey/divinity/stats/ProjectileLaunchSnapshotTest.java b/src/test/java/studio/magemonkey/divinity/stats/ProjectileLaunchSnapshotTest.java new file mode 100644 index 00000000..38af619b --- /dev/null +++ b/src/test/java/studio/magemonkey/divinity/stats/ProjectileLaunchSnapshotTest.java @@ -0,0 +1,476 @@ +package studio.magemonkey.divinity.stats; + +import com.google.common.base.Function; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.EnderPearl; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.Snowball; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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.util.EffectUT; +import studio.magemonkey.divinity.Divinity; +import studio.magemonkey.divinity.api.event.DivinityProjectileLaunchEvent; +import studio.magemonkey.divinity.config.EngineCfg; +import studio.magemonkey.divinity.manager.damage.DamageMeta; +import studio.magemonkey.divinity.manager.effects.main.AdjustStatEffect; +import studio.magemonkey.divinity.stats.bonus.StatBonus; +import studio.magemonkey.divinity.stats.items.ItemStats; +import studio.magemonkey.divinity.stats.items.attributes.DamageAttribute; +import studio.magemonkey.divinity.testutil.MockedTest; + +import java.io.*; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.withSettings; + +/** + * What a projectile carries from its launch to its impact (review of #385): whose stats they are, which + * projectiles get any, when their effects are charged, how long they are held, and what a reload does to them. + */ +@SuppressWarnings("deprecation") +class ProjectileLaunchSnapshotTest extends MockedTest { + private static final double DELTA = 1e-6; + + private TickSafePlayer attacker; + private TickSafePlayer victim; + private TickSafePlayer other; + private int originalMaxAge; + + // The mock plugin jar has no loose resource files, so the shipped arrow is copied into the plugin folder + @BeforeAll + void copyShippedArrowConfig() throws IOException { + File file = new File(server.getPluginsFolder().getAbsoluteFile() + File.separator + + "Divinity-" + System.getProperty("DIVINITY_VERSION") + File.separator + + "modules" + File.separator + "arrows" + File.separator + "items" + File.separator + + "arrow_pierce.yml"); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + file.createNewFile(); + } + try (BufferedReader in = new BufferedReader(new InputStreamReader(Objects.requireNonNull(this.getClass() + .getClassLoader() + .getResourceAsStream("modules/arrows/items/arrow_pierce.yml")))); + FileWriter out = new FileWriter(file)) { + String str; + while ((str = in.readLine()) != null) { + out.write(str + "\n"); + } + } + Divinity.getInstance().reload(); + } + + @BeforeEach + void setup() { + attacker = player("Shooter"); + victim = player("Victim"); + other = player("Other"); + originalMaxAge = EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE; + + EngineCfg.VANILLA_ONLY_ITEM_STATS = true; + doAnswer(ans -> 0D).when(VersionManager.getNms()).getDefaultDamage(any()); + doAnswer(ans -> false).when(VersionManager.getNms()).isWeapon(any()); + doAnswer(ans -> Registry.ATTRIBUTE.get(NamespacedKey.minecraft(((String) ans.getArgument(0)).toLowerCase( + Locale.US)))).when(VersionManager.getNms()).getAttribute(anyString()); + tick(); // Let the refreshes that joining asks for run now + } + + @AfterEach + void tearDown() { + ProjectileStats.resetClock(); + ProjectileStats.clear(); + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = originalMaxAge; + EngineCfg.VANILLA_ONLY_ITEM_STATS = false; + int offset = 0; + for (PlayerMock p : players) { + p.teleport(p.getLocation().add(10_000 + 100 * offset++, 0, 0)); + } + tick(); + players.forEach(EntityStats::purge); + } + + // ------------------------------------------------------------------ // + // Whose stats they are + // ------------------------------------------------------------------ // + + @Test + void aProjectileThatChangedHands_isNotReadFromTheOriginalShootersSnapshot() { + attacker.getInventory().setItemInMainHand(bow(15D)); + attacker.getInventory().setChestplate(damageGear(5D)); + refresh(); + Arrow arrow = launch(attacker); + assertEquals(20D, arrowHit(arrow), DELTA, "Test setup: the snapshot is 15 from the bow and 5 from the armor"); + + // Reflected, or taken over by a plugin: the new owner wears nothing + arrow.setShooter(other); + refresh(); + + assertEquals(15D, arrowHit(arrow), DELTA, "Read live from the new shooter, as before snapshots"); + } + + @Test + void twoProjectilesFromOneShooter_eachKeepTheirOwnSnapshot() { + attacker.getInventory().setItemInMainHand(bow(15D)); + attacker.getInventory().setChestplate(damageGear(5D)); + refresh(); + Arrow first = launch(attacker); + + attacker.getInventory().setChestplate(damageGear(25D)); + EntityStats.get(attacker).updateAll(); + Arrow second = launch(attacker); + + attacker.getInventory().setChestplate(damageGear(100D)); + EntityStats.get(attacker).updateAll(); + + assertEquals(20D, arrowHit(first), DELTA); + assertEquals(40D, arrowHit(second), DELTA); + } + + @Test + void aCustomArrowsBonus_isCarriedFromLaunchToImpact() { + ArrowManagerHolder.requireShippedArrow(plugin); + attacker.getInventory().setItemInMainHand(bow(20D)); + refresh(); + + Arrow plain = launch(attacker); + assertEquals(20D, arrowHit(plain), DELTA); + + Arrow piercing = victim.getWorld().spawn(victim.getLocation(), Arrow.class); + piercing.setShooter(attacker); + piercing.setMetadata("QRPG_ARROW_ID", new FixedMetadataValue(plugin, "arrow_pierce")); + piercing.setMetadata("QRPG_ARROW_LEVEL", new FixedMetadataValue(plugin, 1)); + launchEvent(piercing, attacker); + assertEquals(18D, arrowHit(piercing), DELTA, "Piercing Arrow: 10% less damage"); + + // Gone from the projectile by the time it lands, and still in what it was fired with + piercing.removeMetadata("QRPG_ARROW_ID", plugin); + piercing.removeMetadata("QRPG_ARROW_LEVEL", plugin); + assertEquals(18D, arrowHit(piercing), DELTA); + } + + // ------------------------------------------------------------------ // + // Which projectiles get a snapshot + // ------------------------------------------------------------------ // + + @Test + void arrowsGetASnapshot_pearlsAndSnowballsDoNot() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + + Arrow arrow = victim.getWorld().spawn(victim.getLocation(), Arrow.class); + EnderPearl pearl = victim.getWorld().spawn(victim.getLocation(), EnderPearl.class); + Snowball snowball = victim.getWorld().spawn(victim.getLocation(), Snowball.class); + for (Projectile p : List.of(arrow, pearl, snowball)) { + p.setShooter(attacker); + launchEvent(p, attacker); + } + + assertNotNull(ProjectileStats.getSnapshot(arrow)); + assertNull(ProjectileStats.getSnapshot(pearl)); + assertNull(ProjectileStats.getSnapshot(snowball)); + assertTrue(ProjectileStats.canDealDamage(arrow)); + assertFalse(ProjectileStats.canDealDamage(pearl)); + assertFalse(ProjectileStats.canDealDamage(snowball)); + } + + // ------------------------------------------------------------------ // + // Charges are used at impact + // ------------------------------------------------------------------ // + + @Test + void aPearlOrASnowball_spendsNoCharge() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + AdjustStatEffect effect = oneChargeBonus(10D); + EntityStats.get(attacker).addEffect(effect); + + for (Projectile p : List.of(victim.getWorld().spawn(victim.getLocation(), EnderPearl.class), + victim.getWorld().spawn(victim.getLocation(), Snowball.class))) { + p.setShooter(attacker); + launchEvent(p, attacker); + } + + assertTrue(effect.isAdjusted(physical()), "Throwing something that deals no damage must keep the charge"); + } + + @Test + void anArrowThatIsLaunched_butNeverHits_spendsNoCharge() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + AdjustStatEffect effect = oneChargeBonus(10D); + EntityStats.get(attacker).addEffect(effect); + + launch(attacker); + + assertTrue(effect.isAdjusted(physical()), "A shot that has not landed has not used its charge"); + } + + @Test + void anArrowThatHits_spendsExactlyOneCharge_andHasTheAdjustment() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + AdjustStatEffect effect = oneChargeBonus(10D); + EntityStats.get(attacker).addEffect(effect); + Arrow arrow = launch(attacker); + + assertEquals(25D, arrowHit(arrow), DELTA, "The adjustment it was fired with"); + assertFalse(effect.isAdjusted(physical()), "One charge, and the hit used it"); + + assertEquals(15D, arrowHit(launch(attacker)), DELTA, "Nothing left for the next arrow"); + } + + @Test + void anEffectThatIsGoneAtImpact_isNotChargedAndDoesNotFail() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + AdjustStatEffect effect = oneChargeBonus(10D); + EntityStats.get(attacker).addEffect(effect); + Arrow arrow = launch(attacker); + + EntityStats.get(attacker).removeEffect(effect); // Clears it + + assertEquals(25D, arrowHit(arrow), DELTA); + } + + // ------------------------------------------------------------------ // + // How long they are held + // ------------------------------------------------------------------ // + + @Test + void aProjectileInAnUnloadedChunk_keepsItsSnapshot() { + UUID gone = UUID.randomUUID(); + UUID world = victim.getWorld().getUID(); + assertFalse(victim.getWorld().isChunkLoaded(100_000, 100_000), "Test setup: this chunk is not loaded"); + ProjectileStats.hold(gone, frozen(), world, 100_000, 100_000); + int before = ProjectileStats.snapshotCount(); + + ProjectileStats.sweep(); + + assertEquals(before, ProjectileStats.snapshotCount(), "It may come back when the chunk loads"); + } + + @Test + void aProjectileThatCannotBeFoundInALoadedChunk_isReleased() { + UUID gone = UUID.randomUUID(); + UUID world = victim.getWorld().getUID(); + int cx = victim.getLocation().getBlockX() >> 4; + int cz = victim.getLocation().getBlockZ() >> 4; + victim.getWorld().loadChunk(cx, cz); + assertTrue(victim.getWorld().isChunkLoaded(cx, cz), "Test setup: this chunk is loaded"); + ProjectileStats.hold(gone, frozen(), world, cx, cz); + int before = ProjectileStats.snapshotCount(); + + ProjectileStats.sweep(); + + assertEquals(before - 1, ProjectileStats.snapshotCount()); + } + + @Test + void aSnapshotIsNotHeldPastTheUpperAgeBound_whateverTheChunk() { + AtomicLong now = new AtomicLong(5_000_000L); + ProjectileStats.setClock(now::get); + ProjectileStats.hold(UUID.randomUUID(), frozen(), victim.getWorld().getUID(), 100_000, 100_000); + int held = ProjectileStats.snapshotCount(); + + now.addAndGet(ProjectileStats.MAX_HELD_MILLIS - 1); + ProjectileStats.sweep(); + assertEquals(held, ProjectileStats.snapshotCount()); + + now.addAndGet(2); + ProjectileStats.sweep(); + assertEquals(held - 1, ProjectileStats.snapshotCount()); + } + + // ------------------------------------------------------------------ // + // Reload and the off switch + // ------------------------------------------------------------------ // + + @Test + void aReload_dropsLaunchSnapshotsAndLiveSnapshotsAlike() { + attacker.getInventory().setItemInMainHand(bow(15D)); + attacker.getInventory().setChestplate(damageGear(5D)); + refresh(); + Arrow arrow = launch(attacker); + arrowHit(arrow); // Fills the victim's and the shooter's live snapshots as well + assertTrue(EntityStats.get(victim).hasSnapshot()); + assertNotNull(ProjectileStats.getSnapshot(arrow)); + + plugin.reload(); + + assertNull(ProjectileStats.getSnapshot(arrow), "A launch snapshot holds stat objects that reload replaces"); + assertFalse(EntityStats.isTracked(attacker), "Live snapshots go with the stats they sit on"); + assertFalse(EntityStats.isTracked(victim)); + } + + @Test + void aMaximumAgeOfZero_copiesNoItems() { + attacker.getInventory().setItemInMainHand(bow(15D)); + refresh(); + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 0; + + try (MockedStatic snapshots = mockStatic(StatSnapshot.class, CALLS_REAL_METHODS)) { + EntityStats.get(attacker).getDamageTypes(false); + EntityStats.get(attacker).getItemStat(studio.magemonkey.divinity.stats.items.attributes.api.TypedStat.Type.PVP_DAMAGE, false); + snapshots.verify(() -> StatSnapshot.copyOf(any()), never()); + } + + EngineCfg.PERFORMANCE_STAT_SNAPSHOT_MAX_AGE = 20; + try (MockedStatic snapshots = mockStatic(StatSnapshot.class, CALLS_REAL_METHODS)) { + EntityStats.get(attacker).getDamageTypes(false); + snapshots.verify(() -> StatSnapshot.copyOf(any()), times(1)); + } + } + + // ------------------------------------------------------------------ // + // Helpers + // ------------------------------------------------------------------ // + + /** A frozen snapshot with nothing in it, for the tests that are about how long one is held. */ + private StatSnapshot frozen() { + return new StatSnapshot(UUID.randomUUID(), null, new HashMap<>()); + } + + private TickSafePlayer player(String name) { + TickSafePlayer p = new TickSafePlayer(server, name); + server.addPlayer(p); + players.add(p); + return p; + } + + private DamageAttribute physical() { + return Objects.requireNonNull(ItemStats.getDamageById("physical")); + } + + private AdjustStatEffect oneChargeBonus(double flat) { + return new AdjustStatEffect.Builder(-1).withCharges(1).withAdjust(physical(), v -> v + flat).build(); + } + + private void refresh() { + for (PlayerMock p : List.of(attacker, victim, other)) { + EntityStats.purge(p); + EntityStats.get(p).updateAll(); + } + } + + private void tick() { + try (MockedStatic ignored = mockStatic(EffectUT.class)) { + server.getScheduler().performOneTick(); + } + } + + /** A bow shot by the shooter: the projectile, its weapon and power, and the launch event. */ + private Arrow launch(PlayerMock shooter) { + Arrow arrow = victim.getWorld().spawn(victim.getLocation(), Arrow.class); + arrow.setShooter(shooter); + launchEvent(arrow, shooter); + assertNotNull(ProjectileStats.getSnapshot(arrow), "Test setup: the launch should have taken a snapshot"); + return arrow; + } + + /** + * The real event cannot be built here (its constructor sets properties MockBukkit refuses to set), so it is + * stubbed, and what its constructor records on the projectile is recorded by hand. + */ + private void launchEvent(Projectile projectile, PlayerMock shooter) { + ItemStack bow = shooter.getInventory().getItemInMainHand(); + ProjectileStats.setSrcWeapon(projectile, bow); + ProjectileStats.setPower(projectile, 1D); + DivinityProjectileLaunchEvent event = mock(DivinityProjectileLaunchEvent.class, + withSettings().defaultAnswer(CALLS_REAL_METHODS)); + doReturn(projectile).when(event).getProjectile(); + doReturn(shooter).when(event).getShooter(); + doReturn(bow).when(event).getWeapon(); + doReturn(1D).when(event).getPower(); + doReturn(true).when(event).isBowEvent(); + server.getPluginManager().callEvent(event); + } + + private double arrowHit(Arrow arrow) { + server.getPluginManager().callEvent(new EntityDamageByEntityEvent(arrow, + victim, + DamageCause.PROJECTILE, + modifiers(4), + functions(modifiers(4)))); + DamageMeta meta = Objects.requireNonNull(EntityStats.get(victim).getLastDamageMeta()); + Map damages = new HashMap<>(); + meta.getDamages().forEach((attribute, amount) -> damages.put(attribute.getId(), amount)); + return damages.getOrDefault("physical", 0D); + } + + private ItemStack bow(double physical) { + ItemStack item = new ItemStack(Material.BOW); + physical().add(item, new StatBonus(new double[]{physical}, false, null), -1); + return item; + } + + private ItemStack damageGear(double physical) { + ItemStack item = new ItemStack(Material.IRON_CHESTPLATE); + physical().add(item, new StatBonus(new double[]{physical}, false, null), -1); + return item; + } + + private static Map modifiers(double base) { + Map modifiers = new EnumMap<>(DamageModifier.class); + modifiers.put(DamageModifier.BASE, base); + return modifiers; + } + + private static Map> functions(Map modifiers) { + Map> functions = new EnumMap<>(DamageModifier.class); + modifiers.forEach((modifier, value) -> functions.put(modifier, d -> value)); + return functions; + } + + private static final class ArrowManagerHolder { + static void requireShippedArrow(Divinity plugin) { + assertNotNull(plugin.getModuleCache().getArrowManager(), "ArrowManager module should be enabled"); + assertNotNull(plugin.getModuleCache().getArrowManager().getItemById("arrow_pierce"), + "Shipped 'arrow_pierce' item should have loaded"); + } + } + + /** MockBukkit does not implement the attack cooldown, which the server tick reads for every player. */ + private static class TickSafePlayer extends PlayerMock { + TickSafePlayer(@NotNull ServerMock server, @NotNull String name) { + super(server, name, UUID.randomUUID()); + } + + @Override + public float getAttackCooldown() { + return 1F; + } + } +}