281 lines
17 KiB
Markdown
281 lines
17 KiB
Markdown
# v1.2 experimental offline simulation
|
|
|
|
Implemented as a separate experimental Python model, parallel to original AIR
|
|
runtime research. This is useful approximate combat, not an AIR engine replay.
|
|
|
|
## Public request/result contract
|
|
|
|
`ranch_assistant.battle_simulator.ExperimentalBattleRuntime` implements
|
|
`inspect(request)` and `run(request, cancel_event=None, timeout=30.0)`.
|
|
Both accept dicts or objects with the same attributes. Request fields are
|
|
`context` (`ordinary_stage`, `task_battle`, `task_pass_stage`),
|
|
`original_data` containing the original `battle` dictionary, `roster` containing
|
|
the full raw snapshot (or `snapshot.raw`), `team` (original ordered team string),
|
|
and `battle_position`. Optional `seed` defaults to zero. No game API is called.
|
|
|
|
Every response carries `execution_mode='experimental'`, `approximate=True`,
|
|
`faithful=False`, `settlement_eligible=False`, `diagnostics`, and
|
|
`ignored_mechanics`. `supported` means this approximate model can execute;
|
|
it is never a claim of original engine fidelity or permission to settle.
|
|
Unsupported objectives/controllers/triggers return `outcome='unsupported'`.
|
|
An executed result includes natural `win`/`loss`, or technical `timeout`/`cancelled`,
|
|
`units`, `events`, `elapsed_ms`, AP history, kill counters, and detected
|
|
anomalies. Any `battle_data` will be explicitly model-derived evidence,
|
|
never a fabricated victory or an authorization to submit.
|
|
|
|
### Worker contract
|
|
|
|
```python
|
|
request = {
|
|
"context": "ordinary_stage", # also task_battle / task_pass_stage
|
|
"original_data": {"battle": original_battle_config},
|
|
"roster": snapshot.raw, # full monsters/master/teams/monsterAttributes
|
|
"team": "teamA", # team name, preserves its ordered monster slots
|
|
"battle_position": original_battle_position,
|
|
"seed": 0,
|
|
}
|
|
capability = ExperimentalBattleRuntime().inspect(request)
|
|
result = ExperimentalBattleRuntime().run(request, cancel_event=event, timeout=30.0)
|
|
# result:
|
|
# execution_mode: 'experimental'; approximate: True; faithful: False
|
|
# settlement_eligible: False (offline evidence only, explicit future review required)
|
|
# requires_realtime_wait: True
|
|
# supported: bool; outcome: win/loss/timeout/cancelled/unsupported/error
|
|
# elapsed_ms: modeled game clock; elapsed_seconds: elapsed_ms / 1000
|
|
# timeout_kind: wall_clock / resource_limit for technical timeouts
|
|
# units: per-unit initial stats, hp, position, waiting/active/dead, summon origin
|
|
# events: bounded deterministic trajectory; trace_truncated / omitted_events explicit
|
|
# ap: team -> {initial, current, max, spent, recovered}; kills: all enemy deaths
|
|
# kill_monster: source-selective non-player, non-object, mode==2 death map
|
|
# anomalies: every anomaly detected, unfiltered; diagnostics; ignored_mechanics
|
|
# battle_data: trajectory-derived source fields for completed win/loss only;
|
|
# never treat these as authorized live settlement, never discard anomalies.
|
|
# battle_data.battleMonIds: original ordered roster instance IDs from selected
|
|
# team; includes waiting originals, excludes summons, empty for hideTeamMon
|
|
# execution_status: completed / timed_out / cancelled / unsupported / error
|
|
# terminal: True only for completed model win/loss
|
|
# terminal_reason: elimination / battle_time_limit for completed models
|
|
```
|
|
|
|
Natural expiry of `battle.time` is **completed loss**, with
|
|
`terminal_reason='battle_time_limit'`, `battle_data.win=False`, `leftTime=0`,
|
|
and the full configured modeled elapsed time. Technical worker timeout is
|
|
`outcome='timeout'`, `execution_status='timed_out'`, `terminal=False`, and
|
|
`battle_data=None`. Cancellation also has no battle data. This distinction
|
|
separates incomplete execution from a completed natural loss.
|
|
|
|
`run` uses `Popen([sys.executable, '-m', 'ranch_assistant.battle_simulator',
|
|
'--worker'], CREATE_NO_WINDOW on Windows)` with pipes and bounded output.
|
|
CPU simulation does not run in the GUI process. The worker cannot use sockets;
|
|
it reads only bundled combat artifacts and one JSON request on stdin. It has
|
|
no imports of engine, GUI, battle_runtime, or battles. `simulate(request)` is
|
|
the direct deterministic entrypoint for offline tests. Results return as soon
|
|
as computation ends, without sleeping for the modeled battle duration.
|
|
Orchestration owns any cancellable wait before a future reviewed live route.
|
|
|
|
### Explicit experimental eligibility (latest integration contract)
|
|
|
|
`settlement_eligible=False` and `faithful=False` always refer to original
|
|
engine fidelity. After an actual supported model completes (including a
|
|
natural loss), `experimental_settlement_eligible=True` only when `battle_data`
|
|
was computed and there are no unresolved inputs or detected anomalies.
|
|
Otherwise `experimental_eligibility_reasons` gives the reason and the flag is
|
|
false. Inspection and technical timeout/cancel/error never assert experimental
|
|
eligibility. Known approximate mechanics remain disclosed even when eligible;
|
|
this does **not** claim that original cheat checks ran or were complete.
|
|
|
|
Integration must use the experimental flag only under the explicitly selected
|
|
`policy.battle_mode='experimental'`, never the native route. Production
|
|
integration and the real-time wait remain owned by orchestration; this module
|
|
does not start or settle any live battle.
|
|
|
|
## Original inputs and reproducible static data
|
|
|
|
The builder uses `tools.research_battle_v12.recover_table` with the repaired
|
|
AMF Reader (empty arrays remain `[]`). It rejects any APK whose SHA-256 is not
|
|
`01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d`.
|
|
The retained main SWF SHA-256 is
|
|
`c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf`.
|
|
The SWF header independently decodes to **50.0 fps**; the fixed model clock
|
|
therefore advances 20 ms per tick.
|
|
|
|
```powershell
|
|
python tools/build_battle_simulation_data.py
|
|
python tools/build_battle_simulation_data.py --output local_state/battle_simulator/rebuild
|
|
```
|
|
|
|
Both builds were run; the two gzip artifacts and manifest matched byte for
|
|
byte. Gzip has a fixed zero timestamp, JSON is sorted and compact, and the
|
|
manifest retains per-table original compressed-member digests, logical names,
|
|
decoded sizes, APK identity, and 196 attack profiles' retained AS3 source hashes.
|
|
No personal path or account data enters these artifacts.
|
|
|
|
| Artifact | Bytes | Contents |
|
|
| --- | ---: | --- |
|
|
| `combat_tables.json.gz` | 242,430 | 749 species, 266 skill definitions, original numeric/settings/team/potential/entangle/upstar/item tables, default fields, 196 attack profiles |
|
|
| `combat_battles.json.gz` | 1,465,404 | All 1,178 original stage records' level configs and 1,165 tasks' combat/status steps |
|
|
| `combat_manifest.json` | manifest | Original source and artifact digests and retained-source fingerprints |
|
|
|
|
The runtime validates identity and compressed/decoded artifact hashes, then
|
|
freezes dictionaries and arrays recursively. The independent cache does not
|
|
use Catalog. Normal workers never decode the roughly 62 MB full battle corpus;
|
|
they receive one original battle config and read the small combat bundle.
|
|
`combat_battles()` is a lazy public-static research helper. Neither runtime
|
|
method imports the builder, opens the APK, or contacts the network.
|
|
|
|
## Implemented trajectory
|
|
|
|
Player HP/ATK/DEF/DEX follow `MonsterVo`:
|
|
|
|
```text
|
|
int((base + actualGrowth * (level + min(tpLevel, 4) - 1)
|
|
+ monsterAttributes[stat] + pStat + master.globalStat)
|
|
* (1 + clamp(feel, 0, 200) / 2000 + game_setting.upStarAdd * upStar))
|
|
```
|
|
|
|
Growth comes from the raw monster, never a generic Fighter or midpoint player.
|
|
Potential uses actual `pAtk/pDef/pHp/pDex`. Server `monsterAttributes` supplies
|
|
the aggregate bonuses once; equipment is not added again. Attack interval is
|
|
the species interval plus source integer dex adjustment and `atkSpd`; movement
|
|
uses species speed plus the source two-decimal dex adjustment. Crit and AP cost
|
|
saving come from the same server attributes. Upstar skill replacements and
|
|
breakthrough-derived skill levels use the original tables. Missing growth or a
|
|
nonpositive computed attack interval is rejected, not replaced or clamped.
|
|
|
|
Configured enemies retain their individual authored values. `autoValue` uses
|
|
the source species midpoint construction, level and global additions. Only
|
|
authored `scaleAbility`/`scaleHp` fields change configured enemy numbers; they
|
|
are not user-selectable damage cheats. Normal stage/task combat does not apply
|
|
the unrelated PvP `pveHpScale` or `pveApStartScale`.
|
|
|
|
Teams preserve the selected snapshot team order and original position mapping
|
|
`1,4,2,5,6,7,8`. Player field capacity follows unlocked `team_info.battleTeam`
|
|
slots, capped at four. Enemy capacity comes from original `numMax`. Deployment
|
|
uses original spawn rectangles, `joinTime` in seconds, and per-team waves.
|
|
Wave unlock waits 700 ms; scheduled reinforcements are admitted on the source
|
|
one-second deployment cadence. `hideTeamMon` removes roster combatants and
|
|
allows authored allies. Summons do not consume field capacity.
|
|
|
|
Player AP starts at `startAp + (master.level-1)*addApByLevel`. Enemy AP starts
|
|
at authored `ap` with max `2*ap`. The clock recovers one AP per original
|
|
`apCD=2000` ms; delayed roster joins restore the original fraction of max AP.
|
|
Automatic deployment has **no invented AP charge**: source
|
|
`prepareTimeMonster` checks time/wave/capacity, not cost. AP is spent on actual
|
|
skill casts. Position-command AP spending is outside this automatic model.
|
|
|
|
The model selects spatial targets, moves toward them, tests the source attack
|
|
box (`abs(dx)<range`, `abs(dy)<range*0.5`), schedules original attack action
|
|
hit delays, and adds projectile travel using recovered projectile speed and
|
|
`(distance-30)/speed*(1000/50)`. Target death and skill-5 projectile loss cause
|
|
real misses. Damage uses original critical chance, critical and elemental
|
|
factors, integer stages, dex-dependent random range, defense and reduction.
|
|
HP loss, healing, poison, stun, reflection and lifesteal change the trajectory.
|
|
The model waits the source one-second delayed game-over check after deaths.
|
|
|
|
| Skill | Source mechanics implemented | Remaining approximation |
|
|
| --- | --- | --- |
|
|
| 3 `Skill3Copy` | One summon; original level ability factor; scaled ATK/DEF/DEX; HP from current parent HP; no inherited skills or capacity cost | Physical split impulse, visual/equipment callbacks and exact clone motion |
|
|
| 5 `Skill5FlashMove` | Source distance AI and AP/CD; movement displacement using original speed; loses incoming model projectiles | Impulse is one displacement; inertia and temporary knockback resistance are omitted |
|
|
| 7 `Skill7Copy3` | Exactly three summons; original factor; scaled max HP; child AP-cost metadata 1; no capacity cost | Physical spreading impulses and clone animation |
|
|
| 9 `Skill9AreaHit` | Next attack is ready; original attack factor damages nearby enemies in source +/-150 by +/-91 box; primary hit preserved | Knockback, visual shake and exact projectile-versus-activation timestamp edge cases |
|
|
| 38 `Skill38Miohit` | Four hits; original random attack factor; attack type 28/100 ms windup, 150 ms recovery, 50 ms quick-CD scheduling | Rush motion, final knockback, temporary resistance and skin-specific motions |
|
|
|
|
Known skills use the original random AI probabilities. Player auto-skill checks
|
|
use the source 30-frame cadence, enemy AI 20/60/100 frames by mode, and at most
|
|
one cast per model tick. Missing framework `Cooldowner` initialization and
|
|
callback timing are approximated; the model assumes initial attacks are ready.
|
|
Enemy initial skill readiness is approximated at two seconds.
|
|
|
|
`atkStun`, `defStun`, five-second poison with one-second ticks, thorns,
|
|
`atkVim`, and five-second `selfCure` have trajectory effects. `sunFire`,
|
|
`moonHeal`, and `deadBoom` are not implemented and are explicitly reported when
|
|
present. All other skill IDs are individually listed as omitted by inspection;
|
|
the five implemented skill families are partial, not full-fidelity ports.
|
|
|
|
## Counters, evidence and anomaly retention
|
|
|
|
| Output | Exact model meaning |
|
|
| --- | --- |
|
|
| `kills` / `all_kills` | All modeled non-player, non-object deaths, regardless of adult/juvenile mode; includes summons |
|
|
| `kill_monster` / `battle_data.killMonster` | Source `deadHandler` selection only: non-player, non-object, **mode 2** deaths; includes adult summons |
|
|
| `alive_num` / `battle_data.aliveNum` | Active plus waiting non-object player units, including summons; not just deployed original survivors |
|
|
| `battle_data.battleMonIds` | Selected team order of original roster **instance IDs**, including waiting originals; excludes clones/summons and species IDs; empty when the source hides the roster |
|
|
| `damage_hp_lost`, unit `damage_dealt` | Measured HP actually removed by this model |
|
|
| `battle_data.totalDamage`, `killNum`, `deadNum` | Source-declared integer defaults **0**; no assignments found in retained combat source; never filled from invented counters |
|
|
| `bossDamage` | Source marker `bossPoint=-1` credits actual HP loss; positive markers credit actual deaths |
|
|
|
|
`battle_data` exists for completed model win/loss only. It also carries actual
|
|
model AP, left time and filtered original BattlePosition fields. It is local
|
|
evidence; no callback or game route is invoked here. Unknown/cancelled/timed-out
|
|
execution has no battle data. Internal model errors retain partial traces and
|
|
every anomaly already recorded, while keeping eligibility false.
|
|
|
|
Original observed thresholds are not softened: damage over 80,000 records
|
|
`+10overdamage`/10 points; player requested healing over 20,000 records the
|
|
source's `+15overcure`/**19** points even if effective healing is small.
|
|
The observable snapshot subset of `BattlePanel.cheatCheck` records excess
|
|
affection, growth-derived totals, potential and level with original scores and
|
|
the original temporary/NPC-id exemption. Original full character equivalence,
|
|
runtime memory/table comparison and all skill-specific checks are **not fully
|
|
replayed**. Artifact integrity checks and these partial checks are not a claim
|
|
of a clean original engine execution.
|
|
|
|
Anomalies are retained separately from the bounded event trace and copied
|
|
unchanged into model evidence; they prevent experimental eligibility. Event
|
|
truncation reports `trace_truncated` and `omitted_events`. Default trace limit
|
|
is 2,000 events, maximum 10,000. Input/output are bounded to 16 MiB; 1,024 total
|
|
created units, 10,000 detected anomalies or 180,000 logical ticks stop work as
|
|
a technical resource limit. Recorded anomalies are never removed to manufacture
|
|
an acceptable result. This code does not normalize cheat scores or clear records.
|
|
|
|
## Completeness and offline validation
|
|
|
|
Inspection of the entire original corpus with a synthetic four-unit roster:
|
|
|
|
| Original configurations | Inspected | Admitted by this approximate model |
|
|
| --- | ---: | ---: |
|
|
| Stage level battle configs | 2,512 | 941 |
|
|
| Inline task battle configs | 199 | 106 |
|
|
|
|
Admission is structural model support, not a fidelity or gameplay-success rate.
|
|
Non-elimination objectives, authored battle/monster controllers, triggers,
|
|
protected/destroyed units, and active field areas are rejected with reasons.
|
|
Twelve admitted original stage configs were also executed with a synthetic
|
|
level-20 roster using species 1001010, 1030010, 2004010, 3010010; all twelve
|
|
completed model wins. They were not account replays and were not calibrated
|
|
against recorded AIR fights.
|
|
|
|
Remaining limitations include straight-line movement, no collision/inertia or
|
|
flight height, simplified retargeting/retreat, visual object collision omitted,
|
|
projectile paths/easing/offsets omitted, skill presentation replaced with model
|
|
activation, no full physics/knockback, omitted equipment special words and skin
|
|
attack overrides, and Python RNG rather than original Math.random/Random.
|
|
These limitations accompany every inspection/result even when the model admits
|
|
the battle. No percentage of original engine fidelity is claimed.
|
|
|
|
```powershell
|
|
python -m unittest ranch_assistant.tests.test_battle_simulator -v
|
|
```
|
|
|
|
**38 simulator tests passed**, and **59 tests passed** when combined with the
|
|
estimator and AMF suites: immutable original artifacts and constants; all three
|
|
contexts; snapshot growth/tp/potential/global/feel/upstar/attributes; normal wins,
|
|
natural elimination losses and completed clock-expiry losses; order, capacity,
|
|
waves and join delays; each of skills 3/5/7/9/38; projectiles, statuses/healing;
|
|
waiting/summon alive counts and selective kills; source default counters; hidden
|
|
teams and boss markers; anomaly retention through truncation and model failure;
|
|
explicit unsupported mechanics; identical seeded direct/worker trajectories;
|
|
object/dict requests; all three original route fields and ordered instance-ID
|
|
lists (including waiting/excluding summons); fixed Windows worker command and no GUI imports;
|
|
socket audit rejection; child cancellation, wall timeout and interrupt cleanup.
|
|
|
|
A sample worker completed in approximately 0.16 wall seconds with 2.7 modeled
|
|
seconds. This is an observation, not a performance guarantee. There is no
|
|
offline real-time sleep; `requires_realtime_wait=True` delegates the cancellable
|
|
elapsed-clock wait to orchestration before any separately reviewed live route.
|
|
|
|
Only public original configs and synthetic fixtures were used. No actual
|
|
account input, log, personal identifier, credential, real game request,
|
|
production integration, commit or push was made by this workstream. The
|
|
experimental module is independent of the native original-engine runtime.
|