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
47 changes: 45 additions & 2 deletions doc/COMBAT_RESTRUCTURE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ 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.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 |
| 4.1 Formulas in `combat.yml` | In review (#387) |
| 4.2 Stat snapshots | Done (#385) |
| 4.2b Vanilla Thorns | Done (#384) |
| 4.3 and 5 | Not started |

## Rules for every pull request

Expand Down Expand Up @@ -158,6 +160,47 @@ 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.

## Formulas in `combat.yml` (4.1)

- **Where things are.** `config/CombatCfg` loads and migrates the file and holds what is in force.
`manager/damage/formula/` holds `CombatExpression` (the four expressions, their variables and their default
text), `CombatPreset`, `CombatFormulas` (compiled set plus overrides) and `Formulas`.
`DamageCalculator` keeps the stage order and the bookkeeping between stages; the numbers come from the expressions.
- **Expressions are compiled once with Codex's `Evaluator.compile`** (needs Codex `1.3.0-dev.2`, which is why
`MIN_CORE_VERSION` was raised). A `CompiledExpression` is immutable and safe from any thread, binds variables by
position and returns NaN and infinity as they are, so `CombatFormulas` checks every expression against the sample
values in `CombatExpression` at load. Syntax follows Javaluator: `^` is left associative. **Javaluator, which
Codex bundles, computes `x * 2^-1` wrongly without complaining** (the old string evaluator does too), so
`CombatFormulas` rejects any override with `^` followed by a minus and tells the admin to write `2^(-1)`. Remove
that check only once Codex has fixed the parser.
- **`DamageCalculator` keeps no state between calls** and builds a fresh argument array for each evaluation, so one
calculator can be shared between threads and kept across hits (the stat snapshots in 4.2 may want that). It used
to reuse arrays to avoid the allocation; measured on the benchmark that saved nothing noticeable, and it made
sharing a calculator unsafe. `CombatFormulasTest` has a test that shares one calculator between eight threads and
one that reuses it for many calls; keep both if the calculator changes.
- **`ReferenceDamageCalculator` (test sources) is the formula as it was written in Java.** The equivalence test
compares bit for bit against it for both presets. Never edit its arithmetic to make a test pass.
- **`EngineCfg.LEGACY_COMBAT` is a deprecated override and nothing sets it.** `CombatCharacterizationTest` and
`DamageCalculatorTest` still set it (or `Modifiers.legacyCombat`) to run the legacy preset, which is why the
field and `Modifiers.legacyCombat` still exist. The old `engine.yml` key is read into
`EngineCfg.LEGACY_COMBAT_OLD_KEY` only so migration can pick a preset, and is ignored once `combat.yml` exists.
Do not make production code write `LEGACY_COMBAT` again: a stale `legacy-combat: true` in an old `engine.yml`
would then override the preset in `combat.yml`.
- **Reload.** `Divinity#reload` (Codex's `CodexPlugin#reload`, what a config reload runs) goes through
`ConfigManager.setup`, which calls `Divinity#setConfig`; `CombatCfg.load` runs there after `EngineCfg`, and the
order matters because migration reads the old `legacy-combat` key `EngineCfg` has just read. `CombatReloadTest`
uses the real `plugin.reload()` under MockBukkit and fails if the order changes or `CombatCfg.load` leaves
that path.
- **Variable names use underscores** (`pvp_pve_damage`), because a hyphen is the minus operator. `pvp_pve_damage` and
`pvp_pve_defense` are the PvP values when both sides are players, which is why the names say so.
- **Presets that give NaN or infinity keep doing so.** Only a formula the config overrides is replaced by the
preset's result at hit time; a preset's own non-finite result is passed on as the Java formula always did.
- **Benchmark.** `DamageCalculatorBenchmark` (test sources, not a test, has a `main`) compares the replaced Java
formulas with the configured ones on the same inputs. Run it after changing the evaluator. With Codex
`1.3.0-dev.2` the configured formulas are about 15 times slower on this calculator-only benchmark (roughly 400 ns
against 27 ns per hit, ten evaluations at about 35 ns); that is over the 1.5x the pull request aimed for and is
discussed in its description.

## Stat snapshots (4.2)

Read this before you touch `EntityStats`, `StatSnapshot`, `ProjectileStats` or the equipment handlers in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
public class DependencyRequirement {

/**
* The first Codex build with damage requests, which the damage listener and Divinity's own damage dealers
* use. It is a dev build; the 1.3.0 release and anything later meet it too.
* The first Codex build with damage requests (which the damage listener and Divinity's own damage dealers
* use) and with {@code Evaluator.compile} (which the formulas in combat.yml use). It is a dev build; the 1.3.0
* release and anything later meet it too.
*/
public static final String MIN_CORE_VERSION = "1.3.0-dev.1";
public static final String MIN_CORE_VERSION = "1.3.0-dev.2";

/**
* Whether providedVersion is at least requiredVersion, see {@link #compareVersions}.
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 @@ -16,6 +16,7 @@
import studio.magemonkey.divinity.command.ModifyCommand;
import studio.magemonkey.divinity.command.SetCommand;
import studio.magemonkey.divinity.config.Config;
import studio.magemonkey.divinity.config.CombatCfg;
import studio.magemonkey.divinity.config.EngineCfg;
import studio.magemonkey.divinity.config.Lang;
import studio.magemonkey.divinity.data.DivinityUserData;
Expand Down Expand Up @@ -209,6 +210,8 @@ public void setConfig() {
return;
}

CombatCfg.load(this);

this.lang = new Lang(this);
this.lang.setup();

Expand Down
216 changes: 216 additions & 0 deletions src/main/java/studio/magemonkey/divinity/config/CombatCfg.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package studio.magemonkey.divinity.config;

import com.google.common.annotations.VisibleForTesting;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import studio.magemonkey.divinity.Divinity;
import studio.magemonkey.divinity.manager.damage.formula.CombatExpression;
import studio.magemonkey.divinity.manager.damage.formula.CombatFormulas;
import studio.magemonkey.divinity.manager.damage.formula.CombatPreset;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
* Loads {@code combat.yml}, the damage formulas, and keeps the result for the damage calculator.
* <p>
* Loading never throws and never overwrites an existing {@code combat.yml}. When there is none, one is written:
* from the shipped file, with the preset that matches the old {@code combat.legacy-combat} key of
* {@code engine.yml}. That key is read for this one purpose and is ignored afterwards.
*/
public final class CombatCfg {

public static final String FILE_NAME = "combat.yml";

private static final String PRESET_KEY = "preset";
private static final String EXPRESSIONS_KEY = "expressions";

/** What is in force. Replaced as a whole, so a hit always sees one consistent set. */
private static volatile State state = State.defaults();

private CombatCfg() {
}

/** Loads (and if needed creates) {@code combat.yml} in the plugin's data folder. Call again to reload. */
public static void load(@NotNull Divinity plugin) {
load(plugin.getDataFolder(),
EngineCfg.LEGACY_COMBAT_OLD_KEY,
plugin.getLogger()::info,
plugin.getLogger()::warning);
}

/**
* @param folder the folder that holds (or will hold) {@code combat.yml}
* @param oldLegacyKey the value of {@code combat.legacy-combat} in {@code engine.yml}, or null if it is not there
* @param info receives the one line that reports a migration
* @param warn receives every problem, each once
*/
public static void load(@NotNull File folder,
@Nullable Boolean oldLegacyKey,
@NotNull Consumer<String> info,
@NotNull Consumer<String> warn) {
File file = new File(folder, FILE_NAME);

CombatPreset migrated = null;
if (!file.exists()) {
migrated = migrate(file, oldLegacyKey, info, warn);
}

CombatPreset preset = migrated != null ? migrated : CombatPreset.DEFAULT;
Map<String, Object> overrides = new HashMap<>();

if (file.exists()) {
YamlConfiguration yaml = new YamlConfiguration();
try {
yaml.load(file);
preset = readPreset(yaml, warn);
overrides = readOverrides(yaml, warn);
} catch (IOException | InvalidConfigurationException | RuntimeException e) {
warn.accept(FILE_NAME + " could not be read (" + e.getMessage() + "). Using the "
+ CombatPreset.DEFAULT.key() + " preset. The file is left as it is.");
preset = CombatPreset.DEFAULT;
overrides.clear();
}
}

// Only the preset in use reports its problems; the other one is built for the deprecated override below
CombatFormulas[] byPreset = new CombatFormulas[CombatPreset.values().length];
for (CombatPreset each : CombatPreset.values()) {
byPreset[each.ordinal()] = CombatFormulas.build(each, overrides, each == preset ? warn : null);
}
state = new State(preset, byPreset);
}

/**
* The formulas the damage calculator uses.
*
* @param forceLegacy selects the legacy preset whatever {@code combat.yml} says. Nothing in the plugin sets
* this; it exists for callers of the old {@code EngineCfg.LEGACY_COMBAT} switch.
*/
@NotNull
public static CombatFormulas formulas(boolean forceLegacy) {
State current = state;
return current.byPreset[(forceLegacy ? CombatPreset.LEGACY : current.preset).ordinal()];
}

/** The preset {@code combat.yml} selects. */
@NotNull
public static CombatPreset preset() {
return state.preset;
}

/** Back to the shipped default preset with no overrides, as before anything was loaded. */
@VisibleForTesting
public static void resetToDefaults() {
state = State.defaults();
}

/**
* Writes {@code combat.yml} for a server that has none.
*
* @return the preset the old key selects, or null if nothing was migrated (no old key, and no file written)
*/
@Nullable
private static CombatPreset migrate(@NotNull File file,
@Nullable Boolean oldLegacyKey,
@NotNull Consumer<String> info,
@NotNull Consumer<String> warn) {
CombatPreset preset = Boolean.TRUE.equals(oldLegacyKey) ? CombatPreset.LEGACY : CombatPreset.DEFAULT;

String shipped = readShipped();
if (shipped == null) {
warn.accept(FILE_NAME + " is missing from the plugin jar, so none was written.");
return preset;
}
String text = shipped.replaceFirst("(?m)^preset: default\\s*$", "preset: " + preset.key());

try {
File parent = file.getParentFile();
if (parent != null) parent.mkdirs();
// CREATE_NEW: an existing file is never overwritten, even if one appears after the check above
Files.write(file.toPath(), text.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW);
} catch (FileAlreadyExistsException e) {
return null;
} catch (IOException e) {
warn.accept(FILE_NAME + " could not be written (" + e.getMessage() + "). Using the "
+ preset.key() + " preset for this run.");
return preset;
}

if (oldLegacyKey != null) {
info.accept("Moved 'combat.legacy-combat: " + oldLegacyKey + "' from engine.yml to " + FILE_NAME
+ " (preset: " + preset.key() + "). The old key is now ignored.");
}
return preset;
}

@Nullable
private static String readShipped() {
try (InputStream in = CombatCfg.class.getResourceAsStream("/" + FILE_NAME)) {
if (in == null) return null;
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
return null;
}
}

@NotNull
private static CombatPreset readPreset(@NotNull YamlConfiguration yaml, @NotNull Consumer<String> warn) {
Object value = yaml.get(PRESET_KEY);
if (value == null) return CombatPreset.DEFAULT;

CombatPreset preset = CombatPreset.byKey(String.valueOf(value));
if (preset == null) {
warn.accept(FILE_NAME + ": unknown preset '" + value + "' (use 'default' or 'legacy'). Using '"
+ CombatPreset.DEFAULT.key() + "'.");
return CombatPreset.DEFAULT;
}
return preset;
}

@NotNull
private static Map<String, Object> readOverrides(@NotNull YamlConfiguration yaml,
@NotNull Consumer<String> warn) {
Map<String, Object> overrides = new HashMap<>();
ConfigurationSection section = yaml.getConfigurationSection(EXPRESSIONS_KEY);
if (section == null) return overrides;

for (String key : section.getKeys(false)) {
if (CombatExpression.byKey(key) == null) {
warn.accept(FILE_NAME + ": '" + key + "' is not a formula and is ignored.");
continue;
}
overrides.put(key, section.get(key));
}
return overrides;
}

private static final class State {
final CombatPreset preset;
final CombatFormulas[] byPreset;

State(@NotNull CombatPreset preset, @NotNull CombatFormulas[] byPreset) {
this.preset = preset;
this.byPreset = byPreset;
}

static State defaults() {
CombatFormulas[] all = new CombatFormulas[CombatPreset.values().length];
for (CombatPreset each : CombatPreset.values()) {
all[each.ordinal()] = CombatFormulas.of(each);
}
return new State(CombatPreset.DEFAULT, all);
}
}
}
15 changes: 14 additions & 1 deletion src/main/java/studio/magemonkey/divinity/config/EngineCfg.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,19 @@ public EngineCfg(@NotNull Divinity plugin) throws InvalidConfigurationException
public static double COMBAT_SHIELD_BLOCK_BONUS_RATE;
public static double COMBAT_SHIELD_BLOCK_BONUS_DAMAGE_MOD;
public static int COMBAT_SHIELD_BLOCK_COOLDOWN;
/**
* Forces the legacy preset's formulas, whatever {@code combat.yml} says.
*
* @deprecated Nothing sets this any more: {@code combat.legacy-combat} moved to {@code combat.yml}'s
* {@code preset}, see {@code CombatCfg}. It stays so that code written against the old switch keeps working.
*/
@Deprecated
public static boolean LEGACY_COMBAT;
/**
* The value of the old {@code combat.legacy-combat} key in {@code engine.yml}, or null if it is not there.
* Read only so that {@code CombatCfg} can choose the matching preset when it writes {@code combat.yml}.
*/
public static Boolean LEGACY_COMBAT_OLD_KEY;
/** 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;
Expand Down Expand Up @@ -219,7 +231,8 @@ public void setup() {
// C O M B A T //

path = "combat.";
EngineCfg.LEGACY_COMBAT = cfg.getBoolean(path + "legacy-combat", false);
EngineCfg.LEGACY_COMBAT_OLD_KEY =
cfg.contains(path + "legacy-combat") ? cfg.getBoolean(path + "legacy-combat") : null;
EngineCfg.COMBAT_DISABLE_VANILLA_SWEEP = cfg.getBoolean(path + "disable-vanilla-sweep-attack");
EngineCfg.COMBAT_REDUCE_PLAYER_HEALTH_BAR = cfg.getBoolean(path + "compress-player-health-bar");
EngineCfg.COMBAT_FISHING_HOOK_DO_DAMAGE = cfg.getBoolean(path + "fishing-hook-do-damage");
Expand Down
Loading
Loading