Compare commits

...
8 Commits
Author SHA1 Message Date
phenom 544c1bee91 Release Healer Man 0.1.29 2026-09-11 14:26:15 -04:00
phenom 8c9809d3e0 Release Healer Man 0.1.28 2026-09-10 14:14:02 -04:00
phenom ed8b9e3719 Release Healer Man 0.1.27 2026-09-10 09:54:12 -04:00
phenom 147c2804d4 Release Healer Man 0.1.26 2026-09-09 22:18:15 -04:00
phenom e7cc588bfc Release Healer Man 0.1.25 2026-09-09 16:48:50 -04:00
phenom bac0da9300 Release Healer Man 0.1.24 2026-09-09 16:43:37 -04:00
phenom c4346751a9 Release Healer Man 0.1.23 2026-09-09 14:26:13 -04:00
phenom 7f6001723a Release Healer Man 0.1.22 2026-09-09 11:21:33 -04:00
386 changed files with 61534 additions and 2063 deletions

No files matched your search

+6
View File
@@ -207,6 +207,7 @@ $ReleaseVersion = [ordered]@{
npm run content:test
npm run server:test
npm test
npm run content:publish
npm run build
npm test -- --run src/avatar
npx vitest run src/game/inputManager.test.ts src/game/inputMath.test.ts
@@ -222,6 +223,11 @@ git push origin main
git rev-parse HEAD
```
`content:publish` is a fail-closed pre-build release check. It must report all
54 WoW campaign dungeon packs and refuses to replace the manifest when a pack,
dependency, or catalog-referenced asset is missing. Its local `content/` output
is ignored and must not be staged.
Before `git commit`, read the staged file list printed by `git status --short`.
Do not commit a `.env` file, password, API token, keystore, APK, database,
`content/`, `dist/`, `dist-android/`, `.web-public/`, or `.android-public/`
+430
View File
@@ -4,6 +4,39 @@ This file is the durable record of runtime behavior, regressions, and the
evidence required before calling a visual bug fixed. Update it whenever scene,
camera, input, physics, mob-rendering, or asset-loading code changes.
## 2026-09-10 Personal UI templates and desktop action bars
- Opened Wailing Caverns through the normal offline roster, dungeon, and role
selection screens, then opened Pause > Edit UI & templates.
- Verified five bars containing 12 buttons each, including 2 x 6 and 3 x 4
arrangements. Default stacking accounts for each bar's height. The editor
can collapse or dock on either side so drag handles remain reachable.
- Clicked Renew and pressed Shift+Q in keybind edit mode. Reassigned Shift+Q
to bar 5/button 12 and verified the previous keybind cleared. Assigned Renew
to that button through the ability picker; after saving, Shift+Q cast it and
displayed its cooldown. No spell fired during key capture.
- Dragged the minimap, hid party frames, saved/renamed/overwrote PC slot 1,
loaded it, and round-tripped all layouts through export text and import.
The imported JSON retained the minimap position, hidden party, bar geometry,
ability assignment, key chord, and template name. Restoring a hidden widget
works, and Cancel discards that visibility edit.
- At a 390 x 844 viewport, the editor remained within the viewport and the
Save UI button was visible and 36 CSS pixels high. The in-app browser's
screenshot preview scales the page unusually at this override; DOM bounds
confirmed the editor was 310 CSS pixels wide. This was responsive browser
verification, not an Android hardware playtest.
- Evidence: `playtest-artifacts/ui-layout-desktop.png` and
`playtest-artifacts/ui-layout-phone-viewport.png`. Restored the offline UI
to defaults and removed the temporary template via import after testing.
- Automated coverage includes migration to six slots, owner isolation,
cloud upload/hydration into a separate device cache with a mocked endpoint,
malformed imports, key conflicts, and input precedence. No production
account credentials were used for the cloud round-trip test.
- `npm run build` and the focused 67-test suite passed. The development server
was restarted after an existing watcher hit EBUSY on generated web-bootstrap
assets during a concurrent build; no runtime UI error was logged in the
subsequent playtest.
## 2026-08-18 GM Manastorm administration - COMPLETE
- Server-authorized `Phenom` access, revisioned SQLite configuration, safe
@@ -1728,3 +1761,400 @@ Vite's existing large-chunk advisory remains informational.
audit covered 12,347 compressed textures with zero fallbacks, and the
environment-performance audit found no regressions. The existing large-chunk
advisory and Rapier initialization deprecation warning remain informational.
# 2026-09-08 — WoW dungeon production-functionality audit
- Audited all 54 WoW five-player catalog entries against live runtime contracts,
pinned AzerothCore population/object drafts, and instance-script source. The
composed-runtime content audit is green for 1,193 mobs, 273 bosses, 4,026
attacks, 2,572 specials, and 1,275 native models, but the stricter production-
fidelity gate remains blocked at 0/54.
- The audit found 3,943 source game-object spawns, including 2,321 actionable
doors, buttons, chests/resources, transports, traps, and related objects. Raw
database rows are no longer passed into the typed world-object renderer; all
54 live definitions now have zero malformed world-object records.
- The follow-up implementation sweep completed source review for all 54
instances. Fifty-one now have runtime-wired instance orchestration and the three
genuinely empty stock instance scripts are pinned as source-exact no-ops;
there are no unreviewed instance scripts left. Wailing Caverns remains the
only entry with a reviewed off-mesh link, and the three Ascension-specific
dungeons still lack authoritative server population data.
- Entered Wailing Caverns from the local browser roster as a Priest healer. The
3D environment, populated combat route, party, objective, minimap, and HUD all
loaded; the minimap strip showed one Power Word: Fortitude entry. No uncaught
client runtime errors appeared. Rapier's existing initialization deprecation
warning remained informational.
- The local content manager exposed all 54 WoW entries but only Wailing Caverns
was installed; the other 53 were marked download required. Those dungeons were
therefore checked by source/runtime-contract audit in this pass, not claimed
as completed visual traversal playtests.
- The follow-up world-object compiler converted all 3,943 source rows—including
all 2,321 actionable doors, chests/resources, switches, traps, and
transports—into stable typed definitions with transformed coordinates,
type-aware states, conservative dimensions, and source/template/spawn/type
provenance. Wailing Caverns receives its 57 generated records through the
authored-definition enrichment path as well.
- Client `GameObjectDisplayInfo` metadata resolves a visual display ID for
3,905 records, a native model path for 3,837, and exact bounds for 3,547. The
generated export manifest deduplicates those instances into 458 native legacy
assets, records 38 intentional no-display spell-focus objects, and isolates
the remaining nine missing-model display IDs and 68 no-bounds display IDs for
review.
- An initial live pass exposed colored procedural markers for adapted
chests/resources. Unreviewed source objects are now deliberately hidden,
non-blocking, and non-interactive so incomplete door scripts cannot soft-lock
a dungeon and placeholder art cannot leak into normal play. A second live
Wailing Caverns pass confirmed the clean 3D scene, party combat, HUD, minimap,
and single Fortitude entry. No uncaught client errors appeared; duplicate
KTX2-loader warnings occurred only across deliberate hot-reload cycles.
- The final runtime audit reports 54/54 reviewed dungeons. Fifty-one dungeons use
52 rule-bearing instance-controller definitions (Blackrock Spire has separate
lower- and upper-spire controllers), while three use verified source-exact
no-op scripts. Every catalog objective has a completion action, and the audit
found zero malformed-object, duplicate-id, or encounter-contract issues. All
51 rule-bearing dungeons retain explicit adaptation/gap notes; native object
models and full-route live traversal are not claimed complete.
- The source-combat follow-up gives every runtime-spawnable boss a sourced kit
unless the pinned source really is melee-only. The six deliberate exceptions
are Kresh, Deviate Faerie Dragon, Spirestone Battle Lord, Spirestone Butcher,
Crystal Fang, and Grubbis. Crystal Fang retains its source-exact 15% rare-spawn
behavior and death summon. Trial of the Champion, Utgarde Keep, Hellfire
Ramparts, Sethekk Halls, Mana-Tombs, and Slave Pens event bosses now use their
pinned spell IDs and timing windows; unsupported vehicle, proc, queue, shared-
health, phase, stack, and healing-reduction semantics are explicitly recorded
as adaptations instead of being silently invented.
- Wipe/reset validation exhaustively covered 673,664 reachable encounter states,
180 reset paths, every one of the 68 non-initial reset targets, and all 135
entity-timeout rules. Durable progression now fails closed on a missing entity,
legacy snapshots with unordered action history fail closed, and Frozen Reach's
Arktos is attempt-scoped so a wipe respawns him and can still advance the duo
encounter on the next pull. The two viable post-reset resume states in Scarlet
Cathedral and Halls of Stone are intentional, not soft locks.
- Same-process checkpoint restore and online follower hydration now accept their
trusted save/leader snapshots even when a retained local provider has a newer
reset revision; ordinary stale imports remain rejected. A renderer restart
preserves the current encounter snapshot. Encounter effects use one delivery
path at a time, and obsolete headless queues are cleared on reset or dungeon
switch instead of retaining already-applied envelopes for the process lifetime.
- The generated download topology now contains an installable logical pack for
every one of the 54 campaign dungeons. The three custom dungeons without their
own creature payload are represented by dependency-only packs, while every
non-bundled dungeon pulls its exact environment and shared-creature closure.
The existing live content feed was not deployed or mutated during this pass;
browser traversal therefore still reflects the packs already available there.
- Installed packs now persist v2 verification receipts containing their exact
file set, byte counts, hashes, and dependencies. Browser-cache and native-file
presence are revalidated before entry, production dungeon entry fails closed
when a pack or dependency is missing or stale, and `content:publish` validates
the complete 54-dungeon dependency graph before any release output is written.
- Run completion now leaves the final room active so loot can be collected before
the player explicitly exits and clears the checkpoint. A wipe returns the party
to the saved run spawn while preserving already-cleared bosses and durable run
progress; attempt-scoped actors and effects reset for the next pull.
- The live Priest check used the saved `Rolecheck` character, which advanced from
level 11 to level 12 during the dungeon passes. The latest Wailing Caverns run
displayed 677/677 health, one Power Word: Fortitude alongside Arcane Intellect
(and Holy Concentration while active), and one Frostbolt plus one Icy Touch
debuff. Repeated Frostbolt applications refreshed that one entry from 7.1 to
21 seconds rather than duplicating it. The deterministic geared level-8 check
produced 3,285 mana and increased health from 407 to 437 when Fortitude was
applied.
- Verification remains deliberately split: source coverage, runtime contracts,
reset reachability, and automated behavior are green, while the combined
production-fidelity audit remains 0/54. Its remaining blockers include native
object export/collision, explicitly listed source-semantic gaps, and end-to-end
traversal evidence for every production pack—not unfinished instance-script
review.
- Final release verification passed all 1,109 Vitest cases across 202 files,
TypeScript project compilation, and the production build with 967 modules
transformed. The build staged 5,587 browser-bootstrap files, validated all
eight arenas, audited 12,347 compressed textures with zero fallbacks, and found
no environment-performance regressions. The release-candidate check accepted
all 118 changed paths. The existing large-chunk advisory and Rapier
initialization deprecation warning remain informational.
# 2026-09-09 — fixed per-rank classic mana costs
- Imported WoW mana percentages are now converted into fixed costs at each
spell rank's source level. Player level, Intellect, equipment, and maximum-mana
modifiers no longer increase the cost of an already learned rank; legitimate
talent and aura cost reductions are still applied afterward.
- Shadow Word: Pain rank 4 now costs 133 mana at every level from 26 through 33,
including level 32. Learning rank 5 at level 34 raises the cost to 188 mana.
- AI companions now use real character-scale mana pools so fixed spell costs do
not prevent healing or resurrection. The companion display also resolves the
active spell rank and the same final affordability result as the primary HUD.
- Verification passed all 1,133 Vitest cases across 208 files. The production
build completed with 974 modules transformed; arena, KTX2, and environment-
performance audits remained green, and the release-candidate check passed.
# 2026-09-09 — dungeon wall and nameplate performance regressions
- The 0.1.24 material fallback honored BLEND tags on legacy WoW WMO walls,
floors, and ceilings, disabling their depth writes. WoW environments now use
their authored material roles again; RuneWaker environments retain their
source MASK/BLEND semantics. Shipped Wailing Caverns wall materials, vines,
and water are covered by regression tests.
- The 0.1.25 boss-name occlusion scanned the complete rendered scene with
Three.js raycasts. A live Kalin's Shrine CPU profile was dominated by triangle
intersection and vertex decoding. Boss names and nearby NPC prompts now use
bounded camera-to-label queries against Rapier's existing physical spatial
index, at most ten times per second, skipping offscreen labels. Walls, floors,
and ceilings occlude labels; actors and trigger sensors do not.
- In an isolated offline Edge playtest at 1440 x 900 on an AMD RX 9070 XT,
Kalin's Shrine improved from about 10 FPS (98.5 ms/frame, 167 draw calls,
DPR 1.125) to 55.5-56.1 FPS (17.8-18.0 ms/frame, 168-170 draw calls,
DPR 1.5). This is a representative entrance/combat comparison, not an audit
of all thirty RoM dungeons. The environment alone took about 0.8 ms CPU and
0.5 ms GPU with 14 draw calls.
- Wailing Caverns screenshots show continuous opaque cavern walls and ceilings.
A controlled toggle of the old material flags reproduced the missing wall
sections at the same camera position; restoring depth-writing materials fixed
them. Its full scene ran at about 57 FPS. No uncaught client errors appeared.
- Evidence and repeatable local benchmark helpers are under
`playtest-artifacts/2026-09-09-dungeon-rendering/`: `kalin-before.cpuprofile`,
`kalin-after.cpuprofile`, `kalin-after-metrics.json`, `kalin-before.png`,
`kalin-after.png`, `wailing-regression.png`, and `wailing-restored.png`.
- All 26 focused material, label occlusion, combat sight, aggro visibility,
instancing, and NPC-prompt tests passed. Physical-occlusion tests exercise
actual Rapier worlds rather than just source-code assertions.
# 2026-09-09 — campaign rendering audit and Thor performance preparation
- Audited the actual visual GLB headers for all 54 WoW campaign dungeons:
9,402 materials, including 3,586 legacy BLEND materials restored to opaque
rendering by the shared policy. Every WoW package contained affected
materials. A permanent shipped-asset test covers all 54 definitions and
retains explicit cutout, blend, and additive roles. This is material-policy
coverage, not a claim that every room has been visually traversed.
- Live screenshots checked Wailing Caverns, Shadowfang Keep, Utgarde Pinnacle,
the Nexus, and Tinkertech Showdown. The sampled walls, floors, stairs, and
ceilings remain solid; authored lighting effects remain transparent. Kalin's
Shrine and Forsaken Abbey provided RoM rendering checks. Roster and in-dungeon
screenshots show character bodies and equipped weapon silhouettes after the
shared character animation change.
- A controlled Utgarde Pinnacle entrance test found about 1,739 draw calls,
1.95 million triangles, and 30.5 FPS on the desktop GPU. Clipping at the
existing full-fog distance reduced this to about 209 calls, 567,000 triangles,
and 60 FPS at the same viewpoint. The camera now follows each dungeon's fog
distance, including transitions that retain the existing Canvas/camera.
The background uses the fog color to avoid a clipping seam at the horizon.
All 84 dungeon definitions have render-distance coverage.
- Static dungeon visual transforms are cached until the root or its parent's
world transform changes. Tests verify imported matrices, repeated unchanged
frames, root movement, and parent movement. Characters, moving world objects,
and physics remain outside this immutable visual cache.
The final 63-second Utgarde sample held 60 FPS with 213 draw calls:
main-thread work averaged 9.2 ms/frame, renderer CPU averaged 7.5 ms
(p95 8.3 ms), and GPU averaged 2.7 ms (p95 4.1 ms). Movement and jump input
continued to animate the player while the environment remained stationary.
- Character locomotion and jump clip selections are cached by animation
library and weapon stance. The final Kalin CPU profile contains no sampled
per-frame base-clip selection/name parsing. Frame-cap deadlines now tolerate
sub-millisecond timestamp rounding without drifting or emitting catch-up
frames; tests cover 60 FPS on rounded 60 Hz and 120 Hz callbacks.
- A 31.5-second Kalin sample with a connected browser companion display held
60 FPS: main-thread work averaged 8.7 ms/frame, renderer CPU averaged 5.4 ms
(p95 5.9 ms), and GPU averaged 2.4 ms (p95 3.4 ms). The companion used about
5.1 ms of main-thread time per second. Recent ability-cost snapshot work was
not a dominant hotspot in this sample. Startup warmup is bounded to loading;
companion snapshots are already limited to ten per second during gameplay.
- These are isolated offline Edge desktop samples on an AMD RX 9070 XT at
1920 x 1080 CSS pixels, DPR 1.5 (2880 x 1620 renderbuffer). Party composition
can change between dungeon entries. They do not certify Android performance
or sustained busy-combat headroom. ADB listed no connected Android device.
- Thor acceptance should use the actual model, both native displays, target
resolution, and a sustained 20-minute traversal/combat run after warmup.
Provisional headroom target: p95 main-thread and GPU work each at or below
12 ms, with p99 presented frame intervals within the 16.7 ms 60-FPS budget.
Test large pulls, boss effects, menus, and repeated dungeon transitions;
record thermal behavior and frame-time spikes, not only average FPS.
The environment asset audit still has 60 grandfathered budget exceptions;
its green result means no new asset regression, not a Thor FPS guarantee.
- Evidence is in `playtest-artifacts/2026-09-09-thor-audit/`, including roster,
dungeon, and companion screenshots, CPU profiles, and CPU/GPU JSON samples.
The full material report is
`playtest-artifacts/2026-09-09-dungeon-rendering/wow-material-audit.json`.
- Validation passed 227 focused tests covering avatar rendering and animation,
camera distances, material policies, frame pacing, static transforms, label
visibility, and companion snapshots. The final static-cache change also
passed the 105-test scene subset. The production build and release-candidate
check passed; the existing large-bundle advisory remains.
# 2026-09-09 — additional CPU headroom from culling and shared skeletons
- Prepared dungeon visuals now group static siblings into conservative spatial
bounds. One scene hook checks these bounds after the current camera and world
matrices update, before Three.js traverses individual meshes. Bounds include
complete wall geometry and all instances; lights, animated meshes, and meshes
explicitly disabling frustum culling remain outside these groups. The hook
supports streamed chunks and restores its predecessor after cleanup.
- At the same Utgarde Pinnacle entrance, only 16 of 1,383 spatial groups were
visible. The renderer examined 108 static meshes instead of 7,002, retaining
the same 206 draw calls and 566,913 rendered triangles. Controlled culling
toggles produced byte-identical canvas PNGs across eight camera headings.
- In the same running scene, spatial grouping reduced average main-thread work
from 9.45 to 6.83 ms/frame, and renderer CPU from 7.81 to 5.31 ms/frame.
Removing containers emptied by static instancing reduced the final fresh-run
averages further to 6.49 ms main-thread and 4.85 ms renderer CPU (p95 5.2 ms).
The final sample lasted 87.8 seconds and held 60 FPS. Authored empty scene
nodes are preserved; only containers emptied by our batching are removed.
- The shared character renderer still uses SkeletonUtils.clone, then reuses
equivalent skeleton palettes within that owned clone. Bone identities, order,
and inverse bind matrices must all match; per-mesh bind transforms remain
unchanged. Different characters retain independent bones and animations.
Owned bone textures are now explicitly disposed during character teardown.
- A live character audit found 66 skeleton objects for one player palette and
256 objects for four party palettes. A Wailing Caverns toggle removed 309
duplicate skeletons and produced an identical rendered image. Tests verify
posed vertices, differing bind transforms, incompatible palettes, independent
cloned characters, and redundant texture disposal.
In the same Wailing scene, main-thread work fell from 7.40 to 6.70 ms/frame;
renderer CPU fell from 5.51 to 4.86 ms/frame, and allocated GPU textures fell
from 292 to 217. This measures palette sharing after spatial culling was
already enabled. Both samples held 60 FPS.
- The final built runtime showed a complete roster body and staff with one
skeleton for 66 skinned meshes. Kalin's Shrine showed one player palette and
four independent party palettes; walking retained the player body and weapon
silhouette. Wailing Caverns and Utgarde screenshots retained solid dungeon
surfaces. There were no uncaught client errors during these playtests.
- All 210 targeted avatar, visibility, instancing, material, camera-distance,
and label tests passed. The production build and release-candidate check
passed. The existing large-bundle advisory remains.
- Evidence is under `playtest-artifacts/2026-09-09-static-culling/`: paired PNGs,
eight-heading pixel comparisons, profiles, before/after timing JSON, and
screenshots. Measurements use the same desktop Edge/RX 9070 XT setup as the
preceding audit. These CPU improvements do not certify Thor performance.
# 2026-09-09 — bundled arena assets blocked by the browser content worker
- Reproduced the reported collision-matched fallback in the production build
with the content worker active. Warnorken's `visual.glb?arena-runtime=1`
returned 404 even though the file was bundled and directly served with 200.
The worker omitted `/assets/game/arenas/` from its bundled asset prefixes and
incorrectly rejected these files as uninstalled optional content.
- Added the arena prefix to the worker. Installed updates still take priority;
missing optional dungeon content still returns 404. Behavioral worker tests
failed for all eight arenas before the fix and now cover visual, collision,
and navigation requests with the runtime query parameter.
- The production build passed. Reloading the same browser session activated
the fixed worker without clearing storage or downloading content. Warnorken
rendered textured stone geometry and Nagrand rendered its authored arena
geometry; neither showed the loading/fallback banner after loading, and no
new console errors were recorded. Checks used offline practice in the Codex
browser at `http://127.0.0.1:4174/`, backed by a local test server on port 4173.
- All 22 content tests and the eight-arena asset validator passed. Screenshots,
before/after error logs, asset validation, and build output are saved under
`playtest-artifacts/2026-09-09-arena-loading/`. The existing large-bundle
advisory remains. This verifies the local browser build, not a deployment
or an Android package.
# 2026-09-10 - arena character and gameplay integration
- Replaced the limited arena spell interpreter with a private bundle of the
existing character combat engine. Offline practice and server matches share
casting, channels, resources, auras, pets, talents and equipment mechanics.
Each actor/match keeps its own state; opening panels does not run a second
client simulation or overwrite dungeon state.
- The controlled character uses CharacterModel with saved appearance, gear,
class, specialization, talents and bindings. Other participants also use
character models. The HUD displays actual resources, runes, combo points,
cast/channel status, cooldowns, buffs, pet commands and PC/controller labels.
Spellbook, character, talents, bindings, keybinds, map and options work in
arena. Equipment and talents remain locked to the entered match loadout.
- Fixed Keybinds opening with a shortened custom PC bar: missing slots now
display as empty instead of crashing the React tree. Live checks opened
Keybinds, Character, Talents and Options; the four-slot Q/E/R/T bar cast
Flash Heal and Power Word: Shield with resource/cast/aura feedback.
- Fixed NaN facing, spectator-camera elevation, obstructed starting positions
and camera collision. Shared right-button drag ends on release, blur, lost
capture, menus and teardown without pointer lock. Movement, jump, targeting,
ground placement, feedback, animation and combat effects use arena state.
- Authority uses all collision chunks and navigation triangles. Removed
invisible static proxy walls. All 3v3 starts are grounded, and bots follow
connected routes around walls/ramps. Shortcuts stay on level ground to avoid
falling below waypoints. Detailed scenes use a shaped support surface; the
loading/error fallback now matches collision instead of using a flat box.
- Black Rook's old navigation/anchors were on terrain above the arena. Rebuilt
against restored collision, selected its connected interior component (783
triangles), and placed both starts on the floor near Y=-28.3. Updated the
asset metadata and generator to stop restoring the old terrain navigation.
- Added PvP defender stats, shields, resource drains, pushback, school locks
and control diminishing returns. Fixed duplicate control entries counting
twice, aligned aura/control duration, and made dispels remove movement
restrictions. Dispel Magic supports friends and enemies. Healers can heal
allied pets; melee bots start weapon attacks to generate rage.
- Automated checks: 38 server arena tests and 160 distinct avatar, input,
camera, arena character/rules, combat store and ability catalog tests.
Coverage includes channels/cancellation, runes, combos, pet orders/damage/
healing, interrupts, absorbs, dispels, DR, ground spells, mana burns, RoM
secondary resources, dampening, isolation, matchmaking and match results.
Both-direction walks between team starts pass across all eight arenas.
- Live checks use an isolated in-memory level-80 priest, ArenaPriest, without
changing the user's roster. Warnorken showed its interior, the selected
character and saved spell labels. Movement changed both actor and camera.
Bots traversed, cast spells, reduced health and settled a defeat when idle.
No detailed-asset warning appeared. Evidence uses the arena-complete prefix
under playtest-artifacts; earlier Nagrand/custom-bar evidence retains the
arena-player prefix. The drag probe uses installed input code with scripted
right-button events; rotation changes while held, stops after release, and
pointerLockElement remains null. This is not a physical-device test.
- Final screenshots show the Warnorken interior and character/action bar,
Black Rook's corrected interior floor, the roster body/staff, and the
character/party after returning to Wailing Caverns. Files:
arena-complete-warnorken.png, arena-complete-black-rook.png,
arena-complete-roster.png, arena-complete-dungeon.png and
arena-complete-keybinds.png in playtest-artifacts.
- Production build and release checks passed, with the existing bundle-size
advisory. Run npm run arena:abilities:build after catalog/asset changes;
prebuild also regenerates the engine and geometry. Verification is local
offline practice plus authoritative server tests. Hosted online PvP,
deployment and Android hardware were not exercised.
# 2026-09-10 — profile keybinds and movement-conflict recovery
- Added Pause / Options → Keybinds with 133 actions, PC and Controller tabs,
search/categories, capture and touch selectors, explicit conflict replacement,
clear/reset controls, and Restore movement. Desktop defaults to PC; mobile
and native Android default to Controller. Both tabs remain available.
- Live offline browser check: assigning W to bar 1/button 1 named Move forward
in the conflict prompt; cancelling preserved W. Rebinding forward to T,
saving, closing, and reopening retained T. Restore movement returned it to W.
- At 390 × 844, controller selectors assigned L1 + Triangle to Jump, prompted
before clearing the old layer-2 ability binding, and retained the saved chord
after reopening. Restored the test bindings afterward. The final phone panel
starts at (0, 0), has a 443px scrolling action list, and keeps the footer within
the viewport. Desktop layout checked at 1280 × 900.
- Fixed the inherited 610px panel-height cap, mobile backdrop padding, action
button accessible names, and companion-toggle overlap found during QA.
- 89 targeted tests passed across input dispatch, mouse-drag lifecycle, analog
remapping, conflict recovery, menus, account isolation, cloud transfer, UI
imports, and dual-display synchronization. The full production build and
release candidate check passed; the existing bundle-size advisory remains.
- Controller chord conflicts also cover a modifier button’s standalone action,
preventing combinations such as View + A from opening the companion first.
- Hardware controller / Android APK validation and a physical right-button
drag were unavailable through this browser session. Drag lifecycle and null
pointer-lock assertions passed in the input tests. Browser viewport screenshots
are scaled by the in-app compositor; DOM geometry supplied the viewport checks.
## 2026-09-10 - Original spell media defaults and visual fallback
- Original spell visuals and authentic sounds are enabled by default. The original media pack is prepared before gameplay; download failure leaves generated visuals available and missing sounds silent.
- Saves using the previous generated-only default migrate once to original media while retaining quality, group visibility, mute, and volume settings. Explicit later preferences remain saved.
- Removed synthesized combat audio. Original mode now uses generated visuals when no original phase is mapped or when all original graphs/textures for that phase fail to load; usable original layers remain preferred.
- Validation: 64 targeted tests passed, covering defaults, persistence migration, media installation/retry, rendering selection, original audio playback, silence on missing/invalid audio, and existing effect lifecycles. Production TypeScript and Vite build passed after correcting the installer test mock type; prebuild content/asset checks also passed.
- Browser verification used the production CombatEffects and OriginalCombatEffect components with isolated store/media fixtures and the actual packaged Flash Heal graph/textures. The original case rendered one original emitter and zero generated emitters. Unmapped spell, graph HTTP 404, and texture HTTP 404 cases each rendered zero original emitters and one visible generated effect. Combat reset removed the fallback.
- Evidence: playtest-artifacts/spell-media-20260910/original.png, bad-graph.png, bad-texture.png, and missing.png. The first Vite preview timed out; the bundled isolated preview completed successfully. This was an effect-focused browser check, not a full dungeon or device audio audition.
- Final release check: blocked by existing trailing whitespace in server/generated/arena-combat-runtime.mjs. The files changed for spell media pass the whitespace check; the unrelated generated arena file was left intact.
## 2026-09-10 - All regular dungeons bundled with lossless shared storage
- Web and Android packaging include all 84 regular dungeons and their asset dependencies. Shared Manastorm maps are stored once while every Manastorm pack keeps its optional install flag. Manastorm-only maps remain outside the initial package.
- Packaged assets fell from 3,440,440,928 logical bytes to 1,600,690,686 stored bytes, including 179,063,519 bytes saved by sharing exact duplicate files. No source models, texture resolutions, animations, or audio were changed or generated.
- Gzip representations retain both compressed and original SHA-256/size metadata. Publishing keeps original remote objects for older clients. Browser installs verify both representations, retain compressed shared objects with small aliases, and preserve shared objects until their final pack is removed. Native optional downloads remain resumable and verify their expanded originals before activation.
- Android's packager automatically expanded and renamed .gz files; final objects use .gzip with noCompress instead. Added an APK verifier to the normal Android build workflow, checking every object, every original hash, exact object inventory, and the 84-dungeon/optional-Manastorm boundary.
- Final debug APK: 1,622,100,512 bytes. All 9,106 unique objects (9,194 logical asset references) passed verification from inside the actual APK. Verification report and test APK: artifacts/dungeon-texture-audit-20260910/apk-verification.json and healer-man-0.1.28-debug.apk.
- Validation: production TypeScript/Vite build and asset checks passed; 80 targeted content, Downloads, and avatar tests passed across the final runs, plus nine publisher/server tests. Android Java compilation and assembleDebug passed. Existing bundle-size/import advisories remain.
- Live production browser check used an isolated offline Gziphealer character. Roster and Deadmines rendered the player body, party bodies, equipped weapon silhouettes, and textured dungeon geometry using the bundled compressed objects. Downloads showed all regular dungeon packs included and 75 Manastorm rows not installed. Evidence: artifacts/dungeon-texture-audit-20260910/roster-final.png, deadmines-final.png, and downloads-dom.txt. No new console errors appeared in the final-format dungeon run.
- A concurrent build replaced the shared dist directory during the first preview, causing temporary asset 404s. Repeated visual validation against an isolated build completed successfully. Deadmines displayed a route-blocked party status at its entrance; this was a loading/rendering check, not a full dungeon traversal. Physical Android hardware was not exercised.
+7 -1
View File
@@ -237,10 +237,15 @@ Gitea tag after the signed APK builds successfully.
npm run content:test
npm run server:test
npm test
npm run content:publish
npm run build
```
All four commands must succeed.
All five commands must succeed. `content:publish` is a fail-closed release gate:
it validates that the generated manifest contains all 54 WoW campaign dungeon
packs, their exact dependency closure, and every catalog-referenced asset before
it writes the ignored local `content/` output. Do not build or stage a release
if that validation fails.
Apply these additional targeted checks whenever the matching area was edited:
@@ -540,6 +545,7 @@ Do **not** bump the Android version. Run these exact PowerShell commands:
```powershell
Set-Location F:\Projects\HealerMan
npm run content:test
npm run content:publish
npm run build
git status --short
npm run release:check
+2
View File
@@ -24,6 +24,8 @@ android {
versionName releaseVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Dungeon objects already carry verified lossless gzip compression.
noCompress 'gzip'
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
@@ -0,0 +1,85 @@
package com.phenomrom.healerman;
import android.content.res.AssetManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import com.getcapacitor.Bridge;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/** Streams shared APK objects at their original logical URLs; no expanded disk copy. */
final class BundledContentAssets {
private final Bridge bridge;
private final AssetManager assets;
private JSONObject files;
BundledContentAssets(Bridge bridge) {
this.bridge = bridge;
this.assets = bridge.getContext().getAssets();
}
private synchronized JSONObject files() throws Exception {
if (files == null) {
try (InputStream input = assets.open("public/content/bootstrap-manifest.json")) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[16384];
int count;
while ((count = input.read(buffer)) != -1) output.write(buffer, 0, count);
files = new JSONObject(output.toString("UTF-8")).getJSONObject("files");
}
}
return files;
}
WebResourceResponse intercept(WebResourceRequest request) {
if (!"GET".equals(request.getMethod()) || !bridge.getHost().equals(request.getUrl().getAuthority())
|| !bridge.getScheme().equals(request.getUrl().getScheme())) return null;
String path = request.getUrl().getPath();
if (path == null || !(path.startsWith("/assets/") || path.startsWith("/basis/") || path.startsWith("/data/"))) return null;
try {
JSONObject entry = files().optJSONObject(path);
if (entry == null) return null;
JSONObject download = entry.optJSONObject("download");
String objectUrl = (download == null ? entry : download).getString("url");
if (!objectUrl.matches("/content/bundled/[a-f0-9]{64}\\.[a-z0-9]+(?:\\.g(?:z|zip))?")) return null;
InputStream input = assets.open("public" + objectUrl);
if (download != null) {
try { input = new GZIPInputStream(input, 128 * 1024); }
catch (Exception error) { input.close(); throw error; }
}
Map<String, String> headers = new HashMap<>();
headers.put("Content-Length", String.valueOf(entry.getLong("bytes")));
headers.put("Cache-Control", "public, max-age=3600");
return new WebResourceResponse(mimeType(path), null, 200, "OK", headers, input);
} catch (Exception error) {
return new WebResourceResponse("text/plain", "UTF-8", 500, "Bundled asset unavailable", new HashMap<>(),
new ByteArrayInputStream("Bundled asset unavailable.".getBytes(StandardCharsets.UTF_8)));
}
}
private static String mimeType(String path) {
String extension = path.substring(path.lastIndexOf('.') + 1);
switch (extension) {
case "glb": return "model/gltf-binary";
case "json": return "application/json";
case "js": return "text/javascript";
case "wasm": return "application/wasm";
case "ktx2": return "image/ktx2";
case "png": return "image/png";
case "webp": return "image/webp";
case "avif": return "image/avif";
case "svg": return "image/svg+xml";
case "mp3": return "audio/mpeg";
case "ogg": return "audio/ogg";
case "wav": return "audio/wav";
case "webm": return "video/webm";
default: return "application/octet-stream";
}
}
}
@@ -8,6 +8,10 @@ import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.BridgeWebViewClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -20,6 +24,7 @@ import java.net.URI;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Locale;
import java.util.zip.GZIPInputStream;
/** Streams verified, resumable content objects into Android app-private storage. */
@CapacitorPlugin(name = "ContentStorage")
@@ -27,6 +32,18 @@ public class ContentStoragePlugin extends Plugin {
private static final int BUFFER_BYTES = 128 * 1024;
private static final long PROGRESS_INTERVAL_MS = 200L;
@Override
public void load() {
BundledContentAssets bundled = new BundledContentAssets(bridge);
bridge.setWebViewClient(new BridgeWebViewClient(bridge) {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
WebResourceResponse response = bundled.intercept(request);
return response != null ? response : super.shouldInterceptRequest(view, request);
}
});
}
@PluginMethod
public void download(PluginCall call) {
execute(() -> {
@@ -36,6 +53,10 @@ public class ContentStoragePlugin extends Plugin {
String sha256 = normalizedSha(requiredString(call, "sha256"));
String extension = normalizedExtension(requiredString(call, "extension"));
long expectedBytes = numericLong(call, "bytes", -1L);
boolean compressed = "gzip".equals(call.getString("encoding"));
String transferSha = compressed ? normalizedSha(requiredString(call, "downloadSha256")) : sha256;
long transferBytes = compressed ? numericLong(call, "downloadBytes", -1L) : expectedBytes;
if (expectedBytes < 0 || transferBytes < 0) throw new IllegalArgumentException("Missing content size.");
validateRemoteUrl(url);
File destination = objectFile(sha256, extension);
@@ -47,54 +68,89 @@ public class ContentStoragePlugin extends Plugin {
throw new IllegalStateException("Unable to replace invalid cached content.");
}
File partial = new File(destination.getParentFile(), destination.getName() + ".part");
long existingBytes = partial.isFile() ? partial.length() : 0L;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(15_000);
connection.setReadTimeout(45_000);
connection.setRequestProperty("Accept-Encoding", "identity");
if (existingBytes > 0L) connection.setRequestProperty("Range", "bytes=" + existingBytes + "-");
int status = connection.getResponseCode();
boolean resumed = existingBytes > 0L && status == HttpURLConnection.HTTP_PARTIAL;
if (status != HttpURLConnection.HTTP_OK && status != HttpURLConnection.HTTP_PARTIAL) {
connection.disconnect();
throw new IllegalStateException("Content server returned HTTP " + status + ".");
}
if (!resumed) existingBytes = 0L;
long downloadedBytes = existingBytes;
long totalBytes = expectedBytes > 0L
? expectedBytes
: existingBytes + Math.max(0L, connection.getContentLengthLong());
long lastProgressAt = 0L;
try (
InputStream input = new BufferedInputStream(connection.getInputStream(), BUFFER_BYTES);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(partial, resumed), BUFFER_BYTES)
) {
byte[] buffer = new byte[BUFFER_BYTES];
int count;
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
downloadedBytes += count;
long now = System.currentTimeMillis();
if (now - lastProgressAt >= PROGRESS_INTERVAL_MS) {
notifyProgress(logicalPath, downloadedBytes, totalBytes);
lastProgressAt = now;
File partial = new File(destination.getParentFile(), destination.getName() + (compressed ? "." + transferSha + ".gz" : "") + ".part");
if (!verifies(partial, transferSha, transferBytes)) {
if (partial.isFile() && partial.length() >= transferBytes && !partial.delete()) {
throw new IllegalStateException("Unable to reset an invalid partial download.");
}
long existingBytes = partial.isFile() ? partial.length() : 0L;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(15_000);
connection.setReadTimeout(45_000);
connection.setRequestProperty("Accept-Encoding", "identity");
if (existingBytes > 0L) connection.setRequestProperty("Range", "bytes=" + existingBytes + "-");
int status = connection.getResponseCode();
boolean resumed = existingBytes > 0L && status == HttpURLConnection.HTTP_PARTIAL;
if (status != HttpURLConnection.HTTP_OK && status != HttpURLConnection.HTTP_PARTIAL) {
connection.disconnect();
throw new IllegalStateException("Content server returned HTTP " + status + ".");
}
if (status == HttpURLConnection.HTTP_PARTIAL) {
String range = connection.getHeaderField("Content-Range");
if (!resumed || range == null || !range.startsWith("bytes " + existingBytes + "-")) {
connection.disconnect();
partial.delete();
throw new IllegalStateException("Content server returned an invalid resume range.");
}
}
} finally {
connection.disconnect();
}
notifyProgress(logicalPath, downloadedBytes, totalBytes);
if (!resumed) existingBytes = 0L;
long downloadedBytes = existingBytes;
long totalBytes = transferBytes > 0L
? transferBytes
: existingBytes + Math.max(0L, connection.getContentLengthLong());
long lastProgressAt = 0L;
if (!verifies(partial, sha256, expectedBytes)) {
try (
InputStream input = new BufferedInputStream(connection.getInputStream(), BUFFER_BYTES);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(partial, resumed), BUFFER_BYTES)
) {
byte[] buffer = new byte[BUFFER_BYTES];
int count;
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
downloadedBytes += count;
if (downloadedBytes > transferBytes) throw new IllegalStateException("Downloaded content exceeds expected size.");
long now = System.currentTimeMillis();
if (now - lastProgressAt >= PROGRESS_INTERVAL_MS) {
notifyProgress(logicalPath, downloadedBytes, totalBytes);
lastProgressAt = now;
}
}
} finally {
connection.disconnect();
}
notifyProgress(logicalPath, downloadedBytes, totalBytes);
}
if (!verifies(partial, transferSha, transferBytes)) {
partial.delete();
throw new IllegalStateException("Downloaded content failed SHA-256 or size verification.");
}
File verified = partial;
if (compressed) {
verified = new File(destination.getParentFile(), destination.getName() + ".decoded");
try (InputStream input = new GZIPInputStream(new FileInputStream(partial), BUFFER_BYTES);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(verified), BUFFER_BYTES)) {
byte[] buffer = new byte[BUFFER_BYTES];
long decodedBytes = 0;
int count;
while ((count = input.read(buffer)) != -1) {
decodedBytes += count;
if (decodedBytes > expectedBytes) throw new IllegalStateException("Expanded content exceeds expected size.");
output.write(buffer, 0, count);
}
} catch (Exception error) { verified.delete(); throw error; }
if (!verifies(verified, sha256, expectedBytes)) {
verified.delete();
partial.delete();
throw new IllegalStateException("Expanded content failed SHA-256 or size verification.");
}
partial.delete();
}
if (destination.exists() && !destination.delete()) {
throw new IllegalStateException("Unable to activate downloaded content.");
}
if (!partial.renameTo(destination)) {
if (!verified.renameTo(destination)) {
throw new IllegalStateException("Unable to atomically activate downloaded content.");
}
call.resolve(fileResult(destination, false));
@@ -100,6 +100,8 @@ public abstract class ControllerBridgeActivity extends BridgeActivity {
addAxisTokens(currentTokens, event.getAxisValue(MotionEvent.AXIS_HAT_Y), "Button12", "Button13");
addAxisTokens(currentTokens, leftStickX, "Axis0-", "Axis0+");
addAxisTokens(currentTokens, leftStickY, "Axis1-", "Axis1+");
addAxisTokens(currentTokens, rightStickX, "Axis2-", "Axis2+");
addAxisTokens(currentTokens, rightStickY, "Axis3-", "Axis3+");
addPositiveAxisToken(currentTokens, positiveControllerAxisValue(event, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE), "Button6");
addPositiveAxisToken(currentTokens, positiveControllerAxisValue(event, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS), "Button7");
@@ -288,7 +288,7 @@ public class ThorDualScreenPlugin extends Plugin implements DisplayManager.Displ
webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return bridge.getLocalServer().shouldInterceptRequest(request);
return bridge.getWebViewClient().shouldInterceptRequest(view, request);
}
});
}
+45
View File
@@ -0,0 +1,45 @@
# Lossless game content packaging
`npm run web:prepare` and `npm run android:prepare` include all 84 regular
dungeon packs, the existing core packs, and the dungeons' dependency closure.
Manastorm packs keep their optional install flag even when a regular dungeon
uses the same map. Manastorm-only maps and extra character packs stay optional.
The staging directories contain one object per original SHA-256 and extension
under `content/bundled`. Gzip is used only when it saves space. The packager
expands each compressed object and compares every byte with its source before
writing the bootstrap catalog. Source GLBs, texture resolutions, animations,
and audio are unchanged. No media is generated by this pipeline.
Compressed objects end in `.gzip`, not `.gz`: Android's asset packager expands
and renames `.gz` inputs. The `.gzip` extension is explicitly stored without
additional ZIP compression so the manifest and APK preserve identical bytes.
Each logical asset keeps its original byte count and SHA-256 in the manifest.
An optional `download` record describes its gzip representation, including a
separate compressed hash and byte count. The schema remains compatible with
existing catalogs. Remote publishing retains original objects for older apps;
new clients prefer the compressed representation and verify both hashes.
The Node server and Vite preview middleware resolve bundled logical URLs on
first launch. The browser service worker does the same after activation.
Android streams bundled gzip through its WebView asset handler, including the
companion display, without writing an expanded copy to app storage. Deploy the
browser build with the project's Node server so first-launch asset aliases work.
Browser optional installs store compressed objects once and keep small logical
aliases. Legacy uncompressed cache entries remain readable. Removing a pack
removes an object only after its last installed reference is gone. Android
optional downloads resume the compressed transfer, verify it, expand and verify
the original, and atomically activate the existing shared native object file.
`content/storage-report.json` inside each staging/build directory records actual
unique object bytes and duplicate savings. These are packaged asset sizes, not
GPU memory estimates. Optional Android downloads occupy their expanded size;
bundled Android assets stay compressed inside the APK.
Validation: `npm run content:test`, the content/avatar Vitest suites, the
bundled-content server tests, `npm run build`, Android compilation, and a live
roster plus dungeon screenshot check. Run `npm run release:check` before handoff.
Android build commands also run `scripts/content/verify-android-package.py`
against the resulting APK, checking every stored object and every original hash.
+35 -18
View File
@@ -1,8 +1,17 @@
# Five-player dungeon import checklist
Each dungeon is complete only when its actual instance environment, collision,
This checklist tracks the native asset and population import, not complete
instance gameplay. A checked dungeon has its environment, collision,
navigation, AzerothCore population, boss roster, and native animated creature
models are packaged under `public/assets/game/dungeons/<slug>/`.
models packaged under `public/assets/game/dungeons/<slug>/`. Use
`WOW_DUNGEON_FUNCTIONALITY_REPORT.md` for the separate production-fidelity gate
covering doors, objects, scripted progression, waves, escorts, vehicles,
traversal, resets, checkpoints, and completion playtests.
Instance-source review status (2026-09-08): 54/54 reviewed, 51/54 backed by an
executable instance controller, and 3/54 pinned as source-exact no-op instance
scripts. These counts describe implemented runtime coverage; they do not close
the native game-object export or end-to-end playtest gates.
Run one dungeon at a time:
@@ -88,24 +97,28 @@ TypeScript/production bundle checks passed.
## Ascension-specific five-player instances
- [ ] Tinkertech Showdown (`821`) - blocked on authoritative Ascension server
population/model data. Encounter identity exists for Mechatron (`663012`),
but no creature template, display mapping, or spawn rows exist locally.
- [ ] Frozen Reach (`908`) - blocked on authoritative Ascension server
population/model data. Encounter identity exists for Alva (`97700`), but no
creature template, display mapping, or spawn rows exist locally.
- [ ] Forgotten Mine (`1781`) - blocked on authoritative Ascension server
population/model data. Encounter identity exists for Geolord Vek (`254272`),
but no creature template, display mapping, or spawn rows exist locally.
- [ ] Tinkertech Showdown (`821`) - playable HealerMan-authored adaptation.
Mechatron (`663012`) and the environment are exact; the candidate machine
spell cluster, trash, cadence, positions, models, and phase rules remain
explicitly authored because no server binding or spawn snapshot survived.
- [ ] Frozen Reach (`908`) - playable source-backed adaptation. Alva (`97700`),
Arktos (`97701`), 85 exact spell rows, and summon links for entries `97703`,
`97731`, and `97770` were recovered. Server cadence, positions, stats,
models, targeting, and exact phase behavior remain authored.
- [ ] Forgotten Mine (`1781`) - playable source-backed adaptation. Geolord Vek
(`254272`), 33 exact spell rows, Geospike (`254278`), and Resonite Shard
(`254051`) were recovered. Server cadence, positions, trash, models, and the
exact crystal rule remain authored.
The individual command has been run for all three blocked instances. Their maps
and encounter identities are present in the installed client, but the installed
client and available creature caches do not provide the server-only
entry-to-display and spawn data needed to package their actual mobs/bosses.
They intentionally remain on the documented procedural fallback until an
Ascension server snapshot or reviewed creature/spawn export is supplied.
The individual import command has been run for all three source-limited
instances. Their checksummed recovery manifest lives under `ascension/` and is
validated by `npm run dungeon:ascension:recovery:validate`. Runtime adapters
consume the recovered evidence while retaining explicit `source-backed-adapted`
or `healer-man-authored` labels. The checklist remains open until an
authoritative Ascension creature/spawn/object/server-script snapshot and native
display mappings replace the remaining authored portions.
## Per-dungeon completion gate
## Per-dungeon asset/import gate
These gates passed for every checked dungeon above:
@@ -116,3 +129,7 @@ These gates passed for every checked dungeon above:
- [x] Boss order, entrance, and coordinates reviewed.
- [x] Generated campaign catalog points at `/assets/game/dungeons/<slug>/`.
- [x] Catalog verification, tests, type-check, and production bundle pass.
These checks do not certify instance-script behavior. A dungeon remains
functionally incomplete until its entry in `WOW_DUNGEON_FUNCTIONALITY_REPORT.md`
is green.
+54 -15
View File
@@ -92,8 +92,10 @@ whose preserved source has no recoverable combat ability is explicitly marked
Stock AzerothCore population is used for the standard dungeons. The three
Ascension-specific instances—Tinkertech Showdown, Frozen Reach, and Forgotten
Mine—keep their client encounter identities and use an explicit procedural
trash-population fallback. Non-Epoch recipes keep explicit procedural actor
Mine—keep their recovered client identities, spell/summon evidence where
available, and explicit source-backed or HealerMan-authored runtime adaptations.
Their remaining procedural population is never labeled authoritative.
Non-Epoch recipes keep explicit procedural actor
bodies until reviewed display exports are available. Epoch actors use packaged
client GLBs with their complete native animation libraries; only event-only
controllers without a creature display fall back.
@@ -160,10 +162,13 @@ The audit verifies the complete 54-dungeon catalog, authoritative/fallback
classification, every native environment and creature URL, file sizes,
checksums, animation presence, and compiled entry-to-model bindings. The
2026-07-26 batch packaged 50 native imports; together with the Wailing Caverns
golden fixture, 51/54 dungeons are authoritative. Tinkertech Showdown, Frozen
Reach, and Forgotten Mine remain documented fallbacks because available local
sources contain their maps and encounter identities but no authoritative
Ascension creature templates, display mappings, or spawn rows.
golden fixture, 51/54 dungeons have authoritative WoW population packages.
Tinkertech Showdown, Frozen Reach, and Forgotten Mine now have playable,
provenance-labeled runtime adaptations backed by
`ascension/ASCENSION_CUSTOM_DUNGEON_RECOVERY.json`. They remain outside the
authoritative package count because the recovered client evidence does not
include complete Ascension creature templates, display mappings, spawn/object
coordinates, or server-side cadence.
1. `npm run dungeon:discover -- <slug>` writes deterministic client/server
snapshots, a provenance lock, review-required overrides, and—when server
@@ -224,9 +229,14 @@ The default pass recompiles the 54-dungeon campaign, verifies all packaged
environment and creature assets, audits every mob and boss attack/mechanic,
opens every unique native creature GLB to verify idle, movement, attack, wound,
and death clips, proves the procedural animation path for model-less actors,
and runs the actual runtime-registry coverage test. It writes deterministic
JSON and Markdown reports to WOW_DUNGEON_CONTENT_REPORT.json and
WOW_DUNGEON_CONTENT_REPORT.md.
runs the actual runtime-registry coverage test, and audits instance-level
functionality. It writes deterministic JSON and Markdown reports to
WOW_DUNGEON_CONTENT_REPORT.json, WOW_DUNGEON_CONTENT_REPORT.md,
WOW_DUNGEON_FUNCTIONALITY_REPORT.json, and
WOW_DUNGEON_FUNCTIONALITY_REPORT.md. Catalog compilation also writes
WOW_GAMEOBJECT_ASSET_MANIFEST.json, which deduplicates the source-backed object
spawns by client model path, preserves per-dungeon/display usage, assigns the
planned shipping GLB URL, and lists unresolved display models and bounds.
Useful batch options:
@@ -239,11 +249,40 @@ Useful batch options:
# Re-run green packages, then build the app after validation.
npm run dungeon:wow:all -- --refresh --force --build
# Only re-run combat, mechanic, and animation coverage against current output.
# Re-run combat, animation, and instance-functionality audits against current output.
npm run dungeon:wow:all -- --audit-only
Kresh is intentionally recorded as a source-faithful melee-only boss: entry
3653 has no spell or SmartAI row in the pinned AzerothCore snapshot. Trial of
the Champion is likewise documented as a boss-arena population rather than a
trash route. These exceptions are asserted by exact dungeon/entity IDs; any
new basic-only boss or mob-less dungeon fails the batch.
The functionality report is the production-fidelity gate. It separately checks
typed world-object contracts, source instance scripts, encounter orchestration,
required interactions, traversal evidence, resets, checkpoints, and completion
playtests. A green asset or combat audit does not imply that doors, escorts,
waves, vehicles, keys, chests, or scripted instance progression are implemented.
The report fails closed and lists concrete edit targets for every remaining
dungeon gap.
The 2026-09-08 implementation sweep completed an instance-level source review
for all 54 campaign dungeons. Fifty-one now have runtime-wired reviewed
orchestration in addition to fleet boss/checkpoint/completion declarations; the
three stock instance scripts that are genuinely empty are pinned and recorded
as source-exact no-ops. This means there is no remaining unreviewed instance
script, not that every source feature is already exact or live-traversal validated. Per-dungeon adaptations,
missing primitives, native-object export work, and live traversal evidence stay
open in `WOW_DUNGEON_FUNCTIONALITY_REPORT.md`.
Source-backed object records stay hidden, non-blocking, and non-interactive
until their manifest asset has been exported and the corresponding instance
script transition has been reviewed. This lets the typed data ship through the
runtime contract without leaking placeholder geometry or turning an incomplete
door/transport port into a dungeon soft lock.
Kresh, the Deviate Faerie Dragon, Grubbis, Spirestone Battle Lord, Spirestone
Butcher, and Crystal Fang are intentionally recorded as source-faithful
melee-only bosses. Kresh entry 3653 and the Deviate Faerie Dragon entry 5912
have no spell or SmartAI row in the pinned AzerothCore snapshot; the latter is
also despawned by the Wailing Caverns initialization event. Grubbis entry 7361
has only aggro dialogue and death-completion rows, with no combat spell cast.
The three Blackrock Spire entries are 15% rare spawns whose database rows
contain no active combat cast; Crystal Fang's exact on-death Spire Spiderling
summon is implemented by the reviewed instance adapter. One shared exception
table supplies the runtime test and composed-content audit; stale, duplicate,
or newly introduced basic-only boss keys fail the batch.
+166 -151
View File
@@ -4,19 +4,19 @@
"scope": "HealerMan WoW five-player combat and animation coverage",
"summary": {
"dungeons": 54,
"mobs": 1031,
"bosses": 253,
"attacks": 3765,
"specialAttacks": 2481,
"nativeModels": 1266,
"proceduralModels": 18,
"uniqueNativeModels": 1166,
"mobs": 1193,
"bosses": 273,
"attacks": 4026,
"specialAttacks": 2572,
"nativeModels": 1275,
"proceduralModels": 191,
"uniqueNativeModels": 1167,
"nativeStateFallbacks": 18
},
"documentedExceptions": [
{
"type": "basic-only-boss",
"key": "wailing-caverns:entry-3653",
"key": "wailing-caverns:kresh",
"reason": "Kresh is melee-only in the pinned AzerothCore snapshot; the historical server has no spell or SmartAI row for entry 3653."
},
{
@@ -25,9 +25,24 @@
"reason": "The server-faithful rare entry 5912 has no spell rows and is despawned by the Wailing Caverns initialization event."
},
{
"type": "no-trash-instance",
"key": "trial-of-the-champion",
"reason": "Trial of the Champion is an encounter arena; its imported combat population is the five Grand Champion bosses, not a trash route."
"type": "basic-only-boss",
"key": "gnomeregan:wow-classic-batch-three-entry-7361",
"reason": "Grubbis is melee-only in the pinned AzerothCore snapshot; entry 7361 has aggro dialogue and instance-completion rows but no combat spell cast."
},
{
"type": "basic-only-boss",
"key": "blackrock-spire:entry-9218",
"reason": "Spirestone Battle Lord is a 15% rare spawn in the pinned database and has no combat spell cast beyond its basic melee attack."
},
{
"type": "basic-only-boss",
"key": "blackrock-spire:entry-9219",
"reason": "Spirestone Butcher is a 15% rare spawn in the pinned database and has no combat spell cast beyond its basic melee attack."
},
{
"type": "basic-only-boss",
"key": "blackrock-spire:entry-10376",
"reason": "Crystal Fang is a 15% rare spawn with no active combat spell in the pinned database; its exact on-death Spire Spiderling summon is implemented by the instance adapter."
}
],
"animationFallbacks": [
@@ -180,6 +195,18 @@
],
"issues": [],
"dungeons": [
{
"id": "wailing-caverns",
"title": "Wailing Caverns",
"source": "azerothcore",
"mobs": 23,
"bosses": 9,
"attacks": 72,
"specialAttacks": 40,
"nativeModels": 24,
"proceduralModels": 8,
"status": "green"
},
{
"id": "shadowfang-keep",
"title": "Shadowfang Keep",
@@ -216,18 +243,6 @@
"proceduralModels": 0,
"status": "green"
},
{
"id": "wailing-caverns",
"title": "Wailing Caverns",
"source": "azerothcore",
"mobs": 12,
"bosses": 8,
"attacks": 51,
"specialAttacks": 31,
"nativeModels": 15,
"proceduralModels": 5,
"status": "green"
},
{
"id": "razorfen-kraul",
"title": "Razorfen Kraul",
@@ -244,12 +259,12 @@
"id": "blackfathom-deeps",
"title": "Blackfathom Deeps",
"source": "azerothcore",
"mobs": 21,
"mobs": 23,
"bosses": 6,
"attacks": 65,
"attacks": 67,
"specialAttacks": 38,
"nativeModels": 27,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
@@ -268,36 +283,36 @@
"id": "gnomeregan",
"title": "Gnomeregan",
"source": "azerothcore",
"mobs": 27,
"bosses": 4,
"attacks": 82,
"mobs": 28,
"bosses": 5,
"attacks": 84,
"specialAttacks": 51,
"nativeModels": 31,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
"id": "sunken-temple",
"title": "Sunken Temple",
"source": "azerothcore",
"mobs": 29,
"mobs": 31,
"bosses": 4,
"attacks": 93,
"attacks": 95,
"specialAttacks": 60,
"nativeModels": 33,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
"id": "razorfen-downs",
"title": "Razorfen Downs",
"source": "azerothcore",
"mobs": 19,
"mobs": 21,
"bosses": 6,
"attacks": 63,
"attacks": 65,
"specialAttacks": 38,
"nativeModels": 25,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
@@ -316,60 +331,60 @@
"id": "zulfarrak",
"title": "Zul'Farrak",
"source": "azerothcore",
"mobs": 16,
"mobs": 23,
"bosses": 5,
"attacks": 69,
"attacks": 76,
"specialAttacks": 48,
"nativeModels": 21,
"proceduralModels": 0,
"proceduralModels": 7,
"status": "green"
},
{
"id": "blackrock-spire",
"title": "Blackrock Spire",
"source": "azerothcore",
"mobs": 63,
"bosses": 15,
"attacks": 273,
"specialAttacks": 195,
"mobs": 66,
"bosses": 17,
"attacks": 285,
"specialAttacks": 202,
"nativeModels": 78,
"proceduralModels": 0,
"proceduralModels": 5,
"status": "green"
},
{
"id": "blackrock-depths",
"title": "Blackrock Depths",
"source": "azerothcore",
"mobs": 48,
"mobs": 58,
"bosses": 13,
"attacks": 182,
"attacks": 192,
"specialAttacks": 121,
"nativeModels": 61,
"proceduralModels": 0,
"proceduralModels": 10,
"status": "green"
},
{
"id": "scholomance",
"title": "Scholomance",
"source": "azerothcore",
"mobs": 30,
"mobs": 31,
"bosses": 8,
"attacks": 150,
"attacks": 151,
"specialAttacks": 112,
"nativeModels": 38,
"proceduralModels": 0,
"proceduralModels": 1,
"status": "green"
},
{
"id": "stratholme",
"title": "Stratholme",
"source": "azerothcore",
"mobs": 41,
"mobs": 45,
"bosses": 9,
"attacks": 176,
"attacks": 180,
"specialAttacks": 126,
"nativeModels": 50,
"proceduralModels": 0,
"proceduralModels": 4,
"status": "green"
},
{
@@ -436,12 +451,12 @@
"id": "hellfire-ramparts",
"title": "Hellfire Citadel: Ramparts",
"source": "azerothcore",
"mobs": 10,
"bosses": 2,
"attacks": 41,
"specialAttacks": 29,
"mobs": 11,
"bosses": 4,
"attacks": 47,
"specialAttacks": 32,
"nativeModels": 12,
"proceduralModels": 0,
"proceduralModels": 3,
"status": "green"
},
{
@@ -460,48 +475,48 @@
"id": "underbog",
"title": "Coilfang: The Underbog",
"source": "azerothcore",
"mobs": 18,
"mobs": 20,
"bosses": 4,
"attacks": 80,
"attacks": 82,
"specialAttacks": 58,
"nativeModels": 22,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
"id": "slave-pens",
"title": "Coilfang: The Slave Pens",
"source": "azerothcore",
"mobs": 18,
"bosses": 3,
"attacks": 60,
"specialAttacks": 39,
"mobs": 21,
"bosses": 4,
"attacks": 66,
"specialAttacks": 43,
"nativeModels": 21,
"proceduralModels": 0,
"proceduralModels": 4,
"status": "green"
},
{
"id": "arcatraz",
"title": "Tempest Keep: The Arcatraz",
"source": "azerothcore",
"mobs": 25,
"mobs": 28,
"bosses": 4,
"attacks": 105,
"attacks": 108,
"specialAttacks": 76,
"nativeModels": 29,
"proceduralModels": 0,
"proceduralModels": 3,
"status": "green"
},
{
"id": "botanica",
"title": "Tempest Keep: The Botanica",
"source": "azerothcore",
"mobs": 24,
"mobs": 28,
"bosses": 5,
"attacks": 85,
"attacks": 89,
"specialAttacks": 56,
"nativeModels": 29,
"proceduralModels": 0,
"proceduralModels": 4,
"status": "green"
},
{
@@ -532,72 +547,72 @@
"id": "sethekk-halls",
"title": "Auchindoun: Sethekk Halls",
"source": "azerothcore",
"mobs": 14,
"bosses": 2,
"attacks": 50,
"specialAttacks": 34,
"mobs": 19,
"bosses": 3,
"attacks": 59,
"specialAttacks": 37,
"nativeModels": 16,
"proceduralModels": 0,
"proceduralModels": 6,
"status": "green"
},
{
"id": "mana-tombs",
"title": "Auchindoun: Mana-Tombs",
"source": "azerothcore",
"mobs": 11,
"bosses": 3,
"attacks": 46,
"specialAttacks": 32,
"mobs": 12,
"bosses": 4,
"attacks": 50,
"specialAttacks": 34,
"nativeModels": 14,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
"id": "auchenai-crypts",
"title": "Auchindoun: Auchenai Crypts",
"source": "azerothcore",
"mobs": 12,
"bosses": 2,
"attacks": 44,
"specialAttacks": 30,
"mobs": 13,
"bosses": 3,
"attacks": 48,
"specialAttacks": 32,
"nativeModels": 14,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
"id": "magisters-terrace",
"title": "Magister's Terrace",
"source": "azerothcore",
"mobs": 15,
"mobs": 23,
"bosses": 3,
"attacks": 57,
"attacks": 65,
"specialAttacks": 39,
"nativeModels": 18,
"proceduralModels": 0,
"proceduralModels": 8,
"status": "green"
},
{
"id": "black-morass",
"title": "The Black Morass",
"source": "azerothcore",
"mobs": 4,
"mobs": 13,
"bosses": 3,
"attacks": 25,
"attacks": 34,
"specialAttacks": 18,
"nativeModels": 7,
"proceduralModels": 0,
"proceduralModels": 9,
"status": "green"
},
{
"id": "escape-from-durnholde",
"title": "The Escape From Durnholde",
"source": "azerothcore",
"mobs": 26,
"mobs": 32,
"bosses": 3,
"attacks": 53,
"attacks": 59,
"specialAttacks": 24,
"nativeModels": 29,
"proceduralModels": 0,
"proceduralModels": 6,
"status": "green"
},
{
@@ -605,107 +620,107 @@
"title": "Utgarde Keep",
"source": "azerothcore",
"mobs": 19,
"bosses": 3,
"attacks": 44,
"specialAttacks": 22,
"bosses": 6,
"attacks": 55,
"specialAttacks": 30,
"nativeModels": 22,
"proceduralModels": 0,
"proceduralModels": 3,
"status": "green"
},
{
"id": "utgarde-pinnacle",
"title": "Utgarde Pinnacle",
"source": "azerothcore",
"mobs": 13,
"mobs": 19,
"bosses": 4,
"attacks": 44,
"attacks": 50,
"specialAttacks": 27,
"nativeModels": 17,
"proceduralModels": 0,
"proceduralModels": 6,
"status": "green"
},
{
"id": "the-nexus",
"title": "The Nexus",
"source": "azerothcore",
"mobs": 21,
"mobs": 24,
"bosses": 5,
"attacks": 61,
"attacks": 64,
"specialAttacks": 35,
"nativeModels": 26,
"proceduralModels": 0,
"proceduralModels": 3,
"status": "green"
},
{
"id": "the-oculus",
"title": "The Oculus",
"source": "azerothcore",
"mobs": 8,
"mobs": 17,
"bosses": 4,
"attacks": 33,
"attacks": 42,
"specialAttacks": 21,
"nativeModels": 12,
"proceduralModels": 0,
"proceduralModels": 9,
"status": "green"
},
{
"id": "culling-of-stratholme",
"title": "The Culling of Stratholme",
"source": "azerothcore",
"mobs": 16,
"mobs": 21,
"bosses": 4,
"attacks": 44,
"attacks": 49,
"specialAttacks": 24,
"nativeModels": 20,
"proceduralModels": 0,
"proceduralModels": 5,
"status": "green"
},
{
"id": "halls-of-stone",
"title": "Halls of Stone",
"source": "azerothcore",
"mobs": 13,
"mobs": 16,
"bosses": 4,
"attacks": 42,
"attacks": 45,
"specialAttacks": 25,
"nativeModels": 16,
"proceduralModels": 1,
"proceduralModels": 4,
"status": "green"
},
{
"id": "draktharon-keep",
"title": "Drak'Tharon Keep",
"source": "azerothcore",
"mobs": 18,
"mobs": 20,
"bosses": 4,
"attacks": 45,
"attacks": 47,
"specialAttacks": 23,
"nativeModels": 22,
"proceduralModels": 0,
"proceduralModels": 2,
"status": "green"
},
{
"id": "azjol-nerub",
"title": "Azjol-Nerub",
"source": "azerothcore",
"mobs": 10,
"mobs": 18,
"bosses": 3,
"attacks": 30,
"attacks": 38,
"specialAttacks": 17,
"nativeModels": 13,
"proceduralModels": 0,
"proceduralModels": 8,
"status": "green"
},
{
"id": "halls-of-lightning",
"title": "Halls of Lightning",
"source": "azerothcore",
"mobs": 16,
"mobs": 19,
"bosses": 4,
"attacks": 49,
"attacks": 52,
"specialAttacks": 29,
"nativeModels": 20,
"proceduralModels": 0,
"proceduralModels": 3,
"status": "green"
},
{
@@ -724,24 +739,24 @@
"id": "violet-hold",
"title": "Violet Hold",
"source": "azerothcore",
"mobs": 2,
"mobs": 17,
"bosses": 3,
"attacks": 24,
"attacks": 39,
"specialAttacks": 19,
"nativeModels": 5,
"proceduralModels": 0,
"proceduralModels": 15,
"status": "green"
},
{
"id": "ahnkahet-old-kingdom",
"title": "Ahn'kahet: The Old Kingdom",
"source": "azerothcore",
"mobs": 19,
"mobs": 23,
"bosses": 5,
"attacks": 60,
"attacks": 64,
"specialAttacks": 36,
"nativeModels": 24,
"proceduralModels": 0,
"proceduralModels": 4,
"status": "green"
},
{
@@ -760,36 +775,36 @@
"id": "trial-of-the-champion",
"title": "Trial of the Champion",
"source": "azerothcore",
"mobs": 0,
"bosses": 5,
"attacks": 88,
"specialAttacks": 83,
"mobs": 6,
"bosses": 12,
"attacks": 123,
"specialAttacks": 105,
"nativeModels": 5,
"proceduralModels": 0,
"proceduralModels": 13,
"status": "green"
},
{
"id": "pit-of-saron",
"title": "Pit of Saron",
"source": "azerothcore",
"mobs": 27,
"mobs": 31,
"bosses": 3,
"attacks": 49,
"attacks": 53,
"specialAttacks": 19,
"nativeModels": 30,
"proceduralModels": 0,
"proceduralModels": 4,
"status": "green"
},
{
"id": "halls-of-reflection",
"title": "Halls of Reflection",
"source": "azerothcore",
"mobs": 8,
"mobs": 16,
"bosses": 2,
"attacks": 38,
"attacks": 46,
"specialAttacks": 28,
"nativeModels": 10,
"proceduralModels": 0,
"proceduralModels": 8,
"status": "green"
},
{
@@ -798,8 +813,8 @@
"source": "procedural-fallback",
"mobs": 3,
"bosses": 1,
"attacks": 8,
"specialAttacks": 4,
"attacks": 13,
"specialAttacks": 12,
"nativeModels": 0,
"proceduralModels": 4,
"status": "green"
@@ -808,24 +823,24 @@
"id": "frozen-reach",
"title": "Frozen Reach",
"source": "procedural-fallback",
"mobs": 3,
"mobs": 2,
"bosses": 1,
"attacks": 8,
"specialAttacks": 4,
"attacks": 19,
"specialAttacks": 19,
"nativeModels": 0,
"proceduralModels": 4,
"proceduralModels": 3,
"status": "green"
},
{
"id": "forgotten-mine",
"title": "Forgotten Mine",
"source": "procedural-fallback",
"mobs": 3,
"mobs": 4,
"bosses": 1,
"attacks": 8,
"specialAttacks": 4,
"attacks": 13,
"specialAttacks": 12,
"nativeModels": 0,
"proceduralModels": 4,
"proceduralModels": 5,
"status": "green"
}
]
+45 -42
View File
@@ -4,72 +4,75 @@ Status: **green**
Scope: executable combat populations and creature animation bindings. This report does not certify instance scripts, doors, interactables, escorts, waves, vehicles, or navigation.
Coverage: 54 dungeons, 1031 mobs, 253 bosses, 3765 executable attacks, and 2481 special attacks/mechanics.
Coverage: 54 dungeons, 1193 mobs, 273 bosses, 4026 executable attacks, and 2572 special attacks/mechanics.
Animation paths: 1266 native model bindings and 18 procedural bindings across 1166 unique native GLBs; 18 missing native states use the shared procedural fallback.
Animation paths: 1275 native model bindings and 191 procedural bindings across 1167 unique native GLBs; 18 missing native states use the shared procedural fallback.
| Dungeon | Mobs | Bosses | Attacks | Specials | Native | Procedural | Status |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |
| Wailing Caverns | 23 | 9 | 72 | 40 | 24 | 8 | green |
| Shadowfang Keep | 24 | 7 | 65 | 34 | 31 | 0 | green |
| Stormwind Stockade | 6 | 5 | 42 | 31 | 11 | 0 | green |
| The Deadmines | 15 | 7 | 55 | 33 | 22 | 0 | green |
| Wailing Caverns | 12 | 8 | 51 | 31 | 15 | 5 | green |
| Razorfen Kraul | 31 | 7 | 87 | 49 | 38 | 0 | green |
| Blackfathom Deeps | 21 | 6 | 65 | 38 | 27 | 0 | green |
| Blackfathom Deeps | 23 | 6 | 67 | 38 | 27 | 2 | green |
| Uldaman | 31 | 7 | 104 | 66 | 38 | 0 | green |
| Gnomeregan | 27 | 4 | 82 | 51 | 31 | 0 | green |
| Sunken Temple | 29 | 4 | 93 | 60 | 33 | 0 | green |
| Razorfen Downs | 19 | 6 | 63 | 38 | 25 | 0 | green |
| Gnomeregan | 28 | 5 | 84 | 51 | 31 | 2 | green |
| Sunken Temple | 31 | 4 | 95 | 60 | 33 | 2 | green |
| Razorfen Downs | 21 | 6 | 65 | 38 | 25 | 2 | green |
| Scarlet Monastery | 32 | 5 | 107 | 70 | 37 | 0 | green |
| Zul'Farrak | 16 | 5 | 69 | 48 | 21 | 0 | green |
| Blackrock Spire | 63 | 15 | 273 | 195 | 78 | 0 | green |
| Blackrock Depths | 48 | 13 | 182 | 121 | 61 | 0 | green |
| Scholomance | 30 | 8 | 150 | 112 | 38 | 0 | green |
| Stratholme | 41 | 9 | 176 | 126 | 50 | 0 | green |
| Zul'Farrak | 23 | 5 | 76 | 48 | 21 | 7 | green |
| Blackrock Spire | 66 | 17 | 285 | 202 | 78 | 5 | green |
| Blackrock Depths | 58 | 13 | 192 | 121 | 61 | 10 | green |
| Scholomance | 31 | 8 | 151 | 112 | 38 | 1 | green |
| Stratholme | 45 | 9 | 180 | 126 | 50 | 4 | green |
| Maraudon | 25 | 8 | 95 | 62 | 33 | 0 | green |
| Ragefire Chasm | 7 | 4 | 23 | 12 | 11 | 0 | green |
| Dire Maul | 63 | 12 | 242 | 167 | 75 | 0 | green |
| Hellfire Citadel: The Shattered Halls | 29 | 3 | 92 | 60 | 32 | 0 | green |
| Hellfire Citadel: The Blood Furnace | 14 | 3 | 53 | 36 | 17 | 0 | green |
| Hellfire Citadel: Ramparts | 10 | 2 | 41 | 29 | 12 | 0 | green |
| Hellfire Citadel: Ramparts | 11 | 4 | 47 | 32 | 12 | 3 | green |
| Coilfang: The Steamvault | 14 | 3 | 63 | 46 | 17 | 0 | green |
| Coilfang: The Underbog | 18 | 4 | 80 | 58 | 22 | 0 | green |
| Coilfang: The Slave Pens | 18 | 3 | 60 | 39 | 21 | 0 | green |
| Tempest Keep: The Arcatraz | 25 | 4 | 105 | 76 | 29 | 0 | green |
| Tempest Keep: The Botanica | 24 | 5 | 85 | 56 | 29 | 0 | green |
| Coilfang: The Underbog | 20 | 4 | 82 | 58 | 22 | 2 | green |
| Coilfang: The Slave Pens | 21 | 4 | 66 | 43 | 21 | 4 | green |
| Tempest Keep: The Arcatraz | 28 | 4 | 108 | 76 | 29 | 3 | green |
| Tempest Keep: The Botanica | 28 | 5 | 89 | 56 | 29 | 4 | green |
| Tempest Keep: The Mechanar | 14 | 3 | 69 | 52 | 17 | 0 | green |
| Auchindoun: Shadow Labyrinth | 18 | 4 | 67 | 45 | 22 | 0 | green |
| Auchindoun: Sethekk Halls | 14 | 2 | 50 | 34 | 16 | 0 | green |
| Auchindoun: Mana-Tombs | 11 | 3 | 46 | 32 | 14 | 0 | green |
| Auchindoun: Auchenai Crypts | 12 | 2 | 44 | 30 | 14 | 0 | green |
| Magister's Terrace | 15 | 3 | 57 | 39 | 18 | 0 | green |
| The Black Morass | 4 | 3 | 25 | 18 | 7 | 0 | green |
| The Escape From Durnholde | 26 | 3 | 53 | 24 | 29 | 0 | green |
| Utgarde Keep | 19 | 3 | 44 | 22 | 22 | 0 | green |
| Utgarde Pinnacle | 13 | 4 | 44 | 27 | 17 | 0 | green |
| The Nexus | 21 | 5 | 61 | 35 | 26 | 0 | green |
| The Oculus | 8 | 4 | 33 | 21 | 12 | 0 | green |
| The Culling of Stratholme | 16 | 4 | 44 | 24 | 20 | 0 | green |
| Halls of Stone | 13 | 4 | 42 | 25 | 16 | 1 | green |
| Drak'Tharon Keep | 18 | 4 | 45 | 23 | 22 | 0 | green |
| Azjol-Nerub | 10 | 3 | 30 | 17 | 13 | 0 | green |
| Halls of Lightning | 16 | 4 | 49 | 29 | 20 | 0 | green |
| Auchindoun: Sethekk Halls | 19 | 3 | 59 | 37 | 16 | 6 | green |
| Auchindoun: Mana-Tombs | 12 | 4 | 50 | 34 | 14 | 2 | green |
| Auchindoun: Auchenai Crypts | 13 | 3 | 48 | 32 | 14 | 2 | green |
| Magister's Terrace | 23 | 3 | 65 | 39 | 18 | 8 | green |
| The Black Morass | 13 | 3 | 34 | 18 | 7 | 9 | green |
| The Escape From Durnholde | 32 | 3 | 59 | 24 | 29 | 6 | green |
| Utgarde Keep | 19 | 6 | 55 | 30 | 22 | 3 | green |
| Utgarde Pinnacle | 19 | 4 | 50 | 27 | 17 | 6 | green |
| The Nexus | 24 | 5 | 64 | 35 | 26 | 3 | green |
| The Oculus | 17 | 4 | 42 | 21 | 12 | 9 | green |
| The Culling of Stratholme | 21 | 4 | 49 | 24 | 20 | 5 | green |
| Halls of Stone | 16 | 4 | 45 | 25 | 16 | 4 | green |
| Drak'Tharon Keep | 20 | 4 | 47 | 23 | 22 | 2 | green |
| Azjol-Nerub | 18 | 3 | 38 | 17 | 13 | 8 | green |
| Halls of Lightning | 19 | 4 | 52 | 29 | 20 | 3 | green |
| Gundrak | 15 | 5 | 53 | 33 | 20 | 0 | green |
| Violet Hold | 2 | 3 | 24 | 19 | 5 | 0 | green |
| Ahn'kahet: The Old Kingdom | 19 | 5 | 60 | 36 | 24 | 0 | green |
| Violet Hold | 17 | 3 | 39 | 19 | 5 | 15 | green |
| Ahn'kahet: The Old Kingdom | 23 | 5 | 64 | 36 | 24 | 4 | green |
| The Forge of Souls | 11 | 2 | 23 | 10 | 13 | 0 | green |
| Trial of the Champion | 0 | 5 | 88 | 83 | 5 | 0 | green |
| Pit of Saron | 27 | 3 | 49 | 19 | 30 | 0 | green |
| Halls of Reflection | 8 | 2 | 38 | 28 | 10 | 0 | green |
| Tinkertech Showdown | 3 | 1 | 8 | 4 | 0 | 4 | green |
| Frozen Reach | 3 | 1 | 8 | 4 | 0 | 4 | green |
| Forgotten Mine | 3 | 1 | 8 | 4 | 0 | 4 | green |
| Trial of the Champion | 6 | 12 | 123 | 105 | 5 | 13 | green |
| Pit of Saron | 31 | 3 | 53 | 19 | 30 | 4 | green |
| Halls of Reflection | 16 | 2 | 46 | 28 | 10 | 8 | green |
| Tinkertech Showdown | 3 | 1 | 13 | 12 | 0 | 4 | green |
| Frozen Reach | 2 | 1 | 19 | 19 | 0 | 3 | green |
| Forgotten Mine | 4 | 1 | 13 | 12 | 0 | 5 | green |
## Documented source-faithful exceptions
- wailing-caverns:entry-3653: Kresh is melee-only in the pinned AzerothCore snapshot; the historical server has no spell or SmartAI row for entry 3653.
- wailing-caverns:kresh: Kresh is melee-only in the pinned AzerothCore snapshot; the historical server has no spell or SmartAI row for entry 3653.
- wailing-caverns:deviate-faerie-dragon: The server-faithful rare entry 5912 has no spell rows and is despawned by the Wailing Caverns initialization event.
- trial-of-the-champion: Trial of the Champion is an encounter arena; its imported combat population is the five Grand Champion bosses, not a trash route.
- gnomeregan:wow-classic-batch-three-entry-7361: Grubbis is melee-only in the pinned AzerothCore snapshot; entry 7361 has aggro dialogue and instance-completion rows but no combat spell cast.
- blackrock-spire:entry-9218: Spirestone Battle Lord is a 15% rare spawn in the pinned database and has no combat spell cast beyond its basic melee attack.
- blackrock-spire:entry-9219: Spirestone Butcher is a 15% rare spawn in the pinned database and has no combat spell cast beyond its basic melee attack.
- blackrock-spire:entry-10376: Crystal Fang is a 15% rare spawn with no active combat spell in the pinned database; its exact on-death Spire Spiderling summon is implemented by the instance adapter.
## Issues
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,858 @@
{
"schemaVersion": 1,
"scope": "ascension-custom-five-player-source-recovery",
"status": "partial-authoritative-recovery",
"sourcePolicy": {
"exact": "Values copied from installed-client DBC rows or already checksummed map packages.",
"spellLinked": "Creature and gameobject IDs recovered from summon effects in installed-client Spell.dbc. The link is exact even when the missing creature_template or gameobject_template name is inferred from the spell context.",
"authored": "Timing, phase ownership, placement, health tuning, and any entity explicitly marked authored are adaptation decisions, not claims about Ascension server behavior."
},
"sources": [
{
"id": "ascension-area52-spell-dbc",
"kind": "installed-client-dbc",
"pathHint": "../LadiksMPQEditor/client-current/area-52/patch-D/DBFilesClient/Spell.dbc",
"sha256": "2f77f18b91ffbae32a19568e4bc05ec78ee384b6ba8dd2a6e05f0e97abbb2dce",
"header": {
"signature": "WDBC",
"recordCount": 238891,
"fieldCount": 234,
"recordSize": 936,
"stringBlockSize": 14058299
},
"localeField": "enUS",
"confidence": "exact"
},
{
"id": "manastorm-runtime-catalog",
"kind": "installed-client-encounter-export",
"path": "src/game/generated/manastormRuntimeCatalog.json",
"confidence": "exact"
},
{
"id": "manastorm-asset-packages",
"kind": "installed-client-map-export",
"path": "src/game/generated/manastormAssetPackages.json",
"confidence": "exact-environment-provisional-semantics"
},
{
"id": "campaign-runtime-snapshot",
"kind": "generated-runtime-catalog",
"path": "src/game/generated/dungeonCampaignCatalog.json",
"confidence": "exact-current-state"
},
{
"id": "ascension-db-alva",
"kind": "official-public-database",
"url": "https://db.ascension.gg/?npc=97700",
"confidence": "exact"
},
{
"id": "ascension-db-arktos",
"kind": "official-public-database",
"url": "https://db.ascension.gg/?npc=97701",
"confidence": "exact"
},
{
"id": "ascension-changelog-frozen-reach-blast-arrow",
"kind": "official-changelog",
"url": "https://ascension.gg/en/changelog/1?page=7",
"confidence": "exact-wording-name-differs"
},
{
"id": "ascension-changelog-frozen-reach-rebirth",
"kind": "official-changelog",
"url": "https://ascension.gg/en/changelog/1?page=8",
"confidence": "exact"
},
{
"id": "ascension-changelog-forgotten-mine-crystals",
"kind": "official-changelog",
"url": "https://ascension.gg/en/changelog/1?page=51",
"confidence": "exact"
},
{
"id": "ascension-changelog-forgotten-mine-geospike",
"kind": "official-changelog",
"url": "https://ascension.gg/en/changelog/1?page=29",
"confidence": "exact"
}
],
"localSearchAudit": {
"searchedRoots": [
"../wow-pvt-server-backups-2",
"../WoW-Pvt-Server-Backups",
"../wow-private-server-notes",
"../LadiksMPQEditor",
"../wow335a/Cache",
"../resources/client/Cache"
],
"searchedArtifacts": [
"creature_template and creature spawn SQL",
"gameobject_template and gameobject spawn SQL",
"SmartAI and ScriptName bindings",
"Lua/XML/JSON/CSV encounter data",
"creaturecache.wdb and gameobjectcache.wdb records"
],
"missingAuthoritativeData": [
"creature templates and display mappings for 663012, 97700, and 254272",
"world spawn rows for maps 821, 908, and 1781",
"server-side encounter scripts and cast cadence",
"authoritative trash population and patrol routes",
"authoritative gameobject placements"
],
"publicSnapshotCheck": {
"repository": "https://github.com/Ascension-Addons/Questie-X-AscensionDB.git",
"commit": "cf6710ef94c264d842cf2ea94c4b50e9ece6dd61",
"result": "No target boss IDs, names, spawns, or encounter scripts were present."
}
},
"dungeons": [
{
"mapId": 821,
"id": "tinkertech-showdown",
"title": "Tinkertech Showdown",
"mapDirectory": "TinketechShowdown",
"sourceClassification": "identity-and-environment-only",
"environment": {
"sourceHash": "323c47c081d0a6c39daf9878284863c21e3e38dbced2ba3f58d1d157d080d41d",
"rootWmo": "World/wmo/Dungeon/AZ_Subway/Subway_Dungeon.wmo",
"anchors": {
"player": [
3.648781,
-4.167801,
66.263252
],
"trash": [
10.220209,
-126.067818,
1266.206177
],
"boss": [
-15.779793,
-4.267807,
2439.406006
]
},
"semanticStatus": "provisional-geometry-derived"
},
"encounters": [
{
"encounterId": 9013,
"modeId": 2,
"name": "Mechatron",
"creatureId": 663012,
"identityConfidence": "exact"
}
],
"currentRuntime": {
"bossEntityId": "entry-663012",
"proceduralTrashSpawnCount": 15,
"proceduralMobEntries": [
{
"entityId": "tinkertech-showdown-guardian",
"serverEntry": 2629079128
},
{
"entityId": "tinkertech-showdown-caster",
"serverEntry": 3849447491
},
{
"entityId": "tinkertech-showdown-brute",
"serverEntry": 1787979165
}
]
},
"sourceRecovery": {
"association": "candidate-client-cluster-only",
"associationConfidence": "low",
"reason": "These adjacent client rows form a coherent mechanical-machine kit and include Sound: Goblin Head Machine Loop, but no recovered server row links them to creature 663012.",
"spellRows": {
"257438": "Rocket",
"257459": "Gatling Missile Barrage",
"257460": "Gatling Missile",
"257461": "Gatling Missile",
"257462": "Sound: Goblin Head Machine Loop",
"257470": "Incineration Beam",
"257471": "Energy Ball",
"257472": "Electrified Zone",
"257473": "Electric Shock"
},
"families": {
"rocket": [
257438
],
"gatlingMissileBarrage": [
257459,
257460,
257461
],
"incinerationBeam": [
257470
],
"electrifiedZone": [
257472,
257473
]
}
},
"adaptation": {
"status": "custom-authoring-required",
"populationPlan": {
"disposition": "retain-current-route-as-explicit-adaptation",
"packCount": 5,
"membersPerPack": 3,
"authoredMobs": [
{
"serverEntry": 2629079128,
"name": "Tinkertech Guardbot",
"role": "melee-interceptor"
},
{
"serverEntry": 3849447491,
"name": "Tinkertech Coilcaster",
"role": "electrical-ranged"
},
{
"serverEntry": 1787979165,
"name": "Tinkertech Demolisher",
"role": "rocket-bruiser"
}
]
},
"encounterPlan": [
"Mechatron remains creature 663012 at the provisional boss anchor.",
"Rocket uses a 2.0 second target reticle and splash damage on an authored 8 second cadence.",
"Gatling Missile Barrage uses a 3.0 second warning followed by eight lane impacts over 4 seconds on an authored 14 second cadence.",
"Incineration Beam uses a 2.5 second wind-up and sweeps the subway lane for 5 seconds; immutable web geometry means it visually disables lane sections instead of permanently destroying client platforms.",
"Electrified Zone alternates floor strips after a 1.5 second warning, remains active for 8 seconds, and applies a 1.5 second stun on contact.",
"At 35 percent health, cadence accelerates by 20 percent and two authored Coilcasters enter from the previous pack anchor."
],
"mustBeCustomAuthored": [
"all trash identities, placements, and AI",
"all boss timing and phase thresholds",
"the decision to associate candidate spells 257438 and 257459-257473 with Mechatron",
"platform or lane disable behavior",
"boss and trash visual composites",
"loot and completion scripting"
]
},
"unresolved": [
"No authoritative Mechatron spell-to-creature binding was found.",
"No authoritative trash or gameobject IDs were found.",
"The custom ADT placement transform and all semantic anchors still require playtest approval."
]
},
{
"mapId": 908,
"id": "frozen-reach",
"title": "Frozen Reach",
"mapDirectory": "Alvaencounter",
"sourceClassification": "encounter-spells-and-summons-recovered",
"environment": {
"sourceHash": "5ab771df79c0e062cea3ebda4e416a9245bcf8a4cc6da048077df5e674081f97",
"anchors": {
"player": [
1858.534668,
78.860199,
2229.334473
],
"trash": [
2100.134766,
80.860199,
2132.93457
],
"boss": [
2344.134766,
62.460205,
2134.334717
]
},
"semanticStatus": "provisional-elevated-encounter-component"
},
"encounters": [
{
"encounterId": 2168,
"modeId": 0,
"name": "Alva",
"creatureId": 97700,
"identityConfidence": "exact"
},
{
"encounterId": 2170,
"modeId": 2,
"name": "Alva",
"creatureId": 97700,
"identityConfidence": "exact"
}
],
"entities": [
{
"entryId": 97700,
"name": "Alva",
"role": "boss",
"sourceKind": "encounter-dbc-and-official-db"
},
{
"entryId": 97701,
"name": "Arktos",
"role": "boss-companion",
"sourceKind": "official-db"
},
{
"entryId": 97703,
"name": "Blast Arrow summoned unit",
"role": "area-trigger",
"sourceKind": "spell-linked-name-inferred"
},
{
"entryId": 97731,
"name": "Explosive Trap summoned unit",
"role": "trap",
"sourceKind": "spell-linked-name-inferred"
},
{
"entryId": 97770,
"name": "Alvajar summoned unit",
"role": "add",
"sourceKind": "spell-linked-name-inferred"
}
],
"currentRuntime": {
"bossEntityId": "entry-97700",
"proceduralTrashSpawnCount": 15,
"proceduralMobEntries": [
{
"entityId": "frozen-reach-guardian",
"serverEntry": 1606324391
},
{
"entityId": "frozen-reach-caster",
"serverEntry": 854807736
},
{
"entityId": "frozen-reach-brute",
"serverEntry": 2855026892
}
]
},
"sourceRecovery": {
"association": "explicit-alva-arktos-client-cluster",
"associationConfidence": "high",
"spellRows": {
"255347": "Auto Shot",
"255349": "Rain of Arrows",
"255351": "Rain of Arrows",
"255352": "Unbridled Arrows",
"255353": "Unbridled Arrows",
"255358": "Blast Arrow",
"255359": "Blast Arrow",
"255360": "Pact of the Hunt",
"255362": "Blast Arrow",
"255363": "Blast Arrow",
"255374": "Ice Rock",
"255375": "Ice Rock",
"255377": "Ice Rock",
"255378": "Unholy Frenzy",
"255379": "Carnivorous Bite",
"255380": "Frost Shield",
"255381": "Set Ablaze",
"255382": "Blaze",
"255387": "Frost Strike",
"255389": "Shadow Shroud Surge",
"255390": "Shadow Shroud Rebirth",
"255393": "Sphere of Grief and Wrath",
"255394": "Vengeful Bolt",
"255395": "Vengeful Bolt",
"255397": "Shadow Veil Lance",
"255398": "Shadow Veil Lance",
"255399": "Frost Roar",
"255401": "Cluster Shot",
"255402": "Cluster Shot",
"255403": "Cluster Shot",
"255410": "Alva's Grief",
"255411": "Alva's Grief",
"255412": "Frost orb",
"255413": "Frozen Pulse",
"255417": "Shield Wall",
"255418": "Shield Wall",
"255419": "Alva's Wrath",
"255420": "Throw Explosive Trap",
"255421": "Explosive Trap",
"255423": "Trap Explosion",
"255424": "Charging",
"255426": "Explosive Trap",
"255427": "Frostblade Strike",
"255428": "Frostblade Strike",
"255432": "Army of the Dead",
"255433": "Army of the Dead",
"255434": "Lacerate",
"255435": "Lacerate",
"255436": "Lacerate",
"255437": "Arcing Slice",
"255438": "Rain of Arrows",
"255439": "Rain of Arrows",
"255440": "Cluster Shot",
"255441": "Cluster Shot",
"255442": "Unbridled Arrows",
"255443": "Unbridled Arrows",
"255444": "Blast Arrow",
"255445": "Blast Arrow",
"255446": "Frost Roar",
"255447": "Frost Roar",
"255448": "Vengeful Bolt",
"255449": "Vengeful Bolt",
"255450": "Ice Rock",
"255451": "Ice Rock",
"255452": "Frostblade Strike",
"255453": "Frostblade Strike",
"255454": "Shadow Shroud Surge",
"255455": "Shadow Shroud Surge",
"255456": "Shadow Shroud Rebirth",
"255457": "Shadow Shroud Rebirth",
"255458": "Shadow Veil Lance",
"255459": "Shadow Veil Lance",
"255460": "Alva's Wrath",
"255461": "Alva's Wrath",
"255462": "Sphere of Grief and Wrath",
"255463": "Sphere of Grief and Wrath",
"255464": "Frost Strike",
"255465": "Frost Strike",
"255466": "Predator's Fury",
"255467": "Alva's Grief",
"255468": "Alva's Grief",
"255469": "Trap Explosion",
"255470": "Trap Explosion",
"255471": "Frozen Pulse",
"255472": "Frozen Pulse"
},
"families": {
"alvaRanged": [
255347,
255349,
255351,
255352,
255353,
255358,
255359,
255401,
255402,
255403,
255420,
255421,
255423,
255424
],
"arktos": [
255360,
255374,
255375,
255377,
255378,
255379,
255380,
255381,
255382,
255387,
255399,
255417,
255418,
255434
],
"alvaVengeance": [
255389,
255390,
255393,
255394,
255395,
255397,
255398,
255410,
255411,
255419,
255432,
255433
],
"difficultyOneAndTwoVariants": [
255435,
255436,
255438,
255439,
255440,
255441,
255442,
255443,
255444,
255445,
255446,
255447,
255448,
255449,
255450,
255451,
255452,
255453,
255454,
255455,
255456,
255457,
255458,
255459,
255460,
255461,
255462,
255463,
255464,
255465,
255467,
255468,
255469,
255470,
255471,
255472
]
},
"summonLinks": [
{
"spellId": 255363,
"effectIndex": 0,
"effectType": 28,
"targetKind": "creature",
"entryId": 97703
},
{
"spellId": 255421,
"effectIndex": 0,
"effectType": 28,
"targetKind": "creature",
"entryId": 97731
},
{
"spellId": 255433,
"effectIndex": 0,
"effectType": 28,
"targetKind": "creature",
"entryId": 97770
}
]
},
"adaptation": {
"status": "source-backed-custom-cadence-required",
"populationPlan": {
"disposition": "remove-unverified-generic-trash",
"reason": "Alvaencounter and the recovered spell cluster describe a contained Alva/Arktos encounter; no evidence supports the current 15 generic hallway creatures.",
"encounterEntities": [
97700,
97701,
97703,
97731,
97770
]
},
"encounterPlan": [
"Phase one starts Alva 97700 and Arktos 97701 together, with Pact of the Hunt 255360 active while they remain close.",
"Alva uses Rain of Arrows, Unbridled Arrows, Blast Arrow, Cluster Shot, and summoned Explosive Traps; Arktos uses Carnivorous Bite, Ice Rock, Frost Roar, Lacerate, and defensive Frost Shield or Shield Wall.",
"Blast Arrow can strike Arktos and apply Set Ablaze 255381, causing panic movement, Blaze 255382, and increased damage taken. This matches the official changelog's Blast Shot/Arktos interaction despite the DBC naming it Blast Arrow.",
"Arktos death leaves Alva's Grief 255410 around the corpse and transitions Alva to the vengeance kit.",
"The transition casts Shadow Shroud Rebirth 255390 and summons four Alvajar 97770 around the arena. Rebirth damage must scale by living group size, reaching full value at five or more players per the official changelog.",
"Phase two rotates Vengeful Bolt, Shadow Veil Lance, Sphere of Grief and Wrath, Army of the Dead, and stacking Alva's Wrath as the soft enrage.",
"Wire ASC D0 rows to the current normal experience. Preserve D1 and D2 rows but do not assign public difficulty labels until an authoritative mode mapping is recovered."
],
"authoredCadence": {
"rainOfArrowsMs": 12000,
"unbridledArrowsMs": 20000,
"blastArrowMs": 15000,
"clusterShotMs": 18000,
"explosiveTrapMs": 16000,
"arktosIceRockMs": 12000,
"arktosFrostRoarMs": 18000,
"vengefulBoltMs": 7000,
"shadowVeilLanceMs": 12000,
"sphereOfGriefMs": 20000,
"alvasWrathMs": 25000
},
"mustBeCustomAuthored": [
"all cast cadence and target-selection rules",
"Arktos initial placement and companion pathing",
"phase transition and exact death threshold behavior",
"Alvajar formation and spawn placement",
"trap and area-trigger web-runtime behavior",
"boss and add visual composites",
"loot and completion scripting"
]
},
"unresolved": [
"The server-side spell schedule and encounter script are absent.",
"Creature template stats, display IDs, and exact positions are absent.",
"ASC D0/D1/D2 spell ranks cannot be mapped safely beyond D0 without a surviving difficulty script."
]
},
{
"mapId": 1781,
"id": "forgotten-mine",
"title": "Forgotten Mine",
"mapDirectory": "ForgottenMine",
"sourceClassification": "encounter-spells-creature-summon-and-gameobject-recovered",
"environment": {
"sourceHash": "693b7067aa1109e14beb944bc95aed8299bf64e2ec6ae3dc43f4fab7d18f57b6",
"anchors": {
"player": [
1285.886108,
149.58075,
1724.264526
],
"trash": [
1857.461304,
136.080749,
1871.884277
],
"boss": [
2246.06665,
198.180786,
2147.866699
]
},
"semanticStatus": "provisional-main-navigation-component"
},
"encounters": [
{
"encounterId": 5069,
"modeId": 0,
"name": "Geolord Vek",
"creatureId": 254272,
"identityConfidence": "exact"
},
{
"encounterId": 5071,
"modeId": 2,
"name": "Geolord Vek",
"creatureId": 254272,
"identityConfidence": "exact"
}
],
"entities": [
{
"entryId": 254272,
"name": "Geolord Vek",
"role": "boss",
"sourceKind": "encounter-dbc"
},
{
"entryId": 254278,
"name": "Geospike summoned unit",
"role": "hazard",
"sourceKind": "spell-linked-name-inferred"
}
],
"gameObjects": [
{
"entryId": 254051,
"name": "Resonite Shard",
"role": "clickable-encounter-countermeasure",
"sourceKind": "spell-linked-name-from-create-spell"
}
],
"currentRuntime": {
"bossEntityId": "entry-254272",
"proceduralTrashSpawnCount": 15,
"proceduralMobEntries": [
{
"entityId": "forgotten-mine-guardian",
"serverEntry": 4175632753
},
{
"entityId": "forgotten-mine-caster",
"serverEntry": 647988074
},
{
"entityId": "forgotten-mine-brute",
"serverEntry": 2677742134
}
]
},
"sourceRecovery": {
"association": "explicit-vek-client-cluster",
"associationConfidence": "high",
"reason": "The contiguous cluster contains Vek Death and Vek Reset control rows alongside the complete earth and Resonite kit.",
"spellRows": {
"354000": "Stonebreaker",
"354001": "Quake",
"354002": "Stone Shield",
"354003": "Cosmetic Fear",
"354004": "Geospike",
"354005": "Geospike",
"354006": "Geospike",
"354007": "Vek Death",
"354008": "Vek Reset",
"354009": "Quake",
"354010": "Quake",
"354011": "Stone Shield",
"354012": "Stone Shield",
"354013": "Resonance",
"354014": "Resonance",
"354015": "Geode Barrage",
"354016": "Geode Barrage",
"354017": "Ruptured Earth",
"354018": "Ruptured Earth",
"354019": "Stoneskin",
"354020": "Stoneskin",
"354021": "Stonebreaker",
"354022": "Stonebreaker",
"354023": "Stonebreaker",
"354024": "Stonebreaker",
"354025": "Geospike",
"354026": "Geospike",
"354027": "Geode Barrage",
"354028": "Geode Barrage",
"354029": "Geode Barrage",
"354030": "Geode Barrage",
"354031": "Resonite Cleanse",
"354032": "Create Resonite Shard"
},
"families": {
"control": [
354007,
354008
],
"quake": [
354001,
354009,
354010
],
"stoneShield": [
354002,
354011,
354012
],
"geospike": [
354004,
354005,
354006,
354025,
354026
],
"resonance": [
354013,
354014
],
"geodeBarrage": [
354015,
354016,
354027,
354028,
354029,
354030
],
"rupturedEarth": [
354017,
354018
],
"stoneskin": [
354019,
354020
],
"stonebreaker": [
354000,
354021,
354022,
354023,
354024
],
"resonite": [
354031,
354032
]
},
"summonLinks": [
{
"spellId": 354004,
"effectIndex": 0,
"effectType": 28,
"targetKind": "creature",
"entryId": 254278
},
{
"spellId": 354032,
"effectIndex": 0,
"effectType": 76,
"targetKind": "gameobject",
"entryId": 254051
}
]
},
"adaptation": {
"status": "source-backed-custom-cadence-required",
"populationPlan": {
"disposition": "retain-current-route-as-explicit-adaptation",
"packCount": 5,
"membersPerPack": 3,
"authoredMobs": [
{
"serverEntry": 4175632753,
"name": "Forgotten Mine Stoneguard",
"role": "shielding-melee"
},
{
"serverEntry": 647988074,
"name": "Forgotten Mine Geomancer",
"role": "geode-ranged"
},
{
"serverEntry": 2677742134,
"name": "Forgotten Mine Quarry Brute",
"role": "frontal-bruiser"
}
]
},
"encounterPlan": [
"Geolord Vek 254272 remains at the provisional boss anchor and opens with Stone Shield.",
"Stonebreaker is a telegraphed frontal strike; Quake is a short-range raid pulse; Geode Barrage repeatedly targets one player; Ruptured Earth creates a marked split-damage pillar.",
"Geospike 354004 summons entry 254278 after a clearly visible ground telegraph. The hazard erupts with the matching Geospike damage row and then despawns.",
"Three clickable Resonite Shard gameobjects 254051 appear at authored offsets around the boss. Clicking consumes one and applies Resonite Cleanse 354031, which removes one active earth protection or prevents the next Resonance hit.",
"At 50 percent health, Resonance begins and Vek alternates Quake with Ruptured Earth. Missing crystals respawn once per 30 second cycle.",
"The official changelog requires large, obvious clickable crystal bounds and a high-contrast Geospike telegraph."
],
"authoredGameObjectOffsetsFromBoss": [
[
-12,
0,
0
],
[
6,
0,
10.392
],
[
6,
0,
-10.392
]
],
"authoredCadence": {
"stonebreakerMs": 6500,
"geodeBarrageMs": 11000,
"geospikeMs": 15000,
"quakeMs": 18000,
"rupturedEarthMs": 22000,
"resoniteCycleMs": 30000
},
"mustBeCustomAuthored": [
"all trash identities, placements, and AI",
"all boss cadence, target selection, and phase thresholds",
"the exact Resonite Cleanse interaction because the server script is absent",
"crystal placement, interaction bounds, and respawn rules",
"Geospike hazard placement and lifetime",
"boss, hazard, trash, and crystal visual composites",
"loot and completion scripting"
]
},
"unresolved": [
"Paired low/high-value spell rows do not expose a safe difficulty-label mapping.",
"The authoritative creature and gameobject spawn coordinates are absent.",
"Creature template stats and visual display IDs are absent.",
"The exact Resonite click result is only constrained by client spell text and official changelog behavior."
]
}
]
}
@@ -0,0 +1,97 @@
# Ascension custom dungeon source recovery
This report separates recoverable client facts from the behavior that HealerMan must author for Tinkertech Showdown (821), Frozen Reach (908), and Forgotten Mine (1781). The machine-readable companion is `ASCENSION_CUSTOM_DUNGEON_RECOVERY.json`; its validator checks both the current generated catalogs and the original installed-client `Spell.dbc`.
## Result
| Map | Recovered exactly | Still requires adaptation |
| --- | --- | --- |
| 821 Tinkertech Showdown | Client environment, encounter 9013, boss creature 663012 | Every spawn, trash identity, gameobject, spell binding, boss schedule, phase, visual, loot, and completion rule |
| 908 Frozen Reach | Client environment, encounters 2168/2170, Alva 97700, Arktos 97701, three summoned entries, and 85 encounter spell rows | Positions, stats, cast schedule, target rules, phase scripting, web hazards, visuals, loot, and completion rules |
| 1781 Forgotten Mine | Client environment, encounters 5069/5071, Geolord Vek 254272, Geospike summon 254278, Resonite Shard gameobject 254051, and 33 encounter spell rows | Positions, stats, cast schedule, trash roster, crystal behavior, hazard lifetime, visuals, loot, and completion rules |
The local server/reference repositories, installed WDB caches, addon databases, and the public Questie Ascension snapshot do not contain surviving creature templates, world spawn rows, SmartAI, or encounter scripts for these maps. Client spell rows prove names and summon targets, but they do not prove cast cadence, ownership in every case, or coordinates.
## 821: Tinkertech Showdown
Exact client facts:
- Map directory: `TinketechShowdown` (the client spelling omits the second `r`). Source hash: `323c47c081d0a6c39daf9878284863c21e3e38dbced2ba3f58d1d157d080d41d`.
- The recovered root WMO is `World/wmo/Dungeon/AZ_Subway/Subway_Dungeon.wmo`.
- Manastorm encounter 9013 names Mechatron and binds it to creature 663012 in mode 2.
- The player, trash, and boss anchors in the manifest are geometry-derived and provisional, not recovered server spawn points.
Candidate-only evidence:
- Spell 257438 `Rocket`.
- Spells 257459-257461 `Gatling Missile Barrage` / `Gatling Missile`.
- Spell 257462 `Sound: Goblin Head Machine Loop`.
- Spell 257470 `Incineration Beam`, spell 257471 `Energy Ball`, and spells 257472-257473 `Electrified Zone` / `Electric Shock`.
Those rows form a coherent goblin-machine cluster, but no surviving source binds them to creature 663012. They must stay labeled as an adaptation if used.
Concrete adaptation:
- Retain the current route as five authored three-creature packs. Recast generated entries 2629079128, 3849447491, and 1787979165 as `Tinkertech Guardbot`, `Tinkertech Coilcaster`, and `Tinkertech Demolisher`; these IDs and names remain HealerMan-owned.
- Keep Mechatron 663012 at the provisional boss anchor.
- Use an authored rotation of Rocket reticles, Gatling lane impacts, Incineration Beam lane sweeps, and alternating Electrified Zones. At 35% health, accelerate the rotation and add two Coilcasters.
- Model platform destruction as temporary lane disabling because the imported web geometry is immutable.
Everything in that combat implementation except the boss identity and candidate spell names is custom-authored. It should not be represented as recovered Ascension parity.
## 908: Frozen Reach
Exact client facts:
- Map directory: `Alvaencounter`. Source hash: `5ab771df79c0e062cea3ebda4e416a9245bcf8a4cc6da048077df5e674081f97`.
- Manastorm encounters 2168 and 2170 name Alva and bind her to creature 97700 in modes 0 and 2.
- The official Ascension database identifies Alva as creature 97700 and Arktos as creature 97701.
- Spell 255363 summons creature 97703, spell 255421 summons creature 97731, and spell 255433 summons creature 97770. In context these are the Blast Arrow unit, Explosive Trap, and Alvajar add.
- The client cluster spans 85 exact rows from 255347 through 255472. The principal families are Rain of Arrows, Unbridled Arrows, Blast Arrow, Cluster Shot, Pact of the Hunt, Ice Rock, Carnivorous Bite, Frost Shield, Set Ablaze, Blaze, Frost Strike, Frost Roar, Lacerate, Shield Wall, Shadow Shroud Surge/Rebirth, Vengeful Bolt, Shadow Veil Lance, Sphere of Grief and Wrath, Alva's Grief/Wrath, Explosive Trap, and Army of the Dead.
- The official changelog confirms that the Blast Arrow/“Blast Shot” interaction can hit Arktos and that Shadow Shroud Rebirth reaches full damage scaling at five or more players.
Concrete adaptation:
- Remove the current 15 procedural hallway creatures (entries 1606324391, 854807736, and 2855026892). Available evidence describes a contained Alva/Arktos encounter and provides no support for that generic trash population.
- Start Alva 97700 and Arktos 97701 together with Pact of the Hunt. Give Alva the recovered ranged/trap kit and Arktos the recovered bite, ice, roar, lacerate, and defensive kit.
- Allow Blast Arrow to apply Set Ablaze to Arktos, forcing panic movement and increased damage taken.
- On Arktos's death, leave Alva's Grief at the corpse, cast Shadow Shroud Rebirth, summon four Alvajar 97770, and move Alva into the recovered vengeance spell family.
- Preserve D1/D2 spell variants as source data but use D0 for the current normal experience until a surviving difficulty mapping is found.
The exact cadence in the JSON is an explicit HealerMan proposal. Initial positions, transition rules, summon formation, stats, targeting, and hazard implementation all remain custom-authored.
## 1781: Forgotten Mine
Exact client facts:
- Map directory: `ForgottenMine`. Source hash: `693b7067aa1109e14beb944bc95aed8299bf64e2ec6ae3dc43f4fab7d18f57b6`.
- Manastorm encounters 5069 and 5071 name Geolord Vek and bind him to creature 254272 in modes 0 and 2.
- The contiguous 354000-354032 spell cluster explicitly contains `Vek Death` and `Vek Reset`, tying the cluster to Vek.
- The recovered families are Stonebreaker, Quake, Stone Shield, Geospike, Resonance, Geode Barrage, Ruptured Earth, Stoneskin, Resonite Cleanse, and Create Resonite Shard.
- Spell 354004 summons Geospike creature 254278. Spell 354032 creates gameobject 254051, named by the spell as a Resonite Shard.
- Client text says Resonite counters the power of Earth. Official changelogs additionally require larger clickable crystal bounds and a visible Geospike telegraph.
Concrete adaptation:
- Retain five authored three-creature route packs only as an explicit approximation. Recast generated entries 4175632753, 647988074, and 2677742134 as `Forgotten Mine Stoneguard`, `Forgotten Mine Geomancer`, and `Forgotten Mine Quarry Brute`; these are not recovered Ascension creatures.
- Keep Geolord Vek 254272 at the provisional boss anchor. Rotate Stonebreaker, Quake, Geode Barrage, Geospike, and Ruptured Earth, then begin Resonance at 50% health.
- Spawn three clickable Resonite Shards 254051 at the authored triangular offsets in the JSON. Consuming a shard applies Resonite Cleanse 354031 and removes one active earth protection or prevents the next Resonance hit.
- Give Geospike 254278 a high-contrast ground warning, eruption, and despawn sequence. Make crystal interaction bounds deliberately generous.
The crystal effect is constrained by spell text and changelog behavior but its exact server-side rule did not survive. Trash, timing, targeting, positions, respawn cadence, and visuals are custom-authored.
## Integration boundary
The recovery files intentionally do not change `compile-campaign-catalog.mjs`. Runtime integration should consume the recovered IDs and family lists while preserving three provenance labels:
- `exact`: copied from checksummed client/catalog data.
- `spellLinked`: an entry ID read directly from a DBC summon effect; its descriptive name can still be contextual.
- `authored`: HealerMan timing, placement, visuals, or behavior.
Validate the recovery against the current catalogs and installed client with:
```powershell
node scripts/dungeon-pipeline/validate-ascension-custom-dungeon-recovery.mjs
```
Use `--skip-dbc` only on machines without the checksummed Area-52 client, or pass another byte-identical file with `--dbc <path>`.
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/TempestKeepArcane",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_TempestKeep/TK_Arcane.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/AuchindounDraenei",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Auchindoun/Draenei_wing.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/HellfireDemon",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [58, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [58, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/Hellfire/hellfire_DemonWing.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/TempestKeepAtrium",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_TempestKeep/TK_Atrium.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
@@ -10,7 +10,10 @@
"environmentMode": "global-wmo",
"coordinateAlignment": "source-transform",
"coordinateTransform": {"origin": [1262.4427, -60.8902, 1622.5397], "yawDegrees": 262.143},
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [58, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [58, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/Hellfire/Hellfire_ramparts.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/Sunwell5ManFix",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [70, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [70, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/QT_Sunwell_5Man/Sunwell_5Man.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/AuchindounEthereal",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Auchindoun/ethereal_wing.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/TempestKeepFactory",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_TempestKeep/TK_Factory.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/AuchindounDemon",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Auchindoun/demon_wing.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/AuchindounShadow",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [65, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Auchindoun/shadow_council_wing.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/HellfireMilitary",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/Hellfire/Hellfire_Military.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/CoilfangDraenei",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Coilfang/Coilfang_Draenei.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/CoilfangPumping",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Coilfang/Coilfang_Pumping.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+4 -1
View File
@@ -9,7 +9,10 @@
"mapDirectory": "World/Maps/CoilfangMarsh",
"environmentMode": "global-wmo",
"coordinateAlignment": "source",
"difficultyVariants": [{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]}],
"difficultyVariants": [
{"id": "normal", "difficulty": "normal", "spawnMask": 1, "levelRange": [60, 70]},
{"id": "heroic", "difficulty": "heroic", "spawnMask": 2, "levelRange": [70, 70]}
],
"clientSource": {"rootEnvironmentVariable": "WOW_CLIENT_ROOT", "relativeDefault": "../wow335a"},
"serverSource": {"rootEnvironmentVariable": "WOW_SERVER_DATA", "adapter": "normalized-json", "readOnly": true},
"extraction": {"rootWmo": "World/wmo/Dungeon/OL_Coilfang/Coilfang_Marsh.wmo", "doodadSets": ["Set_$DefaultGlobal"]},
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "healer-man",
"version": "0.1.21",
"version": "0.1.29",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "healer-man",
"version": "0.1.21",
"version": "0.1.29",
"dependencies": {
"@capacitor/android": "8.4.1",
"@capacitor/core": "8.4.1",
+8 -3
View File
@@ -1,7 +1,7 @@
{
"name": "healer-man",
"private": true,
"version": "0.1.21",
"version": "0.1.29",
"type": "module",
"scripts": {
"dev": "vite --host 0.0.0.0",
@@ -52,8 +52,11 @@
"dungeon:five-player:import": "node scripts/dungeon-pipeline/import-five-player-dungeon.mjs",
"dungeon:five-player:import:remaining": "node scripts/dungeon-pipeline/import-remaining-five-player-dungeons.mjs",
"dungeon:five-player:verify": "node scripts/dungeon-pipeline/verify-five-player-dungeon-imports.mjs",
"dungeon:wow:audit": "node scripts/dungeon-pipeline/audit-wow-dungeon-content.mjs",
"dungeon:wow:audit": "vite-node scripts/dungeon-pipeline/audit-wow-dungeon-content.mjs",
"dungeon:wow:functionality:audit": "vite-node scripts/dungeon-pipeline/audit-wow-dungeon-functionality.ts",
"dungeon:wow:test": "vitest run src/game/wowDungeonContent.test.ts",
"dungeon:wow:export-tool:test": "node --test scripts/dungeon-pipeline/wow-export-tool.test.mjs",
"dungeon:ascension:recovery:validate": "node scripts/dungeon-pipeline/validate-ascension-custom-dungeon-recovery.mjs --skip-dbc",
"dungeon:wow:all": "node scripts/dungeon-pipeline/run-all-wow-dungeons.mjs",
"dungeon:extract": "node scripts/dungeon-pipeline/cli.mjs extract",
"dungeon:creatures": "node scripts/dungeon-pipeline/cli.mjs creatures",
@@ -65,6 +68,7 @@
"dungeon:validate": "node scripts/dungeon-pipeline/cli.mjs validate",
"arena:assets:build": "node scripts/arena-pipeline/build-wmo-arenas.mjs && node scripts/arena-pipeline/build-custom-arenas.mjs && node scripts/arena-pipeline/prepare-warnorken.mjs",
"arena:assets:validate": "node scripts/arena-pipeline/validate-arenas.mjs",
"arena:abilities:build": "node scripts/arena-pipeline/build-combat-runtime.mjs && node scripts/arena-pipeline/build-runtime-geometry.mjs",
"dungeon:enable": "node scripts/dungeon-pipeline/cli.mjs enable",
"runewaker:forsaken": "node \"%INIT_CWD%\\scripts\\runewaker-pipeline\\build-forsaken-abbey.mjs\"",
"runewaker:forsaken:actors": "node scripts/runewaker-pipeline/build-forsaken-population.mjs --actors-only",
@@ -92,6 +96,7 @@
"runewaker:audit:encounters": "node scripts/runewaker-pipeline/audit-encounter-implementation.mjs && node --test scripts/runewaker-pipeline/encounter-implementation-report.test.mjs",
"runewaker:audit:environment-assembly": "node scripts/runewaker-pipeline/audit-environment-assembly.mjs && node --test scripts/runewaker-pipeline/environment-assembly.test.mjs",
"runewaker:audit:navigation": "node scripts/runewaker-pipeline/analyze-navigation-gaps.mjs && vitest run src/game/runewakerObjectiveRouteAudit.test.ts",
"runewaker:audit:material-alpha": "node scripts/runewaker-pipeline/audit-material-alpha.mjs",
"assets:wailing:instance": "gltf-transform instance ../wow335a/dungeon-export-work/WailingCaverns/converted/wailing-caverns.visual.glb src/assets/game/dungeons/wailing-caverns/wailing-caverns-visual.glb --min 3",
"assets:wailing:creatures:animated": "node scripts/prepareAnimatedCreatures.mjs",
"assets:wailing:creatures:combat": "node scripts/add-combat-creature-clips.mjs",
@@ -104,7 +109,7 @@
"assets:performance:audit": "node scripts/asset-pipeline/audit-environment-performance.mjs",
"balance:benchmark": "vite-node scripts/combat-benchmark/run.ts",
"balance:smoke": "vite-node scripts/combat-benchmark/run.ts --class mage --role damage --scenario damage-single-burst --seeds 1 --duration-scale 0.2",
"prebuild": "npm run loot:generate && npm run web:prepare && npm run arena:assets:validate && npm run assets:ktx2:audit && npm run assets:performance:audit",
"prebuild": "npm run loot:generate && npm run arena:abilities:build && npm run web:prepare && npm run arena:assets:validate && npm run assets:ktx2:audit && npm run assets:performance:audit",
"build": "node --max-old-space-size=8192 node_modules/typescript/bin/tsc -b && node --max-old-space-size=8192 node_modules/vite/bin/vite.js build",
"build:android:web": "npm run prebuild && npm run android:prepare && node --max-old-space-size=8192 node_modules/typescript/bin/tsc -b && node --max-old-space-size=8192 node_modules/vite/bin/vite.js build --mode android",
"android:sync": "npm run build:android:web && cap sync android",
@@ -8,9 +8,9 @@
"valid": true
}
],
"gridCells": 2074478,
"gridHeight": 994,
"gridWidth": 2087,
"gridCells": 4046196,
"gridHeight": 1812,
"gridWidth": 2233,
"ignoredEmptyTilePackingFailures": 0,
"intermediateRetention": null,
"mode": "solo",
@@ -21,55 +21,55 @@
"tileRows": 1,
"tileSize": null
},
"dungeonId": "black-rook-hold-arena",
"dungeonId": "arena-runtime-black-rook",
"generator": "@recast-navigation/three@0.43.1",
"geometry": {
"bounds": [
[
-92.08255767822266,
-16.14961814880371,
-279.4311218261719
-102.83599853515625,
-49.58357238769531,
-373.1059875488281
],
[
321.9174499511719,
37.25038528442383,
-82.83113098144531
340.9640197753906,
410.1164245605469,
-28.105987548828125
]
],
"boundsTolerance": 0.4,
"rejectedOutOfBoundsTriangles": 0,
"sourceTriangles": 7170,
"sourceVertices": 21510,
"triangles": 7170,
"vertices": 21510
"sourceTriangles": 26724,
"sourceVertices": 80172,
"triangles": 26724,
"vertices": 80172
},
"input": {
"bounds": [
[
-93.08255767822266,
-39.549617767333984,
-280.0311279296875
-103.83599853515625,
-98.98357391357422,
-375.3059997558594
],
[
324.1624450683594,
69.1881103515625,
-81.26593780517578
342.7250061035156,
410.1130065917969,
-13.022000312805176
]
],
"degenerateTriangleCount": 0,
"degenerateTriangleCount": 33,
"invalidIndexCount": 0,
"meshCount": 1,
"nonFiniteCoordinateCount": 0,
"triangleCount": 49821,
"vertexCount": 149463
"triangleCount": 192419,
"vertexCount": 577257
},
"inputChunkChecksums": {
"public/assets/game/arenas/black-rook-hold-arena/navigation-collision.glb": "285bdce7d5b5085eef7d25f82a5b6a5b380605a310c539e8e94984182c835749"
"playtest-artifacts/black-rook-combined.glb": "aa4f39620e2562cea0bf39ec54ff377b19eef799eaa08f0e9ea81896f8a31aba"
},
"inputChunks": [
"public/assets/game/arenas/black-rook-hold-arena/navigation-collision.glb"
"playtest-artifacts/black-rook-combined.glb"
],
"output": "public/assets/game/arenas/black-rook-hold-arena/navigation-raw.glb",
"output": "playtest-artifacts/black-rook-navigation.glb",
"schemaVersion": 1,
"settings": {
"agentHeight": 1.8,
@@ -80,35 +80,6 @@
"cellSize": 0.2
},
"source": {
"adtFiles": [
"blackrookholdarena_28_28.adt",
"blackrookholdarena_28_29.adt",
"blackrookholdarena_28_30.adt",
"blackrookholdarena_29_28.adt",
"blackrookholdarena_29_29.adt",
"blackrookholdarena_29_30.adt",
"blackrookholdarena_30_28.adt",
"blackrookholdarena_30_29.adt",
"blackrookholdarena_30_30.adt"
],
"gameplayBounds": {
"max": [
312,
30,
-110
],
"min": [
-82,
-10,
-242
]
},
"kind": "adt-placed-wmo-repair",
"legacyCollision": "public/assets/game/manastorm/1784-blackrookholdarena/collision.glb",
"placedWmos": [
"../LadiksMPQEditor/patch-WC1/WORLD/WMO/BROKENISLES/VALSHARAH/7VS_BLACKROOKHOLD_MICRO01.WMO",
"../LadiksMPQEditor/patch-WC1/WORLD/WMO/PVP/BUILDINGS/BLACKROOKHOLD/7VS_BLACKROOKHOLD_ARENA.WMO",
"../LadiksMPQEditor/patch-WC1/WORLD/WMO/PVP/BUILDINGS/BLACKROOKHOLD/BLACKROOKHOLD_ARENA_PLATFORMTEST.WMO"
]
"kind": "runtime-collision-repair"
}
}
@@ -56,15 +56,16 @@
"collisionChunks": 4
},
"navigation": {
"triangles": 4948,
"vertices": 14844,
"sourceComponents": 805,
"triangles": 783,
"vertices": 2349,
"sourceComponents": 1078,
"spawnDistances": [
0.009180110009213026,
0.01568599673120942
2.095,
1.026
],
"rawTriangles": 7170,
"report": "recast-report.json"
"rawTriangles": 26724,
"report": "recast-report.json",
"repair": "Rebaked against restored collision. Both teams spawn on the connected interior floor, not the terrain above the arena."
},
"assets": [
{
@@ -94,8 +95,8 @@
},
{
"file": "navigation.glb",
"bytes": 238420,
"sha256": "e463a0220842a4793b2150e95f4fd704f575def288813c781792b021afe8d3f0"
"bytes": 38500,
"sha256": "ee2df9f0c2dbd14d53e84fd66efcc4b48a93ac99c57c27a7d1ea876d29899910"
}
]
}
+56 -1
View File
@@ -1,10 +1,51 @@
const CONTENT_CACHE_NAME = "healer-man-content-v1";
const OBJECT_HEADER = "x-healer-man-content-object";
const ENCODING_HEADER = "x-healer-man-content-encoding";
let bundledManifest;
function mimeType(path) {
const extension = path.split(".").pop();
return ({ glb: "model/gltf-binary", json: "application/json", js: "text/javascript", wasm: "application/wasm",
ktx2: "image/ktx2", png: "image/png", webp: "image/webp", avif: "image/avif", svg: "image/svg+xml",
mp3: "audio/mpeg", ogg: "audio/ogg", wav: "audio/wav", webm: "video/webm" })[extension] ?? "application/octet-stream";
}
async function decodedResponse(response, path, encoding) {
if (encoding !== "gzip") return response;
const headers = new Headers(response.headers);
headers.set("content-type", mimeType(path));
headers.delete("content-length");
headers.delete("content-encoding");
headers.delete(ENCODING_HEADER);
return new Response(response.body.pipeThrough(new DecompressionStream("gzip")), { status: 200, headers });
}
async function bundledAsset(path) {
if (!bundledManifest) {
bundledManifest = fetch("/content/bootstrap-manifest.json", { cache: "no-cache" })
.then((response) => response.ok ? response.json() : null)
.catch(() => null);
}
const manifest = await bundledManifest;
if (!manifest) { bundledManifest = null; return null; }
const entry = manifest.files?.[path];
if (!entry) return null;
const object = entry.download ?? entry;
// Older bootstrap catalogs served their original logical paths directly.
if (!object.url.startsWith("/content/bundled/")) return fetch(path);
const response = await fetch(object.url);
if (!response.ok) return response;
if (entry.download) return decodedResponse(response, path, entry.download.encoding);
return new Response(response.body, { headers: { "content-type": mimeType(path) } });
}
const MANAGED_ASSET_PREFIXES = [
"/assets/characters/",
"/assets/creatures/",
"/assets/equipment/",
"/assets/game/",
"/assets/ui/",
"/basis/",
"/data/",
];
const BUNDLED_ASSET_PREFIXES = [
"/assets/ui/",
@@ -12,6 +53,7 @@ const BUNDLED_ASSET_PREFIXES = [
"/assets/characters/wow335a-v1/manifest.json",
"/assets/characters/wow335a-v1/human/",
"/assets/creatures/wailing-caverns/",
"/assets/game/arenas/",
"/assets/game/dungeons/wailing-caverns/",
];
const BUNDLED_ASSET_PATHS = new Set([
@@ -35,6 +77,10 @@ self.addEventListener("install", (event) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener("message", (event) => {
if (event.data?.type === "refresh-content-bootstrap") bundledManifest = null;
});
self.addEventListener("activate", (event) => {
event.waitUntil((async () => {
const names = await caches.keys();
@@ -55,7 +101,16 @@ self.addEventListener("fetch", (event) => {
event.respondWith((async () => {
const cache = await caches.open(CONTENT_CACHE_NAME);
const cached = await cache.match(request, { ignoreSearch: true });
if (cached) return cached;
if (cached) {
const objectPath = cached.headers.get(OBJECT_HEADER);
if (!objectPath) return cached;
if (objectPath.startsWith("/content/cache-objects/")) {
const object = await cache.match(new URL(objectPath, self.location.origin).toString());
if (object) return decodedResponse(object, url.pathname, object.headers.get(ENCODING_HEADER));
}
}
const bundled = await bundledAsset(url.pathname);
if (bundled) return bundled;
if (BUNDLED_ASSET_PATHS.has(url.pathname)
|| BUNDLED_ASSET_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) {
return fetch(request);
+2 -2
View File
@@ -1,4 +1,4 @@
{
"versionName": "0.1.21",
"versionCode": 1021
"versionName": "0.1.29",
"versionCode": 1029
}
@@ -0,0 +1,38 @@
import { build } from "esbuild";
import { resolve, dirname } from "node:path";
import { readFileSync, readdirSync } from "node:fs";
// A private copy of the existing engine keeps dedicated matches and offline
// practice isolated from the React player's stores. No second spell interpreter.
await build({
entryPoints: ["scripts/arena-pipeline/combat-runtime.ts"],
outfile: "server/generated/arena-combat-runtime.mjs",
bundle: true,
format: "esm",
platform: "neutral",
mainFields: ["module", "main"],
target: "es2022",
// Escape catalog line breaks in string literals, preserving tooltip text
// without generating source lines that end in whitespace.
supported: { "template-literal": false },
minify: true,
define: { "import.meta.env.MODE": '"test"', "import.meta.env.DEV": "false", "import.meta.env.BASE_URL": '"/"', "process.env.NODE_ENV": '"production"' },
plugins: [{
name: "arena-engine-host",
setup(builder) {
builder.onLoad({ filter: /coaAbilityCatalogLoader\.ts$/ }, ({ path }) => {
const paths = readdirSync(resolve(dirname(path), "generated/coaAbilities")).filter((name) => name.endsWith(".json"))
.map((name) => `./generated/coaAbilities/${name}`);
return { contents: readFileSync(path, "utf8").replace(/import\.meta\.glob<[^>]+>\([^;]+\)/, `{${paths.map((name) => `${JSON.stringify(name)}: () => import(${JSON.stringify(name)})`).join(",")}}`), loader: "ts" };
});
builder.onResolve({ filter: /^zustand$/ }, () => ({ path: resolve("scripts/arena-pipeline/runtime-store.ts") }));
builder.onResolve({ filter: /^\.\/store$/ }, ({ importer }) => importer.endsWith("combatStore.ts") ? ({ path: "game-store", namespace: "arena-host" }) : undefined);
builder.onResolve({ filter: /^\.\/dungeonEncounterRuntime$/ }, ({ importer }) => importer.endsWith("combatStore.ts") ? ({ path: "encounter", namespace: "arena-host" }) : undefined);
builder.onResolve({ filter: /^\.\/onlineSessionRuntime$/ }, ({ importer }) => importer.endsWith("combatStore.ts") ? ({ path: "online", namespace: "arena-host" }) : undefined);
builder.onLoad({ filter: /.*/, namespace: "arena-host" }, ({ path }) => ({ contents: path === "game-store"
? 'export const useGameStore = { getState: () => ({ gameMode: "arena" }) };'
: path === "online" ? 'export const onlinePlayerRuntimeActors = () => []; export const onlinePlayerRuntimeActor = () => null;'
: 'export const dispatchDungeonEncounterSignal = () => {}; export const dungeonEncounterStateMatches = () => false;', loader: "js" }));
},
}],
});
@@ -28,9 +28,8 @@ const DEFINITIONS = Object.freeze([
primaryPattern: /7vs_blackrookhold_arena\.wmo$/i,
alignmentOffset: [117.542488, -102.29949, -224.463489],
legacyCollision: "public/assets/game/manastorm/1784-blackrookholdarena/collision.glb",
gameplayBounds: { min: [-82, -10, -242], max: [312, 30, -110] },
legacyNavigation: "public/assets/game/manastorm/1784-blackrookholdarena/navigation.glb",
teamSpawns: [[-66.098564, 8.416428, -201.852448], [123.158585, 9.916428, -219.909592]],
gameplayBounds: { min: [-37, -32, -286], max: [126, 20, -138] },
teamSpawns: [[-35.043, -28.317, -204.435], [108.031, -28.317, -205.573]],
},
{
slug: "ashamanes-fall",
@@ -273,11 +272,8 @@ async function build(definition) {
reportFile: path.join(outputDirectory, "recast-report.json"),
source: { kind: "adt-placed-wmo-repair", adtFiles, placedWmos: sources, legacyCollision: definition.legacyCollision, gameplayBounds: definition.gameplayBounds },
});
const selectionSource = definition.legacyNavigation
? path.join(projectRoot, ...definition.legacyNavigation.split("/"))
: rawNavigationFile;
const connectedNavigation = await extractNavigationComponent({
source: selectionSource,
source: rawNavigationFile,
output: navigationFile,
teamSpawns: definition.teamSpawns,
});
@@ -0,0 +1,38 @@
import { NodeIO } from "@gltf-transform/core";
import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
import { MeshoptDecoder } from "meshoptimizer";
import { Matrix4, Vector3 } from "three";
import { writeFileSync, readdirSync } from "node:fs";
import catalog from "../../shared/arena-stages.json" with { type: "json" };
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.decoder": MeshoptDecoder });
const stages = {};
for (const stage of catalog.stages) {
stages[stage.id] = {};
for (const kind of ["navigation", "collision"]) {
const triangles = [];
const files = kind === "collision" ? readdirSync(`public${stage.assetBaseUrl}`).filter((name) => /^collision(?:-\d+)?\.glb$/.test(name)) : ["navigation.glb"];
for (const file of files) {
const document = await io.read(`public${stage.assetBaseUrl}/${file}`);
for (const node of document.getRoot().listNodes()) {
const mesh = node.getMesh();
if (!mesh) continue;
const matrix = new Matrix4().fromArray(node.getWorldMatrix());
for (const primitive of mesh.listPrimitives()) {
const positions = primitive.getAttribute("POSITION");
if (!positions) continue;
const indices = primitive.getIndices()?.getArray() ?? Array.from({ length: positions.getCount() }, (_, index) => index);
for (let offset = 0; offset < indices.length; offset += 3) {
const triangle = Array.from({ length: 3 }, (_, corner) => new Vector3().fromArray(positions.getElement(indices[offset + corner], [])).applyMatrix4(matrix).toArray());
if ([0, 2].some((axis) => triangle.every((point) => point[axis] < stage.bounds.min[axis] - 3) || triangle.every((point) => point[axis] > stage.bounds.max[axis] + 3))) continue;
triangles.push(...triangle.flat().map((value) => Math.round(value * 1000) / 1000));
}
}
}
}
stages[stage.id][kind] = triangles;
}
console.log(`${stage.id}: ${stages[stage.id].navigation.length / 9} navigation, ${stages[stage.id].collision.length / 9} collision triangles`);
}
writeFileSync("server/generated/arena-geometry.json", `${JSON.stringify(stages)}\n`);
writeFileSync("server/generated/arena-navigation.json", `${JSON.stringify(Object.fromEntries(Object.entries(stages).map(([id, stage]) => [id, stage.navigation])))}\n`);
+281
View File
@@ -0,0 +1,281 @@
import { useCombatStore, PLAYER_AURA_ENTITY_ID, characterCombatDefender, abilityDamageSchool, type CombatState, type CharacterCombatSeed } from "../../src/game/combatStore";
import { usePartyStore } from "../../src/game/partyStore";
import { installCombatClock } from "../../src/game/combatClock";
import { registerCombatSpatialProvider } from "../../src/game/combatSpatial";
import { clearMobRuntimeRegistry, registerMobRuntime, getMobPosition } from "../../src/game/mobRuntimeRegistry";
import { clearPartyRuntimeRegistry, registerPartyRuntimePosition, getPartyRuntimePosition } from "../../src/game/partyRuntimeRegistry";
import { targetingRulesForAbility } from "../../src/game/abilityRules";
import { resourceProfileForClass, abilityAtLevel, isAbilityUnlocked } from "../../src/game/abilityCatalog";
import { deriveCharacterStats } from "../../src/game/wotlkStats";
import { subscribeCombatPresentation } from "../../src/game/combatPresentation";
import { arenaDampening } from "../../server/arena-rules.mjs";
import { createDefaultAppearance } from "../../src/app/characterCatalog";
import { equipmentItemsForOwner, PLAYER_EQUIPMENT_OWNER_ID } from "../../src/game/equipment";
const PLAYER = PLAYER_AURA_ENTITY_ID;
const combatDefaults = useCombatStore.getState();
const partyDefaults = usePartyStore.getState();
let presentation: any[] = [];
subscribeCombatPresentation((message) => { if (message.kind === "event") presentation.push(message.event); });
const remap = (id: string | null | undefined, from: string, to: string) => id === from ? to : id;
const mapAura = (aura: any, from: string, to: string) => ({ ...aura, sourceId: remap(aura.sourceId, from, to), targetId: remap(aura.targetId, from, to) });
const mapEffect = (effect: any, from: string, to: string) => ({ ...effect, sourceActorId: remap(effect.sourceActorId, from, to), targetId: remap(effect.targetId, from, to) });
export function initializeArenaCharacter(actor: any, now: number) {
if (actor.combat) return;
const kit = actor.characterKit;
const seed: CharacterCombatSeed = kit?.seed ?? { classId: kit?.classId ?? (actor.role === "healer" ? "priest" : "warrior"), level: kit?.level ?? 80, actionBindings: kit?.actionBindings };
const restore = installCombatClock(() => now);
try {
usePartyStore.setState({ ...partyDefaults, members: [], playerRole: actor.role === "healer" ? "healer" : "damage" }, true);
useCombatStore.setState(combatDefaults, true);
useCombatStore.getState().initializeCharacter(seed);
actor.combat = useCombatStore.getState();
const state = actor.combat;
actor.avatar = { classId: state.classId, raceId: seed.raceId ?? (actor.team === 1 ? "orc" : "human"),
gender: (seed as any).gender ?? "male", appearance: (seed as any).appearance ?? createDefaultAppearance() };
actor.visualEquipment = equipmentItemsForOwner(state.equipment, state.inventory, PLAYER_EQUIPMENT_OWNER_ID);
const abilities = state.abilities.filter((ability: any) => !ability.passive && isAbilityUnlocked(ability, state.level)
&& (ability.talentEntryId === undefined || (state.talentRanks[`coa-entry-${ability.talentEntryId}`] ?? 0) > 0))
.map((ability: any) => { const resolved = abilityAtLevel(ability, state.level, ability.talentEntryId === undefined ? undefined : state.talentRanks[`coa-entry-${ability.talentEntryId}`]); return { ...resolved, targeting: targetingRulesForAbility(resolved) }; });
actor.characterKit = { ...kit, seed, classId: state.classId, level: state.level,
resource: { ...resourceProfileForClass(state.classId), maximum: state.maxResource, initial: state.resource },
abilities: Object.fromEntries(abilities.map((ability: any) => [ability.id, ability])), actionBindings: state.actionBindings };
actor.health = state.health;
actor.maxHealth = state.maxHealth;
actor.resource = state.resource;
actor.maxResource = state.maxResource;
actor.auras = state.auras.map((aura: any) => mapAura(aura, PLAYER, actor.id));
actor.statuses = [];
} finally { restore(); }
}
export function arenaKitFromSeed(seed: CharacterCombatSeed) {
const actor: any = { id: "kit", role: seed.role ?? "damage", characterKit: { seed } };
initializeArenaCharacter(actor, 0);
return { ...actor.characterKit, stats: { ...deriveCharacterStats(actor.combat.classId, actor.combat.level, actor.combat.gearStats, actor.combat.raceId, {}, actor.combat.secondaryClassId), health: actor.maxHealth } };
}
function partyMember(actor: any) {
const state = actor.combat;
return { id: actor.id, name: actor.name, classId: state.classId, raceId: state.raceId, gender: "male", appearance: {},
specialization: "", specializationId: state.specializationId, talentTreeId: "", talentRanks: state.talentRanks,
role: actor.role === "healer" ? "healer" : "damage", level: state.level, health: actor.health, maxHealth: actor.maxHealth,
resourceType: actor.characterKit.resource.type, resourceName: state.resourceName, resource: actor.resource, maxResource: actor.maxResource,
resourcePools: state.resourcePools, lastResourceSpentAt: state.lastResourceSpentAt, cooldowns: state.cooldowns,
globalCooldownEndsAt: state.globalCooldownEndsAt, activeCast: state.activeCast, activeCastTargetId: actor.targetActorId,
schoolLockedUntil: state.schoolLockedUntil, runes: state.deathKnightRunes, gearStats: state.gearStats,
status: actor.alive ? "ready" : "down", nextActionAt: 0, tauntReadyAt: 0,
controlledUntil: state.controlledUntil, controlMechanic: state.controlMechanic };
}
function enter(simulation: any, actor: any, now: number, ticking: boolean) {
clearMobRuntimeRegistry();
clearPartyRuntimeRegistry();
presentation = [];
const allies = [...simulation.actors.values()].filter((other: any) => other !== actor && other.team === actor.team);
const friendlyPets = allies.flatMap((owner: any) => owner.combat.summons.map((summon: any) => ({ owner, summon })));
const members = [...allies.map(partyMember), ...friendlyPets.map(({ owner, summon }: any) => ({ ...partyMember(owner),
id: summon.id, name: summon.name, health: summon.health, maxHealth: summon.maxHealth,
resource: 0, maxResource: 0, activeCast: null, status: summon.health > 0 ? "ready" : "down" }))];
usePartyStore.setState({ ...partyDefaults, members, playerRole: actor.role === "healer" ? "healer" : "damage",
selectedMemberId: allies.some((other: any) => other.id === actor.targetActorId) ? actor.targetActorId : null,
selfSelected: actor.targetActorId === actor.id }, true);
const effects = simulation.combatEffects ?? [];
const auras = [...simulation.actors.values()].flatMap((other: any) => other.auras).concat(simulation.summonAuras ?? []).map((aura: any) => mapAura(aura, actor.id, PLAYER));
useCombatStore.setState({ ...actor.combat, health: actor.health, maxHealth: actor.maxHealth,
resource: actor.resource, maxResource: actor.maxResource, playerPosition: [...actor.position],
selectedTargetId: simulation.targetActor(actor.targetActorId)?.team !== actor.team ? actor.targetActorId : null,
selectedFriendlyActorId: actor.targetActorId === actor.id ? PLAYER : simulation.targetActor(actor.targetActorId)?.team === actor.team ? actor.targetActorId : null,
auras, effects: effects.filter((effect: any) => !ticking || effect.sourceActorId === actor.id).map((effect: any) => mapEffect(effect, actor.id, PLAYER)),
mobs: {}, actors: {}, combatEvents: [], settings: { ...actor.combat.settings, autoTargetNearest: false } }, true);
for (const other of simulation.actors.values()) {
if (other === actor) continue;
if (other.team === actor.team) { registerPartyRuntimePosition(other.id, other.position); continue; }
registerMobRuntime(other.id, other.position, other.facing);
useCombatStore.getState().registerMob(other.id, { name: other.name, level: other.combat.level, maxHealth: other.maxHealth, xpReward: 0 });
const stats = deriveCharacterStats(other.combat.classId, other.combat.level, other.combat.gearStats, other.combat.raceId, {}, other.combat.secondaryClassId);
useCombatStore.setState((state) => ({ mobs: { ...state.mobs, [other.id]: { ...state.mobs[other.id],
health: other.health, maxHealth: other.maxHealth, dead: !other.alive, armor: stats.armor, maxMana: other.maxResource,
characterDefender: characterCombatDefender({ ...other.combat, auras: other.auras.map((aura: any) => mapAura(aura, other.id, PLAYER)) }),
characterShield: other.combat.shield, characterResources: other.combat.resourcePools,
statuses: other.statuses ?? [], controlDiminishingReturns: other.controlDiminishingReturns ?? {},
mechanicImmunities: other.auras.flatMap((aura: any) => aura.definition.controlImmunities ?? []),
activeCast: other.combat.activeCast ? { ...other.combat.activeCast, attackId: other.combat.activeCast.abilityId, interruptible: true } : null,
schoolLockedUntil: other.combat.schoolLockedUntil, engaged: true, experienceGranted: true,
resistances: { arcane: stats.arcaneResistance, fire: stats.fireResistance, frost: stats.frostResistance, nature: stats.natureResistance, shadow: stats.shadowResistance, holy: 0 },
} } }));
}
for (const owner of simulation.actors.values()) for (const summon of owner.combat.summons) {
if (owner.team === actor.team) {
if (owner !== actor) registerPartyRuntimePosition(summon.id, summon.position);
continue;
}
registerMobRuntime(summon.id, summon.position, owner.facing);
useCombatStore.getState().registerMob(summon.id, { name: summon.name, level: owner.combat.level, maxHealth: summon.maxHealth, xpReward: 0 });
useCombatStore.setState((state) => ({ mobs: { ...state.mobs, [summon.id]: { ...state.mobs[summon.id], health: summon.health, dead: summon.health <= 0, experienceGranted: true } } }));
}
useCombatStore.getState().synchronizeActors();
const restoreClock = installCombatClock(() => now);
const restoreSpatial = registerCombatSpatialProvider({
actor: (id) => { const target = id === PLAYER ? actor : simulation.targetActor(id); return target ? { id, position: target.position, yaw: target.facing } : null; },
hasLineOfSight: (from, to) => simulation.hasLineOfSight({ position: from }, { position: to }),
projectGroundPoint: (requested, range, origin = actor.position) => simulation.projectGroundPoint(origin, requested, range),
});
return () => { restoreSpatial(); restoreClock(); };
}
function commit(simulation: any, actor: any, now: number, ticking: boolean) {
const state = useCombatStore.getState();
const dampening = simulation.activeStartedAt == null ? 0 : arenaDampening(now - simulation.activeStartedAt);
const healed = new Map<string, number>();
const damaged = new Map<string, number>();
const previous = new Map<string, { health: number; maxHealth: number }>([...simulation.actors.values()].map((other: any) => [other.id, { health: other.health, maxHealth: other.maxHealth }]));
for (const event of state.combatEvents) if (event.kind === "healing") {
const id = remap(event.targetActorId, PLAYER, actor.id)!;
healed.set(id, (healed.get(id) ?? 0) + event.effectiveAmount);
}
for (const event of state.combatEvents) if (event.kind === "damage") {
const id = remap(event.targetActorId, PLAYER, actor.id)!;
damaged.set(id, (damaged.get(id) ?? 0) + event.effectiveAmount);
}
const healthAfterHealing = (id: string, health: number, maxHealth = previous.get(id)?.maxHealth ?? health) => {
const before = previous.get(id);
const inferred = before ? Math.max(0, health - before.health + (damaged.get(id) ?? 0) - Math.max(0, maxHealth - before.maxHealth)) : 0;
return Math.max(0, health - Math.round(Math.max(healed.get(id) ?? 0, inferred) * dampening));
};
actor.combat = { ...state, mobs: {}, actors: {}, effects: [], auras: [], health: actor.health <= 0 ? 0 : healthAfterHealing(actor.id, state.health, state.maxHealth) };
actor.health = actor.combat.health;
actor.maxHealth = state.maxHealth;
actor.resource = state.resource;
actor.maxResource = state.maxResource;
actor.position = state.playerPosition.some((value, axis) => value !== actor.position[axis])
? simulation.resolvePosition(actor, state.playerPosition, true) : [...actor.position];
actor.cooldowns = new Map(Object.entries(state.cooldowns));
actor.gcdUntil = state.globalCooldownEndsAt;
actor.casting = state.activeCast ? { ...state.activeCast, targetActorId: remap(state.activeCast.targetId, PLAYER, actor.id) } : null;
actor.statuses = (actor.statuses ?? []).filter((status: any) => status.endsAt > now && !(state.controlledUntil === 0 && ["stun", "fear", "sleep", "freeze", "knockdown"].includes(status.kind)));
for (const member of usePartyStore.getState().members) {
const other = simulation.actor(member.id);
if (!other) {
for (const owner of simulation.actors.values()) if (owner !== actor && owner.combat.summons.some((summon: any) => summon.id === member.id)) {
owner.combat = { ...owner.combat, summons: owner.combat.summons.map((summon: any) => summon.id === member.id ? { ...summon, health: healthAfterHealing(member.id, member.health) } : summon) };
}
continue;
}
other.health = healthAfterHealing(other.id, member.health, member.maxHealth);
other.maxHealth = member.maxHealth;
other.resource = member.resource;
const moved = getPartyRuntimePosition(member.id);
if (moved && moved.some((value, axis) => value !== other.position[axis])) other.position = simulation.resolvePosition(other, moved, true);
other.combat = { ...other.combat, resourcePools: member.resourcePools, schoolLockedUntil: member.schoolLockedUntil,
controlledUntil: member.controlledUntil, controlMechanic: member.controlMechanic, deathKnightRunes: member.runes };
}
for (const mob of Object.values(state.mobs)) {
const other = simulation.actor(mob.id);
if (!other) {
for (const owner of simulation.actors.values()) if (owner !== actor && owner.combat.summons.some((summon: any) => summon.id === mob.id)) {
owner.combat = { ...owner.combat, summons: owner.combat.summons.map((summon: any) => summon.id === mob.id ? { ...summon, health: mob.health } : summon).filter((summon: any) => summon.health > 0) };
}
continue;
}
other.health = mob.health;
other.statuses = mob.statuses;
other.controlDiminishingReturns = mob.controlDiminishingReturns;
const moved = getMobPosition(mob.id);
if (moved && moved.some((value, axis) => value !== other.position[axis])) other.position = simulation.resolvePosition(other, moved, true);
const control = mob.statuses.filter((status) => ["stun", "fear", "confuse", "blind", "charm", "freeze", "knockdown", "sleep"].includes(status.kind)).sort((a, b) => b.endsAt - a.endsAt)[0];
other.combat = { ...other.combat, controlledUntil: control?.endsAt ?? 0, controlMechanic: control?.kind ?? null,
shield: mob.characterShield ?? other.combat.shield, resourcePools: mob.characterResources ?? other.combat.resourcePools,
schoolLockedUntil: mob.schoolLockedUntil, activeCast: mob.activeCast ? { ...other.combat.activeCast, ...mob.activeCast } : null };
other.resource = other.combat.resourcePools[other.characterKit.resource.type] ?? other.resource;
other.casting = other.combat.activeCast;
}
const worldAuras = state.auras.map((aura) => mapAura(aura, PLAYER, actor.id));
simulation.summonAuras = worldAuras.filter((aura) => !simulation.actors.has(aura.targetId));
for (const other of simulation.actors.values()) {
other.auras = worldAuras.filter((aura) => aura.targetId === other.id);
other.statuses = (other.statuses ?? []).filter((status: any) => status.endsAt > now
&& (!status.sourceAbilityId.startsWith("aura:") || other.auras.some((aura: any) => `aura:${aura.definition.id}` === status.sourceAbilityId))
&& !other.auras.some((aura: any) => aura.definition.controlImmunities?.includes(status.kind)));
const control = other.statuses.filter((status: any) => ["stun", "fear", "confuse", "blind", "charm", "freeze", "knockdown", "sleep"].includes(status.kind)).sort((a: any, b: any) => b.endsAt - a.endsAt)[0];
other.combat = { ...other.combat, controlledUntil: control?.endsAt ?? 0, controlMechanic: control?.kind ?? null };
other.alive = other.health > 0;
if (!other.alive) { other.movement = [0, 0]; other.casting = null; other.combat = { ...other.combat, activeCast: null }; }
}
simulation.combatEffects = [
...(ticking ? (simulation.combatEffects ?? []).filter((effect: any) => effect.sourceActorId !== actor.id) : []),
...state.effects.map((effect) => mapEffect(effect, PLAYER, actor.id)),
];
simulation.combatPresentation = [...(simulation.combatPresentation ?? []), ...presentation.map((event) => ({ ...event,
sourceActorId: remap(event.sourceActorId, PLAYER, actor.id), targetActorId: remap(event.targetActorId, PLAYER, actor.id) }))].slice(-80);
simulation.combatEvents = [...(simulation.combatEvents ?? []), ...state.combatEvents.map((event) => ({ ...event,
sourceActorId: remap(event.sourceActorId, PLAYER, actor.id), targetActorId: remap(event.targetActorId, PLAYER, actor.id) }))].slice(-100);
}
export function useArenaCharacterAbility(simulation: any, actor: any, abilityId: string, targetActorId: string | null, now: number, groundPosition?: readonly number[]) {
const ability = actor.characterKit.abilities[abilityId];
if (ability && (actor.statuses ?? []).some((status: any) => status.kind === "silence" && status.endsAt > now)
&& (ability.castRules?.school ?? abilityDamageSchool(actor.combat.classId, ability)) !== "physical") return { accepted: false, reason: "controlled", message: "You are silenced." };
const restore = enter(simulation, actor, now, false);
try {
const requestedTarget = targetActorId ?? actor.targetActorId;
if (requestedTarget === actor.id) {
useCombatStore.setState({ selectedFriendlyActorId: PLAYER, selectedTargetId: null });
usePartyStore.setState({ selfSelected: true, selectedMemberId: null });
}
const result = useCombatStore.getState().castAbility(abilityId, { now, origin: actor.position,
targetActorId: requestedTarget === actor.id ? null : requestedTarget, groundPosition: groundPosition as any });
const message = useCombatStore.getState().feedback?.message;
commit(simulation, actor, now, false);
if (result.ok) { actor.lastAbilityId = abilityId; actor.abilityRevision += 1; }
return { accepted: result.ok, reason: result.reason, message, casting: Boolean(actor.casting) };
} finally { restore(); }
}
export function tickArenaCharacter(simulation: any, actor: any, now: number, delta: number) {
const restore = enter(simulation, actor, now, true);
try {
if (actor.casting && !actor.casting.canCastWhileMoving && Math.hypot(...actor.movement) > .01) useCombatStore.getState().cancelCast("movement");
useCombatStore.getState().tick(delta, now);
commit(simulation, actor, now, true);
} finally { restore(); }
}
export function arenaCharacterSnapshot(actor: any, now: number) {
const state: CombatState = actor.combat;
return { resourcePools: state.resourcePools, maxResourcePools: state.maxResourcePools, runes: state.deathKnightRunes,
talentRanks: state.talentRanks, gearStats: state.gearStats, specializationId: state.specializationId,
comboPoints: state.comboPoints, comboTargetId: state.comboTargetId, shield: state.shield,
activeCast: state.activeCast, playerAnimationEvent: state.playerAnimationEvent, summons: state.summons.map((summon) => ({ ...summon, ownerActorId: actor.id })),
areaEffects: state.areaEffects.map((area) => ({ ...area, sourceActorId: actor.id })),
controlledUntil: state.controlledUntil, schoolLockedUntil: state.schoolLockedUntil, now };
}
export function damageArenaCharacter(simulation: any, actor: any, amount: number, school: any, now: number) {
const restore = enter(simulation, actor, now, false);
try {
useCombatStore.getState().damagePlayer(amount, school);
commit(simulation, actor, now, false);
} finally { restore(); }
}
export function commandArenaCharacter(simulation: any, actor: any, command: string, now: number) {
if (command === "cancel-cast") {
const restore = enter(simulation, actor, now, false);
try { useCombatStore.getState().cancelCast(); commit(simulation, actor, now, false); } finally { restore(); }
}
if (command === "attack" || command === "defend" || command === "stop" || command === "recall") {
const targetId = command === "attack" ? actor.targetActorId : null;
actor.combat = { ...actor.combat, autoAttackTargetId: targetId, summons: actor.combat.summons.map((summon: any) => ({ ...summon,
targetId, ...(command === "recall" ? { position: [...actor.position] } : {}), nextActionAt: command === "stop" ? Number.MAX_SAFE_INTEGER : now })) };
}
}
export function bindArenaCharacter(actor: any, bindings: Record<string, string | null>) {
const next = Object.fromEntries(Object.keys(actor.characterKit.actionBindings).map((id) => [id,
bindings[id] && actor.characterKit.abilities[bindings[id]!] ? bindings[id] : null]));
actor.characterKit = { ...actor.characterKit, actionBindings: next };
actor.combat = { ...actor.combat, actionBindings: next };
}
+18
View File
@@ -0,0 +1,18 @@
// Same vanilla store contract used by Zustand, without a React dependency on
// the dedicated server. Each arena operation restores its own saved state.
export function create<T>(initialize: (set: any, get: () => T, api: any) => T) {
let state: T;
const listeners = new Set<(state: T, previous: T) => void>();
const api = {
getState: () => state,
setState(update: any, replace = false) {
const previous = state;
const patch = typeof update === "function" ? update(state) : update;
state = replace ? patch : Object.assign({}, state, patch);
if (state !== previous) for (const listener of listeners) listener(state, previous);
},
subscribe(listener: (state: T, previous: T) => void) { listeners.add(listener); return () => listeners.delete(listener); },
};
state = initialize(api.setState, api.getState, api);
return api;
}
+62
View File
@@ -0,0 +1,62 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { gzip, gunzip } from "node:zlib";
const compress = promisify(gzip);
const decompress = promisify(gunzip);
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
/** Original hashes remain the runtime contract; gzip is only a storage representation. */
export async function prepareContentObjects(files, { directory, baseUrl, keepOriginal = false }) {
await mkdir(directory, { recursive: true });
const unique = new Map();
for (const file of files) unique.set(`${file.sha256}${file.extension}`, file);
const objects = [...unique.entries()];
const prepared = new Map();
let next = 0;
let writtenObjects = 0;
const writeVerified = async (name, bytes) => {
const destination = path.join(directory, name);
try {
const existing = await readFile(destination);
if (!existing.equals(bytes)) throw new Error(`Published object differs from its hash: ${destination}`);
} catch (error) {
if (error.code !== "ENOENT") throw error;
await writeFile(destination, bytes, { flag: "wx" });
writtenObjects++;
}
};
await Promise.all(Array.from({ length: 4 }, async () => {
while (next < objects.length) {
const [name, file] = objects[next++];
const original = await readFile(file.sourcePath);
if (original.length !== file.bytes || digest(original) !== file.sha256) {
throw new Error(`Asset changed during packaging: ${file.logicalPath}`);
}
const compressed = await compress(original, { level: 6 });
const useful = compressed.length + 64 < original.length;
let download;
if (useful) {
if (!(await decompress(compressed)).equals(original)) throw new Error(`Gzip round trip failed: ${file.logicalPath}`);
const compressedHash = digest(compressed);
// AAPT expands and renames .gz assets even with noCompress. Keep gzip
// bytes under a neutral suffix so APK and browser catalogs stay identical.
const compressedName = `${compressedHash}${file.extension}.gzip`;
await writeVerified(compressedName, compressed);
download = { url: `${baseUrl}/${compressedName}`, encoding: "gzip", sha256: compressedHash, bytes: compressed.length };
}
if (keepOriginal || !useful) await writeVerified(name, original);
prepared.set(name, { objectUrl: `${baseUrl}/${name}`, ...(download ? { download } : {}), storedBytes: useful ? compressed.length : original.length });
}
}));
return {
files: files.map((file) => ({ ...file, ...prepared.get(`${file.sha256}${file.extension}`) })),
writtenObjects,
uniqueObjects: objects.length,
logicalBytes: files.reduce((sum, file) => sum + file.bytes, 0),
uniqueBytes: objects.reduce((sum, [, file]) => sum + file.bytes, 0),
storedBytes: [...prepared.values()].reduce((sum, object) => sum + object.storedBytes, 0),
};
}
+52
View File
@@ -0,0 +1,52 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { gunzipSync } from "node:zlib";
import { prepareContentObjects } from "./content-objects.mjs";
import { selectBootstrapContent } from "./prepare-bootstrap.mjs";
import { createContentManifest } from "./publish-content.mjs";
test("ships one lossless object for identical assets and verifies original bytes", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "healer-content-compression-"));
try {
const sourcePath = path.join(directory, "original.glb");
const original = Buffer.from("original geometry, textures, and animation\n".repeat(4096));
await writeFile(sourcePath, original);
const common = { sourcePath, bytes: original.length, sha256: createHash("sha256").update(original).digest("hex"), extension: ".glb" };
const files = ["first", "second"].map((id) => ({ ...common, logicalPath: `assets/creatures/${id}/model.glb`, packId: `dungeon:${id}` }));
const result = await prepareContentObjects(files, { directory: path.join(directory, "objects"), baseUrl: "/content/bundled" });
assert.equal(result.uniqueObjects, 1);
assert.equal(result.uniqueBytes, original.length);
assert.equal(result.logicalBytes, original.length * 2);
assert.ok(result.storedBytes < original.length / 10);
assert.equal((await readdir(path.join(directory, "objects"))).length, 1);
assert.deepEqual(result.files[0].download, result.files[1].download);
assert.ok(result.files[0].download.url.endsWith(".gzip"), "avoid Android's automatic .gz expansion");
const stored = await readFile(path.join(directory, "objects", path.basename(result.files[0].download.url)));
assert.deepEqual(gunzipSync(stored), original);
assert.deepEqual(await readFile(sourcePath), original);
const again = await prepareContentObjects(files, { directory: path.join(directory, "objects"), baseUrl: "/content/bundled" });
assert.equal(again.writtenObjects, 0);
assert.equal(createContentManifest(result.files).version, createContentManifest(again.files).version);
await writeFile(sourcePath, "changed");
await assert.rejects(prepareContentObjects(files, { directory: path.join(directory, "objects"), baseUrl: "/content/bundled" }), /changed during packaging/);
} finally { await rm(directory, { recursive: true, force: true }); }
});
test("bundles regular dungeons and exact map dependencies without installing Manastorm", () => {
const ids = ["core:ui", "dungeon:first", "dungeon:second", "shared:creatures", "manastorm:shared-map", "manastorm:optional-map", "characters:extra"];
const files = ids.map((packId, index) => ({ logicalPath: `assets/${index}.glb`, packId, sha256: String(index).repeat(64), bytes: 100, extension: ".glb" }));
const result = selectBootstrapContent(files, [
{ id: "dungeon:first", dependencies: ["manastorm:shared-map", "shared:creatures"] },
{ id: "dungeon:second", dependencies: [] },
]);
assert.deepEqual(result.files.map((file) => file.packId), ids.slice(0, 5));
const packs = new Map(result.packDefinitions.map((pack) => [pack.id, pack]));
assert.equal(packs.get("dungeon:first").bundledOnAndroid, true);
assert.equal(packs.get("dungeon:second").bundledOnAndroid, true);
assert.equal(packs.get("manastorm:shared-map").bundledOnAndroid, false);
assert.equal(packs.has("manastorm:optional-map"), false);
});
+2 -68
View File
@@ -1,69 +1,3 @@
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import {
BASIC_HUMAN_TEXTURE_PATHS,
PROJECT_ROOT,
createContentManifest,
scanContentSources,
} from "./publish-content.mjs";
import { prepareBootstrap } from "./prepare-bootstrap.mjs";
const outputDirectory = path.join(PROJECT_ROOT, ".android-public");
if (path.dirname(outputDirectory) !== PROJECT_ROOT || path.basename(outputDirectory) !== ".android-public") {
throw new Error(`Refusing to replace unexpected Android staging directory: ${outputDirectory}`);
}
const sources = [
{ directory: path.join(PROJECT_ROOT, "public", "basis"), logicalPrefix: "basis" },
{ directory: path.join(PROJECT_ROOT, "public", "assets", "ui"), logicalPrefix: "assets/ui" },
{ directory: path.join(PROJECT_ROOT, "public", "assets", "equipment"), logicalPrefix: "assets/equipment" },
{
directory: path.join(PROJECT_ROOT, "public", "assets", "characters", "wow335a-v1", "manifest.json"),
logicalPrefix: "assets/characters/wow335a-v1/manifest.json",
},
{
directory: path.join(PROJECT_ROOT, "public", "assets", "characters", "wow335a-v1", "human"),
logicalPrefix: "assets/characters/wow335a-v1/human",
},
...BASIC_HUMAN_TEXTURE_PATHS.map((logicalPath) => ({
directory: path.join(PROJECT_ROOT, "public", ...logicalPath.split("/")),
logicalPrefix: logicalPath,
})),
{
directory: path.join(PROJECT_ROOT, "public", "assets", "creatures", "wailing-caverns"),
logicalPrefix: "assets/creatures/wailing-caverns",
},
{
directory: path.join(PROJECT_ROOT, "public", "assets", "game", "arenas"),
logicalPrefix: "assets/game/arenas",
},
{
directory: path.join(PROJECT_ROOT, "src", "assets", "game", "dungeons", "wailing-caverns"),
logicalPrefix: "assets/game/dungeons/wailing-caverns",
},
];
await rm(outputDirectory, { recursive: true, force: true });
await mkdir(outputDirectory, { recursive: true });
const files = await scanContentSources(sources);
for (const file of files) {
const destination = path.join(outputDirectory, ...file.logicalPath.split("/"));
await mkdir(path.dirname(destination), { recursive: true });
await copyFile(file.sourcePath, destination);
}
const generated = createContentManifest(files, { baseUrl: "/" });
const bootstrapManifest = {
...generated,
files: Object.fromEntries(Object.entries(generated.files).map(([logicalPath, entry]) => [
logicalPath,
{ ...entry, url: logicalPath },
])),
};
const manifestPath = path.join(outputDirectory, "content", "bootstrap-manifest.json");
await mkdir(path.dirname(manifestPath), { recursive: true });
await writeFile(manifestPath, `${JSON.stringify(bootstrapManifest, null, 2)}\n`, "utf8");
const bytes = files.reduce((total, file) => total + file.bytes, 0);
console.log(`Prepared Android bootstrap content: ${files.length} files (${bytes} bytes)`);
console.log(`Bootstrap version: ${bootstrapManifest.version}`);
await prepareBootstrap("android");
+63
View File
@@ -0,0 +1,63 @@
import { copyFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import {
BUNDLED_ANDROID_PACKS, DEFAULT_CONTENT_SOURCES, PROJECT_ROOT,
createContentManifest, loadCampaignDungeonPackDefinitions, scanContentSources,
} from "./publish-content.mjs";
import { prepareContentObjects } from "./content-objects.mjs";
export function selectBootstrapContent(files, packDefinitions) {
const manifest = createContentManifest(files, { packDefinitions });
const packs = new Map(manifest.packs.map((pack) => [pack.id, pack]));
const included = new Set();
function include(id) {
if (included.has(id)) return;
included.add(id);
for (const dependency of packs.get(id)?.dependencies ?? []) include(dependency);
}
for (const pack of manifest.packs) {
if (BUNDLED_ANDROID_PACKS.includes(pack.id) || pack.id.startsWith("dungeon:")) include(pack.id);
}
return {
files: files.filter((file) => included.has(file.packId)),
packDefinitions: manifest.packs.filter((pack) => included.has(pack.id)).map((pack) => ({
...pack,
// Shared maps can be physically bundled without installing Manastorm gameplay.
bundledOnAndroid: !pack.id.startsWith("manastorm:"),
})),
};
}
export async function prepareBootstrap(platform) {
if (!["web", "android"].includes(platform)) throw new Error(`Unknown bootstrap platform: ${platform}`);
const outputDirectory = path.resolve(PROJECT_ROOT, `.${platform}-public`);
if (path.dirname(outputDirectory) !== PROJECT_ROOT || path.basename(outputDirectory) !== `.${platform}-public`) {
throw new Error(`Refusing to replace unexpected staging directory: ${outputDirectory}`);
}
const files = await scanContentSources([
...DEFAULT_CONTENT_SOURCES,
{ directory: path.join(PROJECT_ROOT, "public/basis"), logicalPrefix: "basis" },
{ directory: path.join(PROJECT_ROOT, "public/data"), logicalPrefix: "data" },
]);
const selected = selectBootstrapContent(files, await loadCampaignDungeonPackDefinitions());
await rm(outputDirectory, { recursive: true, force: true });
const prepared = await prepareContentObjects(selected.files, {
directory: path.join(outputDirectory, "content/bundled"), baseUrl: "/content/bundled",
});
const manifest = createContentManifest(prepared.files, {
baseUrl: "/content/bundled", packDefinitions: selected.packDefinitions,
});
await writeFile(path.join(outputDirectory, "content/bootstrap-manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
await copyFile(path.join(PROJECT_ROOT, "public/content-cache-sw.js"), path.join(outputDirectory, "content-cache-sw.js"));
const storage = {
logicalBytes: prepared.logicalBytes, uniqueBytes: prepared.uniqueBytes, storedBytes: prepared.storedBytes,
duplicateBytesRemoved: prepared.logicalBytes - prepared.uniqueBytes,
uniqueObjects: prepared.uniqueObjects, logicalFiles: selected.files.length,
bundledDungeons: manifest.packs.filter((pack) => pack.id.startsWith("dungeon:")).length,
bundledManastormPacks: manifest.packs.filter((pack) => pack.id.startsWith("manastorm:") && pack.bundledOnAndroid).length,
};
await writeFile(path.join(outputDirectory, "content/storage-report.json"), `${JSON.stringify(storage, null, 2)}\n`);
console.log(`Prepared ${platform} bootstrap: ${storage.bundledDungeons} dungeons, ${prepared.uniqueObjects} shared objects`);
console.log(`Original: ${storage.logicalBytes} bytes; duplicates removed: ${storage.duplicateBytesRemoved} bytes; shipped: ${storage.storedBytes} bytes`);
return { manifest, storage, outputDirectory };
}
+2 -74
View File
@@ -1,75 +1,3 @@
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import {
BASIC_HUMAN_TEXTURE_PATHS,
PROJECT_ROOT,
createContentManifest,
scanContentSources,
} from "./publish-content.mjs";
import { prepareBootstrap } from "./prepare-bootstrap.mjs";
const outputDirectory = path.join(PROJECT_ROOT, ".web-public");
if (path.dirname(outputDirectory) !== PROJECT_ROOT || path.basename(outputDirectory) !== ".web-public") {
throw new Error(`Refusing to replace unexpected browser staging directory: ${outputDirectory}`);
}
const sources = [
{ directory: path.join(PROJECT_ROOT, "public", "basis"), logicalPrefix: "basis" },
{ directory: path.join(PROJECT_ROOT, "public", "data"), logicalPrefix: "data" },
{ directory: path.join(PROJECT_ROOT, "public", "assets", "ui"), logicalPrefix: "assets/ui" },
{ directory: path.join(PROJECT_ROOT, "public", "assets", "equipment"), logicalPrefix: "assets/equipment" },
{
directory: path.join(PROJECT_ROOT, "public", "assets", "characters", "wow335a-v1", "manifest.json"),
logicalPrefix: "assets/characters/wow335a-v1/manifest.json",
},
{
directory: path.join(PROJECT_ROOT, "public", "assets", "characters", "wow335a-v1", "human"),
logicalPrefix: "assets/characters/wow335a-v1/human",
},
...BASIC_HUMAN_TEXTURE_PATHS.map((logicalPath) => ({
directory: path.join(PROJECT_ROOT, "public", ...logicalPath.split("/")),
logicalPrefix: logicalPath,
})),
{
directory: path.join(PROJECT_ROOT, "public", "assets", "creatures", "wailing-caverns"),
logicalPrefix: "assets/creatures/wailing-caverns",
},
{
directory: path.join(PROJECT_ROOT, "public", "assets", "game", "arenas"),
logicalPrefix: "assets/game/arenas",
},
{
directory: path.join(PROJECT_ROOT, "src", "assets", "game", "dungeons", "wailing-caverns"),
logicalPrefix: "assets/game/dungeons/wailing-caverns",
},
];
await rm(outputDirectory, { recursive: true, force: true });
await mkdir(outputDirectory, { recursive: true });
const files = await scanContentSources(sources);
for (const file of files) {
const destination = path.join(outputDirectory, ...file.logicalPath.split("/"));
await mkdir(path.dirname(destination), { recursive: true });
await copyFile(file.sourcePath, destination);
}
await copyFile(
path.join(PROJECT_ROOT, "public", "content-cache-sw.js"),
path.join(outputDirectory, "content-cache-sw.js"),
);
const generated = createContentManifest(files, { baseUrl: "/" });
const bootstrapManifest = {
...generated,
files: Object.fromEntries(Object.entries(generated.files).map(([logicalPath, entry]) => [
logicalPath,
{ ...entry, url: logicalPath },
])),
};
const manifestPath = path.join(outputDirectory, "content", "bootstrap-manifest.json");
await mkdir(path.dirname(manifestPath), { recursive: true });
await writeFile(manifestPath, `${JSON.stringify(bootstrapManifest, null, 2)}\n`, "utf8");
const bytes = files.reduce((total, file) => total + file.bytes, 0);
console.log(`Prepared browser bootstrap content: ${files.length} files (${bytes} bytes)`);
console.log(`Bootstrap version: ${bootstrapManifest.version}`);
await prepareBootstrap("web");
+216 -28
View File
@@ -1,8 +1,7 @@
import { createHash } from "node:crypto";
import {
constants,
copyFile,
mkdir,
readFile,
readdir,
rename,
stat,
@@ -10,11 +9,20 @@ import {
} from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { prepareContentObjects } from "./content-objects.mjs";
const SCRIPT_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
export const PROJECT_ROOT = path.resolve(SCRIPT_DIRECTORY, "../..");
const WOW_CAMPAIGN_CATALOG_PATH = path.join(
PROJECT_ROOT,
"src",
"game",
"generated",
"dungeonCampaignCatalog.json",
);
export const CONTENT_SCHEMA_VERSION = 1;
export const DEFAULT_MINIMUM_APP_VERSION = "0.1.0";
export const WOW_CAMPAIGN_DUNGEON_COUNT = 54;
export const BUNDLED_ANDROID_PACKS = Object.freeze([
"core:ui",
"core:equipment",
@@ -179,15 +187,112 @@ export async function scanContentSources(sources = DEFAULT_CONTENT_SOURCES) {
return [...discovered.values()].sort((left, right) => left.logicalPath.localeCompare(right.logicalPath));
}
function contentVersion(files) {
function contentVersion(files, packs) {
const digest = createHash("sha256");
for (const file of files) digest.update(`${file.logicalPath}\0${file.sha256}\0${file.bytes}\n`);
for (const file of files) digest.update(`${file.logicalPath}\0${file.sha256}\0${file.bytes}\0${JSON.stringify(file.download ?? null)}\n`);
for (const pack of packs) {
digest.update(`pack\0${pack.id}\0${pack.label}\0${pack.bundledOnAndroid}\0${pack.dependencies.join(",")}\n`);
}
return `content-${digest.digest("hex").slice(0, 16)}`;
}
function assetPackId(url) {
if (typeof url !== "string" || !url.startsWith("/")) return null;
return contentPackForPath(url.slice(1));
}
/**
* Builds the logical install topology for the 54-dungeon WoW campaign.
* Environment files intentionally remain in their independently downloadable
* Manastorm packs; a dungeon pack owns its creatures and pulls in exactly the
* environment/shared-creature packs referenced by the generated definition.
*/
export function campaignDungeonPackDefinitions(definitions) {
const packs = new Map();
for (const definition of definitions) {
const dungeonPackId = `dungeon:${definition.id}`;
if (definition.id === "wailing-caverns") {
packs.set(dungeonPackId, {
id: dungeonPackId,
label: definition.title ?? packLabel(dungeonPackId),
bundledOnAndroid: true,
dependencies: [],
});
continue;
}
const environmentUrls = [
...(definition.assets?.visual ?? []).map((asset) => asset.url),
...(definition.assets?.collision ?? []).map((asset) => asset.url),
definition.assets?.navigation?.url,
].filter(Boolean);
const resolvedEnvironmentPacks = environmentUrls.map(assetPackId);
if (!resolvedEnvironmentPacks.length || resolvedEnvironmentPacks.some((id) => !id?.startsWith("manastorm:"))) {
throw new Error(`${definition.id} has an environment asset outside a Manastorm content pack.`);
}
const environmentPackIds = new Set(resolvedEnvironmentPacks);
if (environmentPackIds.size !== 1) {
throw new Error(`${definition.id} must resolve to exactly one Manastorm environment pack.`);
}
const [environmentPackId] = environmentPackIds;
packs.set(environmentPackId, {
id: environmentPackId,
label: packLabel(environmentPackId),
bundledOnAndroid: false,
dependencies: [],
});
const creatureUrls = Object.values(definition.entities ?? {})
.map((entity) => entity.visual?.model?.url)
.filter(Boolean);
const resolvedCreaturePacks = creatureUrls.map(assetPackId);
if (resolvedCreaturePacks.some((id) => !id)) {
throw new Error(`${definition.id} has a creature asset outside a content pack.`);
}
const referencedCreaturePacks = new Set(resolvedCreaturePacks.filter((id) => id !== dungeonPackId));
const unexpectedCreaturePacks = [...referencedCreaturePacks].filter((id) => id !== "shared:creatures");
if (unexpectedCreaturePacks.length) {
throw new Error(`${definition.id} references unexpected creature packs: ${unexpectedCreaturePacks.join(", ")}`);
}
packs.set(dungeonPackId, {
id: dungeonPackId,
label: definition.title ?? packLabel(dungeonPackId),
bundledOnAndroid: false,
dependencies: [environmentPackId, ...referencedCreaturePacks],
});
}
return [...packs.values()].sort((left, right) => left.id.localeCompare(right.id));
}
export async function loadCampaignDungeonPackDefinitions(
catalogPath = WOW_CAMPAIGN_CATALOG_PATH,
) {
const definitions = await loadCampaignDungeonDefinitions(catalogPath);
return campaignDungeonPackDefinitions(definitions);
}
export async function loadCampaignDungeonDefinitions(
catalogPath = WOW_CAMPAIGN_CATALOG_PATH,
) {
const campaign = JSON.parse(await readFile(catalogPath, "utf8"));
if (!Array.isArray(campaign.definitions)) {
throw new Error(`WoW campaign catalog is missing definitions: ${catalogPath}`);
}
if (campaign.definitions.length !== WOW_CAMPAIGN_DUNGEON_COUNT) {
throw new Error(
`WoW campaign catalog must contain ${WOW_CAMPAIGN_DUNGEON_COUNT} dungeons; found ${campaign.definitions.length}.`,
);
}
const dungeonIds = campaign.definitions.map((definition) => definition?.id);
if (dungeonIds.some((id) => typeof id !== "string" || !id)
|| new Set(dungeonIds).size !== dungeonIds.length) {
throw new Error("WoW campaign catalog contains a missing or duplicate dungeon id.");
}
return campaign.definitions;
}
export function createContentManifest(files, options = {}) {
const baseUrl = String(options.baseUrl ?? "/content/objects").replace(/\/+$/, "");
const version = options.version ?? contentVersion(files);
const packs = new Map();
const fileEntries = {};
@@ -199,6 +304,7 @@ export function createContentManifest(files, options = {}) {
url: `${baseUrl}/${encodeUrlPath(objectName)}`,
sha256: file.sha256,
bytes: file.bytes,
...(file.download ? { download: file.download } : {}),
};
const pack = packs.get(file.packId) ?? {
id: file.packId,
@@ -227,32 +333,96 @@ export function createContentManifest(files, options = {}) {
}
}
for (const declared of options.packDefinitions ?? []) {
const current = packs.get(declared.id) ?? {
id: declared.id,
label: packLabel(declared.id),
bytes: 0,
fileCount: 0,
bundledOnAndroid: BUNDLED_ANDROID_PACKS.includes(declared.id),
dependencies: [],
};
packs.set(declared.id, {
...current,
label: declared.label ?? current.label,
bundledOnAndroid: declared.bundledOnAndroid ?? current.bundledOnAndroid,
dependencies: [...declared.dependencies],
});
}
const sortedPacks = [...packs.values()].sort((left, right) => left.id.localeCompare(right.id));
for (const pack of sortedPacks) {
const objects = new Map(files.filter((file) => file.packId === pack.id)
.map((file) => [file.sha256, file.download?.bytes ?? file.bytes]));
pack.downloadBytes = [...objects.values()].reduce((sum, bytes) => sum + bytes, 0);
}
const version = options.version ?? contentVersion(files, sortedPacks);
return {
schemaVersion: CONTENT_SCHEMA_VERSION,
version,
createdAt: options.createdAt ?? new Date().toISOString(),
minimumAppVersion: options.minimumAppVersion ?? DEFAULT_MINIMUM_APP_VERSION,
packs: [...packs.values()].sort((left, right) => left.id.localeCompare(right.id)),
packs: sortedPacks,
files: fileEntries,
};
}
async function copyObjectIfMissing(file, objectDirectory) {
const objectName = `${file.sha256}${file.extension}`;
const destination = path.join(objectDirectory, objectName);
try {
const destinationStats = await stat(destination);
if (destinationStats.size !== file.bytes) throw new Error(`Published object has the wrong size: ${destination}`);
return false;
} catch (error) {
if (error?.code !== "ENOENT") throw error;
export function assertCampaignDungeonManifest(manifest, definitions) {
if (!Array.isArray(definitions) || definitions.length !== WOW_CAMPAIGN_DUNGEON_COUNT) {
throw new Error(`Release content requires exactly ${WOW_CAMPAIGN_DUNGEON_COUNT} WoW dungeon definitions.`);
}
try {
await copyFile(file.sourcePath, destination, constants.COPYFILE_EXCL);
} catch (error) {
if (error?.code !== "EEXIST") throw error;
const expectedDefinitions = campaignDungeonPackDefinitions(definitions);
const manifestPacks = new Map(manifest.packs.map((pack) => [pack.id, pack]));
if (manifestPacks.size !== manifest.packs.length) {
throw new Error("Release content manifest contains duplicate pack ids.");
}
for (const expected of expectedDefinitions) {
const actual = manifestPacks.get(expected.id);
if (!actual) throw new Error(`Release content manifest is missing ${expected.id}.`);
if (actual.bundledOnAndroid !== expected.bundledOnAndroid
|| actual.dependencies.length !== expected.dependencies.length
|| actual.dependencies.some((dependency, index) => dependency !== expected.dependencies[index])) {
throw new Error(`Release content manifest has stale dependencies for ${expected.id}.`);
}
}
for (const pack of manifest.packs) {
const packFiles = Object.values(manifest.files).filter((entry) => entry.packId === pack.id);
const packBytes = packFiles.reduce((total, entry) => total + entry.bytes, 0);
if (pack.fileCount !== packFiles.length || pack.bytes !== packBytes) {
throw new Error(`Release content manifest has invalid file totals for ${pack.id}.`);
}
for (const dependency of pack.dependencies) {
if (!manifestPacks.has(dependency)) {
throw new Error(`Release content manifest is missing dependency ${dependency} for ${pack.id}.`);
}
}
}
for (const definition of definitions) {
const referencedUrls = [
...(definition.assets?.visual ?? []).map((asset) => asset.url),
...(definition.assets?.collision ?? []).map((asset) => asset.url),
definition.assets?.navigation?.url,
...Object.values(definition.entities ?? {}).map((entity) => entity.visual?.model?.url),
].filter(Boolean);
for (const logicalPath of referencedUrls) {
if (!manifest.files[logicalPath]) {
throw new Error(`Release content manifest is missing ${definition.id} asset ${logicalPath}.`);
}
}
}
const dungeonPackCount = definitions.filter((definition) => (
manifestPacks.has(`dungeon:${definition.id}`)
)).length;
if (dungeonPackCount !== WOW_CAMPAIGN_DUNGEON_COUNT) {
throw new Error(
`Release content manifest contains ${dungeonPackCount}/${WOW_CAMPAIGN_DUNGEON_COUNT} WoW dungeon packs.`,
);
}
return true;
}
async function replaceJsonAtomically(destination, value) {
@@ -263,20 +433,37 @@ async function replaceJsonAtomically(destination, value) {
export async function publishContent(options = {}) {
const contentDirectory = path.resolve(options.contentDirectory ?? process.env.CONTENT_DIR ?? path.join(PROJECT_ROOT, "content"));
const files = await scanContentSources(options.sources ?? DEFAULT_CONTENT_SOURCES);
const includeCampaignPacks = options.includeCampaignPacks !== false;
const campaignDefinitions = includeCampaignPacks ? await loadCampaignDungeonDefinitions() : null;
const campaignPackDefinitions = campaignDefinitions
? campaignDungeonPackDefinitions(campaignDefinitions)
: [];
const packDefinitions = [
...campaignPackDefinitions,
...(options.packDefinitions ?? []),
];
if (campaignDefinitions) assertCampaignDungeonManifest(createContentManifest(files, { ...options, packDefinitions }), campaignDefinitions);
const objectDirectory = path.join(contentDirectory, "objects");
const manifestDirectory = path.join(contentDirectory, "manifests");
await mkdir(objectDirectory, { recursive: true });
await mkdir(manifestDirectory, { recursive: true });
const files = await scanContentSources(options.sources ?? DEFAULT_CONTENT_SOURCES);
let copiedObjects = 0;
for (const file of files) {
if (await copyObjectIfMissing(file, objectDirectory)) copiedObjects += 1;
}
const manifest = createContentManifest(files, options);
const prepared = await prepareContentObjects(files, {
directory: objectDirectory,
baseUrl: String(options.baseUrl ?? "/content/objects").replace(/\/+$/, ""),
keepOriginal: true,
});
const manifest = createContentManifest(prepared.files, { ...options, packDefinitions });
await replaceJsonAtomically(path.join(manifestDirectory, `${manifest.version}.json`), manifest);
await replaceJsonAtomically(path.join(contentDirectory, "manifest.json"), manifest);
return { contentDirectory, copiedObjects, manifest };
return {
contentDirectory,
copiedObjects: prepared.writtenObjects,
storage: { logicalBytes: prepared.logicalBytes, uniqueBytes: prepared.uniqueBytes, storedBytes: prepared.storedBytes },
manifest,
campaignDungeonPackCount: campaignDefinitions?.length ?? 0,
};
}
function parseCliArguments(argv) {
@@ -296,6 +483,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
const bytes = result.manifest.packs.reduce((total, pack) => total + pack.bytes, 0);
console.log(`Published ${result.manifest.files ? Object.keys(result.manifest.files).length : 0} files (${bytes} bytes)`);
console.log(`Content version: ${result.manifest.version}`);
console.log(`WoW campaign dungeon packs: ${result.campaignDungeonPackCount}/${WOW_CAMPAIGN_DUNGEON_COUNT}`);
console.log(`New immutable objects: ${result.copiedObjects}`);
console.log(`Manifest: ${path.join(result.contentDirectory, "manifest.json")}`);
}
+170 -3
View File
@@ -1,12 +1,15 @@
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { access, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import {
BUNDLED_ANDROID_PACKS,
PROJECT_ROOT,
assertCampaignDungeonManifest,
contentPackForPath,
createContentManifest,
loadCampaignDungeonPackDefinitions,
publishContent,
scanContentSources,
} from "./publish-content.mjs";
@@ -31,6 +34,160 @@ test("assigns stable player-facing packs from logical asset paths", () => {
assert.equal(contentPackForPath("basis/basis_transcoder.wasm"), "core:runtime");
});
test("gives every WoW campaign dungeon an exact install dependency closure", async () => {
const campaign = JSON.parse(await readFile(path.join(
PROJECT_ROOT,
"src",
"game",
"generated",
"dungeonCampaignCatalog.json",
), "utf8"));
const packDefinitions = await loadCampaignDungeonPackDefinitions();
const dungeonDefinitions = packDefinitions.filter((pack) => pack.id.startsWith("dungeon:"));
const wailingCreatureManifest = JSON.parse(await readFile(path.join(
PROJECT_ROOT,
"public",
"assets",
"creatures",
"wailing-caverns",
"animated-manifest.json",
), "utf8"));
assert.equal(campaign.definitions.length, 54);
assert.equal(dungeonDefinitions.length, 54);
assert.equal(wailingCreatureManifest.creatures.length, 16);
const referencedSourceFiles = [
...campaign.definitions.flatMap((dungeon) => [
...[
...dungeon.assets.visual,
...dungeon.assets.collision,
dungeon.assets.navigation,
].map((asset) => ({ dungeonId: dungeon.id, url: asset.url })),
...Object.values(dungeon.entities).flatMap((entity) => (
entity.visual?.model?.url ? [{ dungeonId: dungeon.id, url: entity.visual.model.url }] : []
)),
]),
...wailingCreatureManifest.creatures.map((creature) => ({
dungeonId: "wailing-caverns",
url: creature.url,
})),
];
await Promise.all(referencedSourceFiles.map(async ({ dungeonId, url }) => {
try {
await access(path.join(PROJECT_ROOT, "public", ...url.slice(1).split("/")));
} catch {
assert.fail(`${dungeonId} is missing ${url}`);
}
}));
await Promise.all([
"wailing-caverns-visual.glb",
"wailing-caverns-collision.glb",
"wailing-caverns-navigation.glb",
].map((fileName) => access(path.join(
PROJECT_ROOT,
"src",
"assets",
"game",
"dungeons",
"wailing-caverns",
fileName,
))));
const logicalFiles = new Map();
const addFile = (logicalPath) => logicalFiles.set(logicalPath, {
logicalPath,
sourcePath: logicalPath,
sha256: "a".repeat(64),
bytes: 1,
extension: path.extname(logicalPath),
packId: contentPackForPath(logicalPath),
});
addFile("assets/game/dungeons/wailing-caverns/visual.glb");
for (const dungeon of campaign.definitions) {
for (const asset of [
...dungeon.assets.visual,
...dungeon.assets.collision,
dungeon.assets.navigation,
]) addFile(asset.url.slice(1));
for (const entity of Object.values(dungeon.entities)) {
if (entity.visual?.model?.url) addFile(entity.visual.model.url.slice(1));
}
}
const manifest = createContentManifest([...logicalFiles.values()], {
packDefinitions,
version: "campaign-contract",
});
assert.doesNotThrow(() => assertCampaignDungeonManifest(manifest, campaign.definitions));
const packs = new Map(manifest.packs.map((pack) => [pack.id, pack]));
for (const dungeon of campaign.definitions) {
const pack = packs.get(`dungeon:${dungeon.id}`);
assert.ok(pack, dungeon.id);
if (dungeon.id === "wailing-caverns") {
assert.equal(pack.bundledOnAndroid, true);
assert.deepEqual(pack.dependencies, []);
continue;
}
const environmentPack = contentPackForPath(dungeon.assets.visual[0].url.slice(1));
const needsSharedCreatures = Object.values(dungeon.entities).some((entity) => (
entity.visual?.model?.url?.startsWith("/assets/game/creatures/shared/")
));
assert.deepEqual(
pack.dependencies,
[environmentPack, ...(needsSharedCreatures ? ["shared:creatures"] : [])],
dungeon.id,
);
assert.deepEqual(packs.get(environmentPack)?.dependencies, [], dungeon.id);
}
for (const [dungeonId, environmentPack] of [
["tinkertech-showdown", "manastorm:821-tinketechshowdown"],
["frozen-reach", "manastorm:908-alvaencounter"],
["forgotten-mine", "manastorm:1781-forgottenmine"],
]) {
const pack = packs.get(`dungeon:${dungeonId}`);
assert.equal(pack.fileCount, 0);
assert.equal(pack.bytes, 0);
assert.deepEqual(pack.dependencies, [environmentPack]);
}
});
test("default release publishing fails before writing an incomplete campaign manifest", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "healer-man-incomplete-content-test-"));
const sourceDirectory = path.join(directory, "source");
const contentDirectory = path.join(directory, "content");
await mkdir(sourceDirectory, { recursive: true });
await writeFile(path.join(sourceDirectory, "placeholder.glb"), Buffer.from("incomplete"));
try {
await assert.rejects(publishContent({
contentDirectory,
sources: [{ directory: sourceDirectory, logicalPrefix: "assets/game/dungeons/placeholder" }],
}), /Release content manifest is missing/);
await assert.rejects(access(contentDirectory), { code: "ENOENT" });
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("content versions change when only logical pack dependencies change", () => {
const files = [{
logicalPath: "assets/game/dungeons/test/creature.glb",
sourcePath: "creature.glb",
sha256: "b".repeat(64),
bytes: 1,
extension: ".glb",
packId: "dungeon:test",
}];
const first = createContentManifest(files, {
packDefinitions: [{ id: "dungeon:test", dependencies: ["manastorm:first"] }],
});
const second = createContentManifest(files, {
packDefinitions: [{ id: "dungeon:test", dependencies: ["manastorm:second"] }],
});
assert.notEqual(first.version, second.version);
});
test("publishes objects before a deterministic latest manifest", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "healer-man-content-test-"));
const sourceDirectory = path.join(directory, "source");
@@ -45,7 +202,12 @@ test("publishes objects before a deterministic latest manifest", async () => {
assert.equal(Object.keys(firstManifest.files).length, 1);
assert.equal(firstManifest.packs[0].id, "dungeon:wailing-caverns");
const first = await publishContent({ contentDirectory, sources, createdAt: "2026-08-14T00:00:00.000Z" });
const first = await publishContent({
contentDirectory,
sources,
includeCampaignPacks: false,
createdAt: "2026-08-14T00:00:00.000Z",
});
assert.equal(first.copiedObjects, 1);
const latest = JSON.parse(await readFile(path.join(contentDirectory, "manifest.json"), "utf8"));
assert.equal(latest.version, first.manifest.version);
@@ -53,7 +215,12 @@ test("publishes objects before a deterministic latest manifest", async () => {
assert.match(entry.url, /^\/content\/objects\/[a-f0-9]{64}\.glb$/);
assert.equal(await readFile(path.join(contentDirectory, "objects", path.basename(entry.url)), "utf8"), "glb-one");
const second = await publishContent({ contentDirectory, sources, createdAt: "2026-08-14T00:00:00.000Z" });
const second = await publishContent({
contentDirectory,
sources,
includeCampaignPacks: false,
createdAt: "2026-08-14T00:00:00.000Z",
});
assert.equal(second.copiedObjects, 0);
assert.equal(second.manifest.version, first.manifest.version);
} finally {
+58
View File
@@ -0,0 +1,58 @@
"""Verify the packaged bytes, including Android asset-name/compression behavior."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
from zipfile import ZIP_STORED, ZipFile
def verify_package(apk: Path) -> dict:
with ZipFile(apk) as archive:
manifest = json.loads(archive.read("assets/public/content/bootstrap-manifest.json"))
checked = set()
object_bytes = 0
for logical_path, entry in manifest["files"].items():
stored = entry.get("download", entry)
if stored["url"] in checked:
continue
checked.add(stored["url"])
name = "assets/public" + stored["url"]
data = archive.read(name)
if len(data) != stored["bytes"] or hashlib.sha256(data).hexdigest() != stored["sha256"]:
raise ValueError(f"Packaged object failed verification: {logical_path}")
object_bytes += len(data)
if "download" in entry:
if archive.getinfo(name).compress_type != ZIP_STORED:
raise ValueError(f"Android recompressed an already compressed object: {name}")
data = gzip.decompress(data)
if len(data) != entry["bytes"] or hashlib.sha256(data).hexdigest() != entry["sha256"]:
raise ValueError(f"Expanded object failed verification: {logical_path}")
dungeons = sum(pack["id"].startswith("dungeon:") and pack["bundledOnAndroid"] for pack in manifest["packs"])
expected_objects = {"assets/public" + url for url in checked}
actual_objects = {name for name in archive.namelist() if name.startswith("assets/public/content/bundled/") and not name.endswith("/")}
if actual_objects != expected_objects:
raise ValueError("APK includes missing or unreferenced bundled objects.")
manastorms = sum(pack["id"].startswith("manastorm:") and pack["bundledOnAndroid"] for pack in manifest["packs"])
if dungeons != 84 or manastorms != 0:
raise ValueError(f"Unexpected bundled content: {dungeons} dungeons, {manastorms} Manastorm packs")
return {
"apk": str(apk.resolve()), "apkBytes": apk.stat().st_size,
"manifestVersion": manifest["version"], "logicalFiles": len(manifest["files"]),
"verifiedUniqueObjects": len(checked), "storedObjectBytes": object_bytes,
"bundledDungeons": dungeons, "bundledManastormPacks": manastorms,
"allOriginalHashesMatch": True,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("apk", type=Path)
parser.add_argument("--report", type=Path)
args = parser.parse_args()
result = json.dumps(verify_package(args.apk), indent=2) + "\n"
if args.report:
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(result, encoding="utf-8")
print(result, end="")
@@ -2,6 +2,11 @@
import { open, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { DUNGEON_DEFINITIONS } from "../../src/game/dungeonRegistry";
import {
WOW_DUNGEON_BASIC_ONLY_BOSS_EXCEPTIONS,
WOW_DUNGEON_NO_TRASH_EXCEPTIONS,
} from "../../src/game/wowDungeonContentExceptions";
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const publicRoot = path.join(projectRoot, "public");
@@ -18,24 +23,14 @@ const validTargets = new Set([
]);
const validSchools = new Set(["physical", "arcane", "fire", "frost", "nature", "shadow", "holy"]);
const validEffects = new Set([
"damage", "heal", "aura", "control", "transform", "summon", "call-for-help", "encounter-event",
]);
const basicOnlyBossExceptions = new Map([
[
"wailing-caverns:entry-3653",
"Kresh is melee-only in the pinned AzerothCore snapshot; the historical server has no spell or SmartAI row for entry 3653.",
],
[
"wailing-caverns:deviate-faerie-dragon",
"The server-faithful rare entry 5912 has no spell rows and is despawned by the Wailing Caverns initialization event.",
],
]);
const noTrashExceptions = new Map([
[
"trial-of-the-champion",
"Trial of the Champion is an encounter arena; its imported combat population is the five Grand Champion bosses, not a trash route.",
],
"damage", "heal", "aura", "target-aura", "control", "transform", "summon", "call-for-help", "encounter-event",
]);
const basicOnlyBossExceptions = new Map(
WOW_DUNGEON_BASIC_ONLY_BOSS_EXCEPTIONS.map(({ key, reason }) => [key, reason]),
);
const noTrashExceptions = new Map(
WOW_DUNGEON_NO_TRASH_EXCEPTIONS.map(({ key, reason }) => [key, reason]),
);
const animationIds = {
idle: new Set([0]),
move: new Set([4, 5]),
@@ -152,13 +147,21 @@ const [campaign, catalog, wailingFixture] = await Promise.all([
readJson("dungeon-pipeline/fixtures/wailing-caverns/runtime-fixture.json"),
]);
const campaignIds = new Set(campaign.dungeons.map((dungeon) => dungeon.slug));
const definitions = catalog.definitions.filter((definition) => campaignIds.has(definition.id));
const definitions = DUNGEON_DEFINITIONS.filter((definition) => campaignIds.has(definition.id));
const coverage = new Map(catalog.coverage.map((entry) => [entry.dungeonId, entry]));
const wailingModels = wailingFixtureModels(wailingFixture);
const issues = [];
if (basicOnlyBossExceptions.size !== WOW_DUNGEON_BASIC_ONLY_BOSS_EXCEPTIONS.length) {
issues.push("The shared basic-only boss exception contract contains a duplicate key.");
}
if (noTrashExceptions.size !== WOW_DUNGEON_NO_TRASH_EXCEPTIONS.length) {
issues.push("The shared no-trash exception contract contains a duplicate key.");
}
const modelUsers = new Map();
const animationFallbacks = [];
const dungeons = [];
const actualBasicOnlyBossKeys = new Set();
const actualNoTrashDungeonKeys = new Set();
if (campaign.dungeons.length !== 54) {
issues.push("Expected 54 campaign dungeons; found " + campaign.dungeons.length + ".");
@@ -179,15 +182,15 @@ for (const dungeon of definitions) {
let specialAttacks = 0;
let nativeModels = 0;
let proceduralModels = 0;
const optionalBossEntityIds = new Set((dungeon.objectiveOrder ?? [])
.filter((objective) => objective.optional)
.map((objective) => dungeon.staticSpawns?.find((spawn) => spawn.id === objective.id)?.entityId)
.filter(Boolean));
if (!entities.length) dungeonIssues.push("has no combat entities.");
if (!bosses.length) dungeonIssues.push("has no bosses.");
if (!mobs.length && !noTrashExceptions.has(dungeon.id)) dungeonIssues.push("has no trash mobs.");
if (!(dungeon.staticSpawns?.length || dungeon.roamingPacks?.length)) dungeonIssues.push("has no combat spawns.");
if (!mobs.length) {
actualNoTrashDungeonKeys.add(dungeon.id);
if (!noTrashExceptions.has(dungeon.id)) dungeonIssues.push("has no trash mobs.");
}
if (!(dungeon.staticSpawns?.length || dungeon.roamingPacks?.length || dungeon.encounterSpawnGroups?.some((group) => group.spawns?.length))) {
dungeonIssues.push("has no combat spawns.");
}
for (const spawn of dungeon.staticSpawns ?? []) {
if (!dungeon.entities?.[spawn.entityId]) {
@@ -201,6 +204,13 @@ for (const dungeon of definitions) {
}
}
}
for (const group of dungeon.encounterSpawnGroups ?? []) {
for (const spawn of group.spawns ?? []) {
if (!dungeon.entities?.[spawn.entityId]) {
dungeonIssues.push("encounter group " + group.id + " references missing entity " + spawn.entityId + ".");
}
}
}
for (const [entityId, entity] of entities) {
const entityAttacks = entity.combat?.attacks ?? [];
@@ -209,8 +219,9 @@ for (const dungeon of definitions) {
attacks += entityAttacks.length;
const specials = entityAttacks.filter((attack) => attack.id !== "basic-attack");
specialAttacks += specials.length;
if (entity.kind === "boss" && !specials.length && !optionalBossEntityIds.has(entityId)) {
if (entity.kind === "boss" && !specials.length) {
const exceptionKey = dungeon.id + ":" + entityId;
actualBasicOnlyBossKeys.add(exceptionKey);
if (!basicOnlyBossExceptions.has(exceptionKey)) {
dungeonIssues.push(entityId + " has no boss mechanic beyond its basic attack.");
}
@@ -247,6 +258,17 @@ for (const dungeon of definitions) {
});
}
for (const key of basicOnlyBossExceptions.keys()) {
if (!actualBasicOnlyBossKeys.has(key)) {
issues.push("Stale basic-only boss exception does not match a runtime boss: " + key + ".");
}
}
for (const key of noTrashExceptions.keys()) {
if (!actualNoTrashDungeonKeys.has(key)) {
issues.push("Stale no-trash exception does not match a runtime dungeon: " + key + ".");
}
}
for (const [url, users] of modelUsers) {
try {
const names = await readGlbAnimationNames(url);
File diff suppressed because it is too large. Load diff
@@ -10,6 +10,11 @@ const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "
const recipesRoot = path.join(projectRoot, "dungeon-pipeline", "recipes");
const workRoot = path.resolve(process.env.DUNGEON_PIPELINE_WORK ?? path.join(projectRoot, "..", "HealerMan-Storage", "pipeline-work", "dungeons"));
const outputFile = path.join(projectRoot, "src", "game", "generated", "dungeonCampaignCatalog.json");
const gameObjectAssetManifestFile = path.join(
projectRoot,
"dungeon-pipeline",
"WOW_GAMEOBJECT_ASSET_MANIFEST.json",
);
const compressedOutputFile = path.join(
projectRoot,
"src",
@@ -81,6 +86,19 @@ const epochSpellDbc = path.join(
"DBFilesClient",
"Spell.dbc",
);
const standardGameObjectDisplayDbc = path.join(
workRoot,
"deadmines",
"client-dbc",
"DBFilesClient",
"GameObjectDisplayInfo.dbc",
);
const epochGameObjectDisplayDbc = path.join(
workRoot,
"epoch-client",
"DBFilesClient",
"GameObjectDisplayInfo.dbc",
);
const WAILING_SERVER_ENCOUNTERS = Object.freeze([
[3671, "Lady Anacondra"],
@@ -200,6 +218,100 @@ function slugPart(value) {
.replace(/^-|-$/g, "") || "unknown";
}
function compileBossProgressionEncounter(recipe, bosses, syntheticTrash) {
const runtimeBosses = bosses.filter((boss) => !boss.eventOnly);
const requiredBosses = runtimeBosses.filter((boss) => !boss.optional);
const rules = runtimeBosses.map((boss, index) => ({
id: `boss-${index + 1}-defeated`,
trigger: { kind: "entities-dead", entityIds: [boss.id] },
actions: [
{
id: `record-boss-${index + 1}`,
kind: "complete-objective",
objectiveId: boss.id,
persistence: "run",
},
...(!boss.optional ? [{
id: `checkpoint-boss-${index + 1}`,
kind: "set-checkpoint",
checkpointId: boss.id,
persistence: "checkpoint",
}] : []),
],
}));
const finalBoss = requiredBosses.at(-1);
// Event-only objectives belong to detailed instance orchestration. A
// baseline must not declare the dungeon complete before that event fires.
if (finalBoss && !bosses.some((boss) => boss.eventOnly)) {
rules.push({
id: "all-required-bosses-defeated",
// Re-evaluate persisted objectives independently of kill order. Tying
// completion to the catalog's final actor can strand a run when players
// defeat that actor early and finish another required boss afterward.
trigger: { kind: "tick" },
guards: requiredBosses.map((boss) => ({
kind: "objective-complete",
objectiveId: boss.id,
equals: true,
})),
actions: [
{
id: "mark-dungeon-complete",
kind: "set-flag",
flagId: "dungeon-complete",
value: true,
persistence: "run",
},
{
id: "enter-complete-phase",
kind: "set-phase",
phase: "complete",
persistence: "run",
},
],
});
}
const sourceBacked = !syntheticTrash;
return {
id: `${recipe.slug}:boss-progression`,
dungeonId: recipe.slug,
initialPhase: "progression",
initialState: { flags: { "dungeon-complete": false } },
resetPolicy: { bossWipePhase: "progression", checkpointPhase: "progression" },
source: {
fidelity: sourceBacked ? "source-backed-adapted" : "healer-man-authored",
scope: "boss-progression",
files: sourceBacked
? [
`dungeon-pipeline/work/${recipe.slug}/runtime-draft.json`,
"src/game/generated/azerothCoreScriptSpells.json",
"src/game/generated/azerothCoreWorldAi.json",
]
: [
`dungeon-pipeline/recipes/${recipe.slug}.json`,
"src/game/generated/manastormRuntimeCatalog.json",
],
reviewedBehavior: sourceBacked
? "Live source-backed boss runtime IDs record persistent objective completion and stable post-boss checkpoints; all required non-event bosses complete the baseline run."
: "Catalog boss identities record persistent objective completion and stable post-boss checkpoints; all required bosses complete the authored fallback run.",
adaptations: [
"Boss progression is intentionally order-independent unless a detailed encounter definition supplies an explicit gate.",
"Optional rare bosses record completion when present but do not gate the final completion state.",
"A checkpoint retains completed objectives and resets temporary combat state; it does not invent a source graveyard or teleport.",
],
remainingGaps: [
...(sourceBacked ? [] : [
"Replace the authored fallback with authoritative Ascension population and instance-script data when those sources become available.",
]),
"Port exact instance-script doors, waves, escorts, vehicles, dialogue, gossip, quests, area triggers, and event-only bosses where the source requires them.",
"Enable source game-object visuals, collision, and state transitions only after their client models and script bindings are reviewed.",
"Record an end-to-end traversal, wipe/reset, checkpoint reload, HUD, collision, and completion playtest before marking the dungeon validated.",
],
},
rules,
};
}
function inferEnvironmentMode(recipe, assetPackage) {
if (recipe.environmentMode !== "detect") return recipe.environmentMode;
const sourceFiles = assetPackage.visual.flatMap((chunk) => chunk.provenance?.sourceFiles ?? []);
@@ -214,6 +326,395 @@ const ADT_SOURCE_BASES = new Set([
]);
const GLOBAL_WMO_SOURCE_BASES = new Set(["draft", "flip-x"]);
const COORDINATE_ALIGNMENTS = new Set(["player-anchor", "source", "source-transform"]);
const SOURCE_GAME_OBJECT_TYPES = new Set(Array.from({ length: 36 }, (_, type) => type));
function rowValue(row, names, fallback = undefined) {
for (const name of names) {
if (row?.[name] !== undefined && row[name] !== null) return row[name];
}
return fallback;
}
function finiteNumber(value, fallback = 0) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : fallback;
}
function clamp(value, minimum, maximum) {
return Math.min(maximum, Math.max(minimum, value));
}
function sourceGameObjectPosition(row) {
const wowX = finiteNumber(rowValue(row, ["position_x", "positionX", "x"]));
const wowY = finiteNumber(rowValue(row, ["position_y", "positionY", "y"]));
const wowZ = finiteNumber(rowValue(row, ["position_z", "positionZ", "z"]));
return [-wowX, wowZ, wowY];
}
function sourceGameObjectKind(type, name) {
const normalized = normalizedName(name);
if (type === 0 || type === 35) {
if (normalized.includes("bridge") || normalized.includes("drawbridge")) return "bridge";
if (normalized.includes("gate") || normalized.includes("portcullis")) return "gate";
return "door";
}
if (type === 1 || type === 31) return "switch";
if (type === 2 || type === 10 || type === 23) return "quest-object";
if (type === 3) return /vein|deposit|herb|plant|school|node/i.test(name) ? "resource" : "chest";
if (type === 5) return "generic";
if (type === 6 || type === 12) return "trap";
if (type === 7 || type === 32) return "chair";
if (type === 8) return "spell-focus";
if (type === 9) return "text";
if (type === 11 || type === 15) return "transport";
if (type === 13) return "camera";
if (type === 18) return "ritual";
if (type === 19) return "mailbox";
if (type === 22) return "spellcaster";
if (type === 25) return "fishing-hole";
if (type === 33) return "destructible";
return type === 30 ? "aura-generator" : "generic";
}
function sourceGameObjectHalfExtents(kind, sourceSize) {
const size = clamp(finiteNumber(sourceSize, 1), 0.1, 6);
if (kind === "door" || kind === "gate") return vector([1.25 * size, 2 * size, 0.2 * size]);
if (kind === "bridge") return vector([2.5 * size, 0.2 * size, 1.25 * size]);
if (kind === "switch") return vector([0.35 * size, 0.5 * size, 0.35 * size]);
if (kind === "chest" || kind === "resource") return vector([0.6 * size, 0.45 * size, 0.45 * size]);
if (kind === "trap" || kind === "trigger") return vector([0.8 * size, 0.1 * size, 0.8 * size]);
if (kind === "transport") return vector([2 * size, 0.25 * size, 2 * size]);
if (kind === "destructible") return vector([1.5 * size, 1.5 * size, 1.5 * size]);
return vector([0.45 * size, 0.65 * size, 0.45 * size]);
}
function clientGameObjectHalfExtents(display, sourceSize) {
if (!display?.bounds) return null;
const size = clamp(finiteNumber(sourceSize, 1), 0.01, 100);
const spans = display.bounds.max.map((value, axis) => value - display.bounds.min[axis]);
if (!spans.every((value) => Number.isFinite(value) && value > 0 && value <= 1_000)) return null;
// Client bounds are x/y/z. Runtime draft space is -x/z/y.
return vector([
clamp(spans[0] * size / 2, 0.025, 500),
clamp(spans[2] * size / 2, 0.025, 500),
clamp(spans[1] * size / 2, 0.025, 500),
]);
}
function parseGameObjectDisplays(buffer) {
if (!buffer || buffer.toString("ascii", 0, 4) !== "WDBC") return new Map();
const recordCount = buffer.readUInt32LE(4);
const fieldCount = buffer.readUInt32LE(8);
const recordSize = buffer.readUInt32LE(12);
const stringSize = buffer.readUInt32LE(16);
if (fieldCount !== 19 || recordSize !== fieldCount * 4) return new Map();
const stringsOffset = 20 + recordCount * recordSize;
const readString = (offset) => {
if (!offset || offset >= stringSize) return "";
const start = stringsOffset + offset;
const end = buffer.indexOf(0, start);
return buffer.toString("utf8", start, end < 0 ? buffer.length : end);
};
const displays = new Map();
for (let index = 0; index < recordCount; index += 1) {
const base = 20 + index * recordSize;
const id = buffer.readUInt32LE(base);
const modelPath = readString(buffer.readUInt32LE(base + 4)).replace(/\\/g, "/");
const min = [12, 13, 14].map((field) => rounded(buffer.readFloatLE(base + field * 4)));
const max = [15, 16, 17].map((field) => rounded(buffer.readFloatLE(base + field * 4)));
displays.set(id, {
id,
modelPath,
bounds: { min, max },
});
}
return displays;
}
function sourceGameObjectStates(kind) {
if (kind === "door" || kind === "gate" || kind === "bridge") {
return [
// Adapted source objects remain non-blocking until an instance-script
// transition has been reviewed; otherwise a closed door with no opener
// would turn an incomplete import into an unavoidable soft lock.
{ id: "closed", label: "Closed", visible: true, blocksMovement: false, blocksSight: false },
{ id: "open", label: "Open", visible: false, blocksMovement: false, blocksSight: false },
];
}
if (kind === "trap") {
return [
{ id: "armed", label: "Armed", visible: true, blocksMovement: false, interactionEnabled: false },
{ id: "disabled", label: "Disabled", visible: false, blocksMovement: false, interactionEnabled: false },
];
}
if (kind === "transport") {
return [
{ id: "stationary", label: "Stationary", visible: true, blocksMovement: false, interactionEnabled: false },
{ id: "moving", label: "Moving", visible: true, blocksMovement: false, interactionEnabled: false },
];
}
if (kind === "destructible") {
return [
{ id: "intact", label: "Intact", visible: true, blocksMovement: false, blocksSight: false },
{ id: "destroyed", label: "Destroyed", visible: false, blocksMovement: false, blocksSight: false },
];
}
return [
{ id: "available", label: "Available", visible: true, blocksMovement: false, interactionEnabled: false },
{ id: "inactive", label: "Inactive", visible: false, blocksMovement: false, interactionEnabled: false },
];
}
function sourceGameObjectInitialState(kind, row) {
const sourceState = finiteNumber(rowValue(row, ["state", "State"]), 1);
if (kind === "door" || kind === "gate" || kind === "bridge") return sourceState === 0 ? "open" : "closed";
if (kind === "trap") return sourceState === 0 ? "disabled" : "armed";
if (kind === "transport") return sourceState === 0 ? "moving" : "stationary";
if (kind === "destructible") return sourceState === 2 ? "destroyed" : "intact";
return sourceState === 0 ? "inactive" : "available";
}
function sourceGameObjectVisual(kind) {
const colors = {
door: "#5f4932",
gate: "#4d4a46",
bridge: "#66543c",
switch: "#c38d35",
chest: "#8f682f",
resource: "#54704b",
trap: "#713b36",
transport: "#53616b",
camera: "#475f78",
ritual: "#74518f",
spellcaster: "#496e87",
"spell-focus": "#5f698d",
"aura-generator": "#586f80",
destructible: "#6b5849",
"quest-object": "#8a773b",
generic: "#65584b",
chair: "#725942",
text: "#806c48",
mailbox: "#596778",
"fishing-hole": "#3d6878",
trigger: "#58606a",
};
return { hidden: true, color: colors[kind] ?? "#65584b" };
}
function compileSourceGameObjects(draft, mapPosition, recipe, gameObjectDisplays) {
const templates = new Map((draft?.gameObjectTemplates ?? []).map((template) => [
finiteNumber(rowValue(template, ["entry", "id"]), -1),
template,
]));
return (draft?.gameObjects ?? [])
.map((row, index) => {
const templateId = finiteNumber(rowValue(row, ["id", "entry"]), -1);
const template = templates.get(templateId);
const type = finiteNumber(rowValue(template, ["type", "Type"]), -1);
if (!template || !SOURCE_GAME_OBJECT_TYPES.has(type)) return null;
const spawnId = finiteNumber(rowValue(row, ["guid", "spawnId"]), index + 1);
const name = String(rowValue(template, ["name", "Name"], `Game object ${templateId}`)).trim()
|| `Game object ${templateId}`;
const kind = sourceGameObjectKind(type, name);
const displayId = finiteNumber(rowValue(template, ["displayId", "displayID", "DisplayID"]), 0);
const display = gameObjectDisplays.get(displayId);
const sourceSize = rowValue(template, ["size", "Size"], 1);
const clientHalfExtents = clientGameObjectHalfExtents(display, sourceSize);
return {
id: `gameobject-${spawnId}`,
name,
kind,
position: mapPosition(sourceGameObjectPosition(row)),
yaw: rounded(-finiteNumber(rowValue(row, ["orientation", "yaw"]))),
halfExtents: clientHalfExtents ?? sourceGameObjectHalfExtents(kind, sourceSize),
initialState: sourceGameObjectInitialState(kind, row),
states: sourceGameObjectStates(kind),
visual: sourceGameObjectVisual(kind),
source: {
fidelity: "source-backed-adapted",
files: [
`dungeon-pipeline/work/${recipe.slug}/source-snapshot.json`,
`dungeon-pipeline/work/${recipe.slug}/runtime-draft.json`,
],
templateId,
spawnId,
gameObjectType: type,
...(displayId > 0 ? { clientDisplayId: displayId } : {}),
...(display?.modelPath ? { clientModelPath: display.modelPath } : {}),
...(clientHalfExtents ? { clientBounds: display.bounds } : {}),
note: clientHalfExtents
? "Source transform/state and exact client display bounds/model path are preserved. Visual assets and collision remain hidden until the model export and instance-script transition are reviewed; interactions remain disabled until ported."
: "Source position, orientation, type, initial state, and template scale are preserved. Visuals and collision remain hidden until client-display bounds/models are reviewed; encounter-script interactions remain disabled until ported.",
},
};
})
.filter(Boolean)
.sort((left, right) => left.id.localeCompare(right.id, undefined, { numeric: true }));
}
function increment(map, key, amount = 1) {
map.set(key, (map.get(key) ?? 0) + amount);
}
function sortedCountEntries(map, keyName) {
return [...map.entries()]
.sort(([left], [right]) => String(left).localeCompare(String(right), undefined, { numeric: true }))
.map(([key, instances]) => ({ [keyName]: key, instances }));
}
function gameObjectAssetManifestFor(definitions) {
const assets = new Map();
const nonVisualObjects = new Map();
const unresolvedModels = new Map();
const unresolvedBounds = new Map();
let typedInstances = 0;
let visualDisplayInstances = 0;
let resolvedModelInstances = 0;
let boundedInstances = 0;
for (const dungeon of definitions) {
for (const object of dungeon.serverGameObjects ?? []) {
if (object.source?.fidelity !== "source-backed-adapted") continue;
typedInstances += 1;
const displayId = Number(object.source.clientDisplayId);
const modelPath = String(object.source.clientModelPath ?? "").replace(/\\/g, "/");
const hasBounds = Boolean(object.source.clientBounds);
if (!Number.isFinite(displayId) || displayId <= 0) {
const templateId = Number(object.source.templateId) || 0;
let nonVisual = nonVisualObjects.get(templateId);
if (!nonVisual) {
nonVisual = {
templateId,
instances: 0,
dungeons: new Map(),
kinds: new Map(),
};
nonVisualObjects.set(templateId, nonVisual);
}
nonVisual.instances += 1;
increment(nonVisual.dungeons, dungeon.id);
increment(nonVisual.kinds, object.kind);
continue;
}
visualDisplayInstances += 1;
if (hasBounds) boundedInstances += 1;
if (!modelPath) {
const key = displayId;
let unresolved = unresolvedModels.get(key);
if (!unresolved) {
unresolved = {
displayId: key,
instances: 0,
dungeons: new Map(),
kinds: new Map(),
templateIds: new Set(),
};
unresolvedModels.set(key, unresolved);
}
unresolved.instances += 1;
increment(unresolved.dungeons, dungeon.id);
increment(unresolved.kinds, object.kind);
if (object.source.templateId) unresolved.templateIds.add(object.source.templateId);
} else {
resolvedModelInstances += 1;
const key = modelPath.toLowerCase();
let asset = assets.get(key);
if (!asset) {
const extension = path.extname(modelPath).toLowerCase().replace(/^\./, "") || "unknown";
const targetPath = modelPath.replace(/\.[^/.]+$/, ".glb");
asset = {
sourceModelPath: modelPath,
sourceType: extension,
targetUrl: `/assets/game/world-objects/${targetPath}`,
instances: 0,
boundedInstances: 0,
displayIds: new Set(),
dungeons: new Map(),
kinds: new Map(),
};
assets.set(key, asset);
}
asset.instances += 1;
if (hasBounds) asset.boundedInstances += 1;
asset.displayIds.add(displayId);
increment(asset.dungeons, dungeon.id);
increment(asset.kinds, object.kind);
}
if (!hasBounds) {
const key = displayId;
let unresolved = unresolvedBounds.get(key);
if (!unresolved) {
unresolved = {
displayId: key,
modelPath: modelPath || undefined,
instances: 0,
dungeons: new Map(),
kinds: new Map(),
templateIds: new Set(),
};
unresolvedBounds.set(key, unresolved);
}
unresolved.instances += 1;
increment(unresolved.dungeons, dungeon.id);
increment(unresolved.kinds, object.kind);
if (object.source.templateId) unresolved.templateIds.add(object.source.templateId);
}
}
}
const serializeUnresolved = (entry) => ({
displayId: entry.displayId,
...(entry.modelPath ? { modelPath: entry.modelPath } : {}),
instances: entry.instances,
templateIds: [...entry.templateIds].sort((left, right) => left - right),
dungeons: sortedCountEntries(entry.dungeons, "dungeonId"),
kinds: sortedCountEntries(entry.kinds, "kind"),
});
return {
schemaVersion: 1,
generatedBy: "scripts/dungeon-pipeline/compile-campaign-catalog.mjs",
summary: {
typedInstances,
visualDisplayInstances,
nonVisualInstances: typedInstances - visualDisplayInstances,
resolvedModelInstances,
boundedInstances,
uniqueAssets: assets.size,
unresolvedModelInstances: visualDisplayInstances - resolvedModelInstances,
unresolvedBoundInstances: visualDisplayInstances - boundedInstances,
unresolvedModelDisplayIds: unresolvedModels.size,
unresolvedBoundDisplayIds: unresolvedBounds.size,
},
assets: [...assets.values()]
.sort((left, right) => left.sourceModelPath.localeCompare(right.sourceModelPath))
.map((asset) => ({
sourceModelPath: asset.sourceModelPath,
sourceType: asset.sourceType,
targetUrl: asset.targetUrl,
instances: asset.instances,
boundedInstances: asset.boundedInstances,
displayIds: [...asset.displayIds].sort((left, right) => left - right),
dungeons: sortedCountEntries(asset.dungeons, "dungeonId"),
kinds: sortedCountEntries(asset.kinds, "kind"),
})),
nonVisualObjects: [...nonVisualObjects.values()]
.sort((left, right) => left.templateId - right.templateId)
.map((entry) => ({
templateId: entry.templateId,
instances: entry.instances,
dungeons: sortedCountEntries(entry.dungeons, "dungeonId"),
kinds: sortedCountEntries(entry.kinds, "kind"),
})),
unresolvedModels: [...unresolvedModels.values()]
.sort((left, right) => left.displayId - right.displayId)
.map(serializeUnresolved),
unresolvedBounds: [...unresolvedBounds.values()]
.sort((left, right) => left.displayId - right.displayId)
.map(serializeUnresolved),
};
}
function sourceBasisFor(recipe, environmentMode) {
if (environmentMode !== "adt-hybrid") {
@@ -371,13 +872,44 @@ function uniqueDraftEncounters(encounterRows, mapId) {
...(resolvedEntry > 0 ? {} : { syntheticGroupEncounter: true }),
};
const key = `${creatureId}:${normalizedName(encounter.name)}`;
if (!byIdentity.has(key)) byIdentity.set(key, encounter);
const previous = byIdentity.get(key);
if (!previous) {
byIdentity.set(key, encounter);
continue;
}
byIdentity.set(key, {
...previous,
modeIds: [...new Set([...previous.modeIds, ...encounter.modeIds])].sort((left, right) => left - right),
sourceRowIds: [...new Set([
...(previous.sourceRowIds ?? []),
...(encounter.sourceRowIds ?? []),
])].sort((left, right) => left - right),
orderIndex: Math.min(previous.orderIndex, encounter.orderIndex),
});
}
return [...byIdentity.values()].sort((left, right) => (
left.orderIndex - right.orderIndex || left.encounterId - right.encounterId
));
}
function encounterSpawnMask(recipe, encounter, candidate) {
const declaredMask = recipe.difficultyVariants.reduce(
(mask, difficulty) => mask | Number(difficulty.spawnMask ?? 0),
0,
);
const candidateMask = Number(candidate?.spawnMask ?? 0) & declaredMask;
if (candidateMask > 0) return candidateMask;
const modeIds = new Set((encounter.modeIds ?? []).map(Number));
const rowMask = recipe.difficultyVariants.reduce((mask, difficulty) => (
difficulty.mapDifficultyId !== undefined
&& modeIds.has(Number(difficulty.mapDifficultyId))
? mask | Number(difficulty.spawnMask ?? 0)
: mask
), 0);
return rowMask || declaredMask || 1;
}
function archetypeFor(name) {
const value = normalizedName(name);
if (/murloc|murk|glub|fin/.test(value)) return "murloc";
@@ -1032,6 +1564,12 @@ async function compile() {
const epochSpells = await exists(epochSpellDbc)
? parseSpells(await readFile(epochSpellDbc), wantedSpellIds)
: ascensionSpells;
const standardGameObjectDisplays = await exists(standardGameObjectDisplayDbc)
? parseGameObjectDisplays(await readFile(standardGameObjectDisplayDbc))
: new Map();
const epochGameObjectDisplays = await exists(epochGameObjectDisplayDbc)
? parseGameObjectDisplays(await readFile(epochGameObjectDisplayDbc))
: standardGameObjectDisplays;
const previousOutput = await exists(outputFile)
? await readJson(outputFile)
@@ -1103,6 +1641,14 @@ async function compile() {
?? draft?.spawns?.[0]?.position
?? playerAnchor.position,
);
const serverGameObjects = compileSourceGameObjects(
draft,
mapPosition,
recipe,
recipe.clientBuild === "3.3.5a-Epoch"
? epochGameObjectDisplays
: standardGameObjectDisplays,
);
const sourceEntities = (draft?.entities ?? [])
.filter((entity) => (
!(recipe.slug === "wailing-caverns" && Number(entity.entry) === 5912)
@@ -1230,6 +1776,11 @@ async function compile() {
const usedBossSpawnIds = new Set();
const bossObjectives = encounters.map((encounter, index) => {
const candidate = bossCandidatesByEntry.get(Number(encounter.creatureId));
const spawnMask = encounterSpawnMask(recipe, encounter, candidate);
const declaredDifficultyMask = recipe.difficultyVariants.reduce(
(mask, difficulty) => mask | Number(difficulty.spawnMask ?? 0),
0,
);
const alpha = encounters.length <= 1 ? 1 : index / (encounters.length - 1);
const routeAlpha = 0.18 + alpha * 0.82;
const nativeRoutePosition = nativeRoutePositions.length
@@ -1253,7 +1804,10 @@ async function compile() {
name: encounter.name,
position,
yaw: candidate?.yaw ?? 0,
...(spawnChance < 1 ? { optional: true } : {}),
spawnMask,
...(spawnChance < 1 || (spawnMask & declaredDifficultyMask) !== declaredDifficultyMask
? { optional: true }
: {}),
...(encounter.eventOnly ? { eventOnly: true } : {}),
};
});
@@ -1313,7 +1867,7 @@ async function compile() {
entityId: boss.entityId,
position: boss.position,
yaw: boss.yaw,
spawnMask: 1,
spawnMask: boss.spawnMask,
});
}
@@ -1426,7 +1980,8 @@ async function compile() {
bosses,
objectiveOrder: bosses,
navigationLinks: [],
serverGameObjects: draft?.gameObjects ?? [],
encounters: [compileBossProgressionEncounter(recipe, bosses, syntheticTrash)],
serverGameObjects,
provenance: {
clientBuild: recipe.clientBuild,
coordinateAlignment,
@@ -1490,7 +2045,13 @@ async function compile() {
};
const serialized = JSON.stringify(output);
const compressed = gzipSync(Buffer.from(serialized), { level: 9 });
const gameObjectAssetManifest = gameObjectAssetManifestFor(definitions);
await writeFile(outputFile, `${serialized}\n`, "utf8");
await writeFile(
gameObjectAssetManifestFile,
`${JSON.stringify(gameObjectAssetManifest, null, 2)}\n`,
"utf8",
);
await writeFile(
compressedOutputFile,
`// Generated by npm run dungeon:catalog. Do not edit.\nexport default "${compressed.toString("base64")}";\n`,
@@ -1517,6 +2078,7 @@ async function compile() {
status: "complete",
output: path.relative(projectRoot, outputFile).replace(/\\/g, "/"),
compressedOutput: path.relative(projectRoot, compressedOutputFile).replace(/\\/g, "/"),
gameObjectAssetManifest: path.relative(projectRoot, gameObjectAssetManifestFile).replace(/\\/g, "/"),
compressedBytes: compressed.length,
dungeons: definitions.length,
encounters: coverage.reduce((total, row) => total + row.encounters, 0),
@@ -1525,6 +2087,11 @@ async function compile() {
roamingPacks: coverage.reduce((total, row) => total + row.roamingPacks, 0),
authoritativeDungeons: coverage.filter((row) => row.source === "azerothcore").length,
fallbackDungeons: coverage.filter((row) => row.source === "procedural-fallback").length,
gameObjectInstances: gameObjectAssetManifest.summary.typedInstances,
nonVisualGameObjectInstances: gameObjectAssetManifest.summary.nonVisualInstances,
gameObjectAssets: gameObjectAssetManifest.summary.uniqueAssets,
unresolvedGameObjectModelInstances: gameObjectAssetManifest.summary.unresolvedModelInstances,
unresolvedGameObjectBoundInstances: gameObjectAssetManifest.summary.unresolvedBoundInstances,
}, null, 2));
}
+25 -23
View File
@@ -1,4 +1,4 @@
import { spawn } from "node:child_process";
import { stat } from "node:fs/promises";
import path from "node:path";
import {
clientRootForRecipe,
@@ -10,24 +10,21 @@ import {
recipesRoot,
workRoot,
} from "./lib.mjs";
import { runWowExporter } from "./wow-export-tool.mjs";
async function runExporter(argumentsList) {
const executable = path.resolve(projectRoot, "../wow335a/dungeon-export-work/tools/wow.export-0.2.19/wow.export.exe");
if (!await exists(executable)) throw new Error("The patched portable wow.export executable was not found.");
await new Promise((resolve, reject) => {
const child = spawn(executable, ["--disable-auto-update", ...argumentsList], {
cwd: path.dirname(executable),
stdio: "inherit",
windowsHide: true,
});
child.once("error", reject);
child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`wow.export exited with code ${code}.`)));
});
async function resultMtime(output) {
const resultFile = path.join(output, "automation-result.json");
return await exists(resultFile) ? (await stat(resultFile)).mtimeMs : 0;
}
async function checkedResult(slug, output) {
async function checkedResult(slug, output, previousMtime) {
const resultFile = path.join(output, "automation-result.json");
if (!await exists(resultFile)) return { status: "blocked", dungeonId: slug, blockers: ["wow.export produced no automation-result.json."] };
if (!await exists(resultFile)) return { status: "blocked", dungeonId: slug, blockers: [`wow.export produced no automation result at ${resultFile}.`] };
if ((await stat(resultFile)).mtimeMs <= previousMtime) return {
status: "blocked",
dungeonId: slug,
blockers: [`wow.export did not refresh ${resultFile}; refusing to accept a stale result from an earlier run.`],
};
const result = await readJson(resultFile);
if (!result.ok) return {
status: "blocked",
@@ -43,13 +40,14 @@ export async function exportDungeonSource(slug) {
const recipe = await loadRecipe(slug);
const clientRoot = clientRootForRecipe(recipe);
const output = path.join(workRoot, slug, "source-export");
await runExporter([
const previousMtime = await resultMtime(output);
await runWowExporter([
"--export-dungeon",
"--recipe", path.join(recipesRoot, `${slug}.json`),
"--client-root", clientRoot,
"--output", output,
]);
const blocked = await checkedResult(slug, output);
], { projectRoot });
const blocked = await checkedResult(slug, output, previousMtime);
if (blocked) return blocked;
return { status: "green", dungeonId: slug, output: path.relative(projectRoot, output).replace(/\\/g, "/") };
}
@@ -58,12 +56,15 @@ export async function exportClientDiscoveryTables(slug) {
const recipe = await loadRecipe(slug);
const clientRoot = clientRootForRecipe(recipe);
const output = path.join(workRoot, slug, "client-dbc");
await runExporter([
const previousMtime = await resultMtime(output);
await runWowExporter([
"--discover-dungeon",
"--recipe", path.join(recipesRoot, `${slug}.json`),
"--client-root", clientRoot,
"--output", output,
]);
], { projectRoot });
const blocked = await checkedResult(slug, output, previousMtime);
if (blocked) throw new Error(blocked.blockers.join("\n"));
return output;
}
@@ -88,13 +89,14 @@ export async function exportCreatureSource(slug) {
blockers: unresolved.map((creature) => `${creature.name ?? creature.slug} has an unresolved display/composite recipe.`),
};
const output = path.join(workRoot, slug, "creature-source");
await runExporter([
const previousMtime = await resultMtime(output);
await runWowExporter([
"--export-creatures",
"--recipe", selected,
"--client-root", clientRoot,
"--output", output,
]);
const blocked = await checkedResult(slug, output);
], { projectRoot });
const blocked = await checkedResult(slug, output, previousMtime);
if (blocked) return blocked;
return { status: "green", dungeonId: slug, output: path.relative(projectRoot, output).replace(/\\/g, "/") };
}
@@ -45,6 +45,9 @@ function runNpm(script, argumentsList = []) {
async function main() {
if (options.has("--audit-only")) {
await runNpm("dungeon:wow:audit");
await runNpm("dungeon:wow:functionality:audit");
await runNpm("dungeon:ascension:recovery:validate");
await runNpm("dungeon:wow:export-tool:test");
await runNpm("dungeon:wow:test");
return;
}
@@ -63,8 +66,11 @@ async function main() {
await runNpm("dungeon:catalog");
await runNpm("dungeon:five-player:verify");
await runNpm("dungeon:wow:audit");
await runNpm("dungeon:wow:functionality:audit");
await runNpm("dungeon:ascension:recovery:validate");
await runNpm("dungeon:wow:export-tool:test");
await runNpm("dungeon:wow:test");
if (options.has("--build")) await runNpm("build");
}
await main();
await main();
@@ -0,0 +1,300 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(scriptDirectory, "..", "..");
const manifestPath = path.join(
projectRoot,
"dungeon-pipeline",
"ascension",
"ASCENSION_CUSTOM_DUNGEON_RECOVERY.json",
);
function fail(message) {
throw new Error(message);
}
function assert(condition, message) {
if (!condition) {
fail(message);
}
}
function assertDeepEqual(actual, expected, message) {
assert(JSON.stringify(actual) === JSON.stringify(expected), message);
}
async function readJson(relativePath) {
const contents = await readFile(path.join(projectRoot, relativePath), "utf8");
return JSON.parse(contents);
}
function resolveDbcPath(manifest) {
const dbcArgumentIndex = process.argv.indexOf("--dbc");
if (dbcArgumentIndex !== -1) {
const value = process.argv[dbcArgumentIndex + 1];
assert(value, "--dbc requires a path");
return path.resolve(process.cwd(), value);
}
if (process.env.ASCENSION_SPELL_DBC) {
return path.resolve(process.env.ASCENSION_SPELL_DBC);
}
const source = manifest.sources.find(
(candidate) => candidate.id === "ascension-area52-spell-dbc",
);
assert(source?.pathHint, "Spell.dbc source path is missing from the manifest");
return path.resolve(projectRoot, source.pathHint);
}
function readCString(buffer, offset) {
const end = buffer.indexOf(0, offset);
assert(end !== -1, `Unterminated DBC string at byte ${offset}`);
return buffer.toString("utf8", offset, end);
}
async function validateSpellDbc(manifest) {
if (process.argv.includes("--skip-dbc")) {
return { skipped: true, reason: "requested with --skip-dbc" };
}
const source = manifest.sources.find(
(candidate) => candidate.id === "ascension-area52-spell-dbc",
);
assert(source, "Spell.dbc source metadata is missing");
const dbcPath = resolveDbcPath(manifest);
let buffer;
try {
buffer = await readFile(dbcPath);
} catch (error) {
if (error?.code === "ENOENT") {
return { skipped: true, reason: `not installed at ${dbcPath}` };
}
throw error;
}
const digest = createHash("sha256").update(buffer).digest("hex");
assert(digest === source.sha256, `Spell.dbc SHA-256 mismatch: ${digest}`);
const header = {
signature: buffer.toString("ascii", 0, 4),
recordCount: buffer.readUInt32LE(4),
fieldCount: buffer.readUInt32LE(8),
recordSize: buffer.readUInt32LE(12),
stringBlockSize: buffer.readUInt32LE(16),
};
assertDeepEqual(header, source.header, "Spell.dbc header does not match the manifest");
const expectedNames = new Map();
const summonLinks = new Map();
for (const dungeon of manifest.dungeons) {
for (const [spellId, name] of Object.entries(dungeon.sourceRecovery.spellRows)) {
expectedNames.set(Number(spellId), name);
}
for (const link of dungeon.sourceRecovery.summonLinks ?? []) {
const links = summonLinks.get(link.spellId) ?? [];
links.push({ ...link, mapId: dungeon.mapId });
summonLinks.set(link.spellId, links);
}
}
const recordStart = 20;
const stringStart = recordStart + header.recordCount * header.recordSize;
const expectedLength = stringStart + header.stringBlockSize;
assert(
expectedLength === buffer.length,
`Spell.dbc length mismatch: expected ${expectedLength}, got ${buffer.length}`,
);
const found = new Map();
for (let recordIndex = 0; recordIndex < header.recordCount; recordIndex += 1) {
const offset = recordStart + recordIndex * header.recordSize;
const spellId = buffer.readUInt32LE(offset);
if (!expectedNames.has(spellId)) {
continue;
}
const nameOffset = buffer.readUInt32LE(offset + 136 * 4);
found.set(spellId, {
name: readCString(buffer, stringStart + nameOffset),
offset,
});
}
for (const [spellId, expectedName] of expectedNames) {
const row = found.get(spellId);
assert(row, `Spell.dbc row ${spellId} is missing`);
assert(
row.name === expectedName,
`Spell.dbc row ${spellId} name mismatch: expected ${JSON.stringify(expectedName)}, got ${JSON.stringify(row.name)}`,
);
}
for (const [spellId, links] of summonLinks) {
const row = found.get(spellId);
assert(row, `Summon spell ${spellId} was not loaded`);
for (const link of links) {
const effectType = buffer.readUInt32LE(row.offset + (71 + link.effectIndex) * 4);
const entryId = buffer.readInt32LE(row.offset + (110 + link.effectIndex) * 4);
assert(
effectType === link.effectType,
`Map ${link.mapId} spell ${spellId} effect ${link.effectIndex} type mismatch: expected ${link.effectType}, got ${effectType}`,
);
assert(
entryId === link.entryId,
`Map ${link.mapId} spell ${spellId} effect ${link.effectIndex} entry mismatch: expected ${link.entryId}, got ${entryId}`,
);
}
}
return {
skipped: false,
path: dbcPath,
spellRows: found.size,
summonLinks: [...summonLinks.values()].flat().length,
};
}
function validateCatalogs(manifest, campaign, runtime, assets) {
assert(manifest.schemaVersion === 1, "Unsupported recovery manifest schema");
assert(manifest.status === "partial-authoritative-recovery", "Unexpected manifest status");
assertDeepEqual(
manifest.dungeons.map((dungeon) => dungeon.mapId),
[821, 908, 1781],
"Recovery manifest must contain exactly maps 821, 908, and 1781 in that order",
);
let spellRows = 0;
let summonLinks = 0;
for (const dungeon of manifest.dungeons) {
const definition = campaign.definitions.find(
(candidate) => candidate.mapId === dungeon.mapId,
);
assert(definition, `Campaign definition for map ${dungeon.mapId} is missing`);
assert(definition.id === dungeon.id, `Map ${dungeon.mapId} campaign ID drifted`);
assert(definition.title === dungeon.title, `Map ${dungeon.mapId} title drifted`);
const assetPackage = assets.packages.find(
(candidate) => candidate.mapId === dungeon.mapId,
);
assert(assetPackage, `Asset package for map ${dungeon.mapId} is missing`);
assert(
assetPackage.source.mapDirectory === dungeon.mapDirectory,
`Map ${dungeon.mapId} client map directory drifted`,
);
assert(
Object.values(assetPackage.source.checksums).includes(dungeon.environment.sourceHash),
`Map ${dungeon.mapId} source checksum drifted`,
);
for (const kind of ["player", "trash", "boss"]) {
const anchor = assetPackage.anchors.find((candidate) => candidate.kind === kind);
assert(anchor, `Map ${dungeon.mapId} ${kind} anchor is missing`);
assertDeepEqual(
anchor.position,
dungeon.environment.anchors[kind],
`Map ${dungeon.mapId} ${kind} anchor drifted`,
);
}
for (const encounter of dungeon.encounters) {
const runtimeEncounter = runtime.encounters.find(
(candidate) =>
candidate.encounterId === encounter.encounterId &&
candidate.mapIds.includes(dungeon.mapId) &&
candidate.modeIds.includes(encounter.modeId),
);
assert(
runtimeEncounter,
`Map ${dungeon.mapId} encounter ${encounter.encounterId} mode ${encounter.modeId} is missing`,
);
assert(
runtimeEncounter.name === encounter.name,
`Encounter ${encounter.encounterId} name drifted`,
);
assert(
runtimeEncounter.creatureId === encounter.creatureId,
`Encounter ${encounter.encounterId} creature ID drifted`,
);
}
const bossEntity = definition.entities[dungeon.currentRuntime.bossEntityId];
const bossCreatureId = dungeon.encounters[0].creatureId;
assert(bossEntity, `Map ${dungeon.mapId} current boss entity is missing`);
assert(
bossEntity.combat.serverEntry === bossCreatureId,
`Map ${dungeon.mapId} current boss server entry drifted`,
);
const generatedTrash = definition.staticSpawns.filter((spawn) =>
spawn.id.startsWith("generated-trash-"),
);
assert(
generatedTrash.length === dungeon.currentRuntime.proceduralTrashSpawnCount,
`Map ${dungeon.mapId} procedural trash count drifted`,
);
for (const proceduralEntity of dungeon.currentRuntime.proceduralMobEntries) {
const entity = definition.entities[proceduralEntity.entityId];
assert(entity, `Map ${dungeon.mapId} procedural entity ${proceduralEntity.entityId} is missing`);
assert(
entity.combat.serverEntry === proceduralEntity.serverEntry,
`Map ${dungeon.mapId} procedural entity ${proceduralEntity.entityId} server entry drifted`,
);
}
const rowIds = new Set(
Object.keys(dungeon.sourceRecovery.spellRows).map((spellId) => Number(spellId)),
);
spellRows += rowIds.size;
for (const [family, familyRows] of Object.entries(dungeon.sourceRecovery.families)) {
for (const spellId of familyRows) {
assert(
rowIds.has(spellId),
`Map ${dungeon.mapId} family ${family} references absent spell ${spellId}`,
);
}
}
for (const link of dungeon.sourceRecovery.summonLinks ?? []) {
summonLinks += 1;
assert(rowIds.has(link.spellId), `Map ${dungeon.mapId} summon spell ${link.spellId} is absent`);
const targetCollection = link.targetKind === "gameobject" ? dungeon.gameObjects : dungeon.entities;
assert(
targetCollection?.some((target) => target.entryId === link.entryId),
`Map ${dungeon.mapId} summon target ${link.targetKind} ${link.entryId} is absent`,
);
}
assert(
dungeon.adaptation.mustBeCustomAuthored.length > 0,
`Map ${dungeon.mapId} must explicitly list custom-authored gaps`,
);
}
return { dungeons: manifest.dungeons.length, spellRows, summonLinks };
}
const manifest = await readJson(
"dungeon-pipeline/ascension/ASCENSION_CUSTOM_DUNGEON_RECOVERY.json",
);
const campaign = await readJson("src/game/generated/dungeonCampaignCatalog.json");
const runtime = await readJson("src/game/generated/manastormRuntimeCatalog.json");
const assets = await readJson("src/game/generated/manastormAssetPackages.json");
const catalogResult = validateCatalogs(manifest, campaign, runtime, assets);
const dbcResult = await validateSpellDbc(manifest);
console.log(
`Validated ${catalogResult.dungeons} Ascension custom dungeons, ${catalogResult.spellRows} recovered spell rows, and ${catalogResult.summonLinks} summon links.`,
);
if (dbcResult.skipped) {
console.log(`Spell.dbc verification skipped: ${dbcResult.reason}.`);
} else {
console.log(
`Spell.dbc verified (${dbcResult.spellRows} rows, ${dbcResult.summonLinks} summon links): ${dbcResult.path}`,
);
}
@@ -0,0 +1,125 @@
import { spawn as spawnChild } from "node:child_process";
import { stat } from "node:fs/promises";
import path from "node:path";
export const WOW_EXPORT_AUTOMATION_VERSION = "0.2.19";
export const WOW_EXPORT_REQUIRED_FLAGS = Object.freeze([
"--disable-auto-update",
"--discover-dungeon",
"--export-dungeon",
"--export-creatures",
]);
export function defaultWowExportExecutable(projectRoot) {
return path.resolve(
projectRoot,
`../wow335a/dungeon-export-work/tools/wow.export-${WOW_EXPORT_AUTOMATION_VERSION}/wow.export.exe`,
);
}
async function inspectCandidate(file, statFile) {
try {
const info = await statFile(file);
return info.isFile()
? { usable: true, reason: null }
: { usable: false, reason: "path exists but is not a file" };
} catch (error) {
if (error?.code === "ENOENT") return { usable: false, reason: "file does not exist" };
return { usable: false, reason: `cannot inspect file (${error?.code ?? error?.message ?? "unknown error"})` };
}
}
function unavailableMessage(checks, configured) {
const checked = checks.map(({ label, file, reason }) => ` - ${label}: ${file} (${reason})`).join("\n");
const selection = configured
? "WOW_EXPORT_BIN is set, so the default location was not used. Correct or unset that variable."
: "Restore the patched portable bundle at the default location, or set WOW_EXPORT_BIN to its exact executable path.";
return [
"HealerMan's patched wow.export automation bridge is unavailable.",
`Required build: wow.export ${WOW_EXPORT_AUTOMATION_VERSION} with these automation flags: ${WOW_EXPORT_REQUIRED_FLAGS.join(", ")}.`,
"Checked:",
checked,
selection,
"A stock GUI-only wow.export executable is not a drop-in replacement unless it includes the HealerMan automation patch.",
"No export was started and no placeholder assets were created.",
].join("\n");
}
export class WowExportUnavailableError extends Error {
constructor(checks, configured) {
super(unavailableMessage(checks, configured));
this.name = "WowExportUnavailableError";
this.code = "WOW_EXPORT_AUTOMATION_UNAVAILABLE";
this.checks = checks;
this.requiredVersion = WOW_EXPORT_AUTOMATION_VERSION;
this.requiredFlags = [...WOW_EXPORT_REQUIRED_FLAGS];
}
}
export async function resolveWowExportExecutable({
projectRoot,
environment = process.env,
statFile = stat,
} = {}) {
if (!projectRoot) throw new TypeError("resolveWowExportExecutable requires projectRoot.");
const configuredValue = environment.WOW_EXPORT_BIN?.trim();
const candidates = configuredValue
? [{ label: "WOW_EXPORT_BIN", file: path.resolve(projectRoot, configuredValue) }]
: [{ label: "default portable path", file: defaultWowExportExecutable(projectRoot) }];
const checks = [];
for (const candidate of candidates) {
const inspection = await inspectCandidate(candidate.file, statFile);
if (inspection.usable) return candidate.file;
checks.push({ ...candidate, reason: inspection.reason });
}
throw new WowExportUnavailableError(checks, Boolean(configuredValue));
}
function exporterFailureMessage(executable, argumentsList, detail) {
const operation = argumentsList.find((argument) => argument.startsWith("--")) ?? "unknown operation";
return [
`wow.export automation failed during ${operation}: ${detail}`,
`Executable: ${executable}`,
`Required automation flags: ${WOW_EXPORT_REQUIRED_FLAGS.join(", ")}.`,
"Verify that WOW_EXPORT_BIN points to the HealerMan-patched build, not the stock GUI-only release.",
"No placeholder assets were created.",
].join("\n");
}
export async function runWowExporter(argumentsList, {
projectRoot,
environment = process.env,
statFile = stat,
spawn = spawnChild,
} = {}) {
const executable = await resolveWowExportExecutable({ projectRoot, environment, statFile });
await new Promise((resolve, reject) => {
const child = spawn(executable, ["--disable-auto-update", ...argumentsList], {
cwd: path.dirname(executable),
stdio: "inherit",
windowsHide: true,
});
let settled = false;
const fail = (error) => {
if (settled) return;
settled = true;
reject(error);
};
child.once("error", (error) => fail(new Error(exporterFailureMessage(
executable,
argumentsList,
`process could not start (${error?.code ?? error?.message ?? "unknown error"})`,
))));
child.once("exit", (code, signal) => {
if (settled) return;
settled = true;
if (code === 0) resolve();
else reject(new Error(exporterFailureMessage(
executable,
argumentsList,
signal ? `process exited after signal ${signal}` : `process exited with code ${code}`,
)));
});
});
return executable;
}
@@ -0,0 +1,125 @@
import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
import path from "node:path";
import test from "node:test";
import {
defaultWowExportExecutable,
resolveWowExportExecutable,
runWowExporter,
WOW_EXPORT_REQUIRED_FLAGS,
} from "./wow-export-tool.mjs";
const projectRoot = path.resolve("fixture/HealerMan");
const fileInfo = { isFile: () => true };
test("resolveWowExportExecutable uses the versioned portable path by default", async () => {
const expected = defaultWowExportExecutable(projectRoot);
const inspected = [];
const resolved = await resolveWowExportExecutable({
projectRoot,
environment: {},
statFile: async (file) => {
inspected.push(file);
return fileInfo;
},
});
assert.equal(resolved, expected);
assert.deepEqual(inspected, [expected]);
});
test("resolveWowExportExecutable honors an explicit relative WOW_EXPORT_BIN", async () => {
const expected = path.resolve(projectRoot, "tools/patched/wow.export.exe");
const resolved = await resolveWowExportExecutable({
projectRoot,
environment: { WOW_EXPORT_BIN: "tools/patched/wow.export.exe" },
statFile: async (file) => {
assert.equal(file, expected);
return fileInfo;
},
});
assert.equal(resolved, expected);
});
test("resolveWowExportExecutable rejects a directory with actionable diagnostics", async () => {
const configured = path.resolve(projectRoot, "tools/not-an-executable");
await assert.rejects(
resolveWowExportExecutable({
projectRoot,
environment: { WOW_EXPORT_BIN: configured },
statFile: async () => ({ isFile: () => false }),
}),
(error) => {
assert.equal(error.code, "WOW_EXPORT_AUTOMATION_UNAVAILABLE");
assert.match(error.message, /path exists but is not a file/);
assert.match(error.message, /Correct or unset that variable/);
assert.match(error.message, /No export was started and no placeholder assets were created/);
for (const flag of WOW_EXPORT_REQUIRED_FLAGS) assert.ok(error.message.includes(flag));
return true;
},
);
});
test("resolveWowExportExecutable reports the exact missing default path", async () => {
const expected = defaultWowExportExecutable(projectRoot);
await assert.rejects(
resolveWowExportExecutable({
projectRoot,
environment: {},
statFile: async () => {
const error = new Error("missing");
error.code = "ENOENT";
throw error;
},
}),
(error) => {
assert.ok(error.message.includes(expected));
assert.match(error.message, /set WOW_EXPORT_BIN/);
assert.match(error.message, /stock GUI-only wow\.export executable is not a drop-in replacement/);
return true;
},
);
});
test("runWowExporter supplies the non-updating automation invocation", async () => {
const executable = path.resolve(projectRoot, "tools/wow.export.exe");
let invocation;
const spawn = (file, args, options) => {
invocation = { file, args, options };
const child = new EventEmitter();
queueMicrotask(() => child.emit("exit", 0, null));
return child;
};
const result = await runWowExporter(["--export-dungeon", "--recipe", "fixture.json"], {
projectRoot,
environment: { WOW_EXPORT_BIN: executable },
statFile: async () => fileInfo,
spawn,
});
assert.equal(result, executable);
assert.deepEqual(invocation.args, ["--disable-auto-update", "--export-dungeon", "--recipe", "fixture.json"]);
assert.equal(invocation.options.cwd, path.dirname(executable));
assert.equal(invocation.options.windowsHide, true);
});
test("runWowExporter identifies an incompatible executable after a failed launch", async () => {
const executable = path.resolve(projectRoot, "tools/wow.export.exe");
const spawn = () => {
const child = new EventEmitter();
queueMicrotask(() => child.emit("exit", 2, null));
return child;
};
await assert.rejects(
runWowExporter(["--export-creatures"], {
projectRoot,
environment: { WOW_EXPORT_BIN: executable },
statFile: async () => fileInfo,
spawn,
}),
(error) => {
assert.match(error.message, /process exited with code 2/);
assert.match(error.message, /HealerMan-patched build/);
assert.match(error.message, /No placeholder assets were created/);
return true;
},
);
});
@@ -36,6 +36,9 @@ async function main() {
&& hasBasisu
&& /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "")
&& issue.message.includes("'image/ktx2'")) return false;
if (issue.code === "IMAGE_UNRECOGNIZED_FORMAT"
&& hasBasisu
&& /^\/images\/\d+$/.test(issue.pointer ?? "")) return false;
return true;
});
rows.push({
+23 -12
View File
@@ -75,6 +75,18 @@ class ReleaseVersion:
version_code: int
def full_release_checks(npm: str) -> tuple[tuple[list[str], str], ...]:
"""Commands that must succeed before a release can be staged."""
return (
([npm, "run", "content:test"], "Content tests"),
([npm, "run", "server:test"], "Server tests"),
([npm, "test"], "Application tests"),
([npm, "run", "content:publish"], "Publish verified 54-dungeon content manifest"),
([npm, "run", "build"], "Production build"),
([npm, "run", "android:sync"], "Android web build and Capacitor sync"),
)
def parse_semver(value: str) -> tuple[int, int, int]:
match = SEMVER_PATTERN.fullmatch(value.strip())
if not match:
@@ -239,11 +251,13 @@ def validate_release_candidates(project_root: Path = PROJECT_ROOT) -> list[str]:
cwd=project_root,
env=environment,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stderr=subprocess.PIPE,
check=False,
)
if result.returncode != 0:
output = result.stdout.decode("utf-8", errors="replace").strip()
output = b"\n".join((result.stdout, result.stderr)).decode(
"utf-8", errors="replace"
).strip()
raise ReleaseError(
f"Release-candidate Git check failed ({result.returncode}): "
f"git {' '.join(args)}\n{output}"
@@ -269,11 +283,15 @@ def validate_release_candidates(project_root: Path = PROJECT_ROOT) -> list[str]:
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stderr=subprocess.PIPE,
check=False,
)
if whitespace_result.returncode != 0:
detail = whitespace_result.stdout.strip()
detail = "\n".join(
part.strip()
for part in (whitespace_result.stdout, whitespace_result.stderr)
if part.strip()
)
raise ReleaseError(
"Release-candidate whitespace check failed. This check includes "
f"tracked and untracked files:\n{detail}"
@@ -1096,14 +1114,7 @@ def launch_gui(*, smoke_test: bool = False) -> int:
f"Recorded Android version {version.version_name} / {version.version_code}."
)
checks = (
([npm, "run", "content:test"], "Content tests"),
([npm, "run", "server:test"], "Server tests"),
([npm, "test"], "Application tests"),
([npm, "run", "build"], "Production build"),
([npm, "run", "android:sync"], "Android web build and Capacitor sync"),
)
for command, label in checks:
for command, label in full_release_checks(npm):
self._run_command(command, label)
self._run_command(["git", "add", "-A"], "Stage release")
staged = True
+7
View File
@@ -47,6 +47,13 @@ class SafetyTests(unittest.TestCase):
self.assertIn("pull --ff-only", block)
self.assertIn('test "$ACTUAL_COMMIT" = "$EXPECTED_COMMIT"', block)
def test_full_release_publishes_verified_content_before_building(self):
checks = release_manager.full_release_checks("npm")
commands = [command for command, _label in checks]
publish_index = commands.index(["npm", "run", "content:publish"])
self.assertLess(publish_index, commands.index(["npm", "run", "build"]))
self.assertLess(publish_index, commands.index(["npm", "run", "android:sync"]))
class ReleaseCandidateTests(unittest.TestCase):
def test_checks_untracked_files_without_changing_the_real_index(self):
+7
View File
@@ -56,6 +56,13 @@ try {
if ($LASTEXITCODE -ne 0) {
throw "Gradle $Task failed with exit code $LASTEXITCODE"
}
$packageType = if ($Task -eq 'assembleRelease') { 'release' } else { 'debug' }
$packageDirectory = Join-Path $projectRoot "android\app\build\outputs\apk\$packageType"
$builtPackage = Get-ChildItem -LiteralPath $packageDirectory -Filter '*.apk' |
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (-not $builtPackage) { throw "No APK was produced in $packageDirectory" }
& python (Join-Path $projectRoot 'scripts\content\verify-android-package.py') $builtPackage.FullName
if ($LASTEXITCODE -ne 0) { throw "Packaged content verification failed." }
} finally {
Pop-Location
}
@@ -0,0 +1,262 @@
import { createHash } from "node:crypto";
import { readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp";
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const recipeDirectory = path.join(projectRoot, "scripts", "runewaker-pipeline", "recipes");
const workRoot = path.join(projectRoot, "runewaker-export-work");
const shippingRoot = path.join(projectRoot, "src", "assets", "game", "dungeons");
const resourceCacheRoot = path.join(workRoot, "resource-cache");
const requestedSlugs = new Set(process.argv.slice(2).filter((value) => !value.startsWith("--")));
const fix = process.argv.includes("--fix");
const alphaClassifications = new Map();
let resourceTextureIndex;
async function exists(file) {
try {
await stat(file);
return true;
} catch {
return false;
}
}
function parseGlb(buffer, file) {
if (buffer.length < 20 || buffer.toString("utf8", 0, 4) !== "glTF") {
throw new Error(`${file} is not a GLB file.`);
}
const chunks = [];
let json;
let offset = 12;
while (offset + 8 <= buffer.length) {
const chunkLength = buffer.readUInt32LE(offset);
const chunkType = buffer.readUInt32LE(offset + 4);
const chunkStart = offset + 8;
const chunkEnd = chunkStart + chunkLength;
if (chunkEnd > buffer.length) break;
const data = buffer.subarray(chunkStart, chunkEnd);
chunks.push({ type: chunkType, data });
if (chunkType === 0x4e4f534a) {
json = JSON.parse(data.toString("utf8").replace(/\0+$/u, "").trim());
}
offset = chunkEnd;
}
if (!json) throw new Error(`${file} does not contain a JSON chunk.`);
return { json, chunks };
}
function serializeGlb(source, json, chunks) {
const encodedJson = Buffer.from(JSON.stringify(json));
const paddedJson = Buffer.alloc(Math.ceil(encodedJson.length / 4) * 4, 0x20);
encodedJson.copy(paddedJson);
const updatedChunks = chunks.map((chunk) => (
chunk.type === 0x4e4f534a ? { ...chunk, data: paddedJson } : chunk
));
const totalLength = 12 + updatedChunks.reduce((total, chunk) => total + 8 + chunk.data.length, 0);
const output = Buffer.alloc(totalLength);
source.copy(output, 0, 0, 12);
output.writeUInt32LE(totalLength, 8);
let offset = 12;
for (const chunk of updatedChunks) {
output.writeUInt32LE(chunk.data.length, offset);
output.writeUInt32LE(chunk.type, offset + 4);
chunk.data.copy(output, offset + 8);
offset += 8 + chunk.data.length;
}
return output;
}
async function classifyAlpha(file) {
if (alphaClassifications.has(file)) return alphaClassifications.get(file);
const metadata = await sharp(file).metadata();
if (!metadata.hasAlpha) {
alphaClassifications.set(file, "opaque");
return "opaque";
}
const { data, info } = await sharp(file).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
let hasTransparentPixel = false;
for (let offset = 3; offset < data.length; offset += info.channels) {
const alpha = data[offset];
if (alpha === 255) continue;
hasTransparentPixel = true;
if (alpha > 0) {
alphaClassifications.set(file, "blend");
return "blend";
}
}
const role = hasTransparentPixel ? "cutout" : "opaque";
alphaClassifications.set(file, role);
return role;
}
function sourceImageIndex(texture) {
return texture?.extensions?.KHR_texture_basisu?.source ?? texture?.source;
}
async function indexResourceTextures() {
if (resourceTextureIndex) return resourceTextureIndex;
resourceTextureIndex = new Map();
if (!(await exists(resourceCacheRoot))) return resourceTextureIndex;
const cacheDirectories = (await readdir(resourceCacheRoot, { withFileTypes: true }))
.filter((entry) => entry.isDirectory())
.sort((left, right) => left.name.localeCompare(right.name));
for (const cacheDirectory of cacheDirectories) {
const textureDirectory = path.join(resourceCacheRoot, cacheDirectory.name, "prepared", "textures");
if (!(await exists(textureDirectory))) continue;
for (const texture of (await readdir(textureDirectory)).filter((file) => file.endsWith(".png")).sort()) {
if (!resourceTextureIndex.has(texture)) {
resourceTextureIndex.set(texture, path.join(textureDirectory, texture));
}
}
}
return resourceTextureIndex;
}
async function resolveSourceTexture(localDirectory, imageName) {
const fileName = `${imageName}.png`;
const localFile = path.join(localDirectory, fileName);
if (await exists(localFile)) return localFile;
return (await indexResourceTextures()).get(fileName);
}
function sha256(buffer) {
return createHash("sha256").update(buffer).digest("hex");
}
async function refreshShippingMetadata(metadataFile, metadata, visualArtifact, visualBuffer) {
visualArtifact.size = visualBuffer.length;
visualArtifact.sha256 = sha256(visualBuffer);
await writeFile(metadataFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
const optimizationFile = path.join(path.dirname(metadataFile), "optimization-report.json");
if (!(await exists(optimizationFile))) return;
const optimization = JSON.parse(await readFile(optimizationFile, "utf8"));
if (optimization.optimized) {
optimization.optimized.size = visualBuffer.length;
if (Object.hasOwn(optimization.optimized, "checksum")) {
optimization.optimized.checksum = sha256(visualBuffer);
}
}
await writeFile(optimizationFile, `${JSON.stringify(optimization, null, 2)}\n`, "utf8");
}
async function auditDungeon(recipe) {
const slug = recipe.slug;
const metadataFile = path.join(shippingRoot, slug, "import-metadata.json");
const preparedTextureDirectory = path.join(workRoot, slug, "prepared", "textures");
if (!(await exists(metadataFile))) {
return { slug, status: "incomplete", problems: [`Missing ${path.relative(projectRoot, metadataFile)}`] };
}
if (!(await exists(preparedTextureDirectory))) {
return {
slug,
status: "incomplete",
problems: [`Missing ${path.relative(projectRoot, preparedTextureDirectory)}`],
};
}
const metadata = JSON.parse(await readFile(metadataFile, "utf8"));
const visualArtifact = (metadata.assets ?? metadata.artifacts ?? [])
.find((artifact) => artifact.role === "visual");
const visualFile = path.join(shippingRoot, slug, visualArtifact?.fileName ?? `${slug}-visual.glb`);
if (!(await exists(visualFile))) {
return { slug, status: "incomplete", problems: [`Missing ${path.relative(projectRoot, visualFile)}`] };
}
const sourceGlb = await readFile(visualFile);
const { json: gltf, chunks } = parseGlb(sourceGlb, visualFile);
const materialResults = [];
const missingTextures = [];
for (const [materialIndex, material] of (gltf.materials ?? []).entries()) {
const textureIndex = material.pbrMetallicRoughness?.baseColorTexture?.index;
const texture = gltf.textures?.[textureIndex];
const image = gltf.images?.[sourceImageIndex(texture)];
if (!image?.name) continue;
const sourceFile = await resolveSourceTexture(preparedTextureDirectory, image.name);
if (!sourceFile) {
missingTextures.push(`${image.name}.png`);
continue;
}
const expectedRole = await classifyAlpha(sourceFile);
const expectedAlphaMode = expectedRole === "blend" ? "BLEND" : expectedRole === "cutout" ? "MASK" : "OPAQUE";
const actualAlphaMode = material.alphaMode ?? "OPAQUE";
const actualRole = material.extras?.semanticRole ?? "missing";
materialResults.push({
materialIndex,
material: material.name ?? `material-${materialIndex}`,
texture: image.name,
expectedRole,
expectedAlphaMode,
actualRole,
actualAlphaMode,
matches: expectedAlphaMode === actualAlphaMode && expectedRole === actualRole,
});
if (fix && (expectedAlphaMode !== actualAlphaMode || expectedRole !== actualRole)) {
if (expectedAlphaMode === "OPAQUE") delete material.alphaMode;
else material.alphaMode = expectedAlphaMode;
if (expectedAlphaMode === "MASK") material.alphaCutoff = 0.5;
else delete material.alphaCutoff;
material.extras = { ...(material.extras ?? {}), semanticRole: expectedRole };
}
}
const mismatches = materialResults.filter((result) => !result.matches);
const alphaMaterials = materialResults.filter((result) => result.expectedRole !== "opaque");
const problems = [
...mismatches.map((result) =>
`${result.texture}: expected ${result.expectedAlphaMode}/${result.expectedRole}, got ${result.actualAlphaMode}/${result.actualRole}`,
),
...[...new Set(missingTextures)].map((file) => `Missing prepared source texture ${file}`),
];
if (fix && mismatches.length > 0 && missingTextures.length === 0) {
const visualBuffer = serializeGlb(sourceGlb, gltf, chunks);
await writeFile(visualFile, visualBuffer);
if (visualArtifact) {
await refreshShippingMetadata(metadataFile, metadata, visualArtifact, visualBuffer);
}
}
return {
slug,
status: problems.length === 0 ? "green" : fix && missingTextures.length === 0 ? "repaired" : "mismatch",
materials: materialResults.length,
alphaMaterials: alphaMaterials.map(({ material, texture, expectedAlphaMode }) => ({
material,
texture,
alphaMode: expectedAlphaMode,
})),
mismatches,
problems,
};
}
const recipeFiles = (await readdir(recipeDirectory))
.filter((file) => file.endsWith(".json") && !file.endsWith("-population.json"))
.sort();
const recipes = [];
for (const recipeFile of recipeFiles) {
const recipe = JSON.parse(await readFile(path.join(recipeDirectory, recipeFile), "utf8"));
if (!recipe.slug || recipe.slug === "runewaker-player-avatars") continue;
if (requestedSlugs.size > 0 && !requestedSlugs.has(recipe.slug)) continue;
recipes.push(recipe);
}
const results = [];
for (const recipe of recipes) {
results.push(await auditDungeon(recipe));
}
const failures = results.filter((result) => !["green", "repaired"].includes(result.status));
const report = {
schemaVersion: 1,
dungeonCount: results.length,
status: failures.length === 0 ? fix ? "repaired" : "green" : "mismatch",
failureCount: failures.length,
alphaDungeonCount: results.filter((result) => result.alphaMaterials?.length > 0).length,
results,
};
console.log(JSON.stringify(report, null, 2));
if (failures.length > 0) process.exitCode = 1;
@@ -6,6 +6,7 @@ Expected invocation:
"""
from __future__ import annotations
from array import array
import json
import math
import os
@@ -111,6 +112,69 @@ def material_image_key(material: bpy.types.Material) -> str:
return f"material:{material.name.casefold()}"
def material_image(material: bpy.types.Material) -> bpy.types.Image | None:
if not material.use_nodes or material.node_tree is None:
return None
for node in material.node_tree.nodes:
if node.type == "TEX_IMAGE" and node.image is not None:
return node.image
return None
def image_alpha_role(image: bpy.types.Image | None) -> str:
"""Classify source alpha without turning fully opaque RGBA textures translucent."""
if image is None or image.channels < 4:
return "opaque"
pixels = array("f", [0.0]) * len(image.pixels)
image.pixels.foreach_get(pixels)
alpha_values = pixels[3::image.channels]
if min(alpha_values, default=1.0) >= 0.999:
return "opaque"
if any(0.001 < alpha < 0.999 for alpha in alpha_values):
return "blend"
return "cutout"
def preserve_material_alpha(material: bpy.types.Material) -> str:
image = material_image(material)
role = image_alpha_role(image)
if role == "opaque" or material.node_tree is None:
return role
image_node = next(
node
for node in material.node_tree.nodes
if node.type == "TEX_IMAGE" and node.image == image
)
principled = next(
(node for node in material.node_tree.nodes if node.type == "BSDF_PRINCIPLED"),
None,
)
if principled is None:
return role
alpha_output = image_node.outputs.get("Alpha")
alpha_input = principled.inputs.get("Alpha")
if alpha_output is None or alpha_input is None:
return role
if role == "blend":
if not alpha_input.is_linked:
material.node_tree.links.new(alpha_output, alpha_input)
material.blend_method = "BLEND"
if hasattr(material, "surface_render_method"):
material.surface_render_method = "BLENDED"
else:
alpha_clip = material.node_tree.nodes.new("ShaderNodeMath")
alpha_clip.name = "RuneWaker Alpha Clip"
alpha_clip.operation = "GREATER_THAN"
alpha_clip.inputs[1].default_value = 0.5
material.node_tree.links.new(alpha_output, alpha_clip.inputs[0])
material.node_tree.links.new(alpha_clip.outputs[0], alpha_input)
material.blend_method = "CLIP"
material.alpha_threshold = 0.5
return role
def deduplicate_materials(objects: list[bpy.types.Object]) -> dict[str, int]:
canonical: dict[str, bpy.types.Material] = {}
replacements = 0
@@ -126,7 +190,7 @@ def deduplicate_materials(objects: list[bpy.types.Object]) -> dict[str, int]:
replacements += 1
else:
canonical[key] = material
material["semanticRole"] = "opaque"
material["semanticRole"] = preserve_material_alpha(material)
material["sourceFormat"] = "RuneWaker DDS"
return {"unique": len(canonical), "replacements": replacements}
@@ -241,6 +241,7 @@ async function cachedResourceAsset(resourceRecord) {
throw new Error("source ROS is missing: " + projectPath(sourceFile));
}
const sourceSha256 = await sha256(sourceFile);
const converterSha256 = await sha256(blenderScript);
const cacheRoot = path.join(resourceCacheDirectory, resourceRecord.cacheKey);
const raw = path.join(cacheRoot, "raw");
const prepared = path.join(cacheRoot, "prepared");
@@ -253,6 +254,7 @@ async function cachedResourceAsset(resourceRecord) {
.map((file) => path.join(cacheRoot, file));
if (cached.source?.resource === resourceRecord.normalizedResource
&& cached.source?.sha256 === sourceSha256
&& cached.toolchain?.converterSha256 === converterSha256
&& cached.coordinateSystem?.metersPerSourceUnit === recipe.coordinateSystem.metersPerSourceUnit
&& (await Promise.all(outputs.map(exists))).every(Boolean)) {
return {
@@ -300,6 +302,9 @@ async function cachedResourceAsset(resourceRecord) {
nativeBridge: recipe.coordinateSystem.nativeBridge,
metersPerSourceUnit: recipe.coordinateSystem.metersPerSourceUnit,
},
toolchain: {
converterSha256,
},
visual: {
file: path.relative(
cacheRoot,
+9
View File
@@ -0,0 +1,9 @@
import { arenaKitFromSeed } from "./generated/arena-combat-runtime.mjs";
/** Server-owned character/loadout data enters the shared character initializer. */
export function arenaKitForLoadout(loadout, character = {}) {
return arenaKitFromSeed({ ...character, classId: loadout.classId, specializationId: loadout.specializationId,
role: loadout.role, level: 80, talentRanks: loadout.talents ?? character.talentRanks,
actionBindings: Object.keys(loadout.actions ?? {}).length ? loadout.actions : character.actionBindings,
settings: { ...character.settings, autoTargetNearest: false } });
}
+63
View File
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import test from "node:test";
import { arenaKitForLoadout } from "./arena-character-kit.mjs";
import { ArenaSimulation } from "./arena-simulation.mjs";
import { ARENA_STAGES } from "./arena-stages.mjs";
function fixture() {
const kit = arenaKitForLoadout({classId:"priest",talents:{},actions:{"primary:face-left":"priest-flash-heal","primary:face-bottom":"priest-smite"}});
const simulation = new ArenaSimulation({id:"character-kit",stage:{ ...ARENA_STAGES[0], id:"test-floorless", lineOfSight:[] },bracket:"2v2",mode:"practice",ruleset:"wow",startedAt:0,
participants:[{actorId:"player",characterId:"saved-priest",name:"My Priest",team:0,role:"healer",isBot:false,characterKit:kit},
{actorId:"ally",team:0,role:"damage",isBot:false},{actorId:"enemy",team:1,role:"damage",isBot:false}]});
for(let i=0;i<200;i++)simulation.step();
const player=simulation.actor("player"), ally=simulation.actor("ally"), enemy=simulation.actor("enemy");
player.position=[0,0,0];ally.position=[1,0,0];enemy.position=[2,0,0];
return {simulation,player,ally,enemy,kit};
}
test("all arena spawns have finite character transforms before the first movement",()=>{
for(const stage of ARENA_STAGES) {
const simulation=new ArenaSimulation({id:stage.id,stage,bracket:"2v2",mode:"practice",ruleset:"wow",participants:[
{actorId:"left",team:0,role:"healer",isBot:false},{actorId:"right",team:1,role:"damage",isBot:false}]});
for(const actor of simulation.snapshot().actors) {
assert.ok(Number.isFinite(actor.facing),stage.id);
assert.ok(actor.position.every(Number.isFinite),stage.id);
assert.deepEqual(actor.position,stage.teamSpawns[actor.team],stage.id);
}
}
});
test("saved priest identity, spell bindings, and usable mana reach the snapshot",()=>{
const {simulation,kit}=fixture();
const player=simulation.snapshot().actors.find(actor=>actor.id==="player");
assert.equal(player.characterId,"saved-priest");assert.equal(player.classId,"priest");
assert.equal(player.actionBindings["primary:face-left"],"priest-flash-heal");
assert.ok(player.resource>kit.abilities["priest-flash-heal"].cost.amount);
assert.equal(simulation.receiveIntent("player",{sequence:1,type:"ability",abilityId:"heal"}).reason,"unknown-ability");
});
test("saved Flash Heal pays mana, has a cast time, heals the chosen ally and reports cooldown",()=>{
const {simulation,player,ally}=fixture();ally.health=200;
const resource=player.resource;
assert.equal(simulation.receiveIntent("player",{sequence:1,type:"ability",abilityId:"priest-flash-heal",targetActorId:"ally"}).accepted,true);
assert.equal(player.resource,resource);assert.equal(ally.health,200);
assert.equal(simulation.receiveIntent("player",{sequence:2,type:"ability",abilityId:"priest-flash-heal",targetActorId:"ally"}).reason,"already-casting");
for(let i=0;i<30;i++)simulation.step();
assert.ok(ally.health>200);assert.ok(player.resource<resource);assert.equal(player.health,player.maxHealth);assert.equal(player.casting,null);
});
test("movement cancels a real spell and impossible targets give feedback",()=>{
const {simulation,player,enemy}=fixture();
enemy.position=[1000,0,0];
assert.equal(simulation.receiveIntent("player",{sequence:1,type:"ability",abilityId:"priest-smite",targetActorId:"enemy"}).reason,"out-of-range");
assert.equal(simulation.receiveIntent("player",{sequence:2,type:"ability",abilityId:"priest-flash-heal",targetActorId:"player"}).accepted,true);
simulation.receiveIntent("player",{sequence:3,type:"movement",movement:{x:1,z:0}});simulation.step();
assert.equal(player.casting,null);
});
test("Shadowfiend uses the character summoning engine",()=>{
const {simulation,player}=fixture();
player.facing=Math.PI/2;
assert.equal(simulation.receiveIntent("player",{sequence:1,type:"ability",abilityId:"wow335-priest-shadowfiend",targetActorId:"enemy"}).accepted,true);
assert.ok(player.combat.summons.length>0);
});
+171
View File
@@ -0,0 +1,171 @@
import geometry from "./generated/arena-geometry.json" with { type: "json" };
const CELL = 4;
const indexes = new Map();
const navigationGraphs = new Map();
function index(stageId, kind) {
const key = `${stageId}:${kind}`;
if (indexes.has(key)) return indexes.get(key);
const triangles = geometry[stageId]?.[kind] ?? [];
const cells = new Map();
for (let offset = 0; offset < triangles.length; offset += 9) {
const xs = [triangles[offset], triangles[offset + 3], triangles[offset + 6]];
const zs = [triangles[offset + 2], triangles[offset + 5], triangles[offset + 8]];
for (let x = Math.floor(Math.min(...xs) / CELL); x <= Math.floor(Math.max(...xs) / CELL); x++) {
for (let z = Math.floor(Math.min(...zs) / CELL); z <= Math.floor(Math.max(...zs) / CELL); z++) {
const cell = `${x},${z}`;
if (!cells.has(cell)) cells.set(cell, []);
cells.get(cell).push(offset);
}
}
}
const value = { triangles, cells };
indexes.set(key, value);
return value;
}
export function arenaFloorHeight(stageId, x, z, previousY, maximumRise = 1) {
const { triangles: t, cells } = index(stageId, "navigation");
let height = null;
for (const o of cells.get(`${Math.floor(x / CELL)},${Math.floor(z / CELL)}`) ?? []) {
const ax = t[o], az = t[o + 2], bx = t[o + 3], bz = t[o + 5], cx = t[o + 6], cz = t[o + 8];
const denominator = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);
if (Math.abs(denominator) < .000001) continue;
const a = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / denominator;
const b = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / denominator;
if (a < -.001 || b < -.001 || a + b > 1.001) continue;
const y = a * t[o + 1] + b * t[o + 4] + (1 - a - b) * t[o + 7];
if (y > previousY + maximumRise) continue;
if (height === null || y > height) height = y;
}
return height;
}
function hitsTriangle(from, to, t, o) {
const dx = to[0] - from[0], dy = to[1] - from[1], dz = to[2] - from[2];
const e1x = t[o + 3] - t[o], e1y = t[o + 4] - t[o + 1], e1z = t[o + 5] - t[o + 2];
const e2x = t[o + 6] - t[o], e2y = t[o + 7] - t[o + 1], e2z = t[o + 8] - t[o + 2];
const px = dy * e2z - dz * e2y, py = dz * e2x - dx * e2z, pz = dx * e2y - dy * e2x;
const determinant = e1x * px + e1y * py + e1z * pz;
if (Math.abs(determinant) < 1e-8) return false;
const inverse = 1 / determinant, sx = from[0] - t[o], sy = from[1] - t[o + 1], sz = from[2] - t[o + 2];
const u = (sx * px + sy * py + sz * pz) * inverse;
if (u < 0 || u > 1) return false;
const qx = sy * e1z - sz * e1y, qy = sz * e1x - sx * e1z, qz = sx * e1y - sy * e1x;
const v = (dx * qx + dy * qy + dz * qz) * inverse;
if (v < 0 || u + v > 1) return false;
const distance = (e2x * qx + e2y * qy + e2z * qz) * inverse;
return distance > .0001 && distance < .9999;
}
export function arenaGeometryLineClear(stageId, from, to) {
const { triangles, cells } = index(stageId, "collision");
const steps = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[2] - from[2]) / (CELL * .5)));
const visited = new Set();
for (let step = 0; step <= steps; step++) {
const ratio = step / steps;
const cell = `${Math.floor((from[0] + (to[0] - from[0]) * ratio) / CELL)},${Math.floor((from[2] + (to[2] - from[2]) * ratio) / CELL)}`;
for (const offset of cells.get(cell) ?? []) {
if (visited.has(offset)) continue;
visited.add(offset);
if (hitsTriangle(from, to, triangles, offset)) return false;
}
}
return true;
}
function navigationGraph(stageId) {
if (navigationGraphs.has(stageId)) return navigationGraphs.get(stageId);
const triangles = geometry[stageId]?.navigation ?? [];
const nodes = [], edges = new Map();
for (let offset = 0; offset < triangles.length; offset += 9) {
const vertices = [0, 3, 6].map((axis) => triangles.slice(offset + axis, offset + axis + 3));
const center = [0, 1, 2].map((axis) => vertices.reduce((sum, point) => sum + point[axis], 0) / 3);
const node = { id: nodes.length, center, neighbors: [], vertices };
nodes.push(node);
for (let edge = 0; edge < 3; edge++) {
const a = vertices[edge], b = vertices[(edge + 1) % 3];
const key = [a.join(","), b.join(",")].sort().join("/");
const portal = a.map((value, axis) => (value + b[axis]) / 2);
for (const other of edges.get(key) ?? []) {
node.neighbors.push({ id: other.id, portal });
other.neighbors.push({ id: node.id, portal });
}
if (!edges.has(key)) edges.set(key, []);
edges.get(key).push(node);
}
}
navigationGraphs.set(stageId, nodes);
return nodes;
}
const distance3 = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
function navigationStepClear(stageId, from, to) {
let height = from[1];
const steps = Math.max(1, Math.ceil(distance3(from, to) / .4));
for (let step = 1; step <= steps; step++) {
const ratio = step / steps;
const x = from[0] + (to[0] - from[0]) * ratio, z = from[2] + (to[2] - from[2]) * ratio;
const floor = arenaFloorHeight(stageId, x, z, height, .6);
if (floor === null || height - floor > .8) return false;
height = floor;
}
return Math.abs(height - to[1]) < .8;
}
function navigationNode(nodes, point) {
let nearest = null, nearestDistance = Infinity;
for (const node of nodes) {
const [a, b, c] = node.vertices;
const denominator = (b[2] - c[2]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[2] - c[2]);
if (Math.abs(denominator) < .000001) continue;
const u = ((b[2] - c[2]) * (point[0] - c[0]) + (c[0] - b[0]) * (point[2] - c[2])) / denominator;
const v = ((c[2] - a[2]) * (point[0] - c[0]) + (a[0] - c[0]) * (point[2] - c[2])) / denominator;
const inside = u >= -.001 && v >= -.001 && u + v <= 1.001;
const height = u * a[1] + v * b[1] + (1 - u - v) * c[1];
const distance = inside ? Math.abs(height - point[1]) : distance3(node.center, point) + 5;
if (distance < nearestDistance) { nearest = node; nearestDistance = distance; }
}
return nearest;
}
/** Follow the shipped walkable mesh around walls, ramps and starting rooms. */
export function arenaNavigationPath(stageId, from, to) {
const nodes = navigationGraph(stageId);
const start = navigationNode(nodes, from), goal = navigationNode(nodes, to);
if (!start || !goal) return [];
const open = new Set([start.id]), costs = new Map([[start.id, 0]]), previous = new Map();
let reached = false;
while (open.size) {
let current = null, score = Infinity;
for (const id of open) {
const candidate = costs.get(id) + distance3(nodes[id].center, goal.center);
if (candidate < score) { current = nodes[id]; score = candidate; }
}
if (current.id === goal.id) { reached = true; break; }
open.delete(current.id);
for (const edge of current.neighbors) {
const next = nodes[edge.id];
edge.walkable ??= navigationStepClear(stageId, current.center, edge.portal) && navigationStepClear(stageId, edge.portal, next.center) && [.55, 1.4].every((height) => {
const lift = (point) => [point[0], point[1] + height, point[2]];
return arenaGeometryLineClear(stageId, lift(current.center), lift(edge.portal))
&& arenaGeometryLineClear(stageId, lift(edge.portal), lift(next.center));
});
if (!edge.walkable) continue;
const cost = costs.get(current.id) + distance3(current.center, edge.portal) + distance3(edge.portal, next.center);
if (cost >= (costs.get(next.id) ?? Infinity)) continue;
costs.set(next.id, cost);
previous.set(next.id, { id: current.id, portal: edge.portal });
open.add(next.id);
}
}
if (!reached) return [];
const path = [[...to]];
for (let id = goal.id; id !== start.id;) {
const edge = previous.get(id);
path.push(edge.portal);
id = edge.id;
}
return path.reverse();
}
+52
View File
@@ -0,0 +1,52 @@
import test from "node:test";
import assert from "node:assert/strict";
import { arenaFloorHeight, arenaGeometryLineClear, arenaNavigationPath } from "./arena-geometry.mjs";
import { ARENA_STAGES } from "./arena-stages.mjs";
import { ArenaSimulation } from "./arena-simulation.mjs";
test("every arena spawn is supported by its shipped navigation surface", () => {
for (const stage of ARENA_STAGES) for (const spawn of stage.teamSpawns) {
const floor = arenaFloorHeight(stage.id, spawn[0], spawn[2], spawn[1], 2);
assert.notEqual(floor, null, `${stage.id} ${spawn}`);
assert.ok(Math.abs(floor - spawn[1]) < 2, `${stage.id} floor=${floor}, spawn=${spawn[1]}`);
}
});
test("characters can move away from both starting anchors into each arena", () => {
for (const stage of ARENA_STAGES) for (const team of [0, 1]) {
const sim = new ArenaSimulation({ id: "traversal", stage, bracket: "2v2", mode: "practice", ruleset: "wow", startedAt: 1000,
participants: [{ actorId: "player", name: "Player", team, role: "healer", isBot: false }] });
sim.phase = "active"; sim.activeStartedAt = 1000;
const actor = sim.actor("player"), start = [...actor.position], gate = stage.preparationGates[team];
const dx = gate[0] - start[0], dz = gate[2] - start[2], length = Math.hypot(dx, dz);
actor.movement = [dx / length, dz / length];
for (let tick = 0; tick < 50; tick++) sim.moveActor(actor, .05);
assert.ok(Math.hypot(actor.position[0] - start[0], actor.position[2] - start[2]) > 3, `${stage.id} team ${team}: ${actor.position} from ${start}`);
assert.ok(actor.position.every(Number.isFinite));
}
});
test("collision geometry blocks arena walls and preserves clear short sight lines", () => {
const stage = ARENA_STAGES.find((entry) => entry.id === "nagrand-arena");
const spawn = stage.teamSpawns[0];
assert.equal(arenaGeometryLineClear(stage.id, [spawn[0], spawn[1] + 1.2, spawn[2]], [spawn[0] + .05, spawn[1] + 1.2, spawn[2]]), true);
assert.equal(arenaGeometryLineClear(stage.id, [-60, 14.5, -42], [-35, 14.5, -42]), false);
});
test("bots can traverse each complete arena between both teams without invisible walls", () => {
for (const stage of ARENA_STAGES) for (const team of [0, 1]) {
const sim = new ArenaSimulation({ id: "path", stage, bracket: "3v3", mode: "practice", ruleset: "wow", startedAt: 1000,
participants: [0, 1, 2].map((index) => ({ actorId: `p${index}`, name: "Player", team, role: "damage", isBot: false })) });
sim.phase = "active"; sim.activeStartedAt = 1000;
for (const actor of sim.actors.values()) assert.notEqual(arenaFloorHeight(stage.id, actor.position[0], actor.position[2], actor.position[1], 2), null, `${stage.id} team ${team} ${actor.id} spawn`);
const actor = sim.actor("p0"), destination = stage.teamSpawns[1 - team];
actor.navigationPath = arenaNavigationPath(stage.id, actor.position, destination);
assert.ok(actor.navigationPath.length, `${stage.id} has a route`);
for (let tick = 0; tick < 2400; tick++) {
sim.tickNumber++;
sim.followBotPath(actor); sim.moveActor(actor, .05);
if (Math.hypot(actor.position[0] - destination[0], actor.position[2] - destination[2]) < 2) break;
}
assert.ok(Math.hypot(actor.position[0] - destination[0], actor.position[2] - destination[2]) < 2, `${stage.id} team ${team} stuck at ${actor.position}`);
}
});
+185
View File
@@ -0,0 +1,185 @@
import assert from "node:assert/strict";
import test from "node:test";
import { ArenaSimulation } from "./arena-simulation.mjs";
import { ARENA_STAGES } from "./arena-stages.mjs";
import { initializeArenaCharacter } from "./generated/arena-combat-runtime.mjs";
function match(classId = "priest", secondaryClassId) {
const simulation = new ArenaSimulation({ id: `runtime-${classId}`, stage: { ...ARENA_STAGES[0], id: "test-floorless", lineOfSight: [] },
bracket: "2v2", mode: "practice", ruleset: "wow", startedAt: 1000,
participants: [{ actorId: "caster", name: "My Character", team: 0, role: "healer", isBot: false,
characterKit: { classId, level: 80, seed: { classId, secondaryClassId, level: 80, actionBindings: { "primary:face-left": "priest-flash-heal" } } } },
{ actorId: "ally", name: "Ally", team: 0, role: "damage", isBot: false },
{ actorId: "enemy", name: "Enemy", team: 1, role: "damage", isBot: false, characterKit: { classId: "mage", level: 80 } }] });
simulation.phase = "active"; simulation.activeStartedAt = 1000; simulation.phaseEndsAt = null;
const caster = simulation.actor("caster"), ally = simulation.actor("ally"), enemy = simulation.actor("enemy");
caster.position = [0, 0, 0]; caster.facing = 0; ally.position = [1, 0, 0]; enemy.position = [0, 0, 3]; enemy.facing = Math.PI;
const cast = (id, target = "enemy", ground) => simulation.useAbility(caster, id, target, ground);
const advance = (ms) => { for (let index = 0; index < ms / 50; index++) simulation.step(); };
return { simulation, caster, ally, enemy, cast, advance };
}
test("melee bots start weapon attacks and generate resources instead of waiting at zero rage", () => {
const { caster, enemy, advance } = match("warrior");
caster.isBot = true; caster.role = "damage";
const health = enemy.health;
advance(8000);
assert.ok(enemy.health < health);
assert.ok(caster.combat.combatEvents.length > 0 || caster.combat.autoAttackTargetId === enemy.id);
});
test("friendly dispels remove the movement restriction as well as the visible debuff", () => {
const { simulation, caster, enemy, cast } = match("priest");
assert.equal(simulation.useAbility(enemy, "mage-frost-nova", caster.id).accepted, true);
assert.equal(caster.statuses.find((status) => status.kind === "root")?.endsAt, 9000);
const dispel = cast("wow335-priest-dispel-magic", caster.id);
assert.equal(dispel.accepted, true, JSON.stringify(dispel));
assert.equal(caster.statuses.some((status) => status.kind === "root"), false);
caster.movement = [1, 0]; simulation.moveActor(caster, .05);
assert.ok(caster.position[0] > 0);
});
test("player crowd control diminishes once per cast, including duplicated catalog status entries", () => {
const { simulation, caster, enemy, advance } = match("priest");
for (const duration of [8000, 4000, 2000, 0]) {
enemy.cooldowns.clear(); enemy.combat = { ...enemy.combat, cooldowns: {}, globalCooldownEndsAt: 0 };
assert.equal(simulation.useAbility(enemy, "mage-frost-nova", caster.id).accepted, true);
const now = simulation.startedAt + simulation.tickNumber * 50;
assert.equal((caster.statuses.find((status) => status.kind === "root")?.endsAt ?? now) - now, duration);
advance(duration + 50);
}
});
test("a healer can target and heal a teammate's pet", () => {
const { simulation, caster, ally, cast, advance } = match("hunter");
assert.equal(cast("wow335-hunter-call-pet", caster.id).accepted, true);
advance(2000);
const pet = caster.combat.summons[0];
caster.combat = { ...caster.combat, summons: [{ ...pet, health: 500 }] };
ally.combat = null; ally.characterKit = { classId: "priest", level: 80 };
initializeArenaCharacter(ally, 3000);
assert.equal(simulation.useAbility(ally, "priest-flash-heal", pet.id).accepted, true);
advance(2000);
assert.ok(caster.combat.summons[0].health > 500);
});
test("channel deals successive damage, heals its caster, and stops on movement", () => {
const { caster, enemy, cast, advance } = match("warlock");
caster.health = 3000;
assert.equal(cast("warlock-drain-life").accepted, true);
assert.equal(caster.casting.mode, "channel");
const initial = enemy.health;
advance(2200);
assert.ok(enemy.health < initial);
assert.ok(caster.health > 3000);
caster.movement = [1, 0]; advance(50);
assert.equal(caster.casting, null);
});
test("runes are spent, gate repeat casts, regenerate, and restore with Empower Rune Weapon", () => {
const { caster, cast, advance } = match("death-knight");
assert.equal(cast("death-knight-icy-touch").accepted, true);
assert.ok(caster.combat.deathKnightRunes.some((rune) => rune.readyAt > 1000));
assert.ok(caster.resource > 0);
advance(1600);
assert.equal(cast("wow335-death-knight-empower-rune-weapon", "caster").accepted, true);
assert.ok(caster.combat.deathKnightRunes.every((rune) => rune.readyAt <= 2600));
});
test("combo points belong to the selected enemy and finishers consume them", () => {
const { caster, cast, advance } = match("rogue");
assert.equal(cast("rogue-sinister-strike").accepted, true);
assert.equal(caster.combat.comboPoints, 1);
assert.equal(caster.combat.comboTargetId, "enemy");
advance(1600);
assert.equal(cast("rogue-eviscerate").accepted, true);
assert.equal(caster.combat.comboPoints, 0);
});
test("pets spawn, receive orders, attack, and dismiss through the same spell engine", () => {
const { simulation, caster, enemy, cast, advance } = match("hunter");
assert.equal(cast("wow335-hunter-call-pet", "caster").accepted, true);
assert.ok(caster.combat.summons.some((summon) => summon.kind === "pet"));
simulation.receiveIntent("caster", { type: "target", targetActorId: "enemy", sequence: 1 });
simulation.receiveIntent("caster", { type: "command", command: "attack", sequence: 2 });
const before = enemy.health;
advance(3100);
assert.ok(enemy.health < before);
assert.equal(cast("wow335-hunter-dismiss-pet", "caster").accepted, true);
advance(Math.max(50, (caster.casting?.completesAt ?? 0) - (1000 + simulation.tickNumber * 50) + 50));
assert.equal(caster.combat.summons.length, 0);
});
test("an opposing player's interrupt cancels the cast and locks its school", () => {
const { simulation, caster, enemy, cast, advance } = match();
assert.equal(cast("priest-smite").accepted, true);
assert.equal(simulation.useAbility(enemy, "wow335-mage-counterspell", "caster").accepted, true);
assert.equal(caster.casting, null);
assert.ok(caster.combat.schoolLockedUntil.holy > 1000);
advance(1600);
assert.equal(cast("priest-smite").accepted, false);
});
test("healing reaches the requested teammate, is dampened, and does not alter another match", () => {
const first = match(), second = match();
first.ally.health = 500;
const untouched = second.caster.resource;
assert.equal(first.cast("priest-flash-heal", "ally").accepted, true);
first.advance(1600);
assert.ok(first.ally.health > 500);
assert.ok(first.caster.resource < untouched);
assert.equal(second.caster.resource, untouched);
assert.equal(second.caster.casting, null);
assert.ok(first.simulation.combatEvents.some((event) => event.kind === "healing" && event.targetActorId === "ally" && event.sourceActorId === "caster"));
assert.ok(first.simulation.combatPresentation.some((event) => event.sourceActorId === "caster"));
});
test("self shields absorb hostile-player damage and are consumed once", () => {
const { simulation, caster, enemy, cast, advance } = match("mage");
assert.equal(cast("mage-mana-shield", "caster").accepted, true);
const shield = caster.combat.shield;
assert.ok(shield > 0 || caster.auras.some((aura) => aura.absorbs.length));
const health = caster.health;
enemy.combat = { ...enemy.combat, gearStats: { ...enemy.combat.gearStats, hitRating: 100000 } };
assert.equal(simulation.useAbility(enemy, "mage-fire-blast", "caster").accepted, true);
assert.ok(caster.health >= health - 1010);
assert.ok(simulation.combatEvents.some((event) => event.kind === "damage" && event.targetActorId === "caster" && event.absorbed > 0), JSON.stringify(simulation.combatEvents));
advance(50);
});
test("RoM primary and secondary resource pools survive arena ticks and casting", () => {
const { caster, cast, advance } = match("rom-warlock", "rom-priest");
assert.ok(Object.keys(caster.combat.resourcePools).length > 1);
const focus = caster.combat.resourcePools.focus;
assert.equal(cast("rom-warlock-general-0").accepted, true);
advance(4000);
assert.ok(Number.isFinite(caster.combat.resourcePools.focus));
assert.ok(caster.combat.resourcePools.focus <= focus);
assert.ok(Number.isFinite(caster.combat.resourcePools.mana));
});
test("ground spells damage targets around the confirmed location", () => {
const { caster, enemy, cast } = match("mage");
const health = enemy.health;
assert.equal(cast("wow335-mage-blizzard", null, enemy.position).accepted, true);
assert.ok(enemy.health < health);
assert.ok(caster.resource >= 0);
});
test("mana burns drain an opposing character's actual resource pool", () => {
const { enemy, cast, advance } = match();
const before = enemy.resource;
assert.equal(cast("wow335-priest-mana-burn").accepted, true);
advance(3500);
assert.ok(enemy.resource < before);
});
test("opponents can target and damage player pets", () => {
const { simulation, caster, enemy, cast } = match("hunter");
assert.equal(cast("wow335-hunter-call-pet", "caster").accepted, true);
const pet = caster.combat.summons[0], before = pet.health;
enemy.combat = { ...enemy.combat, gearStats: { ...enemy.combat.gearStats, hitRating: 100000 } };
assert.equal(simulation.receiveIntent("enemy", { sequence: 1, type: "target", targetActorId: pet.id }).accepted, true);
assert.equal(simulation.useAbility(enemy, "mage-fire-blast", pet.id).accepted, true);
assert.ok((caster.combat.summons.find((entry) => entry.id === pet.id)?.health ?? 0) < before);
});
+17 -12
View File
@@ -3,6 +3,7 @@ import { GameDatabaseError } from "./database.mjs";
import { ARENA_BRACKETS, arenaMatchTolerance, assertArenaQueueInput, validateArenaComposition } from "./arena-rules.mjs";
import { ARENA_STAGES, chooseArenaStage } from "./arena-stages.mjs";
import { ArenaSimulation } from "./arena-simulation.mjs";
import { arenaKitForLoadout } from "./arena-character-kit.mjs";
const READY_CHECK_MS = 15_000;
const PVP_BOT_FILL_MS = 30_000;
@@ -222,18 +223,22 @@ export function createArenaService({ database, random = Math.random, now = () =>
}
function fillTeam(humans, team, bracket, rating) {
const members = humans.map((member) => ({
actorId: `player-${randomUUID()}`,
accountId: member.accountId,
characterId: member.characterId,
name: member.loadout.name || member.username,
team,
role: member.role,
isBot: false,
disconnected: false,
rating: database.getArenaRating(member.accountId, member.characterId, bracket).rating,
loadout: member.loadout,
}));
const members = humans.map((member) => {
const character = database.getCloudSave?.(member.accountId)?.data?.characters?.find((entry) => entry.id === member.characterId) ?? {};
return ({
actorId: `player-${randomUUID()}`,
accountId: member.accountId,
characterId: member.characterId,
name: character.name || member.username,
characterKit: arenaKitForLoadout(member.loadout, character),
team,
role: member.role,
isBot: false,
disconnected: false,
rating: database.getArenaRating(member.accountId, member.characterId, bracket).rating,
loadout: member.loadout,
});
});
const composition = validateArenaComposition(bracket, members.map((member) => member.role), { allowPartial: true });
if (!composition.ok) throw new GameDatabaseError(composition.message, 400, composition.code);
for (let index = 0; index < composition.missing.healer; index += 1) members.push(botMember(team, "healer", rating, index));
+3 -1
View File
@@ -1,5 +1,6 @@
import type {
ArenaAuthoritativeSnapshot,
ArenaCharacterKit,
ArenaCombatIntent,
ArenaResult,
ArenaRole,
@@ -8,6 +9,7 @@ import type {
import type { ArenaBracket, ArenaMode, ArenaRuleset } from "../src/game/arenaRules";
export interface ArenaSimulationParticipant {
characterKit?: ArenaCharacterKit;
actorId: string;
accountId?: string | null;
characterId?: string | null;
@@ -43,5 +45,5 @@ export declare class ArenaSimulation {
stop(): void;
step(): void;
snapshot(): ArenaAuthoritativeSnapshot;
receiveIntent(actorId: string, intent: ArenaCombatIntent): { accepted: boolean; reason?: string };
receiveIntent(actorId: string, intent: ArenaCombatIntent): { accepted: boolean; reason?: string; message?: string };
}
+198 -108
View File
@@ -1,19 +1,11 @@
import { arenaAiProfile, arenaDampening, arenaDrDuration, applyArenaHealing, shouldArenaBotChooseCorrectly } from "./arena-rules.mjs";
import { arenaAiProfile, arenaDampening, shouldArenaBotChooseCorrectly } from "./arena-rules.mjs";
import { initializeArenaCharacter, useArenaCharacterAbility, tickArenaCharacter, arenaCharacterSnapshot, damageArenaCharacter, commandArenaCharacter, bindArenaCharacter } from "./generated/arena-combat-runtime.mjs";
import { arenaFloorHeight, arenaGeometryLineClear, arenaNavigationPath } from "./arena-geometry.mjs";
export const ARENA_TICK_RATE = 20;
export const ARENA_SNAPSHOT_RATE = 10;
export const ARENA_TICK_MS = 1000 / ARENA_TICK_RATE;
const ABILITIES = Object.freeze({
attack: Object.freeze({ cooldownMs: 1500, range: 5, damage: 40 }),
strike: Object.freeze({ cooldownMs: 6000, range: 5, damage: 120 }),
"ranged-attack": Object.freeze({ cooldownMs: 2200, range: 30, damage: 52 }),
heal: Object.freeze({ cooldownMs: 0, range: 40, healing: 150, castMs: 1500, resource: 12 }),
interrupt: Object.freeze({ cooldownMs: 15000, range: 8, lockoutMs: 4000 }),
control: Object.freeze({ cooldownMs: 30000, range: 25, controlMs: 6000, drCategory: "incapacitate" }),
defensive: Object.freeze({ cooldownMs: 90000, range: 0, defensiveMs: 8000 }),
});
function distance2d(left, right) {
return Math.hypot(left.position[0] - right.position[0], left.position[2] - right.position[2]);
}
@@ -34,26 +26,34 @@ function segmentIntersectsBox(from, to, object) {
&& Math.abs(nearestZ - object.position[2]) <= radiusZ;
}
function newActor(participant, spawn, teamIndex, arenaCenter) {
const offset = participant.role === "healer" ? -2 : teamIndex * 2;
const facing = Math.atan2(arenaCenter[0] - spawn[0], arenaCenter[2] - spawn[2]);
function newActor(participant, spawn, teamIndex, preparationGate) {
const facing = Math.atan2(preparationGate[0] - spawn[0], preparationGate[2] - spawn[2]);
// Keep the first player on the validated anchor. Role-based sideways offsets
// put healers inside the starting-room wall in Nagrand.
const offset = teamIndex * 2;
return {
id: participant.actorId,
accountId: participant.accountId ?? null,
characterId: participant.characterId ?? null,
characterKit: participant.characterKit ?? null,
name: participant.name,
team: participant.team,
role: participant.role,
isBot: Boolean(participant.isBot),
disconnected: Boolean(participant.disconnected),
alive: true,
position: [spawn[0], spawn[1], spawn[2] + offset],
position: [spawn[0] + Math.sin(facing) * offset, spawn[1], spawn[2] + Math.cos(facing) * offset],
facing,
movement: [0, 0],
health: 1000,
maxHealth: 1000,
resource: 100,
maxResource: 100,
resource: participant.characterKit?.resource?.initial ?? 100,
maxResource: participant.characterKit?.resource?.maximum ?? 100,
gcdUntil: 0,
lastAbilityId: undefined,
abilityRevision: 0,
auras: [],
periodic: new Map(),
targetActorId: null,
cooldowns: new Map(),
effects: new Map(),
@@ -134,14 +134,13 @@ export class ArenaSimulation {
this.actors = new Map();
this.lastMechanicPulse = new Map();
const teamCounts = [0, 0];
const arenaCenter = [
(this.stage.bounds.min[0] + this.stage.bounds.max[0]) / 2,
(this.stage.bounds.min[2] + this.stage.bounds.max[2]) / 2,
];
for (const participant of options.participants) {
const team = participant.team;
const actor = newActor(participant, this.stage.teamSpawns[team], teamCounts[team]++, arenaCenter);
const teamIndex = teamCounts[team]++;
const actor = newActor(participant, this.stage.teamSpawns[team], teamIndex, this.stage.preparationGates[team]);
if (teamIndex) actor.position[1] = arenaFloorHeight(this.stage.id, actor.position[0], actor.position[2], actor.position[1], 2) ?? actor.position[1];
this.actors.set(actor.id, actor);
initializeArenaCharacter(actor, this.startedAt);
}
for (const object of this.stage.dynamicObjects) {
if (object.initialDelayRangeMs) {
@@ -173,19 +172,68 @@ export class ArenaSimulation {
}
hasLineOfSight(left, right, dynamicStates = null) {
if (!arenaGeometryLineClear(this.stage.id, [left.position[0], left.position[1] + 1.2, left.position[2]], [right.position[0], right.position[1] + 1.2, right.position[2]])) return false;
const states = dynamicStates ?? new Map(this.dynamicObjects().map((state) => [state.id, state]));
return !this.stage.lineOfSight.some((object) => {
if (object.dynamicObjectId && !states.get(object.dynamicObjectId)?.collisionEnabled) return false;
// Static walls come from the real mesh. Old proxy boxes created invisible
// obstacles and blocked routes that are open in the detailed arena.
if (!object.dynamicObjectId || !states.get(object.dynamicObjectId)?.collisionEnabled) return false;
return segmentIntersectsBox(left.position, right.position, object);
});
}
targetActor(actorId) {
const actor = this.actor(actorId);
if (actor) return actor;
for (const owner of this.actors.values()) {
const summon = owner.combat.summons.find((candidate) => candidate.id === actorId);
if (summon) return { ...owner, ...summon, team: owner.team, alive: summon.health > 0, facing: owner.facing };
}
return null;
}
projectGroundPoint(origin, requested, range) {
if (Math.hypot(requested[0] - origin[0], requested[2] - origin[2]) > range) return null;
if ([0, 2].some((axis) => requested[axis] < this.stage.bounds.min[axis] || requested[axis] > this.stage.bounds.max[axis])) return null;
const floor = arenaFloorHeight(this.stage.id, requested[0], requested[2], requested[1], 2);
if (floor === null && arenaFloorHeight(this.stage.id, origin[0], origin[2], origin[1], 2) !== null) return null;
const point = [requested[0], floor ?? requested[1], requested[2]];
return this.hasLineOfSight({ position: origin }, { position: point }) ? point : null;
}
resolvePosition(actor, requested, teleport = false) {
const x = Math.max(this.stage.bounds.min[0] + .35, Math.min(this.stage.bounds.max[0] - .35, requested[0]));
const z = Math.max(this.stage.bounds.min[2] + .35, Math.min(this.stage.bounds.max[2] - .35, requested[2]));
const floor = arenaFloorHeight(this.stage.id, x, z, actor.position[1], teleport ? 3 : 1);
const oldFloor = arenaFloorHeight(this.stage.id, actor.position[0], actor.position[2], actor.position[1], 2);
if (floor === null && oldFloor !== null) return [...actor.position];
const ground = floor ?? actor.groundY ?? actor.position[1];
const target = [x, Math.max(ground, requested[1]), z];
for (const height of [.55, 1.4]) {
const from = [actor.position[0], actor.position[1] + height, actor.position[2]];
const to = [target[0], target[1] + height, target[2]];
if (!arenaGeometryLineClear(this.stage.id, from, to)) return [...actor.position];
}
const dynamic = new Map(this.dynamicObjects().map((entry) => [entry.id, entry]));
for (const object of this.stage.lineOfSight) {
if (!object.dynamicObjectId || !dynamic.get(object.dynamicObjectId)?.collisionEnabled) continue;
if (target[1] > object.position[1] + object.size[1] / 2 || target[1] + 1.8 < object.position[1] - object.size[1] / 2) continue;
if (Math.abs(x - object.position[0]) < object.size[0] / 2 + .35 && Math.abs(z - object.position[2]) < object.size[2] / 2 + .35) return [...actor.position];
}
actor.groundY = ground;
return target;
}
receiveIntent(actorId, intent) {
const actor = this.actor(actorId);
if (!actor || actor.isBot || actor.disconnected || !actor.alive || this.phase !== "active") return { accepted: false, reason: "actor-unavailable" };
if (!actor || actor.isBot || actor.disconnected || !actor.alive || !["active", "preparation"].includes(this.phase)) return { accepted: false, reason: "actor-unavailable" };
const sequence = Math.trunc(Number(intent?.sequence));
if (!Number.isSafeInteger(sequence) || sequence <= actor.lastSequence) return { accepted: false, reason: "stale-sequence" };
actor.lastSequence = sequence;
if (intent.type === "bindings" && intent.actionBindings && typeof intent.actionBindings === "object") {
bindArenaCharacter(actor, intent.actionBindings);
return { accepted: true };
}
if (intent.type === "movement") {
const x = Math.max(-1, Math.min(1, Number(intent.movement?.x) || 0));
const z = Math.max(-1, Math.min(1, Number(intent.movement?.z) || 0));
@@ -198,56 +246,35 @@ export class ArenaSimulation {
return { accepted: true };
}
if (intent.type === "target") {
actor.targetActorId = this.actors.has(intent.targetActorId) ? intent.targetActorId : null;
actor.targetActorId = this.targetActor(intent.targetActorId) ? intent.targetActorId : null;
return { accepted: true };
}
if (intent.type === "ability") {
const ability = actor.characterKit.abilities[String(intent.abilityId ?? "")];
if (this.phase !== "active" && (ability?.target === "hostile" || ability?.effects.some((effect) => ["damage", "dot", "status", "execute", "finisher-damage"].includes(effect.kind)))) return { accepted: false, reason: "preparation" };
const ground = Array.isArray(intent.groundPosition) && intent.groundPosition.length === 3 && intent.groundPosition.every(Number.isFinite) ? intent.groundPosition : undefined;
return this.useAbility(actor, String(intent.abilityId ?? ""), intent.targetActorId, ground);
}
if (intent.type === "command") {
commandArenaCharacter(this, actor, intent.command, this.startedAt + this.tickNumber * ARENA_TICK_MS);
return { accepted: true };
}
if (intent.type === "jump") {
if (!actor.jumpVelocity && actor.combat.controlledUntil <= this.startedAt + this.tickNumber * ARENA_TICK_MS) actor.jumpVelocity = 7;
return { accepted: true };
}
if (intent.type === "ability") return this.useAbility(actor, String(intent.abilityId ?? ""), intent.targetActorId);
return { accepted: false, reason: "unknown-intent" };
}
useAbility(actor, abilityId, targetActorId = null) {
useAbility(actor, abilityId, targetActorId = null, groundPosition) {
const now = this.startedAt + this.tickNumber * ARENA_TICK_MS;
const ability = ABILITIES[abilityId];
if (!ability || !actor.alive || now < (actor.cooldowns.get(abilityId) ?? 0) || now < actor.lockoutUntil) return { accepted: false, reason: "ability-unavailable" };
if (actor.effects.get("control")?.endsAt > now) return { accepted: false, reason: "controlled" };
const target = this.actor(targetActorId ?? actor.targetActorId) ?? (abilityId === "defensive" ? actor : null);
if (!target || !target.alive) return { accepted: false, reason: "invalid-target" };
const friendly = target.team === actor.team;
if ((ability.healing && !friendly) || (!ability.healing && abilityId !== "defensive" && friendly)) return { accepted: false, reason: "invalid-target" };
if (ability.range > 0 && distance2d(actor, target) > ability.range) return { accepted: false, reason: "out-of-range" };
if (target !== actor && !this.hasLineOfSight(actor, target)) return { accepted: false, reason: "line-of-sight" };
if (ability.resource && actor.resource < ability.resource) return { accepted: false, reason: "resource" };
if (ability.castMs) {
actor.resource -= ability.resource ?? 0;
actor.casting = { abilityId, targetActorId: target.id, completesAt: now + ability.castMs };
return { accepted: true, casting: true };
}
actor.cooldowns.set(abilityId, now + ability.cooldownMs);
if (ability.damage) this.damage(target, ability.damage);
if (ability.lockoutMs) {
if (!target.casting) return { accepted: true, interrupted: false };
target.casting = null;
target.lockoutUntil = now + ability.lockoutMs;
}
if (ability.controlMs) {
const state = target.dr.get(ability.drCategory) ?? { applications: 0, endedAt: -Infinity };
const dr = arenaDrDuration(ability.controlMs, state.applications, now - state.endedAt);
if (dr.durationMs > 0) target.effects.set("control", { id: "control", endsAt: now + dr.durationMs, drCategory: ability.drCategory });
target.dr.set(ability.drCategory, { applications: dr.applications, endedAt: now + dr.durationMs });
}
if (ability.defensiveMs) actor.effects.set("defensive", { id: "defensive", endsAt: now + ability.defensiveMs });
return { accepted: true };
if (actor.characterKit) return useArenaCharacterAbility(this, actor, abilityId, targetActorId, now, groundPosition);
return { accepted: false, reason: "actor-unavailable" };
}
damage(target, amount) {
damage(target, amount, school = "physical") {
const now = this.startedAt + this.tickNumber * ARENA_TICK_MS;
const reduction = target.effects.get("defensive")?.endsAt > now ? 0.5 : 0;
target.health = Math.max(0, target.health - Math.round(amount * (1 - reduction)));
if (target.health <= 0) {
target.alive = false;
target.movement = [0, 0];
target.casting = null;
}
damageArenaCharacter(this, target, amount, school, now);
}
dynamicObjects() {
@@ -268,6 +295,8 @@ export class ArenaSimulation {
this.updateActors(simulationNow);
this.applyMechanics(simulationNow);
this.checkResult();
} else if (this.phase === "preparation") {
for (const actor of this.actors.values()) tickArenaCharacter(this, actor, simulationNow, ARENA_TICK_MS / 1000);
}
if (this.tickNumber % (ARENA_TICK_RATE / ARENA_SNAPSHOT_RATE) === 0) this.onSnapshot(this.snapshot());
}
@@ -277,30 +306,33 @@ export class ArenaSimulation {
for (const actor of this.actors.values()) {
for (const [effectId, effect] of actor.effects) if (effect.endsAt <= now) actor.effects.delete(effectId);
for (const [abilityId, endsAt] of actor.cooldowns) if (endsAt <= now) actor.cooldowns.delete(abilityId);
actor.resource = Math.min(actor.maxResource, actor.resource + 3 * deltaSeconds);
tickArenaCharacter(this, actor, now, deltaSeconds);
if (!actor.alive) continue;
if (actor.casting?.completesAt <= now) {
const cast = actor.casting;
actor.casting = null;
if (cast.abilityId === "heal") {
const target = this.actor(cast.targetActorId);
if (target?.alive && target.team === actor.team && distance2d(actor, target) <= ABILITIES.heal.range && this.hasLineOfSight(actor, target)) {
const elapsed = Math.max(0, now - this.activeStartedAt);
target.health = Math.min(target.maxHealth, target.health + applyArenaHealing(ABILITIES.heal.healing, elapsed));
}
}
}
if (!actor.casting && !(actor.effects.get("control")?.endsAt > now)) this.moveActor(actor, deltaSeconds);
if (actor.isBot && actor.navigationPath?.length && !actor.casting) this.followBotPath(actor);
if (actor.combat.controlledUntil <= now) this.moveActor(actor, deltaSeconds);
if (actor.isBot && now >= actor.nextBotDecisionAt) this.botDecision(actor, now);
}
}
moveActor(actor, deltaSeconds) {
const speed = 7;
const statuses = actor.statuses ?? [];
const speed = statuses.some((status) => status.kind === "root") ? 0 : 7 * (1 - Math.max(0, ...statuses.filter((status) => status.kind === "slow").map((status) => status.magnitude ?? 0)));
const nextX = actor.position[0] + actor.movement[0] * speed * deltaSeconds;
const nextZ = actor.position[2] + actor.movement[1] * speed * deltaSeconds;
actor.position[0] = Math.max(this.stage.bounds.min[0], Math.min(this.stage.bounds.max[0], nextX));
actor.position[2] = Math.max(this.stage.bounds.min[2], Math.min(this.stage.bounds.max[2], nextZ));
const previous = actor.position;
actor.position = this.resolvePosition(actor, [nextX, previous[1], nextZ]);
if (actor.position[0] === previous[0] && actor.position[2] === previous[2]) {
actor.position = this.resolvePosition(actor, [nextX, previous[1], previous[2]]);
actor.position = this.resolvePosition(actor, [actor.position[0], previous[1], nextZ]);
}
if (Math.hypot(...actor.movement) > 0.01) actor.facing = Math.atan2(actor.movement[0], actor.movement[1]);
actor.groundY ??= actor.position[1];
if (actor.jumpVelocity || actor.position[1] > actor.groundY + .01) {
actor.jumpVelocity ??= 0;
actor.position[1] += actor.jumpVelocity * deltaSeconds;
actor.jumpVelocity -= 20 * deltaSeconds;
if (actor.position[1] <= actor.groundY) { actor.position[1] = actor.groundY; actor.jumpVelocity = 0; }
}
}
botDecision(actor, now) {
@@ -308,44 +340,86 @@ export class ArenaSimulation {
const profile = arenaAiProfile(rating);
actor.nextBotDecisionAt = now + (profile.reactionMinSeconds + this.random() * (profile.reactionMaxSeconds - profile.reactionMinSeconds)) * 1000;
const allies = [...this.actors.values()].filter((entry) => entry.team === actor.team && entry.alive);
const enemies = [...this.actors.values()].filter((entry) => entry.team !== actor.team && entry.alive && this.hasLineOfSight(actor, entry));
const enemies = [...this.actors.values()].filter((entry) => entry.team !== actor.team && entry.alive);
const target = enemies.sort((left, right) => left.health - right.health)[0];
if (!target) {
actor.movement = [0, 0];
return;
}
actor.targetActorId = target.id;
commandArenaCharacter(this, actor, "attack", now);
const lowAlly = allies.sort((left, right) => left.health / left.maxHealth - right.health / right.maxHealth)[0];
if (actor.role === "healer" && lowAlly.health < lowAlly.maxHealth * 0.86) {
actor.movement = [0, 0];
this.useAbility(actor, "heal", lowAlly.id);
if (actor.characterKit) {
if (actor.casting) { actor.movement = [0, 0]; return; }
const abilities = Object.values(actor.characterKit.abilities).filter((ability) => now >= (actor.cooldowns.get(ability.id) ?? 0));
const has = (ability, kind) => ability.effects.some((effect) => effect.kind === kind);
let candidates = [];
let castTarget = target;
if (actor.role === "healer" && lowAlly.health < lowAlly.maxHealth * .86) {
candidates = abilities.filter((ability) => (ability.target === "friendly" || ability.target === "any") && (has(ability, "heal") || has(ability, "hot")));
castTarget = lowAlly;
} else if (actor.health < actor.maxHealth * .4 && shouldArenaBotChooseCorrectly(profile.correctDefensiveChance, profile.minimumErrorChance, this.random)) {
candidates = abilities.filter((ability) => ability.target === "self" && (has(ability, "heal") || has(ability, "shield") || has(ability, "apply-aura")));
castTarget = actor;
} else {
if (target.casting && shouldArenaBotChooseCorrectly(profile.healerInterruptChance, profile.minimumErrorChance, this.random)) candidates.push(...abilities.filter((ability) => has(ability, "interrupt")));
candidates.push(...abilities.filter((ability) => ability.target === "hostile" && (has(ability, "damage") || has(ability, "finisher-damage") || has(ability, "dot"))));
}
const distance = distance2d(actor, castTarget);
const range = Math.max(4, ...candidates.map((ability) => ability.range.max));
const dx = castTarget.position[0] - actor.position[0], dz = castTarget.position[2] - actor.position[2];
actor.facing = Math.atan2(dx, dz);
const needsMovement = distance > Math.min(range - .5, 24) || !this.hasLineOfSight(actor, castTarget);
if (needsMovement) {
if (!actor.navigationPath?.length || now >= (actor.nextPathAt ?? 0)) {
actor.navigationPath = arenaNavigationPath(this.stage.id, actor.position, castTarget.position);
actor.nextPathAt = now + 2500;
}
actor.movement = [dx / Math.max(.001, distance), dz / Math.max(.001, distance)];
this.followBotPath(actor);
} else { actor.navigationPath = []; actor.movement = [0, 0]; }
actor.targetActorId = castTarget.id;
for (const ability of candidates) {
if (distance <= ability.range.max || ability.target === "self") {
if (this.useAbility(actor, ability.id, castTarget.id, ability.targeting?.shape === "ground" ? castTarget.position : undefined).accepted) {
if (actor.casting) actor.movement = [0, 0];
break;
}
}
}
return;
}
const castingHealer = enemies.find((entry) => entry.role === "healer" && entry.casting);
if (castingHealer && shouldArenaBotChooseCorrectly(profile.healerInterruptChance, profile.minimumErrorChance, this.random)) {
this.useAbility(actor, "interrupt", castingHealer.id);
return;
}
canWalkLine(actor, to) {
const probe = { ...actor, position: [...actor.position] };
const distance = distance2d(actor, { position: to });
const steps = Math.max(1, Math.ceil(distance / .5));
for (let step = 1; step <= steps; step++) {
const requested = [actor.position[0] + (to[0] - actor.position[0]) * step / steps, probe.position[1], actor.position[2] + (to[2] - actor.position[2]) * step / steps];
const resolved = this.resolvePosition(probe, requested);
if (Math.hypot(resolved[0] - requested[0], resolved[2] - requested[2]) > .01) return false;
// Keep the navmesh portals on ramps and drops. A straight shortcut can
// cross an upper floor, fall, and leave the bot below its next waypoint.
if (Math.abs((probe.groundY ?? resolved[1]) - actor.position[1]) > .2) return false;
probe.position = [resolved[0], probe.groundY ?? resolved[1], resolved[2]];
}
if (actor.health < actor.maxHealth * 0.4 && shouldArenaBotChooseCorrectly(profile.correctDefensiveChance, profile.minimumErrorChance, this.random)) {
this.useAbility(actor, "defensive", actor.id);
return;
}
if (shouldArenaBotChooseCorrectly(profile.coordinatedCcChance * 0.25, profile.minimumErrorChance, this.random)) {
const healer = enemies.find((entry) => entry.role === "healer");
if (healer && this.useAbility(actor, "control", healer.id).accepted) return;
}
const distance = distance2d(actor, target);
if (distance > 4.5) {
const dx = target.position[0] - actor.position[0];
const dz = target.position[2] - actor.position[2];
const length = Math.max(0.001, Math.hypot(dx, dz));
actor.movement = [dx / length, dz / length];
if (distance <= 30) this.useAbility(actor, "ranged-attack", target.id);
} else {
actor.movement = [0, 0];
this.useAbility(actor, "strike", target.id);
this.useAbility(actor, "attack", target.id);
return true;
}
followBotPath(actor) {
const path = actor.navigationPath;
if (!path?.length) return;
while (path.length > 1 && distance2d(actor, { position: path[0] }) < .7) path.shift();
// Smooth portals only across a collision-checked, continuously walkable line.
if ((actor.nextPathSmoothTick ?? 0) <= this.tickNumber) {
for (let index = Math.min(path.length - 1, 8); index > 0; index--) {
if (this.canWalkLine(actor, path[index])) { path.splice(0, index); break; }
}
actor.nextPathSmoothTick = this.tickNumber + 10;
}
const dx = path[0][0] - actor.position[0], dz = path[0][2] - actor.position[2], distance = Math.hypot(dx, dz);
actor.movement = distance < .2 ? [0, 0] : [dx / distance, dz / distance];
}
applyMechanics(now) {
@@ -417,6 +491,16 @@ export class ArenaSimulation {
dampening: this.phase === "active" || this.phase === "finished" ? arenaDampening(elapsed) : 0.1,
actors: [...this.actors.values()].map((actor) => ({
id: actor.id, name: actor.name, team: actor.team, role: actor.role,
characterId: actor.characterId,
avatar: actor.avatar, visualEquipment: actor.visualEquipment,
...(actor.characterKit ? {
classId: actor.characterKit.classId, level: actor.characterKit.level,
actionBindings: actor.characterKit.actionBindings, abilityIds: Object.keys(actor.characterKit.abilities),
resourceType: actor.characterKit.resource.type,
gcdRemainingMs: Math.max(0, actor.gcdUntil - now),
lastAbilityId: actor.lastAbilityId, abilityRevision: actor.abilityRevision,
combat: arenaCharacterSnapshot(actor, now),
} : {}),
isBot: actor.isBot, disconnected: actor.disconnected, alive: actor.alive,
position: [...actor.position], facing: actor.facing,
health: actor.health, maxHealth: actor.maxHealth,
@@ -424,11 +508,17 @@ export class ArenaSimulation {
targetActorId: actor.targetActorId,
cooldowns: Object.fromEntries([...actor.cooldowns].map(([id, endsAt]) => [id, Math.max(0, endsAt - now)])),
effects: [
...actor.auras.map((aura) => ({ id: aura.definition.name, icon: aura.definition.icon, disposition: aura.definition.disposition, remainingMs: aura.expiresAt == null ? 0 : Math.max(0, aura.expiresAt - now), stacks: aura.stacks })),
...(actor.statuses ?? []).map((status) => ({ id: status.kind, disposition: "debuff", remainingMs: Math.max(0, status.endsAt - now) })),
...[...actor.periodic.values()].map((effect) => ({ id: effect.id, remainingMs: Math.max(0, effect.nextAt - now) + (effect.ticks - 1) * effect.intervalMs })),
...(this.combatEffects ?? []).filter((effect) => effect.targetId === actor.id).map((effect) => ({ id: effect.sourceAbilityId, disposition: effect.kind === "dot" ? "debuff" : "buff", remainingMs: Math.max(0, effect.nextTickAt - now) + (effect.remainingTicks - 1) * effect.intervalMs })),
...[...actor.effects.values()].map((effect) => ({ id: effect.id, remainingMs: Math.max(0, effect.endsAt - now) })),
...(actor.casting ? [{ id: `casting:${actor.casting.abilityId}`, remainingMs: Math.max(0, actor.casting.completesAt - now) }] : []),
],
})),
dynamicObjects: this.dynamicObjects(),
combatPresentation: this.combatPresentation ?? [],
combatEvents: this.combatEvents ?? [],
};
}
}
+54
View File
@@ -0,0 +1,54 @@
import { createReadStream, readFileSync } from "node:fs";
import path from "node:path";
import { pipeline } from "node:stream";
import { createGunzip } from "node:zlib";
export function contentMimeType(logicalPath) {
return ({
".glb": "model/gltf-binary", ".json": "application/json", ".js": "text/javascript",
".wasm": "application/wasm", ".ktx2": "image/ktx2", ".png": "image/png",
".webp": "image/webp", ".avif": "image/avif", ".svg": "image/svg+xml",
".mp3": "audio/mpeg", ".ogg": "audio/ogg", ".wav": "audio/wav", ".webm": "video/webm",
})[path.extname(logicalPath)] ?? "application/octet-stream";
}
function acceptsGzip(value = "") {
const encodings = new Map(String(value).split(",").map((entry) => {
const [name, ...parameters] = entry.trim().toLowerCase().split(";");
const quality = parameters.find((part) => part.trim().startsWith("q="));
return [name, quality ? Number(quality.trim().slice(2)) : 1];
}));
return (encodings.get("gzip") ?? encodings.get("*") ?? 0) > 0;
}
/** Resolve logical URLs to one immutable bundled object without expanding it on disk. */
export function createBundledContentHandler(root) {
let manifest;
return (request, response, pathname) => {
if (!["GET", "HEAD"].includes(request.method) || !/^\/(assets|basis|data)\//.test(pathname)) return false;
if (manifest === undefined) {
try { manifest = JSON.parse(readFileSync(path.join(root, "content/bootstrap-manifest.json"), "utf8")); }
catch (error) { if (error.code !== "ENOENT") throw error; manifest = null; }
}
const entry = manifest?.files[pathname];
if (!entry) return false;
const object = entry.download ?? entry;
if (!/^\/content\/bundled\/[a-f0-9]{64}\.[a-z0-9]+(?:\.g(?:z|zip))?$/.test(object.url)) return false;
const encoded = entry.download?.encoding === "gzip";
const sendGzip = encoded && acceptsGzip(request.headers["accept-encoding"]);
response.writeHead(200, {
"Content-Type": contentMimeType(pathname),
"Content-Length": sendGzip ? object.bytes : entry.bytes,
"Cache-Control": "public, max-age=3600",
"X-Content-Type-Options": "nosniff",
Vary: "Accept-Encoding",
...(sendGzip ? { "Content-Encoding": "gzip" } : {}),
});
if (request.method === "HEAD") { response.end(); return true; }
const stream = createReadStream(path.join(root, object.url.slice(1)));
const done = (error) => { if (error) response.destroy(error); };
if (encoded && !sendGzip) pipeline(stream, createGunzip(), response, done);
else pipeline(stream, response, done);
return true;
};
}
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { createServer, request } from "node:http";
import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { gzipSync, gunzipSync } from "node:zlib";
import { createBundledContentHandler } from "./bundled-content.mjs";
test("first-launch logical asset URLs serve shared gzip objects with lossless identity fallback", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "healer-bundled-server-"));
const original = Buffer.from("glTF original model bytes ".repeat(1000));
const compressed = gzipSync(original);
const objectUrl = `/content/bundled/${"a".repeat(64)}.glb.gzip`;
await mkdir(path.join(root, "content/bundled"), { recursive: true });
await writeFile(path.join(root, objectUrl.slice(1)), compressed);
await writeFile(path.join(root, "content/bootstrap-manifest.json"), JSON.stringify({ files: {
"/assets/game/dungeons/test/visual.glb": { bytes: original.length, download: { url: objectUrl, encoding: "gzip", bytes: compressed.length } },
} }));
const serve = createBundledContentHandler(root);
const server = createServer((req, res) => {
if (!serve(req, res, new URL(req.url, "http://localhost").pathname)) { res.writeHead(404); res.end(); }
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const port = server.address().port;
const get = (encoding, method = "GET") => new Promise((resolve, reject) => {
request({ host: "127.0.0.1", port, path: "/assets/game/dungeons/test/visual.glb?runtime=1", method, headers: { "Accept-Encoding": encoding } }, (response) => {
const chunks = [];
response.on("data", (chunk) => chunks.push(chunk));
response.on("end", () => resolve({ headers: response.headers, body: Buffer.concat(chunks) }));
}).on("error", reject).end();
});
try {
const gzip = await get("gzip");
assert.equal(gzip.headers["content-encoding"], "gzip");
assert.deepEqual(gzip.body, compressed);
assert.deepEqual(gunzipSync(gzip.body), original);
const identity = await get("gzip;q=0, *;q=1");
assert.equal(identity.headers["content-encoding"], undefined);
assert.deepEqual(identity.body, original);
const head = await get("gzip", "HEAD");
assert.equal(head.body.length, 0);
assert.equal(Number(head.headers["content-length"]), compressed.length);
} finally {
await new Promise((resolve) => server.close(resolve));
await rm(root, { recursive: true, force: true });
}
});
@@ -0,0 +1,6 @@
var ql=Object.create;var xs=Object.defineProperty;var Rl=Object.getOwnPropertyDescriptor;var jl=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,El=Object.prototype.hasOwnProperty;var Ze=(e,a,t)=>()=>{if(t)throw t[0];try{return e&&(a=e(e=0)),a}catch(i){throw t=[i],i}};var we=(e,a)=>()=>{try{return a||e((a={exports:{}}).exports,a),a.exports}catch(t){throw a=0,t}},Yo=(e,a)=>{for(var t in a)xs(e,t,{get:a[t],enumerable:!0})},Bl=(e,a,t,i)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of jl(a))!El.call(e,s)&&s!==t&&xs(e,s,{get:()=>a[s],enumerable:!(i=Rl(a,s))||i.enumerable});return e};var Ce=(e,a,t)=>(t=e!=null?ql(Dl(e)):{},Bl(a||!e||!e.__esModule?xs(t,"default",{value:e,enumerable:!0}):t,e));function fe(e,a={}){return{...Vl,feature:e,...a}}function G(e,a,t,i,s){return{skinColor:e,face:a,hairStyle:t,hairColor:i,feature:s}}function Be(e){let a=e.featureLabel??"Features";return{id:e.id,dbcId:e.dbcId,name:e.name,faction:e.faction,genders:e.genders,unrestrictedClasses:!0,sigil:e.sigil,accent:e.accent,description:e.description,labels:{male:fe(a),female:fe(a)},counts:{male:e.male,female:e.female??e.male}}}function Vi(e){return ai.find(a=>a.id===e)??ai[0]}function fa(e){return qa.find(a=>a.id===e)??qa[0]}function Xe(e){return fa(e).archetype}function Wl(e){return Vi(e).categoryId??"wow"}function As(e){return fa(e).categoryId??"wow"}function Nl(e){return Wl(e)==="rom"}function st(e){return As(e)==="rom"}function Qo(e,a){let t=Vi(e);if(Nl(e)){if(a&&a!=="rom")return[];let o=new Set(Ol[e]);return qa.filter(r=>o.has(r.id))}if(a==="rom")return[];let i=o=>a?As(o.id)===a:As(o.id)!=="rom";if(t.unrestrictedClasses)return qa.filter(o=>i(o));let s=t.dbcId;return qa.filter(o=>i(o)&&_l[o.id].includes(s))}function Zo(e){return Vi(e).genders??["male","female"]}function Xo(){return{skinColor:0,face:0,hairStyle:0,hairColor:0,feature:0}}function er(e,a,t=Math.random){let i=Vi(e).counts[a];return Object.fromEntries(Hl.map(s=>[s,Math.floor(t()*i[s])]))}var Vl,ai,Fl,qs,qa,tt,Rs,it,_l,Ol,Hl,sa=Ze(()=>{Vl={skinColor:"Skin Color",face:"Face",hairStyle:"Hair Style",hairColor:"Hair Color",feature:"Features"};ai=[{id:"human",dbcId:1,name:"Human",faction:"alliance",sigil:"HU",accent:"#6f9dd7",description:"Versatile champions of the Alliance kingdoms.",labels:{male:fe("Facial Hair"),female:fe("Piercings")},counts:{male:G(10,12,17,10,9),female:G(10,15,24,10,7)}},{id:"orc",dbcId:2,name:"Orc",faction:"horde",sigil:"OR",accent:"#bd6450",description:"Unyielding warriors bound by strength and honor.",labels:{male:fe("Facial Hair"),female:fe("Piercings")},counts:{male:G(9,9,12,8,11),female:G(9,9,13,8,7)}},{id:"dwarf",dbcId:3,name:"Dwarf",faction:"alliance",sigil:"DW",accent:"#c58c5a",description:"Hardy mountain folk, explorers, and steadfast allies.",labels:{male:fe("Facial Hair"),female:fe("Piercings")},counts:{male:G(9,10,16,10,11),female:G(9,10,19,10,6)}},{id:"night-elf",dbcId:4,name:"Night Elf",faction:"alliance",sigil:"NE",accent:"#9275cf",description:"Ancient guardians attuned to shadow and nature.",labels:{male:fe("Facial Hair"),female:fe("Markings")},counts:{male:G(9,9,12,8,6),female:G(9,9,12,8,10)}},{id:"undead",dbcId:5,name:"Undead",faction:"horde",sigil:"UD",accent:"#8ba39d",description:"Forsaken survivors wielding grim determination.",labels:{male:fe("Features"),female:fe("Features")},counts:{male:G(6,10,15,10,17),female:G(6,10,15,10,8)}},{id:"tauren",dbcId:6,name:"Tauren",faction:"horde",sigil:"TA",accent:"#ad805c",description:"Powerful nomads guided by the Earth Mother.",labels:{male:fe("Facial Hair",{hairStyle:"Horn Style",hairColor:"Horn Color"}),female:fe("Hair",{hairStyle:"Horn Style",hairColor:"Horn Color"})},counts:{male:G(19,5,13,3,7),female:G(11,4,12,3,5)}},{id:"gnome",dbcId:7,name:"Gnome",faction:"alliance",sigil:"GN",accent:"#d28faf",description:"Brilliant inventors with courage beyond their stature.",labels:{male:fe("Facial Hair"),female:fe("Earrings")},counts:{male:G(5,7,12,9,8),female:G(5,7,12,9,7)}},{id:"troll",dbcId:8,name:"Troll",faction:"horde",sigil:"TR",accent:"#50a99a",description:"Fierce jungle hunters carrying an ancient legacy.",labels:{male:fe("Tusks"),female:fe("Tusks")},counts:{male:G(6,5,10,10,11),female:G(6,6,10,10,6)}},{id:"blood-elf",dbcId:10,name:"Blood Elf",faction:"horde",sigil:"BE",accent:"#d75f76",description:"Arcane survivors rebuilding a proud magical dynasty.",labels:{male:fe("Facial Hair"),female:fe("Earrings")},counts:{male:G(10,10,16,10,10),female:G(10,10,20,10,11)}},{id:"draenei",dbcId:11,name:"Draenei",faction:"alliance",sigil:"DR",accent:"#6986d8",description:"Exiled voyagers devoted to hope and the Light.",labels:{male:fe("Facial Hair"),female:fe("Horn Style")},counts:{male:G(14,10,14,7,8),female:G(12,10,16,7,7)}},Be({id:"goblin",dbcId:9,name:"Goblin",faction:"horde",sigil:"GO",accent:"#84ad4b",description:"Cunning cartels turn invention, nerve, and explosive ambition into power.",male:G(16,5,19,9,24),female:G(9,10,18,9,24)}),Be({id:"zandalari-troll",dbcId:12,name:"Zandalari TrLine truncated
/*! Bundled license information:
@capacitor/core/dist/index.js:
(*! Capacitor: https://capacitorjs.com/ - MIT License *)
*/
+1
View File
@@ -0,0 +1 @@
{"nagrand-arena":{"navigation":[-24.812,12.3,-40.042,-18.812,15.3,-40.842,-25.037,12.2,-41.192,-18.812,15.3,-40.842,-24.375,12.5,-49.678,-24.424,12.5,-44.649,-24.375,12.5,-49.678,-24.994,12.3,-50.66,-25.632,12.2,-49.462,-24.994,12.3,-50.66,-25.612,12.4,-51.642,-26.412,12.4,-50.842,-26.412,12.4,-50.842,-26.612,12.4,-49.242,-25.632,12.2,-49.462,-26.612,12.4,-49.242,-25.487,12.2,-43.492,-25.604,12.2,-48.253,-25.487,12.2,-43.492,-25.037,12.2,-41.192,-24.424,12.5,-44.649,-25.037,12.2,-41.192,-18.812,15.3,-40.842,-24.424,12.5,-44.649,-24.424,12.5,-44.649,-24.375,12.5,-49.678,-25.604,12.2,-48.253,-25.632,12.2,-49.462,-24.994,12.3,-50.66,-26.412,12.4,-50.842,-24.375,12.5,-49.678,-25.632,12.2,-49.462,-25.604,12.2,-48.253,-25.632,12.2,-49.462,-26.612,12.4,-49.242,-25.604,12.2,-48.253,-25.604,12.2,-48.253,-25.487,12.2,-43.492,-24.424,12.5,-44.649,-24.812,12.3,-40.042,-25.037,12.2,-41.192,-25.612,12.2,-41.985,-25.037,12.2,-41.192,-25.487,12.2,-43.492,-25.612,12.2,-41.985,-25.487,12.2,-43.492,-27.612,12.6,-46.842,-25.612,12.2,-41.985,-25.487,12.2,-43.492,-27.412,12.6,-48.442,-27.612,12.6,-46.842,-25.487,12.2,-43.492,-26.612,12.4,-49.242,-27.412,12.6,-48.442,-25.612,12.5,-52.842,-24.212,12.9,-55.242,-24.812,12.9,-54.842,-12.72,17.9,-49.719,-12.812,17.9,-56.642,-18.411,15.6,-49.426,-12.812,17.9,-56.642,-23.072,13.2,-55.382,-18.411,15.6,-49.426,-23.072,13.2,-55.382,-24.212,12.9,-55.242,-25.612,12.5,-52.842,-25.612,12.5,-52.842,-25.612,12.4,-51.642,-24.994,12.3,-50.66,-24.994,12.3,-50.66,-24.375,12.5,-49.678,-23.072,13.2,-55.382,-24.375,12.5,-49.678,-18.812,15.3,-40.842,-18.411,15.6,-49.426,-18.812,15.3,-40.842,-12.612,18,-41.642,-18.411,15.6,-49.426,-12.612,18,-41.642,-12.72,17.9,-49.719,-18.411,15.6,-49.426,-18.411,15.6,-49.426,-23.072,13.2,-55.382,-24.375,12.5,-49.678,-23.072,13.2,-55.382,-25.612,12.5,-52.842,-24.994,12.3,-50.66,-25.012,12.2,-39.642,-24.812,12.3,-40.042,-25.498,12.2,-40.585,-24.812,12.3,-40.042,-25.612,12.2,-41.985,-25.498,12.2,-40.585,-25.612,12.2,-41.985,-28.412,12.7,-46.242,-25.498,12.2,-40.585,-25.612,12.2,-41.985,-27.612,12.6,-46.842,-28.412,12.7,-46.242,-24.212,12.9,-55.242,-23.072,13.2,-55.382,-23.812,13.1,-56.842,-23.072,13.2,-55.382,-22.712,13.4,-56.822,-23.812,13.1,-56.842,-23.072,13.2,-55.382,-12.812,17.9,-56.642,-22.712,13.4,-56.822,21.988,13.6,-56.842,17.188,15.4,-56.642,18.768,14.8,-55.462,17.188,15.4,-56.642,17.157,15.6,-54.273,18.768,14.8,-55.462,17.157,15.6,-54.273,16.988,16,-41.242,18.772,15,-48.227,16.988,16,-41.242,21.788,13.8,-40.642,18.772,15,-48.227,21.788,13.8,-40.642,21.96,13.8,-54.527,18.772,15,-48.227,21.96,13.8,-54.527,21.988,13.6,-56.842,20,14.4,-54.227,21.988,13.6,-56.842,18.768,14.8,-55.462,20,14.4,-54.227,18.768,14.8,-55.462,17.157,15.6,-54.273,20,14.4,-54.227,17.157,15.6,-54.273,18.772,15,-48.227,20,14.4,-54.227,18.772,15,-48.227,21.96,13.8,-54.527,20,14.4,-54.227,21.788,13.8,-40.642,23.388,13.1,-40.442,24.455,12.8,-42.468,24.455,12.8,-42.468,28.188,13.2,-49.562,24.796,12.8,-48.229,28.188,13.2,-49.562,30.321,13.2,-53.615,28.376,13.2,-53.041,30.321,13.2,-53.615,31.388,13.4,-55.642,29.588,13.1,-56.842,29.588,13.1,-56.842,23.074,13.2,-56.842,24.772,12.8,-53.027,23.074,13.2,-56.842,21.988,13.6,-56.842,21.96,13.8,-54.527,21.96,13.8,-54.527,21.788,13.8,-40.642,23.572,13,-47.052,21.788,13.8,-40.642,24.455,12.8,-42.468,23.572,13,-47.052,24.796,12.8,-48.229,28.188,13.2,-49.562,24.792,12.8,-51.824,24.455,12.8,-42.468,24.796,12.8,-48.229,23.572,13,-47.052,28.376,13.2,-53.041,30.321,13.2,-53.615,29.588,13.1,-56.842,28.188,13.2,-49.562,28.376,13.2,-53.041,24.792,12.8,-51.824,24.772,12.8,-53.027,23.074,13.2,-56.842,23.584,13,-53.036,29.588,13.1,-56.842,24.772,12.8,-53.027,28.376,13.2,-53.041,23.074,13.2,-56.842,21.96,13.8,-54.527,23.584,13,-53.036,21.96,13.8,-54.527,23.572,13,-47.052,23.584,13,-53.036,24.796,12.8,-48.229,24.792,12.8,-51.824,23.572,13,-47.052,24.792,12.8,-51.824,28.376,13.2,-53.041,24.772,12.8,-53.027,24.772,12.8,-53.027,23.584,13,-53.036,24.792,12.8,-51.824,23.584,13,-53.036,23.572,13,-47.052,24.792,12.8,-51.824,-4.612,20.9,-51.842,-4.012,20.9,-52.442,-3.612,20.9,-56.442,-12.612,18,-41.642,-10.412,19,-41.842,-11.203,18.7,-44.661,-10.412,19,-41.842,-7.512,20.9,-46.842,-10.015,19.5,-44.653,-7.512,20.9,-46.842,-4.612,20.9,-51.842,-7.62,21,-54.223,-4.612,20.9,-51.842,-3.612,20.9,-56.442,-7.62,21,-54.223,-3.612,20.9,-56.442,-8.212,21.1,-56.542,-7.62,21,-54.223,-8.212,21.1,-56.542,-12.812,17.9,-56.642,-8.808,20.6,-54.231,-12.812,17.9,-56.642,-12.72,17.9,-49.719,-8.808,20.6,-54.231,-12.72,17.9,-49.719,-12.612,18,-41.642,-11.203,18.7,-44.661,-11.203,18.7,-44.661,-10.412,19,-41.842,-10.015,19.5,-44.653,-10.015,19.5,-44.653,-7.512,20.9,-46.842,-9.995,19.6,-47.057,-7.512,20.9,-46.842,-7.62,21,-54.223,-8.808,20.6,-54.231,-7.62,21,-54.223,-8.212,21.1,-56.542,-8.808,20.6,-54.231,-8.808,20.6,-54.231,-12.72,17.9,-49.719,-9.995,19.6,-47.057,-12.72,17.9,-49.719,-11.203,18.7,-44.661,-9.995,19.6,-47.057,-11.203,18.7,-44.661,-10.015,19.5,-44.653,-9.995,19.6,-47.057,-9.995,19.6,-47.057,-7.Line truncated
+1
View File
@@ -0,0 +1 @@
{"nagrand-arena":[-24.812,12.3,-40.042,-18.812,15.3,-40.842,-25.037,12.2,-41.192,-18.812,15.3,-40.842,-24.375,12.5,-49.678,-24.424,12.5,-44.649,-24.375,12.5,-49.678,-24.994,12.3,-50.66,-25.632,12.2,-49.462,-24.994,12.3,-50.66,-25.612,12.4,-51.642,-26.412,12.4,-50.842,-26.412,12.4,-50.842,-26.612,12.4,-49.242,-25.632,12.2,-49.462,-26.612,12.4,-49.242,-25.487,12.2,-43.492,-25.604,12.2,-48.253,-25.487,12.2,-43.492,-25.037,12.2,-41.192,-24.424,12.5,-44.649,-25.037,12.2,-41.192,-18.812,15.3,-40.842,-24.424,12.5,-44.649,-24.424,12.5,-44.649,-24.375,12.5,-49.678,-25.604,12.2,-48.253,-25.632,12.2,-49.462,-24.994,12.3,-50.66,-26.412,12.4,-50.842,-24.375,12.5,-49.678,-25.632,12.2,-49.462,-25.604,12.2,-48.253,-25.632,12.2,-49.462,-26.612,12.4,-49.242,-25.604,12.2,-48.253,-25.604,12.2,-48.253,-25.487,12.2,-43.492,-24.424,12.5,-44.649,-24.812,12.3,-40.042,-25.037,12.2,-41.192,-25.612,12.2,-41.985,-25.037,12.2,-41.192,-25.487,12.2,-43.492,-25.612,12.2,-41.985,-25.487,12.2,-43.492,-27.612,12.6,-46.842,-25.612,12.2,-41.985,-25.487,12.2,-43.492,-27.412,12.6,-48.442,-27.612,12.6,-46.842,-25.487,12.2,-43.492,-26.612,12.4,-49.242,-27.412,12.6,-48.442,-25.612,12.5,-52.842,-24.212,12.9,-55.242,-24.812,12.9,-54.842,-12.72,17.9,-49.719,-12.812,17.9,-56.642,-18.411,15.6,-49.426,-12.812,17.9,-56.642,-23.072,13.2,-55.382,-18.411,15.6,-49.426,-23.072,13.2,-55.382,-24.212,12.9,-55.242,-25.612,12.5,-52.842,-25.612,12.5,-52.842,-25.612,12.4,-51.642,-24.994,12.3,-50.66,-24.994,12.3,-50.66,-24.375,12.5,-49.678,-23.072,13.2,-55.382,-24.375,12.5,-49.678,-18.812,15.3,-40.842,-18.411,15.6,-49.426,-18.812,15.3,-40.842,-12.612,18,-41.642,-18.411,15.6,-49.426,-12.612,18,-41.642,-12.72,17.9,-49.719,-18.411,15.6,-49.426,-18.411,15.6,-49.426,-23.072,13.2,-55.382,-24.375,12.5,-49.678,-23.072,13.2,-55.382,-25.612,12.5,-52.842,-24.994,12.3,-50.66,-25.012,12.2,-39.642,-24.812,12.3,-40.042,-25.498,12.2,-40.585,-24.812,12.3,-40.042,-25.612,12.2,-41.985,-25.498,12.2,-40.585,-25.612,12.2,-41.985,-28.412,12.7,-46.242,-25.498,12.2,-40.585,-25.612,12.2,-41.985,-27.612,12.6,-46.842,-28.412,12.7,-46.242,-24.212,12.9,-55.242,-23.072,13.2,-55.382,-23.812,13.1,-56.842,-23.072,13.2,-55.382,-22.712,13.4,-56.822,-23.812,13.1,-56.842,-23.072,13.2,-55.382,-12.812,17.9,-56.642,-22.712,13.4,-56.822,21.988,13.6,-56.842,17.188,15.4,-56.642,18.768,14.8,-55.462,17.188,15.4,-56.642,17.157,15.6,-54.273,18.768,14.8,-55.462,17.157,15.6,-54.273,16.988,16,-41.242,18.772,15,-48.227,16.988,16,-41.242,21.788,13.8,-40.642,18.772,15,-48.227,21.788,13.8,-40.642,21.96,13.8,-54.527,18.772,15,-48.227,21.96,13.8,-54.527,21.988,13.6,-56.842,20,14.4,-54.227,21.988,13.6,-56.842,18.768,14.8,-55.462,20,14.4,-54.227,18.768,14.8,-55.462,17.157,15.6,-54.273,20,14.4,-54.227,17.157,15.6,-54.273,18.772,15,-48.227,20,14.4,-54.227,18.772,15,-48.227,21.96,13.8,-54.527,20,14.4,-54.227,21.788,13.8,-40.642,23.388,13.1,-40.442,24.455,12.8,-42.468,24.455,12.8,-42.468,28.188,13.2,-49.562,24.796,12.8,-48.229,28.188,13.2,-49.562,30.321,13.2,-53.615,28.376,13.2,-53.041,30.321,13.2,-53.615,31.388,13.4,-55.642,29.588,13.1,-56.842,29.588,13.1,-56.842,23.074,13.2,-56.842,24.772,12.8,-53.027,23.074,13.2,-56.842,21.988,13.6,-56.842,21.96,13.8,-54.527,21.96,13.8,-54.527,21.788,13.8,-40.642,23.572,13,-47.052,21.788,13.8,-40.642,24.455,12.8,-42.468,23.572,13,-47.052,24.796,12.8,-48.229,28.188,13.2,-49.562,24.792,12.8,-51.824,24.455,12.8,-42.468,24.796,12.8,-48.229,23.572,13,-47.052,28.376,13.2,-53.041,30.321,13.2,-53.615,29.588,13.1,-56.842,28.188,13.2,-49.562,28.376,13.2,-53.041,24.792,12.8,-51.824,24.772,12.8,-53.027,23.074,13.2,-56.842,23.584,13,-53.036,29.588,13.1,-56.842,24.772,12.8,-53.027,28.376,13.2,-53.041,23.074,13.2,-56.842,21.96,13.8,-54.527,23.584,13,-53.036,21.96,13.8,-54.527,23.572,13,-47.052,23.584,13,-53.036,24.796,12.8,-48.229,24.792,12.8,-51.824,23.572,13,-47.052,24.792,12.8,-51.824,28.376,13.2,-53.041,24.772,12.8,-53.027,24.772,12.8,-53.027,23.584,13,-53.036,24.792,12.8,-51.824,23.584,13,-53.036,23.572,13,-47.052,24.792,12.8,-51.824,-4.612,20.9,-51.842,-4.012,20.9,-52.442,-3.612,20.9,-56.442,-12.612,18,-41.642,-10.412,19,-41.842,-11.203,18.7,-44.661,-10.412,19,-41.842,-7.512,20.9,-46.842,-10.015,19.5,-44.653,-7.512,20.9,-46.842,-4.612,20.9,-51.842,-7.62,21,-54.223,-4.612,20.9,-51.842,-3.612,20.9,-56.442,-7.62,21,-54.223,-3.612,20.9,-56.442,-8.212,21.1,-56.542,-7.62,21,-54.223,-8.212,21.1,-56.542,-12.812,17.9,-56.642,-8.808,20.6,-54.231,-12.812,17.9,-56.642,-12.72,17.9,-49.719,-8.808,20.6,-54.231,-12.72,17.9,-49.719,-12.612,18,-41.642,-11.203,18.7,-44.661,-11.203,18.7,-44.661,-10.412,19,-41.842,-10.015,19.5,-44.653,-10.015,19.5,-44.653,-7.512,20.9,-46.842,-9.995,19.6,-47.057,-7.512,20.9,-46.842,-7.62,21,-54.223,-8.808,20.6,-54.231,-7.62,21,-54.223,-8.212,21.1,-56.542,-8.808,20.6,-54.231,-8.808,20.6,-54.231,-12.72,17.9,-49.719,-9.995,19.6,-47.057,-12.72,17.9,-49.719,-11.203,18.7,-44.661,-9.995,19.6,-47.057,-11.203,18.7,-44.661,-10.015,19.5,-44.653,-9.995,19.6,-47.057,-9.995,19.6,-47.057,-7.512,20.9,-46.8Line truncated
+6
View File
@@ -7,6 +7,7 @@ import { createArenaService } from "./arena-service.mjs";
import { publicManastormAdminConfig } from "./manastorm-config.mjs";
import { createOnlineSessionManager } from "./online-session.mjs";
import { upgradeArenaWebSocket } from "./websocket.mjs";
import { createBundledContentHandler } from "./bundled-content.mjs";
const MIME_TYPES = new Map([
[".css", "text/css; charset=utf-8"], [".glb", "model/gltf-binary"],
@@ -148,6 +149,7 @@ function createAuthLimiter() {
export function createGameServer(options = {}) {
const staticDir = path.resolve(options.staticDir ?? process.env.STATIC_DIR ?? "dist");
const contentDir = path.resolve(options.contentDir ?? process.env.CONTENT_DIR ?? "content");
const serveBundledContent = createBundledContentHandler(staticDir);
const allowedOrigins = parseAllowedOrigins(options.corsOrigins ?? process.env.CORS_ORIGINS);
const bodyLimit = Math.max(1024, Number(options.bodyLimit ?? process.env.MAX_JSON_BODY_BYTES ?? 5 * 1024 * 1024));
const trustProxy = String(options.trustProxy ?? process.env.TRUST_PROXY ?? "").toLowerCase() === "true";
@@ -344,6 +346,10 @@ export function createGameServer(options = {}) {
json(response, 404, { error: "API route not found.", code: "not_found" });
return;
}
if (serveBundledContent(request, response, url.pathname)) return;
if (url.pathname === "/content/bootstrap-manifest.json" || url.pathname.startsWith("/content/bundled/")) {
if (serveStatic(request, response, staticDir, url.pathname, { spaFallback: false, noCache: true })) return;
}
if (url.pathname === "/content" || url.pathname.startsWith("/content/")) {
const contentPath = url.pathname.slice("/content".length) || "/manifest.json";
const served = serveStatic(request, response, contentDir, contentPath, {
+16 -16
View File
@@ -9,7 +9,7 @@
"assetBaseUrl": "/assets/game/arenas/nagrand-arena",
"bounds": { "min": [-75, 8, -60], "max": [75, 26, 50] },
"teamSpawns": [[-43.41, 13.4, -42.04], [42.03, 14.5, -44.44]],
"preparationGates": [[-35, 14, -38], [34, 15, -40]],
"preparationGates": [[-38.418, 13.4, -41.764], [37.654, 14.5, -42.021]],
"spectatorPositions": [[0, 35, 42], [0, 35, -54]],
"shadowSight": [[0, 14, 18], [0, 14, -18]],
"lineOfSight": [
@@ -26,8 +26,8 @@
"mapId": 562,
"assetBaseUrl": "/assets/game/arenas/blades-edge-arena",
"bounds": { "min": [-18, 27, -68], "max": [78, 83, 68] },
"teamSpawns": [[29.2, 50.7, -51.49], [31.13, 54.4, 49.51]],
"preparationGates": [[29, 51, -44], [31, 54, 42]],
"teamSpawns": [[29.2, 50.702, -51.49], [31.13, 54.403, 49.51]],
"preparationGates": [[29.067, 50.702, -46.492], [29.137, 54.403, 44.924]],
"spectatorPositions": [[-10, 75, 0], [70, 75, 0]],
"shadowSight": [[10, 55, 0], [50, 55, 0]],
"lineOfSight": [
@@ -44,8 +44,8 @@
"mapId": 572,
"assetBaseUrl": "/assets/game/arenas/ruins-of-lordaeron",
"bounds": { "min": [-62, 26, -108], "max": [54, 37, 78] },
"teamSpawns": [[-8.68, 30.1, -73.96], [-5.08, 27.6, 57.28]],
"preparationGates": [[-8, 30, -65], [-5, 28, 49]],
"teamSpawns": [[-8.68, 30.098, -73.96], [-5.08, 27.601, 57.28]],
"preparationGates": [[-8.302, 30.098, -68.974], [-5.032, 27.601, 52.28]],
"spectatorPositions": [[48, 45, -15], [-55, 45, -15]],
"shadowSight": [[18, 29, -15], [-26, 29, -15]],
"lineOfSight": [
@@ -61,8 +61,8 @@
"mapId": 617,
"assetBaseUrl": "/assets/game/arenas/dalaran-sewers",
"bounds": { "min": [-52, 0, -68], "max": [52, 32, 40] },
"teamSpawns": [[-12.41, 20.1, -63.05], [21.79, 20.2, 25.15]],
"preparationGates": [[-10, 20, -55], [20, 20, 18]],
"teamSpawns": [[-12.41, 20.1, -63.05], [21.79, 20.221, 25.65]],
"preparationGates": [[-9.252, 20.1, -59.173], [22.524, 20.221, 20.704]],
"spectatorPositions": [[-45, 31, -14], [45, 31, -14]],
"shadowSight": [[-18, 20, -14], [18, 20, -14]],
"lineOfSight": [
@@ -81,8 +81,8 @@
"mapId": 618,
"assetBaseUrl": "/assets/game/arenas/ring-of-valor",
"bounds": { "min": [-58, 20, -40], "max": [58, 45, 42] },
"teamSpawns": [[0, 27, 25], [0, 27, -25]],
"preparationGates": [[0, 27, 20], [0, 27, -20]],
"teamSpawns": [[-1.5, 26.8, 26], [0, 26.8, -25]],
"preparationGates": [[-3.413, 26.8, 21.381], [-3.536, 26.8, -21.464]],
"spectatorPositions": [[-52, 50, 0], [52, 50, 0]],
"shadowSight": [[-25, 27, 0], [25, 27, 0]],
"lineOfSight": [
@@ -106,8 +106,8 @@
"mapId": 129,
"assetBaseUrl": "/assets/game/arenas/warnorken-arena",
"bounds": { "min": [-47, -24, -47], "max": [47, 25, 47] },
"teamSpawns": [[-42.7, -21.75, 14.12], [41.3, -21.65, -6.58]],
"preparationGates": [[-35, -21.5, 12], [34, -21.5, -5]],
"teamSpawns": [[-42.7, -21.748, 14.12], [41.3, -21.647, -6.58]],
"preparationGates": [[-37.879, -21.748, 12.793], [40.407, -21.647, -1.66]],
"spectatorPositions": [[0, 19, 42], [0, 19, -42]],
"shadowSight": [[0, -21.5, 20], [0, -21.5, -20]],
"lineOfSight": [
@@ -122,9 +122,9 @@
"sourceMap": "BlackrookHoldArena",
"mapId": 1784,
"assetBaseUrl": "/assets/game/arenas/black-rook-hold-arena",
"bounds": { "min": [-72, -8, -228], "max": [130, 28, -128] },
"teamSpawns": [[-66.098564, 8.416428, -201.852448], [123.158585, 9.916428, -219.909592]],
"preparationGates": [[-42, 8.4, -201], [98, 9.9, -218]],
"bounds": { "min": [-37, -32, -286], "max": [126, 20, -138] },
"teamSpawns": [[-35.043, -28.317, -204.435], [108.031, -28.317, -205.573]],
"preparationGates": [[-30.043, -28.317, -204.435], [103.031, -28.317, -205.573]],
"spectatorPositions": [[25, 25, -150], [25, 25, -224]],
"shadowSight": [[15, 9, -181], [15, 9, -215]],
"lineOfSight": [
@@ -141,8 +141,8 @@
"mapId": 1785,
"assetBaseUrl": "/assets/game/arenas/ashamanes-fall",
"bounds": { "min": [14, -4, 2], "max": [58, 16, 36] },
"teamSpawns": [[18.223099, -0.480263, 32.034554], [55.023094, -0.480263, 7.123436]],
"preparationGates": [[25, -0.5, 27], [48, -0.5, 12]],
"teamSpawns": [[18.723, -0.449, 32.035], [55.023, -0.477, 7.123]],
"preparationGates": [[22.737, -0.449, 29.053], [50.916, -0.477, 9.975]],
"spectatorPositions": [[20, 13, 6], [55, 13, 33]],
"shadowSight": [[29, -0.5, 13], [45, -0.5, 27]],
"lineOfSight": [
+21 -4
View File
@@ -6,8 +6,14 @@ import { useManastormAdminStore } from "./game/manastormAdminStore";
import { useAuthoritativeDualScreenSync, useForcedThorDisplays } from "./platform/useThorDualScreen";
import { LoginScreen } from "./ui/LoginScreen";
import { OnlineGroupCoordinator } from "./app/OnlineGroupCoordinator";
import { preloadTalentGameplayResources } from "./ui/talentGameplayResources";
import {
getLoadedGameRuntime,
loadGameRuntime,
preloadSharedGameplayResources,
} from "./ui/gameplayResources";
const GameRuntime = lazy(() => import("./GameRuntime"));
const GameRuntime = lazy(loadGameRuntime);
const CharacterCreateScreen = lazy(() => import("./ui/CharacterCreateScreen").then((module) => ({ default: module.CharacterCreateScreen })));
const CharacterSelectScreen = lazy(() => import("./ui/CharacterSelectScreen").then((module) => ({ default: module.CharacterSelectScreen })));
const ClassHallScreen = lazy(() => import("./ui/ClassHallScreen").then((module) => ({ default: module.ClassHallScreen })));
@@ -32,7 +38,11 @@ function RuntimeCatalogGate({ children }: { readonly children: ReactNode }) {
if (definition.mode === "conquest") return [...BASE_CLASS_IDS, character.classId];
return [character.classId, ...(character.secondaryClassId ? [character.secondaryClassId] : [])];
}, [character]);
const talentClassId = character && !character.classId.startsWith("rom-")
? character.classId
: null;
const requestKey = classIds.join(":");
const originalMediaEnabled = useShellStore((state) => state.combatPresentationSettings.originalMediaEnabled);
const [loadedKey, setLoadedKey] = useState("");
const [failedKey, setFailedKey] = useState("");
@@ -40,13 +50,17 @@ function RuntimeCatalogGate({ children }: { readonly children: ReactNode }) {
if (!requestKey) return;
let active = true;
setFailedKey("");
void preloadAbilityCatalogsForClasses(classIds).then(() => {
void Promise.all([
preloadAbilityCatalogsForClasses(classIds),
talentClassId ? preloadTalentGameplayResources(talentClassId) : Promise.resolve(),
preloadSharedGameplayResources(originalMediaEnabled),
]).then(() => {
if (active) setLoadedKey(requestKey);
}).catch(() => {
if (active) setFailedKey(requestKey);
});
return () => { active = false; };
}, [classIds, requestKey]);
}, [classIds, originalMediaEnabled, requestKey, talentClassId]);
if (!requestKey || loadedKey === requestKey) return children;
if (failedKey === requestKey) {
@@ -61,6 +75,7 @@ export default function App() {
const phase = useShellStore((state) => state.phase);
const session = useShellStore((state) => state.session);
const refreshManastormConfig = useManastormAdminStore((state) => state.refresh);
const PreloadedGameRuntime = getLoadedGameRuntime();
useEffect(() => {
void refreshManastormConfig(session);
@@ -77,7 +92,9 @@ export default function App() {
else if (phase === "arenas") screen = <Suspense fallback={<ShellTransition />}><ArenaSelectScreen /></Suspense>;
else if (phase === "arena-game") screen = <Suspense fallback={<ShellTransition />}><ArenaRuntime /></Suspense>;
else if (phase === "gm-admin") screen = <Suspense fallback={<ShellTransition />}><GmAdminScreen /></Suspense>;
else if (phase === "game") screen = <Suspense fallback={<ShellTransition />}><GameRuntime /></Suspense>;
else if (phase === "game") screen = PreloadedGameRuntime
? <PreloadedGameRuntime />
: <Suspense fallback={<ShellTransition />}><GameRuntime /></Suspense>;
const requiresRuntimeCatalog = !["login", "characters", "create-character"].includes(phase);
return <><OnlineGroupCoordinator />{requiresRuntimeCatalog ? <RuntimeCatalogGate>{screen}</RuntimeCatalogGate> : screen}</>;
}
+128 -121
View File
@@ -1,6 +1,6 @@
import { Clone, useProgress } from "@react-three/drei";
import { Canvas, useFrame } from "@react-three/fiber";
import { Component, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { Component, lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { Group, Vector3 } from "three";
import { selectedCharacter, useShellStore } from "./app/shellStore";
import { CharacterModel } from "./avatar/CharacterModel";
@@ -8,10 +8,27 @@ import { ProceduralAvatar } from "./avatar/ProceduralAvatar";
import { classById } from "./app/characterCatalog";
import { equipmentItemsForOwner, PLAYER_EQUIPMENT_OWNER_ID } from "./game/equipment";
import { useArenaStore } from "./game/arenaStore";
import { arenaCameraPose } from "./game/arenaCamera";
import { arenaCameraPose, arenaSpawnYaw } from "./game/arenaCamera";
import { ArenaPlayerCamera } from "./scene/ArenaPlayerCamera";
import { ArenaActionBar } from "./ui/ArenaActionBar";
import { controlledArenaActor, arenaTargetActor } from "./game/arenaPlayer";
import { abilityById, abilityAtLevel } from "./game/abilityCatalog";
import type { ActionBindingLayer } from "./game/actionBindings";
import { useArenaInput } from "./game/useArenaInput";
import { beginMouseLookDrag, endMouseLookDrag, isDesktopCameraLookPointer } from "./game/inputManager";
import type { CharacterCombatAnimationEvent } from "./game/combatAnimation";
import { arenaStageById } from "./game/arenaStages";
import type { ArenaActorSnapshot, ArenaDynamicObjectSnapshot, ArenaStageManifest } from "./game/arenaTypes";
import { GameGltfLoaderLifecycle, useGameGLTF } from "./scene/useGameGLTF";
import { ArenaCombatEffects, ArenaGroundTarget } from "./scene/ArenaCombatEffects";
import { ArenaPanels } from "./ui/ArenaPanels";
import { useArenaCombatView } from "./game/useArenaCombatView";
import { useGameStore } from "./game/store";
import { targetingRulesForAbility } from "./game/abilityRules";
import type { Vec3Tuple } from "./game/arenaTypes";
import { ArenaNavigationSurface } from "./scene/ArenaNavigationSurface";
const ArenaFallbackStage = lazy(() => import("./scene/ArenaFallbackStage"));
class ArenaStageErrorBoundary extends Component<{
readonly children: ReactNode;
@@ -37,7 +54,7 @@ function StageEnvironment({ stage, onReady }: { stage: ArenaStageManifest; onRea
const visual = stage.assets.find((asset) => asset.id === "visual")?.url;
return (
<>
<ProceduralStage stage={stage} floorOnly />
<ArenaNavigationSurface stageId={stage.id} />
{visual ? <LoadedStage url={visual} onReady={onReady} /> : <StageReady onReady={onReady} />}
</>
);
@@ -56,53 +73,6 @@ function LoadedStage({ url, onReady }: { url: string; onReady: () => void }) {
return <Clone object={gltf.scene} />;
}
function ProceduralStage({ stage, floorOnly = false }: { stage: ArenaStageManifest; floorOnly?: boolean }) {
const width = stage.bounds.max[0] - stage.bounds.min[0];
const depth = stage.bounds.max[2] - stage.bounds.min[2];
const centerX = (stage.bounds.max[0] + stage.bounds.min[0]) / 2;
const centerZ = (stage.bounds.max[2] + stage.bounds.min[2]) / 2;
const floorY = Math.min(...stage.teamSpawns.map((spawn) => spawn[1])) - 0.175;
const wallHeight = 2.4;
return (
<group>
<mesh position={[centerX, floorY, centerZ]} receiveShadow>
<boxGeometry args={[width, 0.25, depth]} />
<meshStandardMaterial color={floorOnly ? "#364038" : "#3d4d43"} roughness={0.92} />
</mesh>
{!floorOnly && (
<>
<gridHelper args={[Math.max(width, depth), 24, "#c8aa5c", "#596c5f"]} position={[centerX, floorY + 0.14, centerZ]} />
{[
[centerX, floorY + wallHeight / 2, stage.bounds.min[2], width, wallHeight, 0.6],
[centerX, floorY + wallHeight / 2, stage.bounds.max[2], width, wallHeight, 0.6],
[stage.bounds.min[0], floorY + wallHeight / 2, centerZ, 0.6, wallHeight, depth],
[stage.bounds.max[0], floorY + wallHeight / 2, centerZ, 0.6, wallHeight, depth],
].map(([x, y, z, sizeX, sizeY, sizeZ], index) => (
<mesh key={`boundary-${index}`} position={[x, y, z]} receiveShadow>
<boxGeometry args={[sizeX, sizeY, sizeZ]} />
<meshStandardMaterial color="#26342d" roughness={0.88} />
</mesh>
))}
{stage.teamSpawns.map((spawn, index) => (
<mesh key={`spawn-${index}`} position={[spawn[0], floorY + 0.2, spawn[2]]} receiveShadow>
<cylinderGeometry args={[3.4, 3.4, 0.18, 32]} />
<meshStandardMaterial color={index === 0 ? "#338dcc" : "#bd4944"} emissive={index === 0 ? "#123d5b" : "#541c1a"} emissiveIntensity={0.7} />
</mesh>
))}
{stage.lineOfSight.map((object) => (
<mesh key={object.id} position={object.position as [number, number, number]} castShadow receiveShadow>
{object.shape === "cylinder"
? <cylinderGeometry args={[object.size[0] / 2, object.size[0] / 2, object.size[1], 16]} />
: <boxGeometry args={object.size as [number, number, number]} />}
<meshStandardMaterial color="#6a6f5e" roughness={0.78} />
</mesh>
))}
</>
)}
</group>
);
}
function DynamicStageObjects({ stage, objects }: { stage: ArenaStageManifest; objects: readonly ArenaDynamicObjectSnapshot[] }) {
const states = useMemo(() => new Map(objects.map((object) => [object.id, object])), [objects]);
const definitions = useMemo(() => new Map(stage.dynamicObjects.map((object) => [object.id, object])), [stage]);
@@ -154,17 +124,21 @@ function DynamicStageObjects({ stage, objects }: { stage: ArenaStageManifest; ob
);
}
function ArenaActor({ actor, local, character, movement, stage }: { actor: ArenaActorSnapshot; local: boolean; character: ReturnType<typeof selectedCharacter>; movement: RefObject<[number, number]>; stage: ArenaStageManifest }) {
const group = useRef<Group>(null);
function ArenaActor({ actor, local, character, player }: { actor: ArenaActorSnapshot; local: boolean; character: ReturnType<typeof selectedCharacter>; player: RefObject<Group | null> }) {
const other = useRef<Group>(null);
const group = local ? player : other;
const initial = useRef<[number, number, number]>([...actor.position]);
const target = useMemo(() => new Vector3(), []);
const movingRef = useRef(false);
const animationEventRef = useRef<CharacterCombatAnimationEvent | null>(null);
useFrame((_, delta) => {
const node = group.current;
if (!node) return;
if (local) {
node.position.x = Math.max(stage.bounds.min[0], Math.min(stage.bounds.max[0], node.position.x + movement.current[0] * 7 * delta));
node.position.z = Math.max(stage.bounds.min[2], Math.min(stage.bounds.max[2], node.position.z + movement.current[1] * 7 * delta));
}
node.position.lerp(new Vector3(...actor.position), Math.min(1, delta * (local ? 4 : 14)));
node.rotation.y = actor.facing;
target.set(...actor.position);
movingRef.current = node.position.distanceToSquared(target) > 0.0025;
node.position.lerp(target, Math.min(1, delta * 18));
if (Number.isFinite(actor.facing)) node.rotation.y = actor.facing;
animationEventRef.current = actor.combat?.playerAnimationEvent ?? null;
});
const color = actor.team === 0 ? "#58b9ff" : "#e45b55";
const cosmeticEquipment = useMemo(
@@ -172,9 +146,10 @@ function ArenaActor({ actor, local, character, movement, stage }: { actor: Arena
[character],
);
return (
<group ref={group} position={actor.position as [number, number, number]} rotation={[0, actor.facing, 0]} visible={actor.alive}>
{local && character ? (
<CharacterModel identity={character} equipment={cosmeticEquipment} fallback={<ProceduralAvatar accent={classById(character.classId).color} />} />
<group ref={group} name={`arena-actor:${actor.id}`} position={initial.current} visible={actor.alive}
onPointerDown={(event) => { if (event.button === 0) useArenaStore.getState().intent({ type: "target", targetActorId: actor.id }); }}>
{(local && character) || actor.avatar ? (
<CharacterModel identity={local && character ? character : actor.avatar} equipment={local ? cosmeticEquipment : actor.visualEquipment} movingRef={movingRef} animationEventRef={animationEventRef} fallback={<ProceduralAvatar accent={color} />} />
) : (
<group>
<mesh position={[0, 0.9, 0]} castShadow><capsuleGeometry args={[0.45, 1, 6, 12]} /><meshStandardMaterial color={color} roughness={0.55} /></mesh>
@@ -186,26 +161,16 @@ function ArenaActor({ actor, local, character, movement, stage }: { actor: Arena
);
}
function ArenaCamera({ actor, stage }: { actor: ArenaActorSnapshot | null; stage: ArenaStageManifest }) {
const target = useMemo(() => new Vector3(), []);
const desired = useMemo(() => new Vector3(), []);
const pose = useMemo(() => arenaCameraPose(stage, actor?.team ?? 0), [actor?.team, stage]);
useFrame(({ camera }, delta) => {
if (!actor) return;
target.set(...pose.target);
desired.set(...pose.position);
camera.position.lerp(desired, Math.min(1, delta * 5));
camera.lookAt(target);
});
return null;
}
function ArenaWorld({ stage, actors, dynamicObjects, localActor, character, movement, detailedAsset, onStageReady, onStageError }: { stage: ArenaStageManifest; actors: readonly ArenaActorSnapshot[]; dynamicObjects: readonly ArenaDynamicObjectSnapshot[]; localActor: ArenaActorSnapshot | null; character: ReturnType<typeof selectedCharacter>; movement: RefObject<[number, number]>; detailedAsset: boolean; onStageReady: () => void; onStageError: (error: unknown) => void }) {
function ArenaWorld({ stage, actors, dynamicObjects, localActor, character, movement, detailedAsset, blocked, onStageReady, onStageError, groundTarget, groundPosition, controller }: { stage: ArenaStageManifest; actors: readonly ArenaActorSnapshot[]; dynamicObjects: readonly ArenaDynamicObjectSnapshot[]; localActor: ArenaActorSnapshot | null; character: ReturnType<typeof selectedCharacter>; movement: RefObject<[number, number]>; detailedAsset: boolean; blocked: boolean; onStageReady: () => void; onStageError: (error: unknown) => void; groundTarget: string | null; groundPosition: RefObject<Vec3Tuple>; controller: boolean }) {
const snapshot = useArenaStore((state) => state.snapshot);
const player = useRef<Group>(null);
const environment = useRef<Group>(null);
const initialCamera = useMemo(() => arenaCameraPose(localActor?.position ?? stage.teamSpawns[0], arenaSpawnYaw(stage, localActor?.team ?? 0)).position, [stage]);
return (
<Canvas
shadows
dpr={[1, 1.35]}
camera={{ fov: 52, near: 0.1, far: 1200, position: [0, 16, 24] }}
camera={{ fov: 62, near: 0.05, far: 1200, position: initialCamera }}
fallback={<div className="arena-render-fallback"><strong>3D arena unavailable</strong><small>This device could not start WebGL. Return to Arena Command and try another renderer.</small></div>}
>
<color attach="background" args={["#111815"]} />
@@ -213,14 +178,19 @@ function ArenaWorld({ stage, actors, dynamicObjects, localActor, character, move
<hemisphereLight args={["#c9d8cd", "#101713", 1.55]} />
<directionalLight castShadow position={[24, 42, 18]} intensity={2.2} color="#f1d6a2" />
<GameGltfLoaderLifecycle>
<group ref={environment}>
{detailedAsset ? (
<ArenaStageErrorBoundary key={stage.id} fallback={null} onError={onStageError}>
<Suspense fallback={<ProceduralStage stage={stage} />}><StageEnvironment stage={stage} onReady={onStageReady} /></Suspense>
<Suspense fallback={<Suspense fallback={null}><ArenaFallbackStage stageId={stage.id} /></Suspense>}><StageEnvironment stage={stage} onReady={onStageReady} /></Suspense>
</ArenaStageErrorBoundary>
) : <ProceduralStage stage={stage} />}
) : <Suspense fallback={null}><ArenaFallbackStage stageId={stage.id} /></Suspense>}
<DynamicStageObjects stage={stage} objects={dynamicObjects} />
{actors.map((actor) => <ArenaActor key={actor.id} actor={actor} local={actor.id === localActor?.id} character={character} movement={movement} stage={stage} />)}
<ArenaCamera actor={localActor} stage={stage} />
</group>
{actors.map((actor) => <ArenaActor key={actor.id} actor={actor} local={actor.id === localActor?.id} character={character} player={player} />)}
<ArenaPlayerCamera key={`${stage.id}:${localActor?.id}`} actor={localActor} stage={stage} player={player} environment={environment} movement={movement} blocked={blocked} />
{snapshot && <ArenaCombatEffects snapshot={snapshot} actorId={localActor?.id} />}
{groundTarget && localActor && <ArenaGroundTarget environment={environment} position={groundPosition} origin={localActor.position}
radius={abilityById(groundTarget)?.radius ?? 8} controller={controller} />}
</GameGltfLoaderLifecycle>
</Canvas>
);
@@ -246,13 +216,16 @@ function ArenaAssetStatus({ stage, ready, fallbackReason }: { readonly stage: Ar
}
function TeamFrames({ actors, team }: { actors: readonly ArenaActorSnapshot[]; team: 0 | 1 }) {
const snapshot = useArenaStore((state) => state.snapshot);
const selected = snapshot?.actors.find((actor) => actor.id === snapshot.controlledActorId)?.targetActorId;
return (
<div className={`arena-team-frames arena-team-frames--${team}`}>
{actors.filter((actor) => actor.team === team).map((actor) => (
<button key={actor.id} type="button" className={!actor.alive ? "is-dead" : ""} onClick={() => useArenaStore.getState().intent({ type: "target", targetActorId: actor.id })}>
<button key={actor.id} type="button" className={`${!actor.alive ? "is-dead" : ""} ${selected === actor.id ? "is-selected" : ""}`} onClick={() => useArenaStore.getState().intent({ type: "target", targetActorId: actor.id })}>
<span><strong>{actor.name}</strong><small>{actor.isBot ? "AI" : "Player"} / {actor.role}</small></span>
<i><b style={{ width: `${actor.health / actor.maxHealth * 100}%` }} /></i>
<em>{actor.health}</em>
<em>{Math.ceil(actor.health)} / {actor.maxHealth}</em>
{actor.combat?.activeCast && <small>{abilityById(actor.combat.activeCast.abilityId)?.name ?? "Casting"}</small>}
</button>
))}
</div>
@@ -269,7 +242,20 @@ export default function ArenaRuntime() {
const session = useShellStore((state) => state.session);
const character = useShellStore(selectedCharacter);
const stage = snapshot ? arenaStageById(snapshot.stageId) : null;
const localActor = snapshot?.actors.find((actor) => actor.id === (snapshot.controlledActorId ?? "practice-player")) ?? null;
const localActor = controlledArenaActor(snapshot, character);
const feedback = useArenaStore((state) => state.error);
const overlay = useGameStore((state) => state.overlay);
const companionOpen = useGameStore((state) => state.companionOpen);
const paused = overlay !== null || companionOpen;
const setPaused = (value: boolean | ((previous: boolean) => boolean)) => {
const next = typeof value === "function" ? value(paused) : value;
if (next) useGameStore.getState().openOverlay("pause"); else useGameStore.getState().closeOverlay();
};
const [groundTarget, setGroundTarget] = useState<string | null>(null);
const groundPosition = useRef<Vec3Tuple>([0, 0, 0]);
useArenaCombatView(character, localActor);
const [actionLayer, setActionLayer] = useState<ActionBindingLayer>("primary");
const [inputMode, setInputMode] = useState<"keyboard" | "gamepad">("keyboard");
const movementRef = useRef<[number, number]>([0, 0]);
const [loadedStageId, setLoadedStageId] = useState<string | null>(null);
const [stageFailure, setStageFailure] = useState<{ readonly stageId: string; readonly reason: string } | null>(null);
@@ -308,38 +294,38 @@ export default function ArenaRuntime() {
});
}, [character, load, session, snapshot]);
useEffect(() => {
const pressed = new Set<string>();
const movement = () => {
const next: [number, number] = [
Number(pressed.has("KeyD") || pressed.has("ArrowRight")) - Number(pressed.has("KeyA") || pressed.has("ArrowLeft")),
Number(pressed.has("KeyS") || pressed.has("ArrowDown")) - Number(pressed.has("KeyW") || pressed.has("ArrowUp")),
];
movementRef.current = next;
intent({ type: "movement", movement: { x: next[0], z: next[1] } });
};
const down = (event: KeyboardEvent) => {
if (["KeyW", "KeyA", "KeyS", "KeyD", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.code)) {
pressed.add(event.code);
movement();
}
if (event.code === "Digit1") intent({ type: "ability", abilityId: "attack" });
if (event.code === "Digit2") intent({ type: "ability", abilityId: "strike" });
if (event.code === "Digit3") intent({ type: "ability", abilityId: "interrupt" });
if (event.code === "Digit4") intent({ type: "ability", abilityId: "control" });
if (event.code === "Digit5") intent({ type: "ability", abilityId: "defensive" });
if (event.code === "Digit6") intent({ type: "ability", abilityId: "heal" });
};
const up = (event: KeyboardEvent) => {
if (pressed.delete(event.code)) movement();
};
window.addEventListener("keydown", down);
window.addEventListener("keyup", up);
return () => {
window.removeEventListener("keydown", down);
window.removeEventListener("keyup", up);
};
}, [intent]);
const cast = useCallback((abilityId: string) => {
const state = useArenaStore.getState();
const player = controlledArenaActor(state.snapshot, character);
if (!player || useGameStore.getState().overlay || state.result) return;
const definition = abilityById(abilityId);
const ability = definition ? abilityAtLevel(definition, player.level ?? character?.level ?? 80) : null;
if (ability && targetingRulesForAbility(ability).shape === "ground" && (targetingRulesForAbility(ability).groundRange ?? 0) > 0) {
groundPosition.current = [player.position[0] + Math.sin(player.facing) * 8, player.position[1], player.position[2] + Math.cos(player.facing) * 8];
setGroundTarget(abilityId);
return;
}
let target = arenaTargetActor(state.snapshot, player.targetActorId) ?? undefined;
if (target && !target.alive && !ability?.effects.some((effect) => effect.kind === "resurrection")) target = undefined;
if (ability?.target === "self" || (ability?.target === "friendly" && target?.team !== player.team)) target = player;
if (ability?.target === "hostile" && (!target || target.team === player.team)) {
target = state.snapshot?.actors.filter((actor) => actor.alive && actor.team !== player.team).sort((a, b) => (
Math.hypot(a.position[0] - player.position[0], a.position[2] - player.position[2])
- Math.hypot(b.position[0] - player.position[0], b.position[2] - player.position[2])
))[0];
}
if (target && target.id !== player.id) state.intent({ type: "target", targetActorId: target.id });
state.intent({ type: "ability", abilityId, targetActorId: target?.id });
}, [character]);
const confirmGroundTarget = () => {
if (!groundTarget) return;
intent({ type: "ability", abilityId: groundTarget, groundPosition: groundPosition.current });
setGroundTarget(null);
};
useArenaInput({ character, blocked: paused || Boolean(result) || !localActor?.alive,
cast, togglePause: () => setPaused((value) => !value), setLayer: setActionLayer, setInputMode,
groundTargetActive: () => Boolean(groundTarget), confirmGroundTarget,
cancelGroundTarget: () => { setGroundTarget(null); intent({ type: "command", command: "cancel-cast" }); } });
const exit = async () => {
await leave(session);
@@ -351,19 +337,40 @@ export default function ArenaRuntime() {
const detailedAsset = stageFailure?.stageId !== stage.id;
return (
<main className="arena-runtime">
<div className="arena-world" key={`${stage.id}:${detailedAsset ? "detailed" : "fallback"}`}><ArenaWorld stage={stage} actors={snapshot.actors} dynamicObjects={snapshot.dynamicObjects} localActor={localActor} character={character} movement={movementRef} detailedAsset={detailedAsset} onStageReady={handleStageReady} onStageError={handleStageError} /></div>
<div className="arena-world" aria-label="Arena 3D view" key={`${stage.id}:${detailedAsset ? "detailed" : "fallback"}`}
onPointerDown={(event) => {
if (event.button === 0 && groundTarget && !paused) { confirmGroundTarget(); return; }
if (paused || result || !isDesktopCameraLookPointer(event.pointerType, event.button)) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
beginMouseLookDrag(event.clientX, event.clientY);
}}
onPointerUp={(event) => { if (event.button === 2) endMouseLookDrag(); }}
onLostPointerCapture={() => endMouseLookDrag()}
onContextMenu={(event) => event.preventDefault()}><ArenaWorld stage={stage} actors={snapshot.actors} dynamicObjects={snapshot.dynamicObjects} localActor={localActor} character={character} movement={movementRef} detailedAsset={detailedAsset} blocked={paused || Boolean(result)} onStageReady={handleStageReady} onStageError={handleStageError} groundTarget={groundTarget} groundPosition={groundPosition} controller={inputMode === "gamepad"} /></div>
<ArenaAssetStatus stage={stage} ready={loadedStageId === stage.id} fallbackReason={stageFailure?.stageId === stage.id ? stageFailure.reason : null} />
<header className="arena-match-header">
<span>{stage.name}</span><strong>{snapshot.bracket} · {snapshot.ruleset.toUpperCase()}</strong><em>Dampening {Math.round(snapshot.dampening * 100)}%</em>
</header>
<TeamFrames actors={snapshot.actors} team={0} />
<TeamFrames actors={snapshot.actors} team={1} />
<div className="arena-combat-log" role="log" aria-label="Arena combat events">{(snapshot.combatEvents ?? []).filter((event) => snapshot.serverTime - event.occurredAt < 3000 && (event.sourceActorId === localActor?.id || event.targetActorId === localActor?.id) && ["damage", "healing", "interrupt"].includes(event.kind)).slice(-4).map((event) => <div key={event.id}>{abilityById(event.abilityId ?? "")?.name ?? event.kind}: {event.outcome === "miss" ? "Miss" : Math.round(event.effectiveAmount)} {event.absorbed > 0 ? `(${event.absorbed} absorbed)` : ""}</div>)}</div>
{snapshot.phase === "preparation" && <div className="arena-countdown"><small>Gates sealed</small><strong>{seconds}</strong><span>Prepare your opening</span></div>}
<nav className="arena-action-bar" aria-label="Arena abilities">
{["attack", "strike", "interrupt", "control", "defensive", "heal"].map((ability, index) => (
<button key={ability} type="button" onClick={() => intent({ type: "ability", abilityId: ability })}><b>{index + 1}</b><span>{ability}</span></button>
))}
{character && <ArenaActionBar character={character} actor={localActor} layer={actionLayer} inputMode={inputMode}
blocked={paused || Boolean(result)} onCast={cast} feedback={feedback} />}
{groundTarget && <div className="arena-ground-hint" role="status">Place {abilityById(groundTarget)?.name} · Click or confirm to cast · Escape to cancel</div>}
{character && <ArenaPanels character={character} actor={localActor} snapshot={snapshot} stage={stage} cast={cast} />}
<nav className="arena-toolbar" aria-label="Arena character menus">
{(["spellbook", "inventory", "talents", "bindings", "keybinds", "map", "options"] as const).map((panel) => <button key={panel} type="button" onClick={() => useGameStore.getState().toggleOverlay(panel)}>{panel === "inventory" ? "Character" : panel}</button>)}
</nav>
{overlay === "pause" && !result && <section className="arena-result-panel" role="dialog" aria-label="Arena menu">
<h1>Arena menu</h1><p>Your character stays in the match while this menu is open.</p>
<button type="button" className="front-button" onClick={() => setPaused(false)}>Resume</button>
<button type="button" className="front-button" onClick={() => useGameStore.getState().openOverlay("options")}>Options</button>
<button type="button" className="front-button" onClick={() => useGameStore.getState().openOverlay("keybinds")}>Keybinds</button>
<button type="button" className="front-button" onClick={() => useGameStore.getState().openOverlay("bindings")}>Assign abilities</button>
<button type="button" className="front-button" onClick={() => void exit()}>Leave arena</button>
</section>}
<button className="arena-exit" type="button" onClick={() => void exit()}>{result ? "Leave arena" : "Exit / bot takeover"}</button>
{result && (
<section className="arena-result-panel" role="dialog" aria-modal="true">
+25 -1
View File
@@ -1,4 +1,5 @@
import { useEffect } from "react";
import "./ui/uiLayout.css";
import { DualDisplayFrame } from "./components/DualDisplayFrame";
import { installInput, releasePointerLock } from "./game/inputManager";
import { CombatBridge } from "./game/CombatBridge";
@@ -26,12 +27,31 @@ import { DungeonRunCheckpointBridge } from "./game/DungeonRunCheckpointBridge";
import { DungeonEncounterEffectBridge } from "./game/DungeonEncounterEffectBridge";
import { interactWithActiveDungeonObject } from "./game/dungeonWorldInteraction";
import { DungeonInteractionPrompt } from "./ui/DungeonInteractionPrompt";
import { UiLayoutEditor } from "./ui/UiLayoutEditor";
import { EditableHudElement } from "./ui/EditableHudElement";
import { activeUiLayout, currentUiDevice } from "./game/uiLayoutStore";
import { useUiLayoutStore } from "./game/uiLayoutStore";
import { profileInputBindings } from "./game/keybindPreferences";
import { KeybindsPanel } from "./ui/KeybindsPanel";
function InputBridge() {
const overlay = useGameStore((state) => state.overlay);
const companionOpen = useGameStore((state) => state.companionOpen);
useEffect(() => installInput({
desktopActionBarsActive: () => currentUiDevice() === "pc" && activeUiLayout().wowBars,
inputSuspended: () => ["ui-layout", "keybinds"].includes(useGameStore.getState().overlay ?? ""),
getBindings: (device) => {
const preferences = useUiLayoutStore.getState().preferences;
const bindings = profileInputBindings(preferences, device);
for (let b = activeUiLayout().barCount; b < 5; b++) for (let s = 0; s < 12; s++) bindings[`bar:${b}:${s}`] = null;
return bindings;
},
castDesktopSlot: (bar, slot) => {
const game = useGameStore.getState(); const button = activeUiLayout().bars[bar]?.slots[slot];
if (button?.abilityId) useCombatStore.getState().castAbility(button.abilityId, game.playerPosition, Date.now());
},
togglePanel: (panel) => useGameStore.getState().toggleOverlay(panel),
togglePause: () => useGameStore.getState().togglePause(),
toggleMap: () => useGameStore.getState().toggleMap(),
toggleInventory: () => useGameStore.getState().toggleOverlay("inventory"),
@@ -77,6 +97,7 @@ function InputBridge() {
}
export default function GameRuntime() {
const editingControls = useGameStore((state) => state.overlay === "keybinds" || state.overlay === "ui-layout");
useEffect(() => () => {
const activeDungeon = requireDungeonDefinition(useGameStore.getState().activeDungeonId);
clearDungeonRuntimeCaches();
@@ -86,6 +107,7 @@ export default function GameRuntime() {
return (
<DualDisplayFrame
contextLabel="Tactical"
companionDisabled={editingControls}
onActiveSurfaceChange={(surface) => useGameStore.getState().setCompanionOpen(surface === "bottom")}
top={
<main className="game-shell">
@@ -98,10 +120,12 @@ export default function GameRuntime() {
<ManastormBridge />
<SceneErrorBoundary><GameScene /></SceneErrorBoundary>
<Hud />
<DungeonInteractionPrompt />
<EditableHudElement id="interaction"><DungeonInteractionPrompt /></EditableHudElement>
<MapPanel />
<GameplayPanels />
<PauseMenu />
<UiLayoutEditor />
<KeybindsPanel />
<GmReviewCard />
<GmWorldEditor />
</main>
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from "vitest";
import type { OnlineGroupActivity } from "./onlineGroupTypes";
import { enterOnlineGroupActivity } from "./OnlineGroupCoordinator";
const DUNGEON_ACTIVITY: OnlineGroupActivity = {
id: "activity-dungeon-1",
type: "dungeon",
contentId: "deadmines",
fillWithAi: true,
partySize: 5,
startingLevel: null,
startedAt: 1,
};
function entryDependencies(enterDungeon: () => boolean) {
return {
installDungeonRuntime: vi.fn(async () => undefined),
enterDungeon: vi.fn(enterDungeon),
installManastormRuntime: vi.fn(async () => undefined),
enterManastorm: vi.fn(() => true),
};
}
describe("online group activity entry", () => {
it("leaves a dungeon activity unconsumed when dungeon entry fails", async () => {
const consumeActivity = vi.fn();
const dependencies = entryDependencies(() => false);
await expect(enterOnlineGroupActivity(
DUNGEON_ACTIVITY,
"healer",
consumeActivity,
dependencies,
)).resolves.toBe(false);
expect(dependencies.installDungeonRuntime).toHaveBeenCalledOnce();
expect(dependencies.enterDungeon).toHaveBeenCalledWith("deadmines", "healer");
expect(consumeActivity).not.toHaveBeenCalled();
});
it("can retry the same dungeon activity and consumes it only after entry succeeds", async () => {
const consumeActivity = vi.fn();
const enterDungeon = vi.fn()
.mockReturnValueOnce(false)
.mockReturnValueOnce(true);
const dependencies = entryDependencies(enterDungeon);
await enterOnlineGroupActivity(DUNGEON_ACTIVITY, "tank", consumeActivity, dependencies);
expect(consumeActivity).not.toHaveBeenCalled();
await expect(enterOnlineGroupActivity(
DUNGEON_ACTIVITY,
"tank",
consumeActivity,
dependencies,
)).resolves.toBe(true);
expect(dependencies.enterDungeon).toHaveBeenCalledTimes(2);
expect(consumeActivity).toHaveBeenCalledOnce();
expect(consumeActivity).toHaveBeenCalledWith(DUNGEON_ACTIVITY.id);
});
it("does not consume the activity when loading the dungeon runtime throws", async () => {
const consumeActivity = vi.fn();
const dependencies = entryDependencies(() => true);
dependencies.installDungeonRuntime.mockRejectedValueOnce(new Error("runtime unavailable"));
await expect(enterOnlineGroupActivity(
DUNGEON_ACTIVITY,
"damage",
consumeActivity,
dependencies,
)).rejects.toThrow("runtime unavailable");
expect(dependencies.enterDungeon).not.toHaveBeenCalled();
expect(consumeActivity).not.toHaveBeenCalled();
});
});
+59 -22
View File
@@ -1,4 +1,4 @@
import { useEffect } from "react";
import { useEffect, useRef } from "react";
import { selectedCharacter, useShellStore } from "./shellStore";
import { useOnlineGroupStore } from "./onlineGroupStore";
import {
@@ -6,11 +6,56 @@ import {
defaultPartyRoleForClass,
type PartyRole,
} from "../game/partyRoles";
import { isManastormPartySize } from "../game/manastormProgress";
import { isManastormPartySize, type ManastormPartySize } from "../game/manastormProgress";
import type { OnlineGroupActivity } from "./onlineGroupTypes";
import { useContentManagerSnapshot } from "../content/useContentManager";
const GROUP_POLL_MS = 2_500;
const ACTIVITY_JOIN_WINDOW_MS = 10 * 60 * 1000;
interface OnlineGroupActivityEntryDependencies {
readonly installDungeonRuntime: () => Promise<void>;
readonly enterDungeon: (dungeonId: string, role?: PartyRole) => boolean;
readonly installManastormRuntime: () => Promise<void>;
readonly enterManastorm: (role?: PartyRole, partySize?: ManastormPartySize, startingLevel?: number) => boolean;
}
const DEFAULT_ACTIVITY_ENTRY_DEPENDENCIES: OnlineGroupActivityEntryDependencies = {
installDungeonRuntime: async () => {
const { installDungeonShellRuntime } = await import("./dungeonShellRuntime");
installDungeonShellRuntime();
},
enterDungeon: (dungeonId, role) => useShellStore.getState().enterDungeon(dungeonId, role),
installManastormRuntime: async () => {
const { installManastormShellRuntime } = await import("./manastormShellRuntime");
installManastormShellRuntime();
},
enterManastorm: (role, partySize, startingLevel) => useShellStore.getState().enterManastorm(
role,
partySize,
startingLevel,
),
};
export async function enterOnlineGroupActivity(
activity: OnlineGroupActivity,
role: PartyRole,
consumeActivity: (activityId: string) => void,
dependencies: OnlineGroupActivityEntryDependencies = DEFAULT_ACTIVITY_ENTRY_DEPENDENCIES,
): Promise<boolean> {
let entered: boolean;
if (activity.type === "dungeon") {
await dependencies.installDungeonRuntime();
entered = dependencies.enterDungeon(activity.contentId, role);
} else {
await dependencies.installManastormRuntime();
const partySize = isManastormPartySize(activity.partySize) ? activity.partySize : 5;
entered = dependencies.enterManastorm(role, partySize, activity.startingLevel ?? undefined);
}
if (entered) consumeActivity(activity.id);
return entered;
}
export function OnlineGroupCoordinator() {
const session = useShellStore((state) => state.session);
const character = useShellStore(selectedCharacter);
@@ -21,6 +66,8 @@ export function OnlineGroupCoordinator() {
const updateMember = useOnlineGroupStore((state) => state.updateMember);
const consumeActivity = useOnlineGroupStore((state) => state.consumeActivity);
const reset = useOnlineGroupStore((state) => state.reset);
const { installedRevision } = useContentManagerSnapshot();
const pendingActivityIds = useRef(new Set<string>());
useEffect(() => {
if (!session || session.kind !== "account" || !session.accessToken) {
@@ -60,26 +107,16 @@ export function OnlineGroupCoordinator() {
if (Date.now() - activity.startedAt > ACTIVITY_JOIN_WINDOW_MS) return;
const member = snapshot.group?.members.find((candidate) => candidate.accountId === session.ownerId);
if (!member?.character || !member.role) return;
consumeActivity(activity.id);
void (async () => {
if (activity.type === "dungeon") {
const { installDungeonShellRuntime } = await import("./dungeonShellRuntime");
installDungeonShellRuntime();
useShellStore.getState().enterDungeon(activity.contentId, member.role ?? undefined);
return;
}
const { installManastormShellRuntime } = await import("./manastormShellRuntime");
installManastormShellRuntime();
const partySize = isManastormPartySize(activity.partySize) ? activity.partySize : 5;
useShellStore.getState().enterManastorm(
member.role ?? undefined,
partySize,
activity.startingLevel ?? undefined,
);
})().catch((error) => {
useShellStore.getState().setNotice(error instanceof Error ? error.message : "The group activity could not be opened.");
});
}, [consumeActivity, consumedActivityIds, phase, session?.ownerId, snapshot.group?.activity?.id]);
if (pendingActivityIds.current.has(activity.id)) return;
pendingActivityIds.current.add(activity.id);
void enterOnlineGroupActivity(activity, member.role, consumeActivity)
.catch((error) => {
useShellStore.getState().setNotice(error instanceof Error ? error.message : "The group activity could not be opened.");
})
.finally(() => {
pendingActivityIds.current.delete(activity.id);
});
}, [consumeActivity, consumedActivityIds, installedRevision, phase, session?.ownerId, snapshot.group?.activity?.id]);
return null;
}
+35 -4
View File
@@ -212,7 +212,7 @@ describe("local profile repository", () => {
}));
expect(loadCombatPresentationSettings("offline-roster", storage))
.toEqual(DEFAULT_COMBAT_PRESENTATION_SETTINGS);
expect(JSON.parse(storage.getItem(PROFILE_STORAGE_KEYS.database)!).version).toBe(5);
expect(JSON.parse(storage.getItem(PROFILE_STORAGE_KEYS.database)!).version).toBe(6);
}
const legacyV3Storage = new MemoryStorage();
@@ -231,13 +231,13 @@ describe("local profile repository", () => {
},
}));
expect(loadCombatPresentationSettings("offline-roster", legacyV3Storage)).toMatchObject({
vfxMode: "generated",
vfxMode: "original",
vfxQuality: "low",
});
expect(JSON.parse(legacyV3Storage.getItem(PROFILE_STORAGE_KEYS.database)!)
.presentationSettingsByOwner["offline-roster"].vfxMode).toBe("generated");
.presentationSettingsByOwner["offline-roster"].vfxMode).toBe("original");
expect(JSON.parse(legacyV3Storage.getItem(PROFILE_STORAGE_KEYS.database)!)
.presentationSettingsByOwner["offline-roster"].originalMediaEnabled).toBe(false);
.presentationSettingsByOwner["offline-roster"].originalMediaEnabled).toBe(true);
const storage = new MemoryStorage();
const firstOwner = (await createLocalAccount("EffectsOne", "eight-plus", storage)).session!.ownerId;
@@ -258,6 +258,37 @@ describe("local profile repository", () => {
.toEqual(DEFAULT_COMBAT_PRESENTATION_SETTINGS);
});
it("migrates the previous media default once while preserving combat controls", () => {
const storage = new MemoryStorage();
storage.setItem(PROFILE_STORAGE_KEYS.database, JSON.stringify({
version: 5,
accounts: [],
rosters: { "offline-roster": [] },
presentationSettingsByOwner: {
"offline-roster": {
...DEFAULT_COMBAT_PRESENTATION_SETTINGS,
originalMediaEnabled: false,
vfxMode: "generated",
vfxQuality: "low",
audioEnabled: { player: true, party: false, enemy: true },
},
},
}));
expect(loadCombatPresentationSettings("offline-roster", storage)).toMatchObject({
originalMediaEnabled: true,
vfxMode: "original",
vfxQuality: "low",
audioEnabled: { player: true, party: false, enemy: true },
});
updateCombatPresentationSettings("offline-roster", {
...DEFAULT_COMBAT_PRESENTATION_SETTINGS,
originalMediaEnabled: false, vfxMode: "generated",
}, storage);
expect(loadCombatPresentationSettings("offline-roster", storage)).toMatchObject({
originalMediaEnabled: false, vfxMode: "generated",
});
});
it("migrates custom-class profiles into the CoA category", () => {
const storage = new MemoryStorage();
const offline = createOfflineSession();
+34 -8
View File
@@ -1,4 +1,5 @@
import type { CharacterProfile, PlayerSession } from "./types";
import { normalizeUiPreferences, type UiPreferences } from "../game/uiLayout";
import {
contentCategoryForClass,
isRomClassId,
@@ -60,10 +61,11 @@ interface LocalAccount {
}
interface ProfileDatabase {
version: 5;
version: 6;
accounts: LocalAccount[];
rosters: Record<string, CharacterProfile[]>;
presentationSettingsByOwner: Record<string, CombatPresentationSettings>;
uiPreferencesByOwner?: Record<string, UiPreferences>;
}
export interface AccountResult {
@@ -102,7 +104,7 @@ function browserSessionStorage(): StorageLike | null {
}
function emptyDatabase(): ProfileDatabase {
return { version: 5, accounts: [], rosters: {}, presentationSettingsByOwner: {} };
return { version: 6, accounts: [], rosters: {}, presentationSettingsByOwner: {} };
}
function isCharacterProfile(value: unknown): value is CharacterProfile {
@@ -202,8 +204,9 @@ function readDatabase(storage: StorageLike | null = browserLocalStorage()): Prof
accounts?: unknown;
rosters?: unknown;
presentationSettingsByOwner?: unknown;
uiPreferencesByOwner?: unknown;
}) | null;
if (!parsed || ![1, 2, 3, 4, 5].includes(parsed.version ?? 0) || !Array.isArray(parsed.accounts) || !parsed.rosters || typeof parsed.rosters !== "object") {
if (!parsed || ![1, 2, 3, 4, 5, 6].includes(parsed.version ?? 0) || !Array.isArray(parsed.accounts) || !parsed.rosters || typeof parsed.rosters !== "object") {
return emptyDatabase();
}
const accounts = parsed.accounts.filter((account): account is LocalAccount => Boolean(
@@ -229,13 +232,22 @@ function readDatabase(storage: StorageLike | null = browserLocalStorage()): Prof
let presentationSettingsMigrated = false;
const presentationSettingsByOwner = Object.fromEntries(
Object.entries(rawPresentationSettings).map(([ownerId, settings]) => {
const normalized = normalizeCombatPresentationSettings(settings);
const storedMode = settings && typeof settings === "object" && !Array.isArray(settings)
? (settings as { vfxMode?: unknown }).vfxMode
: undefined;
const storedOriginalMediaEnabled = settings && typeof settings === "object" && !Array.isArray(settings)
? (settings as { originalMediaEnabled?: unknown }).originalMediaEnabled
: undefined;
// Move saves using the former generated-only default to the new default
// once, retaining their quality, visibility, mute and volume preferences.
const migrateMediaDefault = (parsed.version ?? 0) < 6
&& storedMode === "generated"
&& storedOriginalMediaEnabled !== true;
const normalized = normalizeCombatPresentationSettings(migrateMediaDefault ? {
...(settings as Record<string, unknown>),
originalMediaEnabled: true,
vfxMode: "original",
} : settings);
if (
storedMode !== normalized.vfxMode
|| storedOriginalMediaEnabled !== normalized.originalMediaEnabled
@@ -243,8 +255,10 @@ function readDatabase(storage: StorageLike | null = browserLocalStorage()): Prof
return [ownerId, normalized];
}),
);
const database: ProfileDatabase = { version: 5, accounts, rosters, presentationSettingsByOwner };
if (parsed.version !== 5 || presentationSettingsMigrated) writeDatabase(database, storage);
const rawUi = parsed.uiPreferencesByOwner && typeof parsed.uiPreferencesByOwner === "object" ? parsed.uiPreferencesByOwner : {};
const uiPreferencesByOwner = Object.fromEntries(Object.entries(rawUi).map(([owner, value]) => [owner, normalizeUiPreferences(value)]));
const database: ProfileDatabase = { version: 6, accounts, rosters, presentationSettingsByOwner, uiPreferencesByOwner };
if (parsed.version !== 6 || presentationSettingsMigrated) writeDatabase(database, storage);
return database;
} catch {
return emptyDatabase();
@@ -254,11 +268,23 @@ function readDatabase(storage: StorageLike | null = browserLocalStorage()): Prof
function writeDatabase(database: ProfileDatabase, storage: StorageLike | null = browserLocalStorage()): void {
storage?.setItem(DATABASE_KEY, JSON.stringify(database));
if (!storage || !rosterChangeListener) return;
for (const [ownerId, characters] of Object.entries(database.rosters)) {
rosterChangeListener(ownerId, characters);
for (const ownerId of new Set([...Object.keys(database.rosters), ...Object.keys(database.uiPreferencesByOwner ?? {})])) {
rosterChangeListener(ownerId, database.rosters[ownerId] ?? []);
}
}
export function loadUiPreferences(ownerId: string, storage: StorageLike | null = browserLocalStorage()): UiPreferences {
return normalizeUiPreferences(readDatabase(storage).uiPreferencesByOwner?.[ownerId]);
}
export function saveUiPreferences(ownerId: string, value: unknown, storage: StorageLike | null = browserLocalStorage()): UiPreferences {
const database = readDatabase(storage);
const preferences = normalizeUiPreferences(value);
database.uiPreferencesByOwner = { ...database.uiPreferencesByOwner, [ownerId]: preferences };
writeDatabase(database, storage);
return preferences;
}
function bytesToBase64(bytes: Uint8Array): string {
let result = "";
for (let index = 0; index < bytes.length; index += 3) {
+5
View File
@@ -11,6 +11,7 @@ import { useShellStore } from "./shellStore";
import { registerDungeonShellRuntime } from "./dungeonShellRuntimeBridge";
import { touchCharacter } from "./accountRepository";
import { specializationById } from "../game/specializationCatalog";
import { dungeonContentIsUsable } from "../content/contentManager";
export function installDungeonShellRuntime(): void {
registerDungeonShellRuntime({ enterDungeon });
@@ -22,6 +23,10 @@ function enterDungeon(dungeonId: string, requestedRole?: PartyRole): boolean {
useShellStore.setState({ notice: "That dungeon is not available yet." });
return false;
}
if (!dungeonContentIsUsable(dungeonId)) {
useShellStore.setState({ notice: "Install this expedition from Downloads before entering." });
return false;
}
const { session, selectedCharacterId, characters } = useShellStore.getState();
if (!session || !selectedCharacterId) {
useShellStore.setState({ notice: "Select or create a character first." });
+21 -2
View File
@@ -1,8 +1,11 @@
import { Capacitor } from "@capacitor/core";
import { create } from "zustand";
import {
listCharacters,
replaceCharactersForOwner,
setRosterChangeListener,
loadUiPreferences,
saveUiPreferences,
type AccountResult,
} from "./accountRepository";
import type { CharacterProfile, PlayerSession } from "./types";
@@ -20,7 +23,7 @@ interface AuthResponse {
interface CloudSaveResponse {
revision: number;
updatedAt: number | null;
data: { version?: number; characters?: unknown };
data: { version?: number; characters?: unknown; uiPreferences?: unknown };
}
interface MeResponse {
@@ -39,6 +42,8 @@ let suppressUpload = false;
let pendingCharacters: CharacterProfile[] | null = null;
let saveTimer: ReturnType<typeof setTimeout> | null = null;
let saveQueue = Promise.resolve();
export const useCloudSaveStatus = create<{ state: "local" | "pending" | "synced" | "error"; message: string }>(() => ({ state: "local", message: "" }));
let saveSequence = 0;
export function onlineApiOrigin(): string {
const configured = String(import.meta.env.VITE_API_BASE_URL ?? "").replace(/\/+$/, "");
@@ -100,18 +105,24 @@ function flushCloudSave(): void {
const characters = pendingCharacters;
pendingCharacters = null;
if (!session?.accessToken || !characters) return;
const uiPreferences = loadUiPreferences(session.ownerId);
const sequence = saveSequence;
saveQueue = saveQueue.then(async () => {
await requestOnlineJson<CloudSaveResponse>("/api/cloud-save", {
method: "PUT",
body: JSON.stringify({ data: { version: 1, characters } }),
body: JSON.stringify({ data: { version: 1, characters, uiPreferences } }),
}, session.accessToken);
if (activeSession?.ownerId === session.ownerId && sequence === saveSequence) useCloudSaveStatus.setState({ state: "synced", message: "Saved to your account." });
}).catch((error) => {
console.error("Healer Man cloud save failed", error);
if (activeSession?.ownerId === session.ownerId && sequence === saveSequence) useCloudSaveStatus.setState({ state: "error", message: "Saved on this device. Cloud upload failed; retry before switching devices." });
});
}
function queueCloudSave(ownerId: string, characters: readonly CharacterProfile[]): void {
if (suppressUpload || !activeSession?.accessToken || activeSession.ownerId !== ownerId) return;
saveSequence += 1;
useCloudSaveStatus.setState({ state: "pending", message: "Uploading to your account…" });
pendingCharacters = characters.map((character) => ({ ...character }));
if (saveTimer) clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
@@ -123,15 +134,23 @@ function queueCloudSave(ownerId: string, characters: readonly CharacterProfile[]
setRosterChangeListener(queueCloudSave);
export function activateOnlineSession(session: PlayerSession): void {
if (activeSession?.ownerId !== session.ownerId && saveTimer) {
clearTimeout(saveTimer); saveTimer = null; flushCloudSave();
}
activeSession = session.accessToken ? session : null;
}
export function retryCloudSave(): void {
if (activeSession) queueCloudSave(activeSession.ownerId, listCharacters(activeSession.ownerId));
}
export async function hydrateOnlineSession(session: PlayerSession): Promise<CharacterProfile[]> {
if (!session.accessToken) return listCharacters(session.ownerId);
activateOnlineSession(session);
const cloud = await requestOnlineJson<CloudSaveResponse>("/api/cloud-save", {}, session.accessToken);
suppressUpload = true;
try {
saveUiPreferences(session.ownerId, cloud.data?.uiPreferences);
return replaceCharactersForOwner(session.ownerId, cloud.data?.characters ?? []);
} finally {
suppressUpload = false;
+1 -1
View File
@@ -58,7 +58,7 @@ describe("RoM dual-class persistence", () => {
"priest:none": { "primary:face-bottom": "priest-flash-heal" },
},
});
expect(JSON.parse(storage.getItem(PROFILE_STORAGE_KEYS.database)!).version).toBe(5);
expect(JSON.parse(storage.getItem(PROFILE_STORAGE_KEYS.database)!).version).toBe(6);
});
it("locks selection to level ten and preserves separate bars through atomic swaps", () => {
+16 -1
View File
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createDefaultAppearance } from "./characterCatalog";
import { useShellStore } from "./shellStore";
import { installDungeonShellRuntime } from "./dungeonShellRuntime";
@@ -79,6 +79,10 @@ function prepareSelectedCharacter(): void {
}
describe("shell store", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
beforeEach(() => {
useShellStore.setState({
phase: "login",
@@ -167,6 +171,17 @@ describe("shell store", () => {
expect(useGameStore.getState().distanceTravelled).toBe(42);
});
it("rejects a shipped dungeon whose production content pack is not usable", () => {
vi.stubEnv("DEV", false);
prepareSelectedCharacter();
useShellStore.getState().openMainMenu();
useShellStore.getState().openDungeons();
expect(useShellStore.getState().enterDungeon("deadmines", "healer")).toBe(false);
expect(useShellStore.getState().phase).toBe("dungeons");
expect(useShellStore.getState().notice).toMatch(/downloads/i);
});
it("returns from gameplay to the main menu with the same character selected", () => {
prepareSelectedCharacter();
expect(useShellStore.getState().enterDungeon(DUNGEON_MANIFEST.id)).toBe(true);
+52
View File
@@ -0,0 +1,52 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { loadUiPreferences, saveUiPreferences, setRosterChangeListener } from "./accountRepository";
import { normalizeUiPreferences } from "../game/uiLayout";
import type { PlayerSession } from "./types";
function storage() {
const values = new Map<string, string>();
return { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); }, removeItem: (key: string) => { values.delete(key); } };
}
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); setRosterChangeListener(null); });
describe("profile UI persistence", () => {
it("isolates owners and persists templates without requiring a character", () => {
const local = storage(); const ui = normalizeUiPreferences(null);
ui.slots.pc[1] = { name: "Healer", layout: ui.current.pc };
ui.keybinds.pc["move-forward"] = "ArrowUp";
ui.keybinds.controller.jump = "Button4&Button3";
saveUiPreferences("one", ui, local);
expect(loadUiPreferences("one", local).slots.pc[1]?.name).toBe("Healer");
expect(loadUiPreferences("two", local).slots.pc[1]).toBeNull();
expect(loadUiPreferences("one", local).keybinds).toEqual(ui.keybinds);
expect(loadUiPreferences("two", local).keybinds.pc["move-forward"]).toBe("KeyW");
ui.slots.pc[1].name = "Unsaved change";
expect(loadUiPreferences("one", local).slots.pc[1]?.name).toBe("Healer");
});
it("uploads all six slots and restores them into a separate device cache", async () => {
vi.useFakeTimers();
const first = storage(); const second = storage();
vi.stubGlobal("window", { localStorage: first });
let cloudData: unknown = { version: 1, characters: [] };
vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => {
if (init.method === "PUT") cloudData = JSON.parse(String(init.body)).data;
return new Response(JSON.stringify({ revision: 1, updatedAt: 1, data: cloudData }), { status: 200, headers: { "Content-Type": "application/json" } });
}));
const client = await import("./onlineAccountClient");
const session: PlayerSession = { ownerId: "cloud-user", kind: "account", displayName: "Player", accessToken: "test-token" };
client.activateOnlineSession(session);
const ui = normalizeUiPreferences(null);
ui.slots.pc[2] = { name: "Desktop raid", layout: ui.current.pc };
ui.slots.mobile[1] = { name: "On the go", layout: ui.current.mobile };
ui.keybinds.pc["move-forward"] = "ArrowUp";
ui.keybinds.pc["look-up"] = null;
ui.keybinds.controller.jump = "Button4&Button3";
saveUiPreferences(session.ownerId, ui);
await vi.advanceTimersByTimeAsync(501);
expect(client.useCloudSaveStatus.getState().state).toBe("synced");
vi.stubGlobal("window", { localStorage: second });
await client.hydrateOnlineSession(session);
expect(loadUiPreferences(session.ownerId)).toEqual(ui);
expect(loadUiPreferences("different-account").slots.pc[2]).toBeNull();
});
});
@@ -137,8 +137,8 @@
{
"role": "visual",
"fileName": "aeternal-circle-visual.glb",
"size": 4963912,
"sha256": "42fdcff1b25b58688943a030f69fd14ea839247a7baabbc31b5f6f7faaf49785",
"size": 4963968,
"sha256": "de1ba06b7e3a9237fcff75aff2b00093287975e755cc7e98e77de1b7af6a9c14",
"compression": "meshopt+ktx2"
},
{
@@ -8,8 +8,8 @@
},
"optimized": {
"file": "aeternal-circle-visual.optimized.glb",
"size": 4963912,
"checksum": "42fdcff1b25b58688943a030f69fd14ea839247a7baabbc31b5f6f7faaf49785"
"size": 4963968,
"checksum": "de1ba06b7e3a9237fcff75aff2b00093287975e755cc7e98e77de1b7af6a9c14"
},
"compression": "meshopt+ktx2",
"commands": [
@@ -137,8 +137,8 @@
{
"role": "visual",
"fileName": "barren-caves-visual.glb",
"size": 1710152,
"sha256": "d0f733de4b26c0f432c5e160614765f320bf1753a829be269740b340e7415a12",
"size": 1710188,
"sha256": "e6dc49e6aa6fd20cee1b2afa43324a714f8f8284a6becef8dc514509b432f9bb",
"compression": "meshopt+ktx2"
},
{
@@ -8,8 +8,8 @@
},
"optimized": {
"file": "barren-caves-visual.optimized.glb",
"size": 1710152,
"checksum": "d0f733de4b26c0f432c5e160614765f320bf1753a829be269740b340e7415a12"
"size": 1710188,
"checksum": "e6dc49e6aa6fd20cee1b2afa43324a714f8f8284a6becef8dc514509b432f9bb"
},
"compression": "meshopt+ktx2",
"commands": [
Loaded 100 of 386 files, more files were not shown because too many files have changed in this diff. Show more