Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion doc/COMBAT_RESTRUCTURE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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=<file> 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
Expand All @@ -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.
7 changes: 6 additions & 1 deletion doc/COMBAT_RESTRUCTURE_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 |

Expand Down
3 changes: 3 additions & 0 deletions src/main/java/studio/magemonkey/divinity/Divinity.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<EntityStats> toRemove = new ArrayList<>(EntityStats.getAll());
toRemove.forEach(EntityStats::purge);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.";
Expand Down
41 changes: 39 additions & 2 deletions src/main/java/studio/magemonkey/divinity/data/api/UserProfile.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public class UserProfile {
private final Set<SavedBuff> buffDamage;
private final Set<SavedBuff> buffDefense;
private final Set<SavedBuff> 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
Expand Down Expand Up @@ -192,16 +194,51 @@ public void removeStatBuff(@NotNull String statId) {
}

private void validateBuffs(@NotNull Set<SavedBuff> list) {
list.removeIf(buff -> buff.isExpired());
if (list.removeIf(buff -> buff.isExpired())) this.markBuffsChanged();
}

private void addBuff(@NotNull SavedBuff buff, @NotNull Set<SavedBuff> to) {
this.removeBuff(buff.getStatId(), to);
to.add(buff);
this.markBuffsChanged();
}

private void removeBuff(@NotNull String statId, @NotNull Set<SavedBuff> 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<SavedBuff> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down Expand Up @@ -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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -49,7 +50,7 @@ public Set<? extends ItemLoreStat<?>> getAdjustedStats() {
}

public boolean isAdjusted(@NotNull ItemLoreStat<?> stat) {
return this.functions.containsKey(stat);
return this.functions != null && this.functions.containsKey(stat);
}

@Override
Expand Down
Loading
Loading