371 lines
22 KiB
Python
371 lines
22 KiB
Python
"""Fast, approximate HP/DPS budgets; no movement, animation or skill replay.
|
|
|
|
Inputs and the experimental result/settlement contract come from the existing
|
|
simulator. One-second simultaneous damage budgets are not original-engine hits.
|
|
"""
|
|
from collections import Counter
|
|
from dataclasses import replace
|
|
import math
|
|
import time
|
|
|
|
from . import battle_simulator as sim
|
|
|
|
|
|
ASSUMPTIONS = (
|
|
"Aggregate model: one-second simultaneous HP/DPS budgets, without movement or animation.",
|
|
"Expected damage uses original attack, defense, dexterity, element and critical-hit formulas.",
|
|
"Damage is shared equally among eligible opposing targets; explicit target locks take precedence.",
|
|
"Team capacity, ordered waves, join times and death/time reinforcement gates use coarse numeric steps.",
|
|
"Makers generate original-stat units at an averaged rate, bounded by 128 generated units per battle.",
|
|
"Skills use bounded expected damage/healing contributions; other skill effects are omitted.",
|
|
"HP controllers use averaged healing/damage rates; other control, movement and buff effects are omitted.",
|
|
"This approximate model has not been validated against original AIR battle outcomes.",
|
|
)
|
|
MAX_GENERATED = 128
|
|
MAX_STEPS = 7200
|
|
|
|
|
|
class _MeanRoll:
|
|
@staticmethod
|
|
def uniform(low, high):
|
|
return (low + high) / 2
|
|
|
|
|
|
def prepare(request, tables=None):
|
|
tables = tables if tables is not None else sim.combat_tables()
|
|
scenario, report = sim._prepare(request, tables, quick=True)
|
|
report.update(model="quick-v1-hp-dps", approximate=True, faithful=False,
|
|
simulation_method="aggregate_hp_dps", implemented_skills=[],
|
|
assumptions=list(ASSUMPTIONS), ignored_mechanics=list(ASSUMPTIONS))
|
|
for d in report["diagnostics"]:
|
|
if d["code"] == "unsupported_skill":
|
|
d["code"] = "aggregate_skill"
|
|
d["message"] = d["message"].replace("is omitted", "uses a bounded aggregate expectation where numeric parameters exist")
|
|
elif d["code"] == "aggregate_approximation":
|
|
d["message"] = d["message"].replace("unsupported", "approximated").replace("Unsupported", "Approximated")
|
|
if scenario is not None:
|
|
battle = sim._get(sim._get(request, "original_data", {}), "battle", {})
|
|
kinds = sorted({str(c.get("type", "unknown")) for c in battle.get("controller", ()) or ()}
|
|
| {str(c.get("type", "unknown")) for t in battle.get("teams", ()) for m in t.get("mons", ()) if m
|
|
for c in m.get("controller", ()) or ()})
|
|
report["aggregate_controllers"] = kinds
|
|
report["assumptions"].append("Configured controllers: " + (", ".join(kinds) or "none") + "; only makers, HP rates and numeric target gates affect this model.")
|
|
report["objective"] = {1: "elimination", 2: "survive_until_time", 3: "destroy_any", 4: "destroy_all"}.get(
|
|
scenario.win_types[0] if scenario.win_types else 1, "elimination_approximation")
|
|
for c in list(battle.get("controller", ()) or ()) + [c for t in battle.get("teams", ())
|
|
for m in t.get("mons", ()) if m for c in m.get("controller", ()) or ()]:
|
|
if c.get("type") == "monMaker":
|
|
p = c.get("para", {})
|
|
try:
|
|
if str(sim._int(p.get("monType", 0))) not in tables["monster_info"]:
|
|
raise sim.SimulationInputError("Generated monster species has no original attributes")
|
|
if sim._int(p.get("team", 2)) not in scenario.teams:
|
|
# Standalone controllers can be the only source of enemies.
|
|
scenario.teams[sim._int(p.get("team", 2))] = {"capacity": 4, "initial": 0, "max": 0}
|
|
for name in ("interval", "hp", "hpMax", "atk", "level"):
|
|
if p.get(name) is not None:
|
|
sim._number(p[name])
|
|
except sim.SimulationInputError as exc:
|
|
report["reasons"].append(str(exc))
|
|
report["supported"] = False
|
|
report["teams"] = sim._plain(scenario.teams)
|
|
return scenario, report
|
|
|
|
|
|
class _QuickBattle(sim._Battle):
|
|
def __init__(self, scenario, report, tables, request):
|
|
super().__init__(scenario, report, tables)
|
|
self.pending_triggers = [] # Triggers below affect budgets, never a detailed replay.
|
|
self.raw = sim._get(sim._get(request, "original_data", {}), "battle", {})
|
|
self.raw_mons = {f"configured-{ti + 1}-{mi + 1}": m for ti, t in enumerate(self.raw.get("teams", ()))
|
|
for mi, m in enumerate(t.get("mons", ())) if m}
|
|
roster = sim._get(request, "roster", sim._get(request, "snapshot", {}))
|
|
roster = sim._get(roster, "raw", roster)
|
|
players = {str(m["id"]): m for m in roster.get("monsters", ())}
|
|
self.raw_mons.update({a.unit.key: players[a.unit.source_id] for a in self.actors
|
|
if a.unit.key.startswith("player-")})
|
|
self.triggers = list(self.raw.get("triggers", ()) or ())
|
|
self.gated = set()
|
|
self.join_gates = set()
|
|
for t in self.triggers:
|
|
for e in t.get("effects", ()):
|
|
p = e.get("para", {})
|
|
if e.get("type") == "unlockWave":
|
|
self.gated.add((sim._int(p.get("team", 2)), sim._int(p.get("wave", 1))))
|
|
if e.get("type") == "monJoin":
|
|
self.join_gates.add(str(p.get("mid", "")))
|
|
self.next_wave = {}
|
|
self.generated = 0
|
|
self.damage_checks = set()
|
|
self.peak_dps = Counter()
|
|
self.expectations = {}
|
|
self.hp_rates = {}
|
|
self.makers = []
|
|
for a in self.actors:
|
|
self.configure(a, self.raw_mons.get(a.unit.key, {}))
|
|
for c in self.raw.get("controller", ()) or ():
|
|
if c.get("type") == "monMaker":
|
|
self.makers.append({"vo": c, "owner": None, "credit": 0.,
|
|
"active": c.get("para", {}).get("activited", True) is not False})
|
|
|
|
def configure(self, actor, mon):
|
|
u, row = actor.unit, self.tables["monster_info"][str(actor.unit.species)]
|
|
damage, healing = 1., 0.
|
|
player = u.key.startswith("player-")
|
|
for slot in (1, 2):
|
|
sid = sim._int(mon.get(f"skill_{slot}", -1)) if not player else -1
|
|
sid = sim._int(row.get(f"skill_{slot}", 0)) if sid == -1 else sid
|
|
if player and sim._int(mon.get("upStar", 0)) > 0:
|
|
sid = sim._int(self.tables["upstar_info"].get(str(u.species), {}).get("skill", {}).get(str(slot), sid))
|
|
tp = min(4, sim._int(mon.get("tpLevel", 0)))
|
|
level = sim._int(mon.get(f"skill_{slot}_lv", -1))
|
|
level = max(1, tp + 1 if slot == 1 and not sim._int(row.get("skill_2", 0)) else 1) if level < 1 else level
|
|
skill = self.tables["monster_skill"].get(str(sid), {}).get(f"lv{level}", {})
|
|
p = skill.get("para", {})
|
|
cooldown = max(1., sim._number(skill.get("cd", 10000)) / 1000)
|
|
# At most 25% total expected damage gain, never a stat multiplier.
|
|
extra = max(0., sim._number(p.get("damage", p.get("hurt", 1))) - 1)
|
|
damage += min(.125, extra / cooldown)
|
|
healing += max(0., sim._number(p.get("cure", 0)) + u.stats.atk * sim._number(p.get("cureAtkAdd", 0))) / cooldown
|
|
self.expectations[u.key] = (min(1.25, damage), healing)
|
|
rates = []
|
|
for c in mon.get("controller", ()) or ():
|
|
kind, p = c.get("type"), c.get("para", {})
|
|
if kind == "monMaker":
|
|
self.makers.append({"vo": c, "owner": u.key, "credit": 0., "active": True})
|
|
if kind in ("hp", "hpArea"):
|
|
rates.append((kind, sim._number(p.get("hp", 0)) / max(1., sim._number(p.get("interval", 1000)) / 1000),
|
|
str(p.get("mid", -1))))
|
|
for name, kind in (("selfCure", "hp"), ("sunFire", "enemy"), ("moonHeal", "hpArea")):
|
|
amount = u.effects.get(name, 0)
|
|
if amount:
|
|
rates.append((kind, (-amount if name == "sunFire" else amount) / 5, "-1"))
|
|
self.hp_rates[u.key] = rates
|
|
|
|
def gates(self):
|
|
for trigger in list(self.triggers):
|
|
p, kind = trigger.get("para", {}), trigger.get("type")
|
|
source = self.by_source_id.get(str(p.get("mid", "")))
|
|
ready = kind == "time" and self.now >= sim._number(p.get("time", 0)) * 1000
|
|
ready |= kind == "monDead" and source is not None and source.state == "dead"
|
|
ready |= kind == "waveStart" and self.wave.get(sim._int(p.get("team", 2)), 1) >= sim._int(p.get("wave", 1))
|
|
if not ready:
|
|
continue
|
|
self.triggers.remove(trigger)
|
|
self.event("aggregate_trigger", trigger_kind=kind)
|
|
for effect in trigger.get("effects", ()):
|
|
ep, ek = effect.get("para", {}), effect.get("type")
|
|
if ek == "unlockWave":
|
|
self.unlocked_waves[sim._int(ep.get("team", 2))].add(sim._int(ep.get("wave", 1)))
|
|
elif ek == "monJoin":
|
|
a = self.by_source_id.get(str(ep.get("mid", "")))
|
|
if a:
|
|
a.force_join = True
|
|
elif ek in ("startController", "stopController"):
|
|
for maker in self.makers:
|
|
if str(maker["vo"].get("id", "")) == str(ep.get("id", "")):
|
|
maker["active"] = ek == "startController"
|
|
|
|
def recruit(self):
|
|
self.gates()
|
|
for team in self.s.teams:
|
|
waiting = [a for a in self.actors if a.unit.team == team and a.state == "waiting"]
|
|
active = [a for a in self.actors if a.unit.team == team and a.state == "active" and not a.unit.is_object]
|
|
if waiting and not active:
|
|
wave = min(a.unit.wave for a in waiting)
|
|
if (team, wave) not in self.gated:
|
|
due = self.next_wave.setdefault((team, wave), self.now + (0 if wave <= 1 else 700))
|
|
if self.now >= due:
|
|
self.unlocked_waves[team].add(wave)
|
|
self.wave[team] = wave
|
|
counts = Counter(a.unit.team for a in self.active() if a.unit.count_unit)
|
|
for a in self.actors:
|
|
u = a.unit
|
|
if a.state != "waiting" or (not a.force_join and (
|
|
u.wave not in self.unlocked_waves[u.team] or self.now < max(0, u.join_time) * 1000
|
|
or u.source_id in self.join_gates)):
|
|
continue
|
|
if u.count_unit and counts[u.team] >= self.s.teams[u.team]["capacity"]:
|
|
continue
|
|
a.state, a.joined_ms = "active", self.now
|
|
counts[u.team] += int(u.count_unit)
|
|
self.event("deploy", actor=u.key, team=u.team, wave=u.wave, count_unit=u.count_unit, ap_charged=0)
|
|
|
|
def generate(self, seconds):
|
|
for maker in self.makers:
|
|
p = maker["vo"].get("para", {})
|
|
parent = self.by_key.get(maker["owner"])
|
|
if not maker["active"] or parent is not None and parent.state != "active":
|
|
continue
|
|
after = sim._number(p.get("afterTime", 0))
|
|
before = sim._number(p.get("beforeTime", 0))
|
|
after = after * 1000 if after < 1000 else after
|
|
before = before * 1000 if before < 1000 else before
|
|
if self.now < after or before > 0 and self.now > before:
|
|
continue
|
|
maker["credit"] += seconds / max(1., sim._number(p.get("interval", 1000)) / 1000)
|
|
count = min(int(maker["credit"]), MAX_GENERATED - self.generated)
|
|
maker["credit"] -= count
|
|
for _ in range(count):
|
|
if len(self.actors) >= sim.MAX_UNITS:
|
|
self.resource_limited = True
|
|
return
|
|
spec = {"type": p.get("monType"), "autoValue": True, "level": p.get("level", 1),
|
|
"team": p.get("team", parent.unit.team if parent else 2), "mode": p.get("mode", 2),
|
|
"skill_1": 0, "skill_2": 0, "countUnit": False}
|
|
unit = sim._enemy(spec, {"team": spec["team"]}, self.tables, f"generated-{self.generated + 1}",
|
|
{}, lambda *a, **k: None, {})
|
|
hp = sim._int(p.get("hpMax") if p.get("hpMax") is not None else p.get("hp") if p.get("hp") is not None else unit.stats.hp)
|
|
unit = replace(unit, stats=replace(unit.stats, hp=hp, atk=sim._int(p.get("atk") if p.get("atk") is not None else unit.stats.atk)),
|
|
is_object=p.get("isObject", False) is True, source_id=f"-{self.generated + 1}")
|
|
if hp <= 0 or unit.stats.atk < 0 or unit.team not in self.s.teams:
|
|
raise sim.SimulationInputError("Generated monster attributes/team are invalid")
|
|
a = sim.Actor(unit, min(hp, sim._int(p.get("hp") if p.get("hp") is not None else hp)), state="active", joined_ms=self.now)
|
|
self.actors.append(a)
|
|
self.by_key[unit.key], self.by_source_id[unit.source_id] = a, a
|
|
self.expectations[unit.key], self.hp_rates[unit.key] = (1., 0.), []
|
|
self.generated += 1
|
|
self.event("aggregate_spawn", actor=unit.key, team=unit.team, hp=a.hp)
|
|
|
|
def budgets(self, seconds):
|
|
active = self.active()
|
|
damage, healing, dealt = Counter(), Counter(), Counter()
|
|
team_rates = Counter()
|
|
for a in active:
|
|
u = a.unit
|
|
locked = self.by_source_id.get(u.lock_target)
|
|
targets = [locked] if locked and locked.state == "active" else [b for b in active if b.unit.team != u.team]
|
|
if not locked:
|
|
targets = [b for b in targets if b.unit.auto_target] or targets
|
|
if not u.is_object and targets and u.ai_search != 0:
|
|
for b in targets:
|
|
attack = u.stats.atk
|
|
counter = self.tables["monster_setting"]["element"].get(str(u.stats.element), {}).get("counter")
|
|
if counter == b.unit.stats.element:
|
|
attack = int(attack * self.game["counterAdd"])
|
|
hit = sim.damage_roll(attack, u.stats.dex, b.unit.stats, self.game, _MeanRoll())
|
|
quarter = int((u.stats.dex - b.unit.stats.dex) / 4)
|
|
crit = min(1., .02 + u.stats.crit / 100 + (quarter / (quarter + 120) if quarter >= 0 else 0))
|
|
hit *= 1 + crit * (self.game["critAdd"] - 1)
|
|
element = str(u.stats.element)
|
|
if element in b.unit.hurt_types and element in b.unit.hurt_elements:
|
|
hit *= b.unit.hurt_elements[element]
|
|
elif str(u.species) in b.unit.hurt_types:
|
|
hit *= b.unit.hurt_types[str(u.species)]
|
|
hit = max(0, int(hit * (1 - b.unit.stats.damage_reduction) * self.expectations[u.key][0]))
|
|
hit = self.final_damage(hit, a, b)
|
|
# Apply the desktop cap per expected hit, before summing DPS.
|
|
amount = hit * 1000 / u.stats.attack_ms * seconds / len(targets)
|
|
damage[b.unit.key] += amount
|
|
dealt[u.key] += amount
|
|
team_rates[u.team] += amount / seconds
|
|
if hit > 80000 and (u.key, b.unit.key) not in self.damage_checks:
|
|
self.damage_checks.add((u.key, b.unit.key))
|
|
self.anomaly("+10overdamage", points=10, damage=hit, hurt_team=b.unit.team,
|
|
actor=u.key, target=b.unit.key, approximate=True)
|
|
healing[u.key] += self.expectations[u.key][1] * seconds
|
|
for kind, rate, mid in self.hp_rates[u.key]:
|
|
if kind == "hp":
|
|
target = a if mid == "-1" else self.by_source_id.get(mid)
|
|
targets = [target] if target and target.state == "active" else []
|
|
else:
|
|
targets = [b for b in active if (b.unit.team == u.team) == (rate >= 0)]
|
|
for b in targets:
|
|
(healing if rate >= 0 else damage)[b.unit.key] += abs(rate) * seconds
|
|
for team, rate in team_rates.items():
|
|
self.peak_dps[team] = max(self.peak_dps[team], rate)
|
|
self.now += int(seconds * 1000)
|
|
for a in active:
|
|
key = a.unit.key
|
|
lost = min(a.hp, damage[key])
|
|
a.hp -= lost
|
|
a.total_hurt += damage[key]
|
|
self.hp_lost[a.unit.team] += lost
|
|
a.damage_dealt += dealt[key]
|
|
if a.unit.boss_point == -1:
|
|
self.boss_points += int(lost)
|
|
if lost:
|
|
self.event("damage", actor=None, target=key, damage=round(damage[key], 3),
|
|
hp_lost=round(lost, 3), hp=round(a.hp, 3), reason="aggregate_dps")
|
|
# Healing is a simultaneous sustain budget; it cannot resurrect.
|
|
if a.hp > 0:
|
|
gained = min(a.unit.stats.hp - a.hp, healing[key])
|
|
a.hp += gained
|
|
a.healed += gained
|
|
if gained:
|
|
self.event("heal", actor=key, amount=round(gained, 3), hp=round(a.hp, 3), reason="aggregate_sustain")
|
|
else:
|
|
a.hp = 0
|
|
self.finish_death(a)
|
|
|
|
def objectives(self):
|
|
if self.now >= self.s.duration_ms:
|
|
return "win" if 2 in self.s.win_types else "loss"
|
|
if not any(a.unit.team == 1 and a.state != "dead" for a in self.actors):
|
|
return "loss"
|
|
# A still-running generator represents a future enemy HP/DPS budget,
|
|
# including when its effective population bound has been reached.
|
|
future = any(m["active"] and (m["owner"] is None or self.by_key[m["owner"]].state != "dead")
|
|
and sim._int(m["vo"].get("para", {}).get("team", 2)) != 1
|
|
and (not sim._number(m["vo"].get("para", {}).get("beforeTime", 0)) or
|
|
self.now < (sim._number(m["vo"]["para"]["beforeTime"]) *
|
|
(1000 if sim._number(m["vo"]["para"]["beforeTime"]) < 1000 else 1)))
|
|
for m in self.makers)
|
|
if 1 in self.s.win_types and not future and not any(a.unit.team != 1 and a.state != "dead"
|
|
and (a.state == "active" or not a.unit.is_object) for a in self.actors):
|
|
return "win"
|
|
protected = [a for a in self.actors if a.unit.protect_target]
|
|
destroyed = [a for a in self.actors if a.unit.destroy_target]
|
|
if protected and (3 in self.s.lose_types and any(a.state == "dead" for a in protected)
|
|
or 4 in self.s.lose_types and all(a.state == "dead" for a in protected)):
|
|
return "loss"
|
|
if destroyed and (3 in self.s.win_types and any(a.state == "dead" for a in destroyed)
|
|
or 4 in self.s.win_types and all(a.state == "dead" for a in destroyed)):
|
|
return "win"
|
|
return None
|
|
|
|
def result(self, outcome, timeout_kind=None):
|
|
result = super().result(outcome, timeout_kind)
|
|
result["team_budgets"] = {str(team): {
|
|
"initial_hp": sum(u.stats.hp for u in self.s.units if u.team == team),
|
|
"remaining_hp": round(sum(a.hp for a in self.actors if a.unit.team == team), 3),
|
|
"peak_expected_dps": round(self.peak_dps[team], 3)} for team in self.s.teams}
|
|
result["generated_units"] = self.generated
|
|
result["spawn_bound_reached"] = self.generated >= MAX_GENERATED
|
|
return result
|
|
|
|
|
|
def simulate_quick(request, *, cancel_event=None, timeout=30., tables=None):
|
|
started = time.monotonic()
|
|
timeout = sim._number(timeout, "timeout")
|
|
if timeout < 0:
|
|
raise sim.SimulationInputError("timeout must be nonnegative")
|
|
tables = tables if tables is not None else sim.combat_tables()
|
|
scenario, report = prepare(request, tables)
|
|
if not report["supported"]:
|
|
return dict(report, outcome="unsupported", execution_status="unsupported", terminal=False,
|
|
terminal_reason="unsupported_scenario", elapsed_ms=0, elapsed_seconds=0, events=[])
|
|
try:
|
|
battle = _QuickBattle(scenario, report, tables, request)
|
|
for step in range(min(MAX_STEPS, scenario.duration_ms // 1000 + 1)):
|
|
if cancel_event is not None and cancel_event.is_set():
|
|
return battle.result("cancelled")
|
|
if time.monotonic() - started >= timeout:
|
|
return battle.result("timeout", "wall_clock")
|
|
battle.recruit()
|
|
battle.generate(min(1., (scenario.duration_ms - battle.now) / 1000))
|
|
outcome = battle.objectives()
|
|
if outcome:
|
|
reason = "battle_time_limit" if battle.now >= scenario.duration_ms else "elimination" if 1 in scenario.win_types else "objective"
|
|
battle.event("complete", outcome=outcome, reason=reason)
|
|
return dict(battle.result(outcome), terminal_reason=reason)
|
|
if battle.resource_limited:
|
|
return battle.result("timeout", "resource_limit")
|
|
battle.budgets(min(1., (scenario.duration_ms - battle.now) / 1000))
|
|
return battle.result("timeout", "resource_limit")
|
|
except (sim.SimulationInputError, KeyError, TypeError, ValueError, ZeroDivisionError):
|
|
# Do not include account material or arbitrary parameter values in errors.
|
|
return dict(report, supported=False, outcome="unsupported", execution_status="unsupported", terminal=False,
|
|
terminal_reason="invalid_numeric_battle_data", elapsed_ms=0, elapsed_seconds=0, events=[],
|
|
reasons=list(report["reasons"]) + ["Missing or invalid original numeric combat/controller data"])
|