Release Healer Man 0.1.39

This commit is contained in:
phenom committed 2026-09-13 11:07:56 -04:00
1 parent b417b7c3c3
commit ed0d2fea3d
51 files changed
+17811 -49

No files matched your search

+117
View File
@@ -2762,3 +2762,120 @@ Vite's existing large-chunk advisory remains informational.
passed, along with the native vocation-import regression. The production passed, along with the native vocation-import regression. The production
TypeScript/Vite build and release-bundle verification passed. The final TypeScript/Vite build and release-bundle verification passed. The final
release candidate check includes the new tests and generated catalogs. release candidate check includes the new tests and generated catalogs.
## RoM dungeon enemy durability — September 13, 2026
- Reproduced Barren Caves' low health with a RoM Priest and the four shipped
companions. Tested 108 combinations: 12 party seeds at levels 1, 2, 4, 8, 9,
20, 40, 70, and 80. The old fallback had 94 health at level 1 and 1,832 at
level 80; kills took 0–1.9 seconds from the first damaging NPC hit.
- Normal RoM dungeons now use a party-health baseline of
`1000 + 100 * enemyLevel + 8 * enemyLevel * enemyLevel`, with authored
creature/boss multipliers applied separately. This is explicit Healer Man
balancing because native RoM creature health tables are not packaged.
Barren Caves' Anglo retains his 7.5 multiplier and one-level advantage.
- Loaded RoM creatures receive the new health when the character levels up.
Re-registration preserves wounds as a health percentage and keeps corpses
dead. Enemy attack damage also rebases on a level change instead of retaining
its original low-level value. Regression checks cover these transitions.
- With the new health, the 108 isolated party-damage pulls lasted 3–17.5
seconds. A separate pull exercised actual enemy attacks and Priest healing
before the enemy died, with all companions surviving. These are opening
pulls with baseline equipment, rather than an audit of every geared build.
- Live PC check at 1280×720: created the offline Human Priest Barrenaudit and
entered Barren Caves as Healer. A level-1 Cave Sand Bug had 1,108 health.
At 10 seconds it still had 374 health, with 734 party damage on the meter.
The completed first fight showed 14 seconds and 1,108 total damage:
Morgha 370, Ilyen 369, Maerwen 289, and Cael 80. Urgent Heal then restored
Maerwen to 407/407 while the next pull was active. No browser errors were
captured during that bounded combat check.
- Concurrent navigation edits triggered development hot reloads around the
playtest; the captures above were taken during uninterrupted combat. This
check did not complete the dungeon or use physical Ayn Thor hardware.
Restored the original Hudtest roster selection, closed the test tab, and
stopped the temporary development servers.
- Evidence: `artifacts/rom-dungeon-health/report.json`,
`barren-caves-health.png`, `barren-caves-combat.png`, `barren-caves-healed.png`,
`live-combat-dom.txt`, and `browser-errors.json`.
- Validation: all 407 focused combat, party, CoA, RoM, DPS-meter, stat, and
dungeon-scaling tests passed across 52 files. The final production
TypeScript/Vite build and release-bundle verification passed.
## 2026-09-13 - WoW dungeon lighting and stair fleet pass
- Applied environment-specific readable lighting to all 54 WoW dungeon entries,
using the reviewed Stockades ambient/hemisphere fill as the baseline. Stone,
cavern, fire, arcane, crypt, and outdoor profiles preserve distinct coloration.
Stockades' existing presentation/three ramps and RuneWaker lighting are unchanged.
- Scanned every shipped WoW collision package, including authored Wailing
Caverns' actual source assets. Added 347 verified walking proxies across 22
other dungeons and eight filled navigation portal bridges in Uldaman. Rendered
steps and source visual/collision/navigation GLBs remain unchanged.
- Added package-identity gates and a compiler-independent shared runtime adapter.
Collision preparation spatially indexes flights; rejected candidates cannot
supply geometry needed by accepted proxies. Existing navigation validation,
content, encounter, and availability gates were not promoted to green.
- Shipping-asset regressions independently pass all 347 new proxies through
prepared collision and the live NPC segment validator uphill/downhill at the
center and two interior lateral lanes. Exact portal matching and all existing
Stockades player/NPC/wall tests pass.
- The game-playtest visual viewer uses shipped meshes and runtime lighting and
material policies without touching saved character/party state. At 1280x720,
Uldaman's old/new-fill comparison showed clearer stonework; Wailing Caverns
retained green, readable rock; Mechanar retained cool arcane interiors;
Scholomance's visible entrance steps/masonry remained intact and readable.
Blood Furnace's dark source textures remained visible at its wall-facing
entrance viewpoint. Durnholde's visual load completed without console errors.
- Zul'Farrak entrance/boss views and Durnholde's exterior boss view showed
geometry/terrain/viewpoint gaps, recorded for separate investigation. This is
not exhaustive staircase certification: curved/short/heavily-decimated flights,
rejected candidates, outer stair edges/landing lips, complete dungeon routes,
full clears, and physical Android QA still require individual review.
- Evidence/coverage: `dungeon-pipeline/WOW_ENVIRONMENT_REVIEW.md`,
`src/game/generated/wowDungeonStairs.generated.json`, and screenshots in
`artifacts/wow-dungeon-environment/`. No hosted release was published.
- Validation: 247 Vitest files passed, 1,599 tests passed, six existing tests
skipped. Production TypeScript/Vite build, texture/performance audits, bundle
compression/verification, and release candidate check passed. Existing physics
initialization and bundle-size/import advisories remain.
## 2026-09-13 - Dungeon completion results and run leaderboards
- Fixed missing RuneWaker completion bookkeeping for the 21 dungeons with
configured bosses. Barren Caves now awards Anglo's objective on his actual
death and announces the completed run. Bossless placeholder entries do not
fabricate a completion.
- Run timing starts when the dungeon is playable, survives wipes, pauses, and
saved resumes, and freezes at the final-boss objective. Older checkpoints
without a recorded start time still announce completion but remain unranked.
- The results dialog shows the final-boss time, final-clear and full-clear
placement, party classes/levels, and defeated bosses. Stay and loot, reopening
results, and Return to main menu were verified through the live UI. Returning
clears the completed checkpoint.
- Replaced the dungeon picker's minimap with persistent completion-time
leaderboards. Final Boss clears includes all qualifying runs; Full dungeon
clears requires every available boss for the selected difficulty. Expanded
entries show each party member and boss status. Normal/heroic rankings are
separate; disconnected results use an explicitly labeled device leaderboard.
- An actual combat integration check fought Barren Caves' level-2 Anglo with
9,240 health using NPC ability selection, enemy attacks, and Priest healing.
NPCs dealt 9,239 damage after a one-damage player tag; healing totaled 441.
The final death awarded completion at 84.1 seconds with all companions alive.
- Manual browser combat confirmed NPC damage and healing on Barren Caves
trash. The live results check restored the integration fight's completed
checkpoint through an isolated local QA account: 01:24.1 ranked #1 of three
seeded local-server entries in both filters. This was not a manual browser
full clear and no production leaderboard entries were published.
- PC results and expanded final/full leaderboard layouts were visually
reviewed at 1280x720. The built-in Thor preview displayed the leaderboard,
filters, and role-selection control within its 960x540 main surface. Compact
480x360 DOM bounds kept the dialog footer inside the viewport; the in-app
browser's viewport-override screenshot scaled incorrectly, so that capture
does not establish compact visual quality. Physical Thor hardware was not used.
- Evidence: `artifacts/dungeon-runs/combat-completion.json`, `results-world.png`,
`leaderboard-final-expanded.png`, `leaderboard-full-expanded.png`, and
`leaderboard-thor.png`. The bounded final browser check captured no errors.
- Validation: 70 completion, checkpoint, encounter, catalog, client, and UI
tests plus the real-combat integration test passed. The 432-test focused
combat/party/class/health/input regression suite and 18 server tests passed.
Production build, final TypeScript check, and release candidate check passed.
+119
View File
@@ -0,0 +1,119 @@
# WoW dungeon lighting and stair review - 2026-09-13
## Implemented coverage
All 54 campaign WoW dungeons now receive environment-specific lighting using
Stockades' reviewed ambient/hemisphere fill as the baseline. Stone, cavern,
fire, arcane, crypt, and outdoor profiles preserve atmosphere without applying
the old dark expansion palettes. Stockades' existing presentation and three
reviewed stair proxies remain unchanged. RuneWaker environments are excluded.
The fleet scan produced 347 additional collision-verified walking proxies in
22 dungeons, and eight filled Recast boundary bridges in Uldaman. This makes
350 walking proxies including the three existing Stockades flights. Visual
stairs remain steps: source visual/collision/navigation GLBs were not modified.
The shared prepared collision is used by players, companions, and enemies.
| Dungeon | Additional walking proxies | Additional navigation bridges |
| --- | ---: | ---: |
| Shadowfang Keep | 41 | 0 |
| Blackfathom Deeps | 5 | 0 |
| Uldaman | 5 | 8 |
| Gnomeregan | 4 | 0 |
| Sunken Temple | 2 | 0 |
| Scarlet Monastery | 37 | 0 |
| Zul'Farrak | 1 | 0 |
| Scholomance | 36 | 0 |
| Stratholme | 12 | 0 |
| Blood Furnace | 1 | 0 |
| Shadow Labyrinth | 1 | 0 |
| Mana-Tombs | 3 | 0 |
| Auchenai Crypts | 5 | 0 |
| Magister's Terrace | 10 | 0 |
| Escape From Durnholde | 120 | 0 |
| Utgarde Keep | 8 | 0 |
| Utgarde Pinnacle | 32 | 0 |
| Culling of Stratholme | 11 | 0 |
| Halls of Stone | 2 | 0 |
| Halls of Lightning | 1 | 0 |
| Pit of Saron | 1 | 0 |
| Halls of Reflection | 9 | 0 |
The machine-readable `src/game/generated/wowDungeonStairs.generated.json`
records a scan for every WoW dungeon, including entries with no accepted new
proxy, collision package identities, candidate/rejection counts, and exact
navigation portals. Authored Wailing Caverns is scanned against its actual
source assets, rather than the campaign's separate canonical package.
## Safety and verification
- Require repeated short risers with consistent rise/run and overlapping width.
- Merge compatible continuous flights; independently verify short fallbacks
when a merged flight is unsafe.
- Rebuild after rejected proxies are removed, so accepted paths do not depend
on rejected geometry edits.
- Check real terrain support and capsule sweeps uphill/downhill along the center
and two interior lateral lanes at approximately 0.35m intervals.
- Fill only separate existing boundary portals wholly within a verified flight.
Do not invent off-mesh links across unrelated floors or walls.
- Gate generated coordinates by collision package URL/checksum identity, and
navigation identity where exact portal bridges are present.
- Keep existing validation/availability gates unchanged. Stair checks do not
certify boss routes, encounters, resets, checkpoints, or complete runs.
- Spatially index ramp footprints during preparation to avoid checking every
ramp against every vertex in large, multi-chunk environments.
The shipping-asset regression tests independently exercise all 347 new proxies
through `prepareCollision` and the live NPC direct-segment validator in both
directions and all three tested lanes. All generated portals match the actual
shipping navigation vertices. Existing Stockades player/NPC/wall regressions pass.
Full validation: 247 Vitest files passed, 1,599 tests passed, six existing tests
skipped. Production TypeScript/Vite build, texture/performance audits, bundle
compression/verification, and release candidate checking passed. Existing
physics initialization and bundle-size/import advisories remain.
## Visual evidence and remaining QA
The local visual viewer uses the runtime definitions/material policy, shipped
GLBs, Meshopt/KTX2 decoding, ACES tone mapping, and 1280x720 screenshots. It does
not modify saved characters or party state. Evidence is under
`artifacts/wow-dungeon-environment/` (ignored QA artifacts).
Uldaman's new/old-fill comparison shows clearer stone walls, columns, and floor
tiles. Wailing Caverns retains green coloration with readable rock formations.
Mechanar retains cool purple/blue interiors and unchanged visible steps.
Scholomance's entrance stairs and masonry remain visible with the crypt profile.
Blood Furnace's dark source textures remain atmospheric; the entrance viewpoint
faces a nearby wall, so this is not a full-room traversal review.
Zul'Farrak showed a geometry/viewpoint gap in the standalone entrance and boss
views. Do not treat its lighting profile or passing isolated proxy sweep as an
end-to-end visual/playability pass. Durnholde's large package completed loading
without console errors; its cavern entrance and outdoor fort masonry/trees were
readable, but the boss viewpoint also showed missing terrain/viewpoint coverage.
That environment needs a separate terrain/spawn review and live traversal check.
This is not an exhaustive certification that every staircase is repaired.
Conservative repeated-riser detection can miss curved flights, one/two-step
transitions, and heavily decimated source geometry. A rejected candidate may be
decorative, lack headroom/ground, or require an individually reviewed footprint.
An entry with no new proxy is not proof that it contains no stairs. Full-dungeon
actor traversal, entrance/exit lips, outer stair edges, manual review of rejected
or undetected flights, full clears, and physical Android QA remain open.
## Repeating the checks
Requires the project's Node 24 runtime for native TypeScript pipeline execution.
```text
npm run dungeon:wow:stairs:audit
npm run dungeon:wow:stairs:refresh
npm run dungeon:wow:stairs:audit -- scholomance --diagnostics
node scripts/dungeon-pipeline/audit-wow-stairs.ts wailing-caverns --update
npm test -- --run src/game/wowDungeonStairAssets.test.ts
```
The audit is read-only by default. Refresh writes the full generated catalog;
`--update` replaces only the named entry while retaining the other entries.
Campaign regeneration does not erase the runtime lighting/stair adapter.
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "healer-man", "name": "healer-man",
"version": "0.1.38", "version": "0.1.39",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "healer-man", "name": "healer-man",
"version": "0.1.38", "version": "0.1.39",
"dependencies": { "dependencies": {
"@capacitor/android": "8.4.1", "@capacitor/android": "8.4.1",
"@capacitor/core": "8.4.1", "@capacitor/core": "8.4.1",
+3 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "healer-man", "name": "healer-man",
"private": true, "private": true,
"version": "0.1.38", "version": "0.1.39",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite --host 0.0.0.0", "dev": "vite --host 0.0.0.0",
@@ -56,6 +56,8 @@
"dungeon:five-player:verify": "node scripts/dungeon-pipeline/verify-five-player-dungeon-imports.mjs", "dungeon:five-player:verify": "node scripts/dungeon-pipeline/verify-five-player-dungeon-imports.mjs",
"dungeon:wow:audit": "vite-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:functionality:audit": "vite-node scripts/dungeon-pipeline/audit-wow-dungeon-functionality.ts",
"dungeon:wow:stairs:audit": "node --max-old-space-size=8192 scripts/dungeon-pipeline/audit-wow-stairs.ts",
"dungeon:wow:stairs:refresh": "node --max-old-space-size=8192 scripts/dungeon-pipeline/audit-wow-stairs.ts --write",
"dungeon:wow:test": "vitest run src/game/wowDungeonContent.test.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: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:ascension:recovery:validate": "node scripts/dungeon-pipeline/validate-ascension-custom-dungeon-recovery.mjs --skip-dbc",
+2 -2
View File
@@ -1,4 +1,4 @@
{ {
"versionName": "0.1.38", "versionName": "0.1.39",
"versionCode": 1038 "versionCode": 1039
} }
@@ -0,0 +1,142 @@
import { readFileSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { DungeonDefinition } from "../../src/game/dungeonTypes";
import { detectDungeonStairRamps, dungeonStairNavigationBridges, dungeonStairRisers, readDungeonGeometry } from "./wow-stair-geometry.ts";
import RAPIER from "@dimforge/rapier3d-compat";
import { dungeonRampHeight, smoothDungeonStairGeometry } from "../../src/game/dungeonTraversalRamps.ts";
import type { DungeonTraversalRamp } from "../../src/game/dungeonTypes";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const catalog = JSON.parse(readFileSync(path.join(root, "src/game/generated/dungeonCampaignCatalog.json"), "utf8"));
const outputFile = path.join(root, "src/game/generated/wowDungeonStairs.generated.json");
const output: Record<string, unknown> = process.argv.includes("--update")
? JSON.parse(readFileSync(outputFile, "utf8")).dungeons : {};
const requested = process.argv.slice(2).find((arg) => !arg.startsWith("--"));
if (requested && !catalog.definitions.some((dungeon: DungeonDefinition) => dungeon.id === requested)) {
throw new Error(`Unknown WoW dungeon: ${requested}`);
}
await RAPIER.init();
function rampTraversable(world: RAPIER.World, ramp: DungeonTraversalRamp): boolean {
const rejected = (reason: string, detail: unknown) => {
if (process.argv.includes("--diagnostics")) console.log(ramp.id, reason, JSON.stringify(detail));
return false;
};
const dx = ramp.end[0] - ramp.start[0];
const dz = ramp.end[2] - ramp.start[2];
const length = Math.hypot(dx, dz);
const shape = new RAPIER.Capsule(0.32, 0.34);
const rotation = { x: 0, y: 0, z: 0, w: 1 };
// Test both directions across the center and two capsule-safe lateral lanes.
const lateral = Math.max(0, Math.min(ramp.width / 4, ramp.width / 2 - 0.45));
for (const lane of [0, -lateral, lateral]) {
const count = Math.max(3, Math.ceil(length / 0.35) + 1);
const points = Array.from({ length: count }, (_, index) => {
const t = index / (count - 1);
return {
x: ramp.start[0] + dx * t - dz / length * lane,
y: ramp.start[1] + (ramp.end[1] - ramp.start[1]) * t,
z: ramp.start[2] + dz * t + dx / length * lane,
};
});
for (const point of points) {
const floor = world.castRayAndGetNormal(new RAPIER.Ray({ ...point, y: point.y + 1.25 }, { x: 0, y: -1, z: 0 }), 2, true);
if (!floor || floor.normal.y < 0.65 || Math.abs(1.25 - floor.timeOfImpact) > 0.55) return rejected("floor", { lane, point, normal: floor?.normal, heightDelta: floor ? 1.25 - floor.timeOfImpact : null });
}
for (let index = 1; index < points.length; index += 1) {
for (const [start, end] of [[points[index - 1], points[index]], [points[index], points[index - 1]]]) {
const delta = { x: end.x - start.x, y: end.y - start.y, z: end.z - start.z };
const distance = Math.hypot(delta.x, delta.y, delta.z);
const hit = world.castShape({ ...start, y: start.y + 1.02 }, rotation, delta, shape, 0.025, 1, false);
if (hit && hit.time_of_impact < 1 - 0.04 / distance) return rejected("sweep", { lane, start, end, hit: hit.time_of_impact });
}
}
}
return true;
}
for (const dungeon of catalog.definitions as DungeonDefinition[]) {
if (requested && dungeon.id !== requested) continue;
if (dungeon.id === "stormwind-stockade") {
output[dungeon.id] = { collision: dungeon.assets.collision, ramps: [], reviewedOverride: true };
console.log(`${dungeon.id}: preserving three reviewed ramps`);
continue;
}
const risers = [];
const geometries = [];
// Wailing Caverns retains its authored environment rather than the campaign's
// canonical Manastorm package. Audit the assets actually used by that entry.
const collisionAssets = dungeon.id === "wailing-caverns" ? [{
fileName: "wailing-caverns-collision.glb", url: undefined,
checksum: createHash("sha256").update(readFileSync(path.join(root, "src/assets/game/dungeons/wailing-caverns/wailing-caverns-collision.glb"))).digest("hex"),
}] : dungeon.assets.collision;
const assetFile = (asset: { url?: string; fileName: string }) => asset.url
? path.join(root, "public", asset.url)
: path.join(root, "src/assets/game/dungeons", dungeon.id, asset.fileName);
const navigationAsset = dungeon.id === "wailing-caverns" ? {
fileName: "wailing-caverns-navigation.glb", url: undefined,
checksum: createHash("sha256").update(readFileSync(path.join(root, "src/assets/game/dungeons/wailing-caverns/wailing-caverns-navigation.glb"))).digest("hex"),
} : dungeon.assets.navigation;
for (const asset of collisionAssets) {
for (const geometry of await readDungeonGeometry(assetFile(asset))) {
risers.push(...dungeonStairRisers(geometry));
geometries.push(geometry);
}
}
const candidates = detectDungeonStairRamps(risers);
const verify = (input: DungeonTraversalRamp[]): DungeonTraversalRamp[] => {
let ramps = input;
// Rebuild after rejection: accepted ramps must not depend on rejected geometry changes.
while (ramps.length) {
const world = new RAPIER.World({ x: 0, y: -18, z: 0 });
try {
for (const source of geometries) {
const geometry = source.clone();
smoothDungeonStairGeometry(geometry, ramps);
world.createCollider(RAPIER.ColliderDesc.trimesh(
Float32Array.from(geometry.getAttribute("position").array),
Uint32Array.from(geometry.index?.array ?? Array.from({ length: geometry.getAttribute("position").count }, (_, index) => index)),
));
geometry.dispose();
}
world.step();
const accepted = ramps.filter((ramp) => rampTraversable(world, ramp));
if (accepted.length === ramps.length) break;
ramps = accepted;
} finally { world.free(); }
}
return ramps;
};
let ramps = verify(candidates);
// If a long merged flight was unsafe, retain independently verified shorter
// flights instead. Do not let fallback fragments reshape an accepted plane.
const fallback = detectDungeonStairRamps(risers, false).filter((ramp) => !ramps.some((accepted) => {
const within = (a: DungeonTraversalRamp, b: DungeonTraversalRamp) => [b.start, b.end,
b.start.map((v, i) => (v + b.end[i]) / 2)].some((point) => {
const height = dungeonRampHeight(a, point[0], point[2]);
return height !== null && Math.abs(point[1] - height) <= 0.85;
});
return within(accepted, ramp) || within(ramp, accepted);
})).map((ramp, index) => ({ ...ramp, id: `stair-fallback-${index + 1}` }));
ramps = verify([...ramps, ...fallback]);
output[dungeon.id] = {
collision: collisionAssets.map(({ fileName, url, checksum }) => ({ fileName, url, checksum })),
navigation: navigationAsset,
ramps, candidateCount: candidates.length + fallback.length,
rejectedCount: candidates.length + fallback.length - ramps.length,
};
if (ramps.length && navigationAsset) {
const navigation = await readDungeonGeometry(assetFile(navigationAsset));
const largest = navigation.sort((a, b) => b.getAttribute("position").count - a.getAttribute("position").count)[0];
(output[dungeon.id] as { ramps: DungeonTraversalRamp[] }).ramps = dungeonStairNavigationBridges(largest, ramps);
navigation.forEach((geometry) => geometry.dispose());
}
console.log(`${dungeon.id}: ${ramps.length}/${candidates.length + fallback.length} collision-verified stair proxies`);
geometries.forEach((geometry) => geometry.dispose());
}
if (process.argv.includes("--write") || process.argv.includes("--update")) {
if (requested && !process.argv.includes("--update")) throw new Error("Refusing to replace the fleet catalog with a single-dungeon scan.");
writeFileSync(outputFile, `${JSON.stringify({ schemaVersion: 1, dungeons: output }, null, 2)}\n`);
}
@@ -0,0 +1,249 @@
import { NodeIO } from "@gltf-transform/core";
import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
import { MeshoptDecoder } from "meshoptimizer";
import { BufferAttribute, BufferGeometry, Float32BufferAttribute, Matrix4 } from "three";
import type { DungeonTraversalRamp } from "../../src/game/dungeonTypes";
import { dungeonRampHeight } from "../../src/game/dungeonTraversalRamps.ts";
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS)
.registerDependencies({ "meshopt.decoder": MeshoptDecoder });
/** Decode exactly as GLTFLoader does, expanding quantized coordinates before baking transforms. */
export async function readDungeonGeometry(file: string): Promise<BufferGeometry[]> {
await MeshoptDecoder.ready;
const document = await io.read(file);
const geometries: BufferGeometry[] = [];
for (const node of document.getRoot().listNodes()) {
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
const accessor = primitive.getAttribute("POSITION");
if (!accessor?.getArray()) continue;
const source = new BufferAttribute(accessor.getArray()!, 3, accessor.getNormalized());
const positions = new Float32Array(source.count * 3);
for (let index = 0; index < source.count; index += 1) {
positions.set([source.getX(index), source.getY(index), source.getZ(index)], index * 3);
}
const geometry = new BufferGeometry();
geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
const indices = primitive.getIndices()?.getArray();
if (indices) geometry.setIndex(Array.from(indices));
geometry.applyMatrix4(new Matrix4().fromArray(node.getWorldMatrix()));
geometries.push(geometry);
}
}
return geometries;
}
interface Riser {
direction: number;
along: number;
low: number;
high: number;
left: number;
right: number;
}
/** Repeated short vertical faces, not arbitrary slopes or nearby disconnected floors. */
export function dungeonStairRisers(geometry: BufferGeometry): Riser[] {
const p = geometry.getAttribute("position");
const indices = geometry.index?.array ?? Array.from({ length: p.count }, (_, i) => i);
const faces = new Map<string, Riser>();
for (let offset = 0; offset + 2 < indices.length; offset += 3) {
const vertices = [indices[offset], indices[offset + 1], indices[offset + 2]];
const points = vertices.map((i) => [p.getX(i), p.getY(i), p.getZ(i)]);
const [a, b, c] = points;
const ab = b.map((v, i) => v - a[i]);
const ac = c.map((v, i) => v - a[i]);
const nx = ab[1] * ac[2] - ab[2] * ac[1];
const ny = ab[2] * ac[0] - ab[0] * ac[2];
const nz = ab[0] * ac[1] - ab[1] * ac[0];
if (Math.hypot(nx, nz) < 0.1 || Math.abs(ny) / Math.hypot(nx, ny, nz) > 0.025) continue;
const low = Math.min(...points.map((v) => v[1]));
const high = Math.max(...points.map((v) => v[1]));
if (high - low < 0.08 || high - low > 0.82) continue;
// Opposite winding still describes the same plane. Quantization permits ~1 degree noise.
const direction = ((Math.round(Math.atan2(nz, nx) / Math.PI * 180) % 180) + 180) % 180;
const angle = direction * Math.PI / 180;
const along = points.reduce((sum, v) => sum + v[0] * Math.cos(angle) + v[2] * Math.sin(angle), 0) / 3;
const across = points.map((v) => -v[0] * Math.sin(angle) + v[2] * Math.cos(angle));
const left = Math.min(...across);
const right = Math.max(...across);
if (right - left < 0.9) continue;
const key = [direction, Math.round(along / 0.04), Math.round(low / 0.04), Math.round(high / 0.04)].join(":");
const previous = faces.get(key);
if (previous && Math.min(previous.right, right) - Math.max(previous.left, left) >= -0.04) {
previous.left = Math.min(previous.left, left);
previous.right = Math.max(previous.right, right);
} else faces.set(`${key}${previous ? `:${Math.round(left / 0.04)}` : ""}`, { direction, along, low, high, left, right });
}
return [...faces.values()];
}
export function detectDungeonStairRamps(risers: Riser[], merge = true): DungeonTraversalRamp[] {
const ramps: DungeonTraversalRamp[] = [];
const used = new Set<Riser>();
const sorted = [...risers].sort((a, b) => a.direction - b.direction || a.along - b.along || a.low - b.low);
for (const first of sorted) {
if (used.has(first)) continue;
const neighbors = sorted.filter((r) => Math.min(Math.abs(r.direction - first.direction), 180 - Math.abs(r.direction - first.direction)) <= 2)
.map((source) => {
const difference = (source.direction - first.direction) * Math.PI / 180;
const across = (source.left + source.right) / 2;
const halfWidth = (source.right - source.left) / 2 * Math.abs(Math.cos(difference));
const center = source.along * Math.sin(difference) + across * Math.cos(difference);
return { source, ...source, along: source.along * Math.cos(difference) - across * Math.sin(difference), left: center - halfWidth, right: center + halfWidth };
}).sort((a, b) => a.along - b.along || a.low - b.low);
const chain = [first];
const chainSources = [first];
let sign = 0;
while (true) {
const current = chain[chain.length - 1];
const next = neighbors.find((candidate) => {
if (used.has(candidate.source)) return false;
const run = candidate.along - current.along;
const rise = candidate.low - current.low;
const overlap = Math.min(...chain.map((r) => r.right), candidate.right)
- Math.max(...chain.map((r) => r.left), candidate.left);
return run > 0.12 && run < 2.5 && Math.abs(rise) >= 0.08 && Math.abs(rise) <= 0.82
&& Math.abs(rise) / run < 0.85 && overlap >= 1
&& (!sign || Math.sign(rise) === sign)
&& Math.min(Math.abs(candidate.low - current.high), Math.abs(candidate.high - current.low)) < 0.22;
});
if (!next) break;
if (chain.length > 1) {
const run = chain[1].along - first.along;
const rise = chain[1].low - first.low;
if (Math.abs(next.low - (first.low + rise / run * (next.along - first.along))) > 0.1) break;
}
chain.push(next);
chainSources.push(next.source);
sign = Math.sign(next.low - current.low);
}
if (chain.length < 3) continue;
const last = chain[chain.length - 1];
const run = (last.along - first.along) / (chain.length - 1);
const rise = (last.low - first.low) / (chain.length - 1);
const left = Math.max(...chain.map((r) => r.left));
const right = Math.min(...chain.map((r) => r.right));
const across = (left + right) / 2;
const angle = first.direction * Math.PI / 180;
const point = (along: number, y: number): [number, number, number] => [
along * Math.cos(angle) - across * Math.sin(angle), y,
along * Math.sin(angle) + across * Math.cos(angle),
];
// Meet the lower/upper landings, including the first/last riser, without a lip.
ramps.push({
id: `stair-flight-${ramps.length + 1}`,
start: point(first.along - (sign < 0 ? run : 0.04), sign < 0 ? first.high : first.low),
end: point(last.along + (sign > 0 ? run : 0.04), sign > 0 ? last.high : last.low),
width: right - left + 0.02,
});
chainSources.forEach((r) => used.add(r));
}
return merge ? mergeDungeonStairRamps(ramps) : ramps;
}
/** Keep one plane per continuous flight; independent overlapping fragments introduce new lips. */
export function mergeDungeonStairRamps(input: DungeonTraversalRamp[]): DungeonTraversalRamp[] {
const ramps = [...input].sort((a, b) => Math.hypot(b.end[0] - b.start[0], b.end[2] - b.start[2])
- Math.hypot(a.end[0] - a.start[0], a.end[2] - a.start[2]));
const result: DungeonTraversalRamp[] = [];
for (const ramp of ramps) {
let combined = false;
for (let index = 0; index < result.length; index += 1) {
const previous = result[index];
const dx = previous.end[0] - previous.start[0]; const dz = previous.end[2] - previous.start[2];
const length = Math.hypot(dx, dz);
const rdX = ramp.end[0] - ramp.start[0]; const rdZ = ramp.end[2] - ramp.start[2];
const rLength = Math.hypot(rdX, rdZ);
if ((dx * rdX + dz * rdZ) / length / rLength < 0.999) continue;
const along = (p: readonly number[]) => ((p[0] - previous.start[0]) * dx + (p[2] - previous.start[2]) * dz) / length;
const across = (p: readonly number[]) => (-(p[0] - previous.start[0]) * dz + (p[2] - previous.start[2]) * dx) / length;
const start = along(ramp.start); const end = along(ramp.end);
const acrossOffset = (across(ramp.start) + across(ramp.end)) / 2;
const left = Math.max(-previous.width / 2, acrossOffset - ramp.width / 2);
const right = Math.min(previous.width / 2, acrossOffset + ramp.width / 2);
if (right - left < 1 || start > length + 1.5 || end < -1.5) continue;
const slope = (previous.end[1] - previous.start[1]) / length;
const rSlope = (ramp.end[1] - ramp.start[1]) / rLength;
if (Math.abs(slope - rSlope) > 0.12
|| Math.abs(ramp.start[1] - (previous.start[1] + start * slope)) > 0.32
|| Math.abs(ramp.end[1] - (previous.start[1] + end * slope)) > 0.32) continue;
const low = Math.min(0, start); const high = Math.max(length, end);
const center = (left + right) / 2;
const point = (t: number, y: number): [number, number, number] => [
previous.start[0] + dx / length * t - dz / length * center, y,
previous.start[2] + dz / length * t + dx / length * center,
];
result[index] = {
id: previous.id,
start: point(low, start < 0 ? ramp.start[1] : previous.start[1]),
end: point(high, end > length ? ramp.end[1] : previous.end[1]),
width: right - left,
};
combined = true;
break;
}
if (!combined) result.push(ramp);
}
return result.map((ramp, index) => ({ ...ramp, id: `stair-flight-${index + 1}` }));
}
/** Fill only separate Recast boundary portals wholly inside a verified stair footprint. */
export function dungeonStairNavigationBridges(geometry: BufferGeometry, ramps: DungeonTraversalRamp[]): DungeonTraversalRamp[] {
const p = geometry.getAttribute("position");
const indices = geometry.index?.array ?? Array.from({ length: p.count }, (_, i) => i);
const parents = Array.from({ length: p.count }, (_, i) => i);
const root = (i: number): number => {
while (parents[i] !== i) { parents[i] = parents[parents[i]]; i = parents[i]; }
return i;
};
const weld = new Map<string, number>();
const point = (i: number): [number, number, number] => [p.getX(i), p.getY(i), p.getZ(i)];
for (let i = 0; i < p.count; i += 1) {
const key = point(i).map((v) => Math.round(v / 0.002)).join(":");
const previous = weld.get(key);
if (previous !== undefined) parents[i] = previous;
else weld.set(key, i);
}
const edges = new Map<string, { a: number; b: number; count: number }>();
for (let offset = 0; offset + 2 < indices.length; offset += 3) {
const triangle = [indices[offset], indices[offset + 1], indices[offset + 2]];
for (let side = 0; side < 3; side += 1) {
const a = triangle[side]; const b = triangle[(side + 1) % 3];
const wa = weld.get(point(a).map((v) => Math.round(v / 0.002)).join(":"))!;
const wb = weld.get(point(b).map((v) => Math.round(v / 0.002)).join(":"))!;
parents[root(a)] = root(b);
const key = wa < wb ? `${wa}:${wb}` : `${wb}:${wa}`;
const edge = edges.get(key);
if (edge) edge.count += 1;
else edges.set(key, { a, b, count: 1 });
}
}
const boundary = [...edges.values()].filter((e) => e.count === 1);
return ramps.map((ramp) => {
const dx = ramp.end[0] - ramp.start[0]; const dz = ramp.end[2] - ramp.start[2];
const length = Math.hypot(dx, dz);
const along = (v: number[]) => ((v[0] - ramp.start[0]) * dx + (v[2] - ramp.start[2]) * dz) / length;
const across = (v: number[]) => (-(v[0] - ramp.start[0]) * dz + (v[2] - ramp.start[2]) * dx) / length;
const portals = boundary.flatMap((e) => {
const points = [point(e.a), point(e.b)].sort((a, b) => across(a) - across(b));
if (points.some((v) => {
const y = dungeonRampHeight(ramp, v[0], v[2]);
return y === null || Math.abs(v[1] - y) > 0.8;
})) return [];
if (Math.abs(along(points[0]) - along(points[1])) > 0.15 || across(points[1]) - across(points[0]) < 0.7) return [];
return [{ ...e, points: points as [[number, number, number], [number, number, number]], along: (along(points[0]) + along(points[1])) / 2 }];
}).sort((a, b) => a.along - b.along);
const bridges = [];
for (let index = 1; index < portals.length; index += 1) {
const a = portals[index - 1]; const b = portals[index];
const gap = b.along - a.along;
if (gap < 0.15 || gap > 2.5 || root(a.a) === root(b.a)) continue;
const overlap = Math.min(across(a.points[1]), across(b.points[1])) - Math.max(across(a.points[0]), across(b.points[0]));
if (overlap < 0.7) continue;
bridges.push({ linkId: `${ramp.id}-seam-${bridges.length + 1}`, startPortal: a.points, endPortal: b.points });
parents[root(a.a)] = root(b.a);
}
return bridges.length ? { ...ramp, navigationBridges: bridges } : ramp;
});
}
+2
View File
@@ -11,6 +11,7 @@ import {
import { arenaRatingBand, calculateArenaRating, clampArenaRating } from "./arena-rules.mjs"; import { arenaRatingBand, calculateArenaRating, clampArenaRating } from "./arena-rules.mjs";
import { arenaRoleForSpecialization } from "./arena-specializations.mjs"; import { arenaRoleForSpecialization } from "./arena-specializations.mjs";
import { createDungeonReportRepository } from "./dungeon-reports.mjs"; import { createDungeonReportRepository } from "./dungeon-reports.mjs";
import { createDungeonLeaderboardRepository } from "./dungeon-leaderboards.mjs";
const scrypt = promisify(scryptCallback); const scrypt = promisify(scryptCallback);
@@ -897,6 +898,7 @@ export function openGameDatabase(options = {}) {
return { return {
databasePath, databasePath,
...createDungeonReportRepository(database, { isGameMaster, ErrorType: GameDatabaseError }), ...createDungeonReportRepository(database, { isGameMaster, ErrorType: GameDatabaseError }),
...createDungeonLeaderboardRepository(database, { ErrorType: GameDatabaseError }),
register, register,
login, login,
authenticate, authenticate,
+112
View File
@@ -0,0 +1,112 @@
import catalog from "../src/game/generated/dungeonLeaderboardCatalog.generated.json" with { type: "json" };
const dungeons = new Map(catalog.dungeons.map((entry) => [entry.id, entry]));
const classes = new Set(catalog.classes.map((entry) => entry.id));
export function createDungeonLeaderboardRepository(database, { ErrorType }) {
database.exec(`
CREATE TABLE IF NOT EXISTS dungeon_runs (
id TEXT PRIMARY KEY,
dungeon_id TEXT NOT NULL,
difficulty_id TEXT NOT NULL,
duration_ms INTEGER NOT NULL CHECK (duration_ms > 0),
full_clear INTEGER NOT NULL CHECK (full_clear IN (0, 1)),
finished_at INTEGER NOT NULL,
party_json TEXT NOT NULL,
bosses_json TEXT NOT NULL,
submitted_by_account_id TEXT REFERENCES accounts(id) ON DELETE SET NULL,
received_at INTEGER NOT NULL
) STRICT;
CREATE INDEX IF NOT EXISTS dungeon_runs_times_idx
ON dungeon_runs(dungeon_id, difficulty_id, duration_ms, finished_at, id);
CREATE INDEX IF NOT EXISTS dungeon_runs_full_times_idx
ON dungeon_runs(dungeon_id, difficulty_id, full_clear, duration_ms);
`);
const byId = database.prepare("SELECT * FROM dungeon_runs WHERE id = ?");
const insert = database.prepare(`INSERT INTO dungeon_runs
(id, dungeon_id, difficulty_id, duration_ms, full_clear, finished_at, party_json, bosses_json, submitted_by_account_id, received_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
const fail = (message) => { throw new ErrorType(message, 400, "invalid_dungeon_run"); };
const record = (row) => ({ id: row.id, dungeonId: row.dungeon_id, difficultyId: row.difficulty_id,
durationMs: Number(row.duration_ms), finishedAt: Number(row.finished_at), fullClear: row.full_clear === 1,
party: JSON.parse(row.party_json), killedBossIds: JSON.parse(row.bosses_json) });
function selection(input) {
const dungeon = dungeons.get(input.dungeonId);
if (!dungeon) fail("Choose a known dungeon.");
const difficultyId = input.difficultyId || dungeon.defaultDifficultyId;
if (!dungeon.difficulties.some((entry) => entry.id === difficultyId)) fail("Choose a supported dungeon difficulty.");
const difficulty = dungeon.difficulties.find((entry) => entry.id === difficultyId);
return { dungeon, difficultyId, difficulty };
}
function placement(run) {
const counts = database.prepare(`SELECT COUNT(*) AS total,
COALESCE(SUM(CASE WHEN duration_ms < ? THEN 1 ELSE 0 END), 0) AS faster,
COALESCE(SUM(full_clear), 0) AS full_total,
COALESCE(SUM(CASE WHEN full_clear = 1 AND duration_ms < ? THEN 1 ELSE 0 END), 0) AS full_faster
FROM dungeon_runs WHERE dungeon_id = ? AND difficulty_id = ?`)
.get(run.durationMs, run.durationMs, run.dungeonId, run.difficultyId);
return { finalRank: Number(counts.faster) + 1, finalTotal: Number(counts.total),
fullRank: run.fullClear ? Number(counts.full_faster) + 1 : null, fullTotal: Number(counts.full_total) };
}
return {
submitDungeonRun(account, input) {
if (!input || typeof input !== "object" || Array.isArray(input)) fail("Provide a completed dungeon run.");
const { dungeon, difficultyId, difficulty } = selection(input);
if (!difficulty.finalBossId) fail("This dungeon does not have a configured final boss yet.");
if (typeof input.id !== "string" || !/^[A-Za-z0-9_-]{8,100}$/.test(input.id)) fail("Provide a valid run id.");
if (!Number.isSafeInteger(input.durationMs) || input.durationMs < 1 || input.durationMs > 7 * 24 * 60 * 60 * 1000)
fail("Provide a valid completion time.");
if (!Number.isSafeInteger(input.finishedAt) || input.finishedAt < 0 || input.finishedAt > Date.now() + 60_000)
fail("Provide a valid finish timestamp.");
if (!Array.isArray(input.killedBossIds) || input.killedBossIds.length > 100
|| input.killedBossIds.some((id) => !difficulty.bossIds.includes(id))) fail("Provide bosses from this dungeon and difficulty.");
const killedBossIds = [...new Set(input.killedBossIds)].sort();
if (!killedBossIds.includes(difficulty.finalBossId)) fail("The final boss must be defeated before recording a run.");
if (!Array.isArray(input.party) || input.party.length < 1 || input.party.length > 5) fail("Provide the run's party.");
const party = input.party.map((member) => {
if (!member || typeof member !== "object" || typeof member.name !== "string" || !member.name.trim()
|| member.name.length > 40 || !classes.has(member.classId)
|| !Number.isInteger(member.level) || member.level < 1 || member.level > 80
|| !["tank", "healer", "damage"].includes(member.role) || typeof member.npc !== "boolean"
|| (member.secondaryClassId !== undefined && !classes.has(member.secondaryClassId))) fail("Provide valid party classes and levels.");
return { name: member.name.trim(), classId: member.classId, level: member.level,
role: member.role, npc: member.npc,
...(member.secondaryClassId ? { secondaryClassId: member.secondaryClassId } : {}) };
});
const fullClear = difficulty.bossIds.every((id) => killedBossIds.includes(id));
const run = { id: input.id, dungeonId: dungeon.id, difficultyId, durationMs: input.durationMs,
finishedAt: input.finishedAt, killedBossIds, party, fullClear };
const existing = byId.get(run.id);
if (existing) {
if (JSON.stringify(record(existing)) !== JSON.stringify({ id: run.id, dungeonId: run.dungeonId,
difficultyId: run.difficultyId, durationMs: run.durationMs, finishedAt: run.finishedAt,
fullClear: run.fullClear, party: run.party, killedBossIds: run.killedBossIds }))
throw new ErrorType("That run id already belongs to a different result.", 409, "run_conflict");
} else insert.run(run.id, run.dungeonId, run.difficultyId, run.durationMs, fullClear ? 1 : 0,
run.finishedAt, JSON.stringify(party), JSON.stringify(killedBossIds), account?.id ?? null, Date.now());
return { run, placement: placement(run) };
},
getDungeonRun(id) {
const row = byId.get(id);
if (!row) throw new ErrorType("That dungeon run is not recorded yet.", 404, "run_not_found");
const run = record(row);
return { run, placement: placement(run) };
},
listDungeonLeaderboard(input) {
const { dungeon, difficultyId } = selection(input);
const filter = input.clear || "final";
if (!["full", "final"].includes(filter)) fail("Choose full dungeon clears or final boss clears.");
const offset = Number(input.offset ?? 0);
const limit = Number(input.limit ?? 20);
if (!Number.isSafeInteger(offset) || offset < 0 || offset > 1_000_000
|| !Number.isSafeInteger(limit) || limit < 1 || limit > 100) fail("Choose a valid leaderboard page.");
const condition = filter === "full" ? "AND full_clear = 1" : "";
const rows = database.prepare(`SELECT *, RANK() OVER (ORDER BY duration_ms) AS place FROM dungeon_runs
WHERE dungeon_id = ? AND difficulty_id = ? ${condition}
ORDER BY duration_ms, finished_at, id LIMIT ? OFFSET ?`).all(dungeon.id, difficultyId, limit, offset);
const total = database.prepare(`SELECT COUNT(*) AS total FROM dungeon_runs
WHERE dungeon_id = ? AND difficulty_id = ? ${condition}`).get(dungeon.id, difficultyId).total;
return { entries: rows.map((row) => ({ ...record(row), rank: Number(row.place) })), total: Number(total) };
},
};
}
+89
View File
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { openGameDatabase } from "./database.mjs";
import { createGameServer } from "./server.mjs";
import catalog from "../src/game/generated/dungeonLeaderboardCatalog.generated.json" with { type: "json" };
function run(id, durationMs, fullClear = true, dungeonId = "deadmines", difficultyId) {
const dungeon = catalog.dungeons.find((entry) => entry.id === dungeonId);
return { id, dungeonId, difficultyId: difficultyId ?? dungeon.defaultDifficultyId, durationMs,
finishedAt: 1700000000000, killedBossIds: fullClear ? dungeon.bosses.map((boss) => boss.id) : [dungeon.finalBossId],
party: [{ name: "Tester", classId: "priest", level: 20, role: "healer", npc: false },
{ name: "Garrick", classId: "warrior", level: 20, role: "tank", npc: true }] };
}
async function withDatabase(callback) {
const directory = mkdtempSync(path.join(os.tmpdir(), "healer-man-leaderboard-test-"));
let database = openGameDatabase({ dataDir: directory });
try { await callback(database, () => { database.close(); database = openGameDatabase({ dataDir: directory }); return database; }); }
finally { database.close(); rmSync(directory, { recursive: true, force: true }); }
}
test("persists ranked party/boss records, derives all-boss eligibility, handles ties, and retries without duplicates", () => withDatabase((database, reopen) => {
database.submitDungeonRun(null, run("run-fastest", 1000, false));
database.submitDungeonRun(null, run("run-full-one", 2000));
database.submitDungeonRun(null, run("run-full-tie", 2000));
const last = run("run-slowest", 3000);
const result = database.submitDungeonRun(null, last);
assert.deepEqual(result.placement, { finalRank: 4, finalTotal: 4, fullRank: 3, fullTotal: 3 });
assert.deepEqual(database.submitDungeonRun(null, last), result);
assert.throws(() => database.submitDungeonRun(null, { ...last, durationMs: 5 }), { status: 409 });
const final = database.listDungeonLeaderboard({ dungeonId: "deadmines", clear: "final" });
assert.deepEqual(final.entries.map((entry) => entry.rank), [1, 2, 2, 4]);
const full = database.listDungeonLeaderboard({ dungeonId: "deadmines", clear: "full" });
assert.deepEqual(full.entries.map((entry) => entry.rank), [1, 1, 3]);
assert.deepEqual(full.entries[0].party, last.party);
assert.equal(full.entries[0].killedBossIds.length, last.killedBossIds.length);
const page = database.listDungeonLeaderboard({ dungeonId: "deadmines", clear: "final", limit: 2, offset: 2 });
assert.equal(page.total, 4); assert.deepEqual(page.entries.map((entry) => entry.rank), [2, 4]);
database = reopen();
assert.deepEqual(database.getDungeonRun(last.id), result);
}));
test("validates final boss, dungeon/difficulty, duration and party without trusting client full-clear flags", () => withDatabase((database) => {
const valid = run("valid-run-id", 1000, false);
for (const invalid of [{ ...valid, durationMs: 0 }, { ...valid, durationMs: Infinity },
{ ...valid, killedBossIds: [] }, { ...valid, killedBossIds: ["fake-boss"] },
{ ...valid, dungeonId: "unknown" }, { ...valid, difficultyId: "fake" },
{ ...valid, party: [] }, { ...valid, party: [{ ...valid.party[0], classId: "fake" }] },
{ ...valid, party: [{ ...valid.party[0], level: 81 }] }])
assert.throws(() => database.submitDungeonRun(null, invalid), { code: "invalid_dungeon_run" });
assert.equal(database.submitDungeonRun(null, { ...valid, fullClear: true }).run.fullClear, false);
const caves = run("barren-caves-test", 2000, true, "barren-caves");
caves.party[0].classId = "rom-priest";
assert.equal(database.submitDungeonRun(null, caves).placement.fullRank, 1);
assert.equal(database.listDungeonLeaderboard({ dungeonId: "deadmines" }).total, 1);
assert.throws(() => database.listDungeonLeaderboard({ dungeonId: "deadmines", clear: "bad" }), { status: 400 });
assert.throws(() => database.listDungeonLeaderboard({ dungeonId: "deadmines", offset: -1 }), { status: 400 });
}));
test("public HTTP leaderboards accept completion records and return results with rank while rejecting unfinished runs", async () => {
const directory = mkdtempSync(path.join(os.tmpdir(), "healer-man-leaderboard-http-"));
const { server } = createGameServer({ dataDir: directory, enableShelvedModes: false });
try {
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const payload = run("http-caves-clear", 15555, true, "barren-caves");
const response = await fetch(`${base}/api/dungeon-runs`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
assert.equal(response.status, 201);
const result = await response.json(); assert.equal(result.placement.finalRank, 1);
const leaderboard = await fetch(`${base}/api/dungeon-leaderboards?dungeon=barren-caves&clear=full`);
assert.equal(leaderboard.status, 200); assert.equal((await leaderboard.json()).entries[0].durationMs, 15555);
assert.deepEqual(await (await fetch(`${base}/api/dungeon-runs/${payload.id}`)).json(), result);
const bad = await fetch(`${base}/api/dungeon-runs`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...payload, id: "unfinished-run", killedBossIds: [] }) });
assert.equal(bad.status, 400);
const unauthorized = await fetch(`${base}/api/dungeon-runs`, { method: "POST", headers: { Authorization: "Bearer invalid", "Content-Type": "application/json" }, body: JSON.stringify(payload) });
assert.equal(unauthorized.status, 401);
} finally { await new Promise((resolve) => server.close(resolve)); rmSync(directory, { recursive: true, force: true }); }
});
test("separates normal and heroic times and counts only bosses that exist on each difficulty", () => withDatabase((database) => {
const dungeon = catalog.dungeons.find((entry) => entry.difficulties.length > 1 && entry.difficulties.every((difficulty) => difficulty.finalBossId));
for (const difficulty of dungeon.difficulties) {
const payload = run(`difficulty-${difficulty.id}-test`, 1000, true, dungeon.id, difficulty.id);
payload.killedBossIds = difficulty.bossIds;
const result = database.submitDungeonRun(null, payload);
assert.equal(result.run.fullClear, true);
assert.equal(result.placement.finalRank, 1); assert.equal(result.placement.finalTotal, 1);
assert.equal(database.listDungeonLeaderboard({ dungeonId: dungeon.id, difficultyId: difficulty.id, clear: "full" }).total, 1);
}
}));
+20
View File
@@ -182,6 +182,7 @@ export function createGameServer(options = {}) {
const arenaService = createArenaService({ database: gameDatabase, autoPump: enableShelvedModes }); const arenaService = createArenaService({ database: gameDatabase, autoPump: enableShelvedModes });
const allowAuthRequest = createAuthLimiter(); const allowAuthRequest = createAuthLimiter();
const allowReportRequest = createAuthLimiter(); const allowReportRequest = createAuthLimiter();
const allowDungeonRunRequest = createAuthLimiter();
gameDatabase.pruneExpiredSessions(); gameDatabase.pruneExpiredSessions();
const server = createServer(async (request, response) => { const server = createServer(async (request, response) => {
@@ -240,6 +241,25 @@ export function createGameServer(options = {}) {
json(response, 200, { account: gameDatabase.authenticate(bearerToken(request)) }); json(response, 200, { account: gameDatabase.authenticate(bearerToken(request)) });
return; return;
} }
if (url.pathname === "/api/dungeon-leaderboards" && request.method === "GET") {
json(response, 200, gameDatabase.listDungeonLeaderboard({ dungeonId: url.searchParams.get("dungeon"),
difficultyId: url.searchParams.get("difficulty"), clear: url.searchParams.get("clear"),
offset: url.searchParams.get("offset"), limit: url.searchParams.get("limit") }));
return;
}
if (url.pathname === "/api/dungeon-runs" && request.method === "POST") {
const token = bearerToken(request);
const account = token ? gameDatabase.authenticate(token) : null;
if (!allowDungeonRunRequest(account?.id ?? request.socket.remoteAddress))
throw new GameDatabaseError("Too many run submissions. Please try again shortly.", 429, "rate_limited");
json(response, 201, gameDatabase.submitDungeonRun(account, await readJson(request, 32 * 1024)));
return;
}
const dungeonRunMatch = /^\/api\/dungeon-runs\/([A-Za-z0-9_-]{8,100})$/.exec(url.pathname);
if (dungeonRunMatch && request.method === "GET") {
json(response, 200, gameDatabase.getDungeonRun(dungeonRunMatch[1]));
return;
}
if (url.pathname === "/api/dungeon-reports" && request.method === "GET") { if (url.pathname === "/api/dungeon-reports" && request.method === "GET") {
json(response, 200, gameDatabase.listDungeonReports({ json(response, 200, gameDatabase.listDungeonReports({
status: url.searchParams.get("status"), status: url.searchParams.get("status"),
+5 -1
View File
@@ -20,6 +20,8 @@ import { PauseMenu } from "./ui/PauseMenu";
import { SceneErrorBoundary } from "./ui/SceneErrorBoundary"; import { SceneErrorBoundary } from "./ui/SceneErrorBoundary";
import { OnlineSessionBridge } from "./game/OnlineSessionBridge"; import { OnlineSessionBridge } from "./game/OnlineSessionBridge";
import { DungeonRunCheckpointBridge } from "./game/DungeonRunCheckpointBridge"; import { DungeonRunCheckpointBridge } from "./game/DungeonRunCheckpointBridge";
import { DungeonRunBridge } from "./game/DungeonRunBridge";
import { DungeonRunResults } from "./ui/DungeonRunResults";
import { DungeonEncounterEffectBridge } from "./game/DungeonEncounterEffectBridge"; import { DungeonEncounterEffectBridge } from "./game/DungeonEncounterEffectBridge";
import { interactWithActiveDungeonObject } from "./game/dungeonWorldInteraction"; import { interactWithActiveDungeonObject } from "./game/dungeonWorldInteraction";
import { DungeonInteractionPrompt } from "./ui/DungeonInteractionPrompt"; import { DungeonInteractionPrompt } from "./ui/DungeonInteractionPrompt";
@@ -37,7 +39,7 @@ function InputBridge() {
useEffect(() => installInput({ useEffect(() => installInput({
desktopActionBarsActive: () => currentUiDevice() === "pc" && activeUiLayout().wowBars, desktopActionBarsActive: () => currentUiDevice() === "pc" && activeUiLayout().wowBars,
inputSuspended: () => ["ui-layout", "keybinds"].includes(useGameStore.getState().overlay ?? ""), inputSuspended: () => ["ui-layout", "keybinds", "dungeon-results"].includes(useGameStore.getState().overlay ?? ""),
getBindings: (device) => { getBindings: (device) => {
const preferences = useUiLayoutStore.getState().preferences; const preferences = useUiLayoutStore.getState().preferences;
const bindings = profileInputBindings(preferences, device); const bindings = profileInputBindings(preferences, device);
@@ -115,6 +117,7 @@ export default function GameRuntime() {
<DungeonRunCheckpointBridge /> <DungeonRunCheckpointBridge />
<CombatBridge /> <CombatBridge />
<PartyBridge /> <PartyBridge />
<DungeonRunBridge />
<ShelvedGameBridges /> <ShelvedGameBridges />
<SceneErrorBoundary><GameScene /></SceneErrorBoundary> <SceneErrorBoundary><GameScene /></SceneErrorBoundary>
<Hud /> <Hud />
@@ -122,6 +125,7 @@ export default function GameRuntime() {
<MapPanel /> <MapPanel />
<GameplayPanels /> <GameplayPanels />
<PauseMenu /> <PauseMenu />
<DungeonRunResults />
<UiLayoutEditor /> <UiLayoutEditor />
<KeybindsPanel /> <KeybindsPanel />
</main> </main>
+44
View File
@@ -0,0 +1,44 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { localDungeonLeaderboard, localDungeonRunPlacement, saveLocalDungeonRun, submitDungeonRun } from "./dungeonLeaderboardClient";
import type { DungeonRunRecord } from "../game/dungeonRunTypes";
import catalog from "../game/generated/dungeonLeaderboardCatalog.generated.json";
const dungeon = catalog.dungeons.find((entry) => entry.id === "deadmines")!;
const record = (id: string, durationMs: number, fullClear = true): DungeonRunRecord => ({
id, dungeonId: dungeon.id, difficultyId: dungeon.defaultDifficultyId, durationMs, finishedAt: 100000,
party: [{ name: "Tester", classId: "priest", level: 20, role: "healer", npc: false }],
killedBossIds: fullClear ? dungeon.bosses.map((boss) => boss.id) : [dungeon.finalBossId], fullClear,
});
beforeEach(() => {
const values = new Map<string, string>();
vi.stubGlobal("localStorage", { getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value) });
});
afterEach(() => vi.unstubAllGlobals());
describe("offline dungeon leaderboard", () => {
it("persists full/final filters, ties, pages, and the placement of a run outside the first page", () => {
for (let index = 0; index < 25; index += 1) saveLocalDungeonRun(record(`offline-${index}`, 1000 + index * 100));
const fastest = record("offline-fastest", 500, false);
saveLocalDungeonRun(fastest); saveLocalDungeonRun(fastest);
saveLocalDungeonRun(record("offline-tie", 1000));
const all = localDungeonLeaderboard(dungeon.id, dungeon.defaultDifficultyId, "final");
expect(all.total).toBe(27); expect(all.entries[0].id).toBe(fastest.id);
expect(all.entries.slice(0, 3).map((entry) => entry.rank)).toEqual([1, 2, 2]);
expect(localDungeonLeaderboard(dungeon.id, dungeon.defaultDifficultyId, "full").total).toBe(26);
const page = localDungeonLeaderboard(dungeon.id, dungeon.defaultDifficultyId, "final", 20);
expect(page.entries).toHaveLength(7);
expect(localDungeonRunPlacement(record("offline-24", 3400))).toEqual({ finalRank: 27, finalTotal: 27, fullRank: 26, fullTotal: 26 });
});
it("retains the local time after a failed upload and uses the same run id when retried", async () => {
const run = record("offline-retry-test", 4321);
saveLocalDungeonRun(run);
const fetch = vi.fn().mockRejectedValueOnce(new Error("offline"))
.mockResolvedValueOnce(new Response(JSON.stringify({ placement: { finalRank: 2, finalTotal: 3, fullRank: 1, fullTotal: 2 } }), { status: 201 }));
vi.stubGlobal("fetch", fetch);
await expect(submitDungeonRun(run, null)).rejects.toThrow();
expect(localDungeonLeaderboard(dungeon.id, dungeon.defaultDifficultyId, "final").entries[0].durationMs).toBe(4321);
await expect(submitDungeonRun(run, null)).resolves.toMatchObject({ finalRank: 2 });
expect(fetch.mock.calls.map((call) => JSON.parse(call[1].body).id)).toEqual([run.id, run.id]);
});
});
+102
View File
@@ -0,0 +1,102 @@
import { requestOnlineJson } from "./onlineAccountClient";
import type { PlayerSession } from "./types";
import catalog from "../game/generated/dungeonLeaderboardCatalog.generated.json";
import { normalizeDungeonRunProgress, type DungeonClearFilter, type DungeonLeaderboard,
type DungeonRunPlacement, type DungeonRunRecord } from "../game/dungeonRunTypes";
const STORAGE_KEY = "healer-man:dungeon-runs:v1";
const listeners = new Set<() => void>();
let memory: DungeonRunRecord[] = [];
export const DUNGEON_LEADERBOARD_PAGE_SIZE = 20;
export type LeaderboardScope = "world" | "device";
export function subscribeDungeonLeaderboard(listener: () => void) {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
function localRuns(): DungeonRunRecord[] {
try {
const input: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]");
if (Array.isArray(input)) memory = input.flatMap((value: DungeonRunRecord) => {
if (!value || typeof value !== "object") return [];
const progress = normalizeDungeonRunProgress({ ...value, startedAt: value.finishedAt - value.durationMs, timed: true });
const dungeon = catalog.dungeons.find((entry) => entry.id === progress?.dungeonId);
const difficulty = dungeon?.difficulties.find((entry) => entry.id === progress?.difficultyId);
if (!progress || progress.finishedAt === null || progress.durationMs === null || !dungeon
|| !difficulty || !progress.killedBossIds.includes(difficulty.finalBossId)
|| progress.killedBossIds.some((id) => !difficulty.bossIds.includes(id))) return [];
return [{ ...value, ...progress, durationMs: progress.durationMs, finishedAt: progress.finishedAt,
fullClear: difficulty.bossIds.every((id) => progress.killedBossIds.includes(id)) }];
});
} catch { /* In-memory results remain available if storage is disabled. */ }
return memory;
}
export function saveLocalDungeonRun(record: DungeonRunRecord): void {
memory = [record, ...localRuns().filter((entry) => entry.id !== record.id)]
.sort((a, b) => b.finishedAt - a.finishedAt).slice(0, 1000);
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(memory)); } catch { /* Keep the current session's results. */ }
listeners.forEach((listener) => listener());
}
export function localDungeonLeaderboard(dungeonId: string, difficultyId: string,
filter: DungeonClearFilter, offset = 0): DungeonLeaderboard {
const runs = localRuns().filter((entry) => entry.dungeonId === dungeonId && entry.difficultyId === difficultyId
&& (filter === "final" || entry.fullClear)).sort((a, b) => a.durationMs - b.durationMs
|| a.finishedAt - b.finishedAt || a.id.localeCompare(b.id));
return { total: runs.length, entries: runs.slice(offset, offset + DUNGEON_LEADERBOARD_PAGE_SIZE)
.map((entry) => ({ ...entry, rank: 1 + runs.filter((other) => other.durationMs < entry.durationMs).length })) };
}
export function localDungeonRunPlacement(record: DungeonRunRecord): DungeonRunPlacement {
const final = localDungeonLeaderboard(record.dungeonId, record.difficultyId, "final");
const full = localDungeonLeaderboard(record.dungeonId, record.difficultyId, "full");
const runs = localRuns().filter((entry) => entry.dungeonId === record.dungeonId && entry.difficultyId === record.difficultyId);
return { finalRank: 1 + runs.filter((entry) => entry.durationMs < record.durationMs).length,
finalTotal: final.total, fullTotal: full.total,
fullRank: record.fullClear ? 1 + runs.filter((entry) => entry.fullClear && entry.durationMs < record.durationMs).length : null };
}
export async function fetchDungeonLeaderboard(dungeonId: string, difficultyId: string,
filter: DungeonClearFilter, offset: number, signal?: AbortSignal): Promise<DungeonLeaderboard> {
const query = new URLSearchParams({ dungeon: dungeonId, difficulty: difficultyId, clear: filter,
offset: String(offset), limit: String(DUNGEON_LEADERBOARD_PAGE_SIZE) });
return requestOnlineJson(`/api/dungeon-leaderboards?${query}`, { signal });
}
const submissions = new Map<string, Promise<DungeonRunPlacement>>();
export function submitDungeonRun(record: DungeonRunRecord, session: PlayerSession | null): Promise<DungeonRunPlacement> {
const existing = submissions.get(record.id);
if (existing) return existing;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);
const submission = requestOnlineJson<{ placement: DungeonRunPlacement }>("/api/dungeon-runs", {
method: "POST", body: JSON.stringify(record), signal: controller.signal,
}, session?.accessToken).then((result) => {
listeners.forEach((listener) => listener());
return result.placement;
}).catch((error: unknown) => { submissions.delete(record.id); throw error; })
.finally(() => clearTimeout(timeout));
submissions.set(record.id, submission);
return submission;
}
/** Group followers read the leader's single shared run instead of submitting duplicate entries. */
export async function awaitSharedDungeonRunPlacement(id: string): Promise<DungeonRunPlacement> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 8000);
try {
for (let attempt = 0; attempt < 8; attempt += 1) {
try {
const response = await requestOnlineJson<{ placement: DungeonRunPlacement }>(`/api/dungeon-runs/${encodeURIComponent(id)}`,
{ signal: controller.signal });
return response.placement;
} catch (error) {
if (attempt === 7 || controller.signal.aborted) throw error;
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
throw new Error("The shared run is not recorded yet.");
} finally { clearTimeout(timeout); }
}
+2
View File
@@ -61,6 +61,8 @@ function enterDungeon(dungeonId: string, requestedRole?: PartyRole): boolean {
if (!activateDungeonSession(dungeonId, resume?.difficultyId, { if (!activateDungeonSession(dungeonId, resume?.difficultyId, {
spawn: resume?.spawn, spawn: resume?.spawn,
encounterSnapshots: resume?.encounters, encounterSnapshots: resume?.encounters,
runProgress: resume?.run,
legacyResume: Boolean(resume && !resume.run),
})) { })) {
useShellStore.setState({ useShellStore.setState({
notice: dungeon.availabilityReason ?? "That dungeon failed its latest validation gate.", notice: dungeon.availabilityReason ?? "That dungeon failed its latest validation gate.",
+66
View File
@@ -0,0 +1,66 @@
import { useEffect } from "react";
import { useShellStore } from "../app/shellStore";
import { useOnlineSessionStore } from "../app/onlineSessionStore";
import { useOnlineGroupStore } from "../app/onlineGroupStore";
import { activeDungeonCompletedObjectiveIds, subscribeDungeonEncounterSnapshots } from "./dungeonEncounterRuntime";
import { useCombatStore } from "./combatStore";
import { usePartyStore } from "./partyStore";
import { useGameStore } from "./store";
import { useDungeonRunStore } from "./dungeonRunStore";
import type { DungeonRunMember } from "./dungeonRunTypes";
function currentRunParty(): readonly DungeonRunMember[] {
const shell = useShellStore.getState();
const character = shell.activeCharacter;
if (!character) return [];
const members: DungeonRunMember[] = [{ name: character.name, classId: character.classId,
level: useCombatStore.getState().level, role: shell.activeDungeonRole, npc: false,
...(character.secondaryClassId ? { secondaryClassId: character.secondaryClassId } : {}) }];
const online = useOnlineSessionStore.getState().snapshot;
for (const player of online?.players ?? []) {
if (player.accountId === shell.session?.ownerId || !player.character) continue;
members.push({ name: player.character.name, classId: player.character.classId,
level: player.character.level, role: player.role ?? "damage", npc: false });
}
for (const member of usePartyStore.getState().members) {
members.push({ name: member.name, classId: member.classId, level: member.level, role: member.role, npc: true });
}
return members.slice(0, 5);
}
/** Wall-clock run timing survives wipes, pauses, checkpoints, and renderer retries. */
export function DungeonRunBridge() {
useEffect(() => {
let announcedId: string | null = null;
const advance = () => {
const game = useGameStore.getState();
const shell = useShellStore.getState();
if (shell.phase !== "game" || game.gameMode !== "dungeon" || game.gmTestMode
|| !["ready", "proxy"].includes(game.assetStatus)) return;
const run = useDungeonRunStore.getState();
if (run.progress?.dungeonId !== game.activeDungeonId) return;
const party = currentRunParty();
const activity = useOnlineGroupStore.getState().activeActivity;
if (activity?.type === "dungeon" && activity.contentId === game.activeDungeonId
&& run.progress.finishedAt === null && run.progress.id !== activity.id) {
useDungeonRunStore.setState({ progress: { ...run.progress, id: activity.id,
startedAt: activity.startedAt, party } });
}
run.start(Date.now(), party);
run.advance(activeDungeonCompletedObjectiveIds(game.activeDungeonId),
Object.values(useCombatStore.getState().mobs).filter((mob) => mob.dead && !mob.despawned).map((mob) => mob.id),
Date.now(), party);
const progress = useDungeonRunStore.getState().progress;
if (progress?.finishedAt !== null && progress && announcedId !== progress.id) {
announcedId = progress.id;
useGameStore.getState().openOverlay("dungeon-results");
}
};
const unsubscribeEncounters = subscribeDungeonEncounterSnapshots(advance);
const unsubscribeGame = useGameStore.subscribe(advance);
const interval = setInterval(advance, 250);
advance();
return () => { unsubscribeEncounters(); unsubscribeGame(); clearInterval(interval); };
}, []);
return null;
}
+6 -1
View File
@@ -6,6 +6,7 @@ import {
} from "./dungeonEncounterRuntime"; } from "./dungeonEncounterRuntime";
import { DUNGEON_RUN_CHECKPOINT_VERSION } from "./dungeonRunCheckpoint"; import { DUNGEON_RUN_CHECKPOINT_VERSION } from "./dungeonRunCheckpoint";
import { useGameStore } from "./store"; import { useGameStore } from "./store";
import { useDungeonRunStore } from "./dungeonRunStore";
function checkpointSignature(dungeonId: string): string { function checkpointSignature(dungeonId: string): string {
const game = useGameStore.getState(); const game = useGameStore.getState();
@@ -15,6 +16,7 @@ function checkpointSignature(dungeonId: string): string {
difficultyId: game.activeDifficultyId, difficultyId: game.activeDifficultyId,
spawn: game.activeSpawn, spawn: game.activeSpawn,
encounters, encounters,
run: useDungeonRunStore.getState().progress,
}); });
} }
@@ -41,10 +43,13 @@ export function DungeonRunCheckpointBridge() {
spawn: game.activeSpawn, spawn: game.activeSpawn,
encounters, encounters,
savedAt: Date.now(), savedAt: Date.now(),
run: useDungeonRunStore.getState().progress ?? undefined,
}); });
}; };
save(); save();
return subscribeDungeonEncounterSnapshots(save); const unsubscribeEncounters = subscribeDungeonEncounterSnapshots(save);
const unsubscribeRun = useDungeonRunStore.subscribe(save);
return () => { unsubscribeEncounters(); unsubscribeRun(); };
}, [activeCharacterId, phase]); }, [activeCharacterId, phase]);
return null; return null;
+5 -3
View File
@@ -3589,11 +3589,11 @@ export const useCombatStore = create<CombatState>((set, get) => ({
0, 0,
registration.moveSpeed ?? existing?.moveSpeed ?? (boss ? 3.15 : 3.5), registration.moveSpeed ?? existing?.moveSpeed ?? (boss ? 3.15 : 3.5),
); );
const attackDamage = existing && registration.damageMultiplier !== undefined const attackDamage = existing && level === existing.level && registration.damageMultiplier !== undefined
? Math.max(1, Math.round( ? Math.max(1, Math.round(
existing.attackDamage * (damageMultiplier / Math.max(0.01, existing.damageMultiplier)), existing.attackDamage * (damageMultiplier / Math.max(0.01, existing.damageMultiplier)),
)) ))
: existing?.attackDamage ?? Math.max(1, Math.round( : (existing && level === existing.level ? existing.attackDamage : undefined) ?? Math.max(1, Math.round(
defaults.attackDamage * damageMultiplier, defaults.attackDamage * damageMultiplier,
)); ));
const mob: MobCombatState = existing const mob: MobCombatState = existing
@@ -3621,7 +3621,9 @@ export const useCombatStore = create<CombatState>((set, get) => ({
leashRange, leashRange,
moveSpeed, moveSpeed,
attackDamage, attackDamage,
health: Math.min(existing.health, maxHealth), health: existing.dead || existing.health <= 0
? 0
: clamp(Math.round(existing.health / Math.max(1, existing.maxHealth) * maxHealth), 1, maxHealth),
xpReward, xpReward,
hasLoot, hasLoot,
} }
@@ -0,0 +1,26 @@
import { readFileSync, writeFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CLASSES } from "../app/characterCatalog";
import { DUNGEON_DEFINITIONS } from "./dungeonRegistry";
import { dungeonBossesForDifficulty, finalDungeonBoss } from "./dungeonRunStore";
describe("dungeon leaderboard catalog", () => {
it("keeps the server's final bosses, boss lists, difficulties, and classes aligned with the game", () => {
const catalog = {
dungeons: DUNGEON_DEFINITIONS.map((dungeon) => ({ id: dungeon.id, title: dungeon.title,
finalBossId: finalDungeonBoss(dungeon)?.id ?? "",
bosses: dungeon.bosses.map((boss) => ({ id: boss.id, name: boss.name })),
difficulties: dungeon.difficultyVariants.map((difficulty) => ({ id: difficulty.id, name: difficulty.difficulty,
bossIds: dungeonBossesForDifficulty(dungeon, difficulty.id).map((boss) => boss.id),
finalBossId: finalDungeonBoss(dungeon, difficulty.id)?.id ?? "" })),
defaultDifficultyId: dungeon.defaultDifficultyId,
})).sort((a, b) => a.id.localeCompare(b.id)),
classes: CLASSES.map((entry) => ({ id: entry.id, name: entry.name })),
};
expect(catalog.dungeons).toHaveLength(84);
expect(catalog.dungeons.filter((dungeon) => dungeon.bosses.length > 0 && !dungeon.finalBossId)).toEqual([]);
const path = "src/game/generated/dungeonLeaderboardCatalog.generated.json";
if (process.env.WRITE_DUNGEON_LEADERBOARD_CATALOG === "1") writeFileSync(path, `${JSON.stringify(catalog, null, 2)}\n`);
expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(catalog);
});
});
+16 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { scaledDungeonEnemyLevel } from "./dungeonLevelScaling"; import { dungeonEnemyHealthBaseline, scaledDungeonEnemyLevel } from "./dungeonLevelScaling";
describe("normal dungeon level scaling", () => { describe("normal dungeon level scaling", () => {
it("scales opening-tier trash to the character and gives bosses a one-level edge", () => { it("scales opening-tier trash to the character and gives bosses a one-level edge", () => {
@@ -13,4 +13,19 @@ describe("normal dungeon level scaling", () => {
expect(scaledDungeonEnemyLevel(80, false)).toBe(80); expect(scaledDungeonEnemyLevel(80, false)).toBe(80);
expect(scaledDungeonEnemyLevel(80, true)).toBe(80); expect(scaledDungeonEnemyLevel(80, true)).toBe(80);
}); });
it("grows RoM health with ability ranks and clamps invalid levels", () => {
expect(dungeonEnemyHealthBaseline(1, "runewaker")).toBeGreaterThan(1_000);
expect(dungeonEnemyHealthBaseline(20, "runewaker")).toBeGreaterThan(dungeonEnemyHealthBaseline(8, "runewaker")!);
expect(dungeonEnemyHealthBaseline(70, "runewaker")).toBeGreaterThan(dungeonEnemyHealthBaseline(20, "runewaker")! * 5);
expect(dungeonEnemyHealthBaseline(0, "runewaker")).toBe(dungeonEnemyHealthBaseline(1, "runewaker"));
expect(dungeonEnemyHealthBaseline(100, "runewaker")).toBe(dungeonEnemyHealthBaseline(80, "runewaker"));
expect(dungeonEnemyHealthBaseline(Number.NaN, "runewaker")).toBe(dungeonEnemyHealthBaseline(1, "runewaker"));
});
it("retains native WoW creature health across its three expansions", () => {
for (const expansion of ["classic", "burning-crusade", "wrath"] as const) {
expect(dungeonEnemyHealthBaseline(20, expansion)).toBeUndefined();
}
});
}); });
+13
View File
@@ -1,4 +1,5 @@
import { clampPlayerLevel } from "./progression"; import { clampPlayerLevel } from "./progression";
import type { DungeonExpansion } from "./dungeonTypes";
/** /**
* Normal campaign dungeons scale to the character instead of retaining the * Normal campaign dungeons scale to the character instead of retaining the
@@ -8,3 +9,15 @@ import { clampPlayerLevel } from "./progression";
export function scaledDungeonEnemyLevel(characterLevel: number, boss: boolean): number { export function scaledDungeonEnemyLevel(characterLevel: number, boss: boolean): number {
return clampPlayerLevel(characterLevel + (boss ? 1 : 0)); return clampPlayerLevel(characterLevel + (boss ? 1 : 0));
} }
/**
* RoM creatures do not have packaged native health tables. Give their dungeon
* baseline enough growth for a full party's rank-scaled abilities; the old
* 72 + level * 22 solo-target fallback was overwhelmed by the opening volley.
* Authored creature and boss health multipliers are applied separately.
*/
export function dungeonEnemyHealthBaseline(level: number, expansion: DungeonExpansion): number | undefined {
if (expansion !== "runewaker") return undefined;
const safeLevel = clampPlayerLevel(level);
return 1_000 + safeLevel * 100 + safeLevel * safeLevel * 8;
}
+4
View File
@@ -7,6 +7,7 @@ import compressedCampaign from "./generated/dungeonCampaignCatalog.compressed";
import { gunzipSync, strFromU8 } from "fflate"; import { gunzipSync, strFromU8 } from "fflate";
import { DEFAULT_DUNGEON_ID as DEFAULT_DUNGEON_KEY } from "./dungeonDefaults"; import { DEFAULT_DUNGEON_ID as DEFAULT_DUNGEON_KEY } from "./dungeonDefaults";
import { withRunewakerEncounterContent } from "./runewakerEncounterCatalog"; import { withRunewakerEncounterContent } from "./runewakerEncounterCatalog";
import { withRunewakerCompletion } from "./runewakerCompletion";
import { withWowEncounterContent } from "./wowEncounterContentCatalog"; import { withWowEncounterContent } from "./wowEncounterContentCatalog";
import { withWowProgressionObjectContent } from "./wowProgressionObjectContentCatalog"; import { withWowProgressionObjectContent } from "./wowProgressionObjectContentCatalog";
import { withAscensionCustomEncounterContent } from "./ascensionCustomEncounterCatalog"; import { withAscensionCustomEncounterContent } from "./ascensionCustomEncounterCatalog";
@@ -19,6 +20,7 @@ import { withWowVerifiedNoOpInstanceContent } from "./wowVerifiedNoOpInstanceCat
import { withWowClassicEncounterBatchTwo } from "./wowClassicEncounterBatchTwoCatalog"; import { withWowClassicEncounterBatchTwo } from "./wowClassicEncounterBatchTwoCatalog";
import { withWowClassicEncounterBatchThree } from "./wowClassicEncounterBatchThreeCatalog"; import { withWowClassicEncounterBatchThree } from "./wowClassicEncounterBatchThreeCatalog";
import { withWowTbcEncounterBatchTwoContent } from "./wowTbcEncounterBatchTwoCatalog"; import { withWowTbcEncounterBatchTwoContent } from "./wowTbcEncounterBatchTwoCatalog";
import { withWowDungeonEnvironment } from "./wowDungeonEnvironment";
export { DEFAULT_DUNGEON_ID } from "./dungeonDefaults"; export { DEFAULT_DUNGEON_ID } from "./dungeonDefaults";
@@ -151,6 +153,7 @@ if (authoredWailingCaverns.id !== DEFAULT_DUNGEON_KEY) {
const DUNGEON_CONTENT_ADAPTERS: readonly ( const DUNGEON_CONTENT_ADAPTERS: readonly (
(definition: DungeonDefinition) => DungeonDefinition (definition: DungeonDefinition) => DungeonDefinition
)[] = Object.freeze([ )[] = Object.freeze([
withWowDungeonEnvironment,
withWowEncounterContent, withWowEncounterContent,
withWowClassicEncounterContent, withWowClassicEncounterContent,
withWowClassicEncounterBatchTwo, withWowClassicEncounterBatchTwo,
@@ -164,6 +167,7 @@ const DUNGEON_CONTENT_ADAPTERS: readonly (
withWowTbcEncounterBatchTwoContent, withWowTbcEncounterBatchTwoContent,
withAscensionCustomEncounterContent, withAscensionCustomEncounterContent,
withRunewakerEncounterContent, withRunewakerEncounterContent,
withRunewakerCompletion,
]); ]);
function applyDungeonContentAdapters(definition: DungeonDefinition): DungeonDefinition { function applyDungeonContentAdapters(definition: DungeonDefinition): DungeonDefinition {
+8
View File
@@ -14,6 +14,14 @@ const definition: DungeonEncounterDefinition = {
}; };
describe("dungeon run checkpoints", () => { describe("dungeon run checkpoints", () => {
it("round-trips a saved timer and rejects a timer belonging to another dungeon", () => {
const input = { version: DUNGEON_RUN_CHECKPOINT_VERSION, dungeonId: "test", difficultyId: "normal",
checkpointId: "entrance", spawn: { footPosition: [1, 2, 3], yaw: 0.5 }, encounters: [], savedAt: 123,
run: { id: "checkpoint-timer", dungeonId: "test", difficultyId: "normal", startedAt: 100,
finishedAt: null, durationMs: null, timed: true, killedBossIds: [], party: [] } };
expect(normalizeDungeonRunCheckpoint(JSON.parse(JSON.stringify(input)))?.run).toEqual(input.run);
expect(normalizeDungeonRunCheckpoint({ ...input, run: { ...input.run, dungeonId: "other" } })).toBeNull();
});
it("normalizes JSON-safe encounter progress and world spawn", () => { it("normalizes JSON-safe encounter progress and world spawn", () => {
const result = normalizeDungeonRunCheckpoint({ const result = normalizeDungeonRunCheckpoint({
version: DUNGEON_RUN_CHECKPOINT_VERSION, version: DUNGEON_RUN_CHECKPOINT_VERSION,
+5
View File
@@ -1,6 +1,7 @@
import type { DungeonEncounterSnapshot } from "./dungeonEncounterTypes"; import type { DungeonEncounterSnapshot } from "./dungeonEncounterTypes";
import { DUNGEON_ENCOUNTER_SNAPSHOT_SCHEMA_VERSION } from "./dungeonEncounterTypes"; import { DUNGEON_ENCOUNTER_SNAPSHOT_SCHEMA_VERSION } from "./dungeonEncounterTypes";
import type { Vector3Tuple, WorldSpawn } from "./dungeonTypes"; import type { Vector3Tuple, WorldSpawn } from "./dungeonTypes";
import { normalizeDungeonRunProgress, type DungeonRunProgress } from "./dungeonRunTypes";
// Version 1 snapshots sorted consumed action ids and cannot be migrated // Version 1 snapshots sorted consumed action ids and cannot be migrated
// reliably when multiple durable actions write the same state slot. Failing // reliably when multiple durable actions write the same state slot. Failing
@@ -15,6 +16,7 @@ export interface DungeonRunCheckpoint {
readonly spawn: WorldSpawn; readonly spawn: WorldSpawn;
readonly encounters: readonly DungeonEncounterSnapshot[]; readonly encounters: readonly DungeonEncounterSnapshot[];
readonly savedAt: number; readonly savedAt: number;
readonly run?: DungeonRunProgress;
} }
function finiteVector(value: unknown): Vector3Tuple | null { function finiteVector(value: unknown): Vector3Tuple | null {
@@ -115,6 +117,8 @@ export function normalizeDungeonRunCheckpoint(value: unknown): DungeonRunCheckpo
) return null; ) return null;
const encounters = input.encounters.map(normalizeSnapshot); const encounters = input.encounters.map(normalizeSnapshot);
if (encounters.some((entry) => entry === null)) return null; if (encounters.some((entry) => entry === null)) return null;
const run = input.run === undefined ? undefined : normalizeDungeonRunProgress(input.run);
if (run === null || (run && (run.dungeonId !== input.dungeonId || run.difficultyId !== input.difficultyId))) return null;
return Object.freeze({ return Object.freeze({
version: DUNGEON_RUN_CHECKPOINT_VERSION, version: DUNGEON_RUN_CHECKPOINT_VERSION,
dungeonId: input.dungeonId, dungeonId: input.dungeonId,
@@ -123,5 +127,6 @@ export function normalizeDungeonRunCheckpoint(value: unknown): DungeonRunCheckpo
spawn: { footPosition: position, yaw }, spawn: { footPosition: position, yaw },
encounters: Object.freeze(encounters as DungeonEncounterSnapshot[]), encounters: Object.freeze(encounters as DungeonEncounterSnapshot[]),
savedAt: input.savedAt, savedAt: input.savedAt,
...(run ? { run } : {}),
}); });
} }
@@ -0,0 +1,95 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { expect, it } from "vitest";
import { createCharacter } from "../app/accountRepository";
import { randomAppearance } from "../app/characterCatalog";
import { abilitiesForClass } from "./abilityCatalog";
import { useCombatStore } from "./combatStore";
import { subscribeCombatEvents } from "./combatEvents";
import { deriveDungeonEncounterCombatEvents, type DungeonEncounterMobCursor } from "./dungeonEncounterCombatEvents";
import { activateDungeonEncounterDefinitions, activeDungeonCompletedObjectiveIds, activeDungeonRunIsComplete,
advanceDungeonEncounters, dispatchActiveDungeonEntityEvent, exportDungeonEncounterCheckpointSnapshots, resetDungeonEncounters } from "./dungeonEncounterRuntime";
import { requireDungeonDefinition } from "./dungeonRegistry";
import { dungeonEnemyHealthBaseline, scaledDungeonEnemyLevel } from "./dungeonLevelScaling";
import { completedDungeonRun, finalDungeonBoss, useDungeonRunStore } from "./dungeonRunStore";
import { clearMobRuntimeRegistry, setMobPosition } from "./mobRuntimeRegistry";
import { usePartyStore } from "./partyStore";
import { advanceDungeonPartyCombat, partyCombatRangeBand, resetPartyRuntimeClock } from "./partyRuntime";
import { clearPartyRuntimeRegistry, registerPartyRuntimePosition, updatePartyRuntimeTargetVisibility } from "./partyRuntimeRegistry";
import { useGameStore } from "./store";
it("turns an actual RoM party's lethal damage to Anglo into one timed completion and a resumable result", () => {
const dungeon = requireDungeonDefinition("barren-caves");
const boss = finalDungeonBoss(dungeon)!;
const spawn = dungeon.staticSpawns.find((entry) => entry.id === boss.id)!;
const entity = dungeon.entities[spawn.entityId];
const bossCombat = entity.combat;
if (!bossCombat) throw new Error("Anglo must have a combat definition");
const healthMultiplier = bossCombat.healthMultiplier ?? 1;
clearMobRuntimeRegistry(); clearPartyRuntimeRegistry(); resetPartyRuntimeClock();
useGameStore.setState({ activeDungeonId: dungeon.id, activeDifficultyId: "normal", gameMode: "dungeon", gmTestMode: false });
activateDungeonEncounterDefinitions(dungeon.id, dungeon.encounters ?? [], "normal");
resetDungeonEncounters("dungeon", dungeon.id);
const combat = useCombatStore.getState();
combat.initializeCharacter({ classId: "rom-priest", raceId: "rom-human", level: 1 });
combat.setPlayerPosition([-18, 0, 0]);
usePartyStore.getState().initializeParty("completion-run", 1, useCombatStore.getState().health, "healer", 5, "rom");
combat.synchronizeActors();
const bossLevel = scaledDungeonEnemyLevel(1, true);
combat.registerMob(boss.id, { name: entity.name, boss: true, level: bossLevel, xpReward: 0,
maxHealth: dungeonEnemyHealthBaseline(bossLevel, "runewaker")! * healthMultiplier,
healthMultiplier, attacks: bossCombat.attacks });
setMobPosition(boss.id, [0, 0, 0]);
for (const member of usePartyStore.getState().members) {
registerPartyRuntimePosition(member.id, [-partyCombatRangeBand(member).preferred, 0, 0]);
updatePartyRuntimeTargetVisibility(member.id, boss.id, true);
}
const party = () => [{ name: "Runview", classId: "rom-priest", level: 1, role: "healer", npc: false },
...usePartyStore.getState().members.map((member) => ({ name: member.name, classId: member.classId,
level: member.level, role: member.role, npc: true }))];
const epoch = Date.now() - 181000;
const run = useDungeonRunStore.getState(); run.begin(dungeon.id, "normal"); run.start(epoch, party());
combat.damageMob(boss.id, 1, epoch);
const heal = abilitiesForClass("rom-priest").find((ability) => ability.name === "Urgent Heal")!;
let cursor: DungeonEncounterMobCursor = {};
let npcDamage = 0; let healing = 0; let deaths = 0;
const stop = subscribeCombatEvents((event) => {
if (event.kind === "damage" && event.targetActorId === boss.id && event.sourceActorId !== "player") npcDamage += event.effectiveAmount;
if (event.kind === "healing") healing += event.effectiveAmount;
});
try {
for (let now = epoch + 100; now <= epoch + 181000; now += 100) {
combat.tick(.1, now); advanceDungeonPartyCombat(now); combat.advanceMobCombat(now);
const tank = usePartyStore.getState().members.find((member) => member.role === "tank")!;
if (tank.health < tank.maxHealth * .65 && !useCombatStore.getState().activeCast) {
usePartyStore.getState().selectMember(tank.id); combat.castAbility(heal.id, undefined, now);
}
const mobs = useCombatStore.getState().mobs;
const events = deriveDungeonEncounterCombatEvents(cursor, mobs, now); cursor = events.cursor;
for (const event of events.events) { dispatchActiveDungeonEntityEvent(event); if (event.kind === "entity-death") deaths += 1; }
const dead = Object.values(mobs).filter((mob) => mob.dead).map((mob) => mob.id);
advanceDungeonEncounters(dungeon.id, { kind: "tick", now, facts: { registeredEntityIds: Object.keys(mobs), deadEntityIds: dead } });
run.advance(activeDungeonCompletedObjectiveIds(dungeon.id), dead, now, party());
if (useDungeonRunStore.getState().progress?.finishedAt !== null) break;
}
const progress = useDungeonRunStore.getState().progress!;
expect(useCombatStore.getState().mobs[boss.id].dead).toBe(true);
expect(activeDungeonRunIsComplete(dungeon.id)).toBe(true);
expect(npcDamage).toBeGreaterThan(0); expect(healing).toBeGreaterThan(0); expect(deaths).toBe(1);
expect(completedDungeonRun(progress)).toMatchObject({ fullClear: true, killedBossIds: [boss.id] });
expect(progress.durationMs).toBeGreaterThan(20000);
expect(usePartyStore.getState().members.every((member) => member.health > 0)).toBe(true);
const snapshots = exportDungeonEncounterCheckpointSnapshots(dungeon.id, 0);
if (process.env.DUNGEON_RUN_REPORT === "1") {
const values = new Map<string, string>();
const character = createCharacter({ ownerId: "qa-owner", name: "Runview", raceId: "rom-human", classId: "rom-priest",
categoryId: "rom", gender: "female", appearance: randomAppearance("rom-human", "female", () => 0) },
{ getItem: (key) => values.get(key) ?? null, setItem: (key, value) => { values.set(key, value); },
removeItem: (key) => { values.delete(key); } }).character!;
mkdirSync("artifacts/dungeon-runs", { recursive: true });
writeFileSync("artifacts/dungeon-runs/combat-completion.json", `${JSON.stringify({ npcDamage, healing, deaths, progress,
character: { ...character, dungeonRunCheckpoint: { version: 2, dungeonId: dungeon.id, difficultyId: "normal",
checkpointId: "entrance", spawn: { footPosition: dungeon.entrance.footPosition, yaw: dungeon.entrance.yaw },
encounters: snapshots, savedAt: Date.now(), run: progress } } }, null, 2)}\n`);
}
} finally { stop(); clearMobRuntimeRegistry(); clearPartyRuntimeRegistry(); }
});
+96
View File
@@ -0,0 +1,96 @@
import { beforeEach, describe, expect, it } from "vitest";
import { DUNGEON_DEFINITIONS, requireDungeonDefinition } from "./dungeonRegistry";
import { completedDungeonRun, finalDungeonBoss, useDungeonRunStore } from "./dungeonRunStore";
import { normalizeDungeonRunProgress, formatDungeonDuration, type DungeonRunMember } from "./dungeonRunTypes";
import { activateDungeonEncounterDefinitions, activeDungeonCompletedObjectiveIds, activeDungeonRunIsComplete,
advanceDungeonEncounters, createDungeonEncounterSnapshot, exportDungeonEncounterCheckpointSnapshots,
importDungeonEncounterSnapshots, reduceDungeonEncounter, resetDungeonEncounters } from "./dungeonEncounterRuntime";
const party: readonly DungeonRunMember[] = [{ name: "Tester", classId: "rom-priest", level: 1, role: "healer", npc: false }];
beforeEach(() => { useDungeonRunStore.setState({ progress: null }); });
describe("dungeon completion and run timing", () => {
it("completes Barren Caves when Anglo dies, records its real spawn id, and survives checkpoint hydration", () => {
const dungeon = requireDungeonDefinition("barren-caves");
activateDungeonEncounterDefinitions(dungeon.id, dungeon.encounters ?? [], "normal");
resetDungeonEncounters("dungeon", dungeon.id);
const run = useDungeonRunStore.getState();
run.begin(dungeon.id, "normal"); run.start(1000, party);
advanceDungeonEncounters(dungeon.id, { kind: "tick", now: 1000, facts: { registeredEntityIds: [], deadEntityIds: [] } });
expect(activeDungeonRunIsComplete(dungeon.id)).toBe(false);
const boss = finalDungeonBoss(dungeon)!;
expect(boss.name).toBe("Anglo");
advanceDungeonEncounters(dungeon.id, { kind: "tick", now: 12456,
facts: { registeredEntityIds: [boss.id], deadEntityIds: [boss.id] } });
run.advance(activeDungeonCompletedObjectiveIds(dungeon.id), [boss.id], 12456, party);
expect(activeDungeonRunIsComplete(dungeon.id)).toBe(true);
expect(completedDungeonRun(useDungeonRunStore.getState().progress!)).toMatchObject({
durationMs: 11456, fullClear: true, killedBossIds: [boss.id], party,
});
const snapshots = exportDungeonEncounterCheckpointSnapshots(dungeon.id, 0);
resetDungeonEncounters("dungeon", dungeon.id);
importDungeonEncounterSnapshots(dungeon.id, snapshots, { authoritative: true });
expect(activeDungeonRunIsComplete(dungeon.id)).toBe(true);
const result = useDungeonRunStore.getState().progress;
run.advance([boss.id], [boss.id], 99999, []); run.start(99999, []);
expect(useDungeonRunStore.getState().progress).toBe(result);
});
it("adds durable completion bookkeeping to every RoM dungeon with configured bosses, without awarding missing bosses", () => {
for (const dungeon of DUNGEON_DEFINITIONS.filter((entry) => entry.expansion === "runewaker" && entry.bosses.length > 0)) {
const baseline = dungeon.encounters!.find((entry) => entry.id === `${dungeon.id}:completion-baseline`)!;
expect(baseline, dungeon.id).toBeDefined();
let snapshot = createDungeonEncounterSnapshot(baseline, 0);
snapshot = reduceDungeonEncounter(baseline, snapshot, { kind: "tick", now: 10,
facts: { registeredEntityIds: [], deadEntityIds: [] } }).snapshot;
expect(snapshot.flags["dungeon-complete"], dungeon.id).toBe(false);
const ordinary = [...new Set([...dungeon.objectiveOrder, ...dungeon.bosses]
.filter((boss) => !boss.eventOnly).map((boss) => boss.id))];
snapshot = reduceDungeonEncounter(baseline, snapshot, { kind: "tick", now: 20,
facts: { registeredEntityIds: ordinary, deadEntityIds: ordinary } }).snapshot;
expect(snapshot.completedObjectiveIds, dungeon.id).toEqual(expect.arrayContaining(ordinary));
if (!dungeon.objectiveOrder.some((boss) => !boss.optional && boss.eventOnly)) {
expect(snapshot.flags["dungeon-complete"], dungeon.id).toBe(true);
}
}
});
it("finishes a final boss clear even when earlier bosses were skipped, but keeps it out of full clears", () => {
const dungeon = requireDungeonDefinition("deadmines");
const final = finalDungeonBoss(dungeon)!;
const run = useDungeonRunStore.getState();
run.begin(dungeon.id, dungeon.defaultDifficultyId); run.start(1000, party);
run.advance([], [final.id], 2000, party);
expect(useDungeonRunStore.getState().progress?.finishedAt).toBeNull();
run.advance([final.id], [final.id], 3000, party);
expect(completedDungeonRun(useDungeonRunStore.getState().progress!)).toMatchObject({ durationMs: 2000, fullClear: false });
});
it("keeps the original wall-clock timer and boss history through a wipe and a saved resume", () => {
const dungeon = requireDungeonDefinition("deadmines");
const run = useDungeonRunStore.getState();
run.begin(dungeon.id, "normal"); run.start(1000, party);
run.advance([], [dungeon.bosses[0].id], 2000, party);
const saved = normalizeDungeonRunProgress(JSON.parse(JSON.stringify(useDungeonRunStore.getState().progress)))!;
run.begin(dungeon.id, "normal", saved); run.start(5000, party);
run.advance([finalDungeonBoss(dungeon)!.id], [], 9000, party);
expect(useDungeonRunStore.getState().progress).toMatchObject({ id: saved.id, startedAt: 1000,
durationMs: 8000, killedBossIds: expect.arrayContaining([dungeon.bosses[0].id]) });
});
it("announces legacy resumed runs without inventing a leaderboard time", () => {
const run = useDungeonRunStore.getState(); run.begin("barren-caves", "normal", undefined, true);
run.start(1000, party); run.advance([finalDungeonBoss(requireDungeonDefinition("barren-caves"))!.id], [], 2000, party);
expect(useDungeonRunStore.getState().progress?.finishedAt).toBe(2000);
expect(completedDungeonRun(useDungeonRunStore.getState().progress!)).toBeNull();
});
it("rejects corrupted saved timers and impossible party levels", () => {
useDungeonRunStore.getState().begin("barren-caves", "normal");
const progress = useDungeonRunStore.getState().progress!;
expect(normalizeDungeonRunProgress({ ...progress, startedAt: NaN })).toBeNull();
expect(normalizeDungeonRunProgress({ ...progress, startedAt: 100, finishedAt: 50, durationMs: 10 })).toBeNull();
expect(normalizeDungeonRunProgress({ ...progress, party: [{ ...party[0], level: 81 }] })).toBeNull();
expect(formatDungeonDuration(123456)).toBe("02:03.4");
});
});
+67
View File
@@ -0,0 +1,67 @@
import { create } from "zustand";
import { dungeonDefinitionById } from "./dungeonRegistry";
import type { DungeonDefinition } from "./dungeonTypes";
import type { DungeonRunMember, DungeonRunProgress, DungeonRunRecord } from "./dungeonRunTypes";
export function dungeonBossesForDifficulty(definition: DungeonDefinition, difficultyId = definition.defaultDifficultyId) {
const difficulty = definition.difficultyVariants.find((variant) => variant.id === difficultyId);
return definition.bosses.filter((boss) => {
const spawn = definition.staticSpawns.find((entry) => entry.id === boss.id);
return !spawn || (((spawn.spawnMask ?? 1) & (difficulty?.spawnMask ?? 1)) !== 0);
});
}
export function finalDungeonBoss(definition: DungeonDefinition, difficultyId = definition.defaultDifficultyId) {
const bosses = dungeonBossesForDifficulty(definition, difficultyId);
const bossIds = new Set(bosses.map((boss) => boss.id));
return definition.objectiveOrder.filter((objective) => !objective.optional && bossIds.has(objective.id)).at(-1)
?? bosses.filter((boss) => !boss.optional).at(-1);
}
export function completedDungeonRun(progress: DungeonRunProgress): DungeonRunRecord | null {
const definition = dungeonDefinitionById(progress.dungeonId);
if (!definition || !progress.timed || progress.finishedAt === null || progress.durationMs === null) return null;
return { id: progress.id, dungeonId: progress.dungeonId, difficultyId: progress.difficultyId,
finishedAt: progress.finishedAt, durationMs: progress.durationMs, killedBossIds: progress.killedBossIds,
party: progress.party, fullClear: dungeonBossesForDifficulty(definition, progress.difficultyId)
.every((boss) => progress.killedBossIds.includes(boss.id)) };
}
interface DungeonRunState {
readonly progress: DungeonRunProgress | null;
begin: (dungeonId: string, difficultyId: string, resume?: DungeonRunProgress, legacyResume?: boolean) => void;
start: (now: number, party: readonly DungeonRunMember[]) => void;
advance: (completedObjectiveIds: readonly string[], deadBossIds: readonly string[], now: number,
party: readonly DungeonRunMember[]) => void;
}
export const useDungeonRunStore = create<DungeonRunState>((set, get) => ({
progress: null,
begin: (dungeonId, difficultyId, resume, legacyResume = false) => set({
progress: resume?.dungeonId === dungeonId && resume.difficultyId === difficultyId ? resume : {
id: globalThis.crypto.randomUUID(), dungeonId, difficultyId, startedAt: null,
finishedAt: null, durationMs: null, killedBossIds: [], party: [], timed: !legacyResume,
},
}),
start: (now, party) => {
const progress = get().progress;
if (!progress || progress.startedAt !== null || party.length === 0) return;
set({ progress: { ...progress, startedAt: now, party: [...party] } });
},
advance: (completedObjectiveIds, deadBossIds, now, party) => {
const progress = get().progress;
if (!progress || progress.startedAt === null || progress.finishedAt !== null) return;
const definition = dungeonDefinitionById(progress.dungeonId);
if (!definition) return;
const bossIds = new Set(definition.bosses.map((boss) => boss.id));
const killedBossIds = [...new Set([...progress.killedBossIds, ...completedObjectiveIds, ...deadBossIds])]
.filter((id) => bossIds.has(id));
const finalBoss = finalDungeonBoss(definition, progress.difficultyId);
// A scripted final boss must award its objective; despawns and raw corpse states cannot complete it.
const finished = finalBoss !== undefined && completedObjectiveIds.includes(finalBoss.id);
if (!finished && killedBossIds.length === progress.killedBossIds.length) return;
set({ progress: { ...progress, killedBossIds,
...(finished ? { finishedAt: Math.max(now, progress.startedAt), durationMs: Math.max(1, Math.round(now - progress.startedAt)),
party: [...party] } : {}) } });
},
}));
+78
View File
@@ -0,0 +1,78 @@
export interface DungeonRunMember {
readonly name: string;
readonly classId: string;
readonly level: number;
readonly secondaryClassId?: string;
readonly role: string;
readonly npc: boolean;
}
export interface DungeonRunProgress {
readonly id: string;
readonly dungeonId: string;
readonly difficultyId: string;
readonly startedAt: number | null;
readonly finishedAt: number | null;
readonly durationMs: number | null;
readonly timed: boolean;
readonly killedBossIds: readonly string[];
readonly party: readonly DungeonRunMember[];
}
export interface DungeonRunRecord {
readonly id: string;
readonly dungeonId: string;
readonly difficultyId: string;
readonly durationMs: number;
readonly finishedAt: number;
readonly killedBossIds: readonly string[];
readonly party: readonly DungeonRunMember[];
readonly fullClear: boolean;
}
export type DungeonClearFilter = "full" | "final";
export interface RankedDungeonRun extends DungeonRunRecord { readonly rank: number }
export interface DungeonLeaderboard {
readonly entries: readonly RankedDungeonRun[];
readonly total: number;
}
export interface DungeonRunPlacement {
readonly finalRank: number;
readonly finalTotal: number;
readonly fullRank: number | null;
readonly fullTotal: number;
}
export function formatDungeonDuration(durationMs: number): string {
const tenths = Math.floor(Math.max(0, durationMs) / 100);
const seconds = Math.floor(tenths / 10);
const minutes = Math.floor(seconds / 60);
return `${String(minutes).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}.${tenths % 10}`;
}
/** Untrusted checkpoint/local-storage data must never reset or invent a ranked timer. */
export function normalizeDungeonRunProgress(value: unknown): DungeonRunProgress | null {
if (!value || typeof value !== "object") return null;
const input = value as DungeonRunProgress;
const text = (entry: unknown) => typeof entry === "string" && entry.length > 0 && entry.length <= 100;
const time = (entry: unknown) => entry === null || (typeof entry === "number" && Number.isFinite(entry) && entry >= 0);
if (!text(input.id) || !text(input.dungeonId) || !text(input.difficultyId)
|| !time(input.startedAt) || !time(input.finishedAt) || !time(input.durationMs)
|| typeof input.timed !== "boolean" || !Array.isArray(input.killedBossIds)
|| input.killedBossIds.length > 100 || !input.killedBossIds.every(text)
|| !Array.isArray(input.party) || input.party.length > 5
|| !input.party.every((member) => member && text(member.name) && text(member.classId)
&& Number.isInteger(member.level) && member.level >= 1 && member.level <= 80
&& ["tank", "healer", "damage"].includes(member.role) && typeof member.npc === "boolean"
&& (member.secondaryClassId === undefined || text(member.secondaryClassId)))
|| (input.finishedAt !== null && (input.startedAt === null || input.finishedAt < input.startedAt))
|| (input.durationMs !== null && (input.finishedAt === null || input.durationMs < 1))
|| (input.finishedAt !== null && (input.durationMs === null || input.party.length === 0
|| input.durationMs !== Math.max(1, Math.round(input.finishedAt - input.startedAt!))))) return null;
return { id: input.id, dungeonId: input.dungeonId, difficultyId: input.difficultyId,
startedAt: input.startedAt, finishedAt: input.finishedAt, durationMs: input.durationMs,
timed: input.timed, killedBossIds: [...new Set(input.killedBossIds)],
party: input.party.map((member) => ({ name: member.name, classId: member.classId,
level: member.level, role: member.role, npc: member.npc,
...(member.secondaryClassId ? { secondaryClassId: member.secondaryClassId } : {}) })) };
}
+8
View File
@@ -18,6 +18,8 @@ import {
} from "./dungeonEncounterRuntime"; } from "./dungeonEncounterRuntime";
import type { DungeonEncounterSnapshot } from "./dungeonEncounterTypes"; import type { DungeonEncounterSnapshot } from "./dungeonEncounterTypes";
import { dungeonContentIsUsable } from "../content/contentManager"; import { dungeonContentIsUsable } from "../content/contentManager";
import { useDungeonRunStore } from "./dungeonRunStore";
import type { DungeonRunProgress } from "./dungeonRunTypes";
export interface DungeonSessionOptions { export interface DungeonSessionOptions {
readonly gameMode?: GameMode; readonly gameMode?: GameMode;
@@ -28,6 +30,8 @@ export interface DungeonSessionOptions {
readonly preserveCharacter?: boolean; readonly preserveCharacter?: boolean;
/** Hydrates save-safe state after definitions have been activated and reset. */ /** Hydrates save-safe state after definitions have been activated and reset. */
readonly encounterSnapshots?: readonly DungeonEncounterSnapshot[]; readonly encounterSnapshots?: readonly DungeonEncounterSnapshot[];
readonly runProgress?: DungeonRunProgress;
readonly legacyResume?: boolean;
} }
/** /**
@@ -47,6 +51,10 @@ export function activateDungeonSession(
const previousDefinition = dungeonDefinitionById(useGameStore.getState().activeDungeonId); const previousDefinition = dungeonDefinitionById(useGameStore.getState().activeDungeonId);
if (previousDefinition) releaseDungeonGltfCache(previousDefinition); if (previousDefinition) releaseDungeonGltfCache(previousDefinition);
if (!options.preserveCharacter) {
useDungeonRunStore.getState().begin(dungeonId, difficultyId ?? definition.defaultDifficultyId,
options.runProgress, options.legacyResume);
}
activateDungeonEncounterDefinitions( activateDungeonEncounterDefinitions(
dungeonId, dungeonId,
definition.encounters ?? [], definition.encounters ?? [],
+2 -2
View File
@@ -37,8 +37,8 @@ describe("reviewed dungeon stair proxies", () => {
it("bridges exactly the existing reviewed portal vertices and rejects stale asset coordinates", () => { it("bridges exactly the existing reviewed portal vertices and rejects stale asset coordinates", () => {
const geometry = new BufferGeometry(); const geometry = new BufferGeometry();
geometry.setAttribute("position", new Float32BufferAttribute([ geometry.setAttribute("position", new Float32BufferAttribute([
...RAMP.navigationBridge.startPortal.flat(), ...RAMP.navigationBridge!.startPortal.flat(),
...RAMP.navigationBridge.endPortal.flat(), ...RAMP.navigationBridge!.endPortal.flat(),
], 3)); ], 3));
geometry.setIndex([]); geometry.setIndex([]);
smoothDungeonStairGeometry(geometry, [RAMP], 0.05); smoothDungeonStairGeometry(geometry, [RAMP], 0.05);
+42 -8
View File
@@ -6,7 +6,7 @@ import type { DungeonTraversalRamp, Vector3Tuple } from "./dungeonTypes";
const MAX_STAIR_SURFACE_DELTA = 0.85; const MAX_STAIR_SURFACE_DELTA = 0.85;
const PORTAL_VERTEX_TOLERANCE = 0.002; const PORTAL_VERTEX_TOLERANCE = 0.002;
function rampHeight( export function dungeonRampHeight(
ramp: DungeonTraversalRamp, ramp: DungeonTraversalRamp,
x: number, x: number,
z: number, z: number,
@@ -36,10 +36,38 @@ export function smoothDungeonStairGeometry(
surfaceClearance = 0, surfaceClearance = 0,
): void { ): void {
const position = geometry.getAttribute("position"); const position = geometry.getAttribute("position");
// Fleet packages can contain many short flights and hundreds of thousands of
// vertices. Index their footprints once rather than checking every flight
// (and validating/recomputing its direction) for every collision vertex.
const cellSize = 16;
const cells = new Map<string, { ramp: DungeonTraversalRamp; dx: number; dz: number; length: number }[]>();
for (const ramp of ramps) {
dungeonRampHeight(ramp, ramp.start[0], ramp.start[2]);
const dx = ramp.end[0] - ramp.start[0];
const dz = ramp.end[2] - ramp.start[2];
const length = Math.hypot(dx, dz);
const xPadding = Math.abs(dz) / length * ramp.width / 2;
const zPadding = Math.abs(dx) / length * ramp.width / 2;
for (let x = Math.floor((Math.min(ramp.start[0], ramp.end[0]) - xPadding) / cellSize);
x <= Math.floor((Math.max(ramp.start[0], ramp.end[0]) + xPadding) / cellSize); x += 1) {
for (let z = Math.floor((Math.min(ramp.start[2], ramp.end[2]) - zPadding) / cellSize);
z <= Math.floor((Math.max(ramp.start[2], ramp.end[2]) + zPadding) / cellSize); z += 1) {
const key = `${x}:${z}`;
const bucket = cells.get(key) ?? [];
bucket.push({ ramp, dx, dz, length });
cells.set(key, bucket);
}
}
}
for (let vertex = 0; vertex < position.count; vertex += 1) { for (let vertex = 0; vertex < position.count; vertex += 1) {
for (const ramp of ramps) { const x = position.getX(vertex); const z = position.getZ(vertex);
const height = rampHeight(ramp, position.getX(vertex), position.getZ(vertex)); for (const { ramp, dx, dz, length } of cells.get(`${Math.floor(x / cellSize)}:${Math.floor(z / cellSize)}`) ?? []) {
if (height === null || Math.abs(position.getY(vertex) - height) > MAX_STAIR_SURFACE_DELTA) continue; const offsetX = x - ramp.start[0]; const offsetZ = z - ramp.start[2];
const along = (offsetX * dx + offsetZ * dz) / length;
const across = (offsetX * dz - offsetZ * dx) / length;
if (along < 0 || along > length || Math.abs(across) > ramp.width / 2) continue;
const height = ramp.start[1] + (ramp.end[1] - ramp.start[1]) * along / length;
if (Math.abs(position.getY(vertex) - height) > MAX_STAIR_SURFACE_DELTA) continue;
position.setY(vertex, height + surfaceClearance); position.setY(vertex, height + surfaceClearance);
break; break;
} }
@@ -57,7 +85,7 @@ export function bridgeDungeonStairNavigation(
? Array.from(geometry.index.array) ? Array.from(geometry.index.array)
: Array.from({ length: position.count }, (_, vertex) => vertex); : Array.from({ length: position.count }, (_, vertex) => vertex);
const portalVertex = (ramp: DungeonTraversalRamp, point: Vector3Tuple): number => { const portalVertex = (ramp: DungeonTraversalRamp, point: Vector3Tuple): number => {
const height = rampHeight(ramp, point[0], point[2]); const height = dungeonRampHeight(ramp, point[0], point[2]);
if (height === null) throw new Error(`${ramp.id}: navigation portal is outside the stair ramp.`); if (height === null) throw new Error(`${ramp.id}: navigation portal is outside the stair ramp.`);
for (let vertex = 0; vertex < position.count; vertex += 1) { for (let vertex = 0; vertex < position.count; vertex += 1) {
if (Math.hypot( if (Math.hypot(
@@ -69,9 +97,15 @@ export function bridgeDungeonStairNavigation(
throw new Error(`${ramp.id}: reviewed navigation portal no longer matches the source GLB.`); throw new Error(`${ramp.id}: reviewed navigation portal no longer matches the source GLB.`);
}; };
for (const ramp of ramps) { for (const ramp of ramps) {
const [a, b] = ramp.navigationBridge.startPortal.map((point) => portalVertex(ramp, point)); for (const bridge of dungeonRampNavigationBridges(ramp)) {
const [c, d] = ramp.navigationBridge.endPortal.map((point) => portalVertex(ramp, point)); const [a, b] = bridge.startPortal.map((point) => portalVertex(ramp, point));
indices.push(a, b, d, a, d, c); const [c, d] = bridge.endPortal.map((point) => portalVertex(ramp, point));
indices.push(a, b, d, a, d, c);
}
} }
geometry.setIndex(indices); geometry.setIndex(indices);
} }
export function dungeonRampNavigationBridges(ramp: DungeonTraversalRamp) {
return [...(ramp.navigationBridge ? [ramp.navigationBridge] : []), ...(ramp.navigationBridges ?? [])];
}
+6 -1
View File
@@ -162,11 +162,16 @@ export interface DungeonTraversalRamp {
readonly start: Vector3Tuple; readonly start: Vector3Tuple;
readonly end: Vector3Tuple; readonly end: Vector3Tuple;
readonly width: number; readonly width: number;
readonly navigationBridge: { readonly navigationBridge?: {
readonly linkId: string; readonly linkId: string;
readonly startPortal: readonly [Vector3Tuple, Vector3Tuple]; readonly startPortal: readonly [Vector3Tuple, Vector3Tuple];
readonly endPortal: readonly [Vector3Tuple, Vector3Tuple]; readonly endPortal: readonly [Vector3Tuple, Vector3Tuple];
}; };
readonly navigationBridges?: readonly {
readonly linkId: string;
readonly startPortal: readonly [Vector3Tuple, Vector3Tuple];
readonly endPortal: readonly [Vector3Tuple, Vector3Tuple];
}[];
} }
export interface DungeonEncounterSpawnGroupDefinition { export interface DungeonEncounterSpawnGroupDefinition {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,6 +1,6 @@
import { BufferGeometry, Float32BufferAttribute, type Group, type Mesh } from "three"; import { BufferGeometry, Float32BufferAttribute, type Group, type Mesh } from "three";
import type { DungeonNavigationLink, DungeonTraversalRamp } from "./dungeonTypes"; import type { DungeonNavigationLink, DungeonTraversalRamp } from "./dungeonTypes";
import { bridgeDungeonStairNavigation, smoothDungeonStairGeometry } from "./dungeonTraversalRamps"; import { bridgeDungeonStairNavigation, dungeonRampNavigationBridges, smoothDungeonStairGeometry } from "./dungeonTraversalRamps";
import { import {
buildPartyNavigationGraph, buildPartyNavigationGraph,
type PartyNavigationGraph, type PartyNavigationGraph,
@@ -77,7 +77,7 @@ export function preparePartyNavigationGraph(
smoothDungeonStairGeometry(geometry, ramps, 0.05); smoothDungeonStairGeometry(geometry, ramps, 0.05);
bridgeDungeonStairNavigation(geometry, ramps, 0.05); bridgeDungeonStairNavigation(geometry, ramps, 0.05);
} }
const bridgedLinks = new Set(ramps.map((ramp) => ramp.navigationBridge.linkId)); const bridgedLinks = new Set(ramps.flatMap((ramp) => dungeonRampNavigationBridges(ramp).map((bridge) => bridge.linkId)));
graph = buildPartyNavigationGraph(geometry, { graph = buildPartyNavigationGraph(geometry, {
maxSourceTriangles: MAX_SYNCHRONOUS_PARTY_NAVIGATION_TRIANGLES, maxSourceTriangles: MAX_SYNCHRONOUS_PARTY_NAVIGATION_TRIANGLES,
offMeshLinks: offMeshLinks.filter((link) => !bridgedLinks.has(link.id)), offMeshLinks: offMeshLinks.filter((link) => !bridgedLinks.has(link.id)),
+151
View File
@@ -0,0 +1,151 @@
import { afterAll, describe, expect, it } from "vitest";
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { useCombatStore } from "./combatStore";
import { usePartyStore } from "./partyStore";
import { dungeonEnemyHealthBaseline, scaledDungeonEnemyLevel } from "./dungeonLevelScaling";
import { BARREN_CAVES_ENTITIES } from "./generated/barrenCavesPopulation.generated";
import { clearMobRuntimeRegistry, setMobPosition } from "./mobRuntimeRegistry";
import { advanceDungeonPartyCombat, partyCombatRangeBand, resetPartyRuntimeClock } from "./partyRuntime";
import { clearPartyRuntimeRegistry, registerPartyRuntimePosition, updatePartyRuntimeTargetVisibility } from "./partyRuntimeRegistry";
import { subscribeCombatEvents } from "./combatEvents";
import { abilitiesForClass } from "./abilityCatalog";
const report: unknown[] = [];
const trash = BARREN_CAVES_ENTITIES["rw-barren-caves-101456"];
const boss = BARREN_CAVES_ENTITIES["rw-barren-caves-101462"];
afterAll(() => {
if (process.env.ROM_DUNGEON_HEALTH_REPORT !== "1") return;
const directory = resolve("artifacts/rom-dungeon-health");
mkdirSync(directory, { recursive: true });
writeFileSync(resolve(directory, "report.json"), `${JSON.stringify({ results: report }, null, 2)}\n`);
});
function initializePull(level: number, seed: string, maxHealth: number, isBoss = false): void {
clearMobRuntimeRegistry();
clearPartyRuntimeRegistry();
resetPartyRuntimeClock();
useCombatStore.getState().initializeCharacter({ classId: "rom-priest", raceId: "rom-human", level });
useCombatStore.getState().setPlayerPosition([-18, 0, 0]);
usePartyStore.getState().initializeParty(seed, level, useCombatStore.getState().health, "healer", 5, "rom");
useCombatStore.getState().synchronizeActors();
const definition = isBoss ? boss : trash;
useCombatStore.getState().registerMob("pull", {
name: definition.name,
boss: isBoss,
level: scaledDungeonEnemyLevel(level, isBoss),
maxHealth,
healthMultiplier: definition.combat.healthMultiplier,
attacks: definition.combat.attacks,
xpReward: 0,
});
setMobPosition("pull", [0, 0, 0]);
for (const member of usePartyStore.getState().members) {
registerPartyRuntimePosition(member.id, [-partyCombatRangeBand(member).preferred, 0, 0]);
updatePartyRuntimeTargetVisibility(member.id, "pull", true);
}
useCombatStore.getState().damageMob("pull", 1, 100);
}
function measurePull(level: number, seed: string, maxHealth: number, isBoss = false) {
initializePull(level, seed, maxHealth, isBoss);
let firstDamageAt: number | null = null;
let diedAt: number | null = null;
let openingHealth = maxHealth;
const stop = subscribeCombatEvents((event) => {
if (event.targetActorId !== "pull") return;
if (event.kind === "damage" && event.effectiveAmount > 0) firstDamageAt ??= event.occurredAt;
});
try {
for (let now = 1_000; now <= 121_000; now += 100) {
useCombatStore.getState().tick(0.1, now);
advanceDungeonPartyCombat(now);
const mob = useCombatStore.getState().mobs.pull;
if (firstDamageAt !== null && now <= firstDamageAt + 1_000) openingHealth = mob.health;
if (mob.dead) {
diedAt = mob.diedAt ?? now;
break;
}
}
return { maxHealth, seconds: diedAt === null || firstDamageAt === null ? null : (diedAt - firstDamageAt) / 1_000,
openingHealth, classes: usePartyStore.getState().members.map((member) => member.classId) };
} finally {
stop();
}
}
describe("RoM dungeon enemy durability", () => {
for (const level of [1, 2, 4, 8, 9, 20, 40, 70, 80]) {
it(`Barren Caves trash survives a full RoM party's opening volley at level ${level}`, () => {
for (let seed = 0; seed < 12; seed += 1) {
const partySeed = `rom-health-${seed}`;
const before = measurePull(level, partySeed, 72 + level * 22);
const after = measurePull(level, partySeed, dungeonEnemyHealthBaseline(level, "runewaker")!);
report.push({ level, seed: partySeed, before, after });
expect(after.openingHealth, JSON.stringify({ level, before, after })).toBeGreaterThan(0);
expect(after.seconds, JSON.stringify({ level, before, after })).not.toBeNull();
expect(after.seconds!, JSON.stringify({ level, before, after })).toBeGreaterThanOrEqual(3);
expect(after.seconds!, JSON.stringify({ level, before, after })).toBeLessThanOrEqual(30);
}
});
}
it("retains Barren Caves' authored boss health multiplier", () => {
const level = 8;
const maxHealth = dungeonEnemyHealthBaseline(scaledDungeonEnemyLevel(level, true), "runewaker")!
* boss.combat.healthMultiplier;
const result = measurePull(level, "rom-health-0", maxHealth, true);
report.push({ level, boss: boss.name, ...result });
expect(result.seconds).not.toBeNull();
expect(result.seconds!).toBeGreaterThanOrEqual(20);
expect(result.seconds!).toBeLessThanOrEqual(120);
});
it("allows enemy attacks and Priest healing before an opening pull ends", () => {
const level = 1;
initializePull(level, "rom-health-0", dungeonEnemyHealthBaseline(level, "runewaker")!);
const heal = abilitiesForClass("rom-priest").find((ability) => ability.name === "Urgent Heal")!;
let incomingDamage = 0;
let healing = 0;
const stop = subscribeCombatEvents((event) => {
if (event.sourceActorId === "pull" && event.kind === "damage") incomingDamage += event.effectiveAmount;
if (event.kind === "healing") healing += event.effectiveAmount;
});
try {
for (let now = 1_000; now <= 31_000; now += 100) {
useCombatStore.getState().tick(0.1, now);
advanceDungeonPartyCombat(now);
useCombatStore.getState().advanceMobCombat(now);
const tank = usePartyStore.getState().members.find((member) => member.role === "tank")!;
if (tank.health < tank.maxHealth && !useCombatStore.getState().activeCast) {
usePartyStore.getState().selectMember(tank.id);
useCombatStore.getState().castAbility(heal.id, undefined, now);
}
if (useCombatStore.getState().mobs.pull.dead) break;
}
expect(useCombatStore.getState().mobs.pull.dead).toBe(true);
expect(incomingDamage).toBeGreaterThan(0);
expect(healing).toBeGreaterThan(0);
expect(usePartyStore.getState().members.every((member) => member.health > 0)).toBe(true);
} finally {
stop();
}
});
it("updates loaded enemies on level-up while retaining wounds and fallen enemies", () => {
const initial = dungeonEnemyHealthBaseline(1, "runewaker")!;
const scaled = dungeonEnemyHealthBaseline(8, "runewaker")!;
initializePull(1, "rom-health-level-up", initial);
useCombatStore.getState().damageMob("pull", initial / 2 - 1, 1_000);
useCombatStore.getState().registerMob("pull", { name: trash.name, level: 8, maxHealth: scaled });
expect(useCombatStore.getState().mobs.pull).toMatchObject({ level: 8, maxHealth: scaled, health: scaled / 2,
attackDamage: 20 });
useCombatStore.getState().registerMob("pull", { name: trash.name, level: 8, maxHealth: scaled });
expect(useCombatStore.getState().mobs.pull.health).toBe(scaled / 2);
useCombatStore.getState().damageMob("pull", scaled, 2_000);
useCombatStore.getState().registerMob("pull", { name: trash.name, level: 20,
maxHealth: dungeonEnemyHealthBaseline(20, "runewaker") });
expect(useCombatStore.getState().mobs.pull).toMatchObject({ dead: true, health: 0 });
});
});
+38
View File
@@ -0,0 +1,38 @@
import type { DungeonDefinition } from "./dungeonTypes";
import type { DungeonEncounterDefinition } from "./dungeonEncounterTypes";
/** Authored completion bookkeeping, independent of reviewed RoM encounter scripts. */
export function withRunewakerCompletion(definition: DungeonDefinition): DungeonDefinition {
if (definition.expansion !== "runewaker" || definition.bosses.length === 0) return definition;
const objectives = [...new Map([...definition.objectiveOrder, ...definition.bosses]
.map((objective) => [objective.id, objective] as const)).values()];
const encounter: DungeonEncounterDefinition = {
id: `${definition.id}:completion-baseline`,
dungeonId: definition.id,
initialPhase: "running",
initialState: { flags: { "dungeon-complete": false } },
source: {
fidelity: "healer-man-authored", scope: "instance-orchestration",
files: ["src/game/runewakerCompletion.ts"],
reviewedBehavior: "Records defeated dungeon bosses and completes the required objectives.",
adaptations: ["Completion bookkeeping uses runtime spawn ids and persists across checkpoints."],
remainingGaps: [],
},
rules: [
...objectives.filter((objective) => !objective.eventOnly).map((objective) => ({
id: `defeated:${objective.id}`,
trigger: { kind: "entities-dead" as const, entityIds: [objective.id] },
actions: [{ id: `record:${objective.id}`, kind: "complete-objective" as const,
objectiveId: objective.id, persistence: "run" as const }],
})),
{
id: "complete", trigger: { kind: "tick" },
guards: objectives.filter((objective) => !objective.optional).map((objective) => ({
kind: "objective-complete", objectiveId: objective.id, equals: true,
})),
actions: [{ id: "complete", kind: "set-flag", flagId: "dungeon-complete", value: true, persistence: "run" }],
},
],
};
return { ...definition, encounters: [...definition.encounters ?? [], encounter] };
}
+1 -1
View File
@@ -8,7 +8,7 @@ import type { GmReviewTarget } from "./gmContentReview";
export type AssetStatus = "checking" | "loading" | "ready" | "proxy" | "error"; export type AssetStatus = "checking" | "loading" | "ready" | "proxy" | "error";
export type InputMode = "keyboard" | "gamepad"; export type InputMode = "keyboard" | "gamepad";
export type GameMode = "dungeon" | "manastorm"; export type GameMode = "dungeon" | "manastorm";
export type GameOverlay = "pause" | "report-issue" | "party" | "inventory" | "map" | "boss-guide" | "spellbook" | "talents" | "bindings" | "options" | "ui-layout" | "keybinds" | "gm" | null; export type GameOverlay = "pause" | "report-issue" | "party" | "inventory" | "map" | "boss-guide" | "spellbook" | "talents" | "bindings" | "options" | "ui-layout" | "keybinds" | "gm" | "dungeon-results" | null;
interface PlayerSnapshot { interface PlayerSnapshot {
position: Vector3Tuple; position: Vector3Tuple;
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { DUNGEON_DEFINITIONS, requireDungeonDefinition } from "./dungeonRegistry";
import { FORSAKEN_ABBEY_DEFINITION } from "./dungeons/forsakenAbbey";
import { WOW_DUNGEON_LIGHTING, withWowDungeonEnvironment, wowDungeonLightingProfile } from "./wowDungeonEnvironment";
import stairs from "./generated/wowDungeonStairs.generated.json";
import stockadesOverride from "../../dungeon-pipeline/runtime-overrides/stormwind-stockade.json";
describe("fleet-wide WoW dungeon environment policy", () => {
const wowDungeons = DUNGEON_DEFINITIONS.filter((dungeon) => dungeon.expansion !== "runewaker");
it("gives every WoW dungeon readable ambient and hemisphere fill without changing fog draw distance or material roles", () => {
expect(wowDungeons).toHaveLength(54);
for (const dungeon of wowDungeons) {
const profile = WOW_DUNGEON_LIGHTING[wowDungeonLightingProfile(dungeon.id)];
expect(dungeon.presentation.ambientLight).toEqual(profile.ambientLight);
expect(dungeon.presentation.hemisphereLight).toEqual(profile.hemisphereLight);
expect(dungeon.presentation.fog.far).toBeGreaterThan(dungeon.presentation.fog.near);
const updated = withWowDungeonEnvironment(dungeon);
expect(updated.presentation.materials).toBe(dungeon.presentation.materials);
expect(updated.assets).toBe(dungeon.assets);
expect(updated.validation).toBe(dungeon.validation);
}
});
it("keeps Stockades' reviewed lighting, ramps and navigation links intact", () => {
const stockades = requireDungeonDefinition("stormwind-stockade");
// The existing campaign compiler stores package vectors at four decimals.
const compiled = (value: unknown) => JSON.parse(JSON.stringify(value, (_key, item) => typeof item === "number" ? Number(item.toFixed(4)) : item));
expect(stockades.traversalRamps).toEqual(compiled(stockadesOverride.traversalRamps));
expect(stockades.navigationLinks).toEqual(compiled(stockadesOverride.navigationLinks));
expect(stockades.presentation.directionalLight).toEqual(stockadesOverride.presentation.directionalLight);
});
it("does not apply WoW changes to RuneWaker environments", () => {
expect(withWowDungeonEnvironment(FORSAKEN_ABBEY_DEFINITION)).toBe(FORSAKEN_ABBEY_DEFINITION);
});
it("records a scan for every shipped WoW dungeon and installs only package-matched proxies", () => {
expect(Object.keys(stairs.dungeons).sort()).toEqual(wowDungeons.map((dungeon) => dungeon.id).sort());
for (const dungeon of wowDungeons) {
const record = (stairs.dungeons as Record<string, { ramps: unknown[] }>)[dungeon.id];
if (record.ramps.length) expect(dungeon.traversalRamps).toEqual(record.ramps);
}
});
it("rejects stale ramp coordinates when collision content is replaced", () => {
const dungeon = wowDungeons.find((entry) => entry.id !== "stormwind-stockade" && entry.traversalRamps?.length)!;
expect(dungeon).toBeDefined();
const replaced = { ...dungeon, traversalRamps: undefined, assets: { ...dungeon.assets, collision: dungeon.assets.collision.map((asset) => ({ ...asset, checksum: "replacement" })) } };
expect(withWowDungeonEnvironment(replaced).traversalRamps).toBeUndefined();
});
});
+85
View File
@@ -0,0 +1,85 @@
import type { DungeonDefinition, DungeonPresentation, DungeonTraversalRamp } from "./dungeonTypes";
import stairCatalog from "./generated/wowDungeonStairs.generated.json";
type LightingProfile = Pick<DungeonPresentation, "background" | "ambientLight" | "hemisphereLight" | "directionalLight"> & {
readonly fog: Pick<DungeonPresentation["fog"], "color" | "near">;
};
// Imported WoW environments do not carry the original client's baked lighting.
// Stockades' reviewed fill levels are the baseline; color remains environment-specific.
export const WOW_DUNGEON_LIGHTING: Readonly<Record<string, LightingProfile>> = {
stone: {
background: "#171815", fog: { color: "#1b1c18", near: 44 },
ambientLight: { color: "#d8c9aa", intensity: 0.58 },
hemisphereLight: { skyColor: "#cfc3a5", groundColor: "#292820", intensity: 0.86 },
directionalLight: { color: "#ffe0a8", intensity: 1.1, offset: [10, 18, -5] },
},
cavern: {
background: "#121914", fog: { color: "#172019", near: 44 },
ambientLight: { color: "#bcccaf", intensity: 0.58 },
hemisphereLight: { skyColor: "#b2c6b5", groundColor: "#242b22", intensity: 0.86 },
directionalLight: { color: "#dce5bc", intensity: 1.1, offset: [10, 18, -5] },
},
fire: {
background: "#211612", fog: { color: "#291c17", near: 44 },
ambientLight: { color: "#d3bca9", intensity: 0.58 },
hemisphereLight: { skyColor: "#d1bca6", groundColor: "#30251f", intensity: 0.86 },
directionalLight: { color: "#ffd3a1", intensity: 1.1, offset: [10, 18, -5] },
},
arcane: {
background: "#161827", fog: { color: "#1c2030", near: 44 },
ambientLight: { color: "#c4c8de", intensity: 0.58 },
hemisphereLight: { skyColor: "#bdc9e6", groundColor: "#25283a", intensity: 0.86 },
directionalLight: { color: "#e0e9ff", intensity: 1.1, offset: [10, 18, -5] },
},
crypt: {
background: "#171721", fog: { color: "#1d1d28", near: 44 },
ambientLight: { color: "#c8c3d1", intensity: 0.58 },
hemisphereLight: { skyColor: "#c0c2d3", groundColor: "#282530", intensity: 0.86 },
directionalLight: { color: "#e7ddcf", intensity: 1.1, offset: [10, 18, -5] },
},
outdoor: {
background: "#293330", fog: { color: "#35423e", near: 80 },
ambientLight: { color: "#d4dccb", intensity: 0.58 },
hemisphereLight: { skyColor: "#c9d9e5", groundColor: "#30382b", intensity: 0.86 },
directionalLight: { color: "#fff0cd", intensity: 1.1, offset: [10, 18, -5] },
},
};
const PROFILE_DUNGEONS: Readonly<Record<string, readonly string[]>> = {
cavern: ["wailing-caverns", "razorfen-kraul", "razorfen-downs", "blackfathom-deeps", "maraudon", "underbog", "slave-pens", "steamvault"],
fire: ["ragefire-chasm", "blackrock-depths", "blackrock-spire", "hellfire-ramparts", "blood-furnace", "shattered-halls"],
arcane: ["gnomeregan", "arcatraz", "botanica", "mechanar", "magisters-terrace", "the-nexus", "the-oculus", "violet-hold", "tinkertech-showdown"],
crypt: ["shadowfang-keep", "scholomance", "stratholme", "sunken-temple", "auchenai-crypts", "mana-tombs", "sethekk-halls", "shadow-labyrinth", "azjol-nerub", "ahnkahet-old-kingdom", "forge-of-souls", "halls-of-reflection"],
outdoor: ["zulfarrak", "black-morass", "escape-from-durnholde", "culling-of-stratholme", "trial-of-the-champion", "pit-of-saron", "frozen-reach"],
};
export function wowDungeonLightingProfile(id: string): string {
return Object.entries(PROFILE_DUNGEONS).find(([, ids]) => ids.includes(id))?.[0] ?? "stone";
}
/** Shared adapter also covers authored Wailing Caverns and survives campaign regeneration. */
export function withWowDungeonEnvironment(definition: DungeonDefinition): DungeonDefinition {
if (definition.expansion === "runewaker") return definition;
const profile = WOW_DUNGEON_LIGHTING[wowDungeonLightingProfile(definition.id)];
const stairs = (stairCatalog.dungeons as unknown as Readonly<Record<string, {
readonly collision: readonly { readonly url: string; readonly checksum: string }[];
readonly navigation?: { readonly url: string; readonly checksum: string };
readonly ramps: readonly DungeonTraversalRamp[];
}>>)[definition.id];
// Never apply package-space coordinates to a newly replaced environment.
const matchingAssets = stairs && definition.assets.collision.length === stairs.collision.length
&& definition.assets.collision.every((asset, index) => asset.url === stairs.collision[index].url
&& asset.checksum === stairs.collision[index].checksum);
const matchingNavigation = !stairs?.ramps.some((ramp) => ramp.navigationBridges?.length)
|| (definition.assets.navigation?.url === stairs?.navigation?.url
&& definition.assets.navigation?.checksum === stairs?.navigation?.checksum);
return {
...definition,
presentation: definition.id === "stormwind-stockade" ? definition.presentation : {
...definition.presentation, ...profile,
fog: { ...definition.presentation.fog, ...profile.fog },
},
...(matchingAssets && matchingNavigation && stairs.ramps.length ? { traversalRamps: stairs.ramps } : {}),
};
}
+81
View File
@@ -0,0 +1,81 @@
import path from "node:path";
import RAPIER from "@dimforge/rapier3d-compat";
import { BufferGeometry, Group, Mesh } from "three";
import { beforeAll, describe, expect, it } from "vitest";
import type { DungeonTraversalRamp } from "./dungeonTypes";
import stairs from "./generated/wowDungeonStairs.generated.json";
import { requireDungeonDefinition } from "./dungeonRegistry";
import { bridgeDungeonStairNavigation, smoothDungeonStairGeometry } from "./dungeonTraversalRamps";
import { collisionTrimeshes, prepareCollision } from "../scene/productionDungeonCollision";
import { DUNGEON_PHYSICAL_COLLISION_GROUPS } from "../scene/dungeonLineOfSight";
import { createPartyDirectSegmentValidator } from "../scene/partyTraversal";
const pipelineModule = "../../scripts/dungeon-pipeline/wow-stair-geometry.ts";
const { readDungeonGeometry } = await import(pipelineModule) as {
readDungeonGeometry(file: string): Promise<BufferGeometry[]>;
};
const packages = Object.entries(stairs.dungeons).filter(([, entry]) => entry.ramps.length);
beforeAll(async () => { await RAPIER.init(); });
describe("shipping WoW dungeon stair proxies", () => {
it.each(packages)("%s supports live NPC capsule sweeps uphill/downhill in three lanes", async (id) => {
const definition = requireDungeonDefinition(id);
const ramps = definition.traversalRamps!;
const source = new Group();
for (const asset of definition.assets.collision) {
for (const geometry of await readDungeonGeometry(path.join(process.cwd(), "public", asset.url!))) {
source.add(new Mesh(geometry));
}
}
const prepared = prepareCollision(source, ramps);
const world = new RAPIER.World({ x: 0, y: -18, z: 0 });
try {
for (const mesh of collisionTrimeshes(prepared)) {
world.createCollider(RAPIER.ColliderDesc.trimesh(Float32Array.from(mesh.vertices), Uint32Array.from(mesh.indices))
.setCollisionGroups(DUNGEON_PHYSICAL_COLLISION_GROUPS));
}
world.step();
const allowed = createPartyDirectSegmentValidator(RAPIER, world);
for (const ramp of ramps) {
const dx = ramp.end[0] - ramp.start[0]; const dz = ramp.end[2] - ramp.start[2];
const length = Math.hypot(dx, dz);
const count = Math.max(3, Math.ceil(length / 0.35) + 1);
const lateral = Math.max(0, Math.min(ramp.width / 4, ramp.width / 2 - 0.45));
for (const lane of [0, -lateral, lateral]) {
const points = Array.from({ length: count }, (_, index): [number, number, number] => {
const t = index / (count - 1);
return [ramp.start[0] + dx * t - dz / length * lane,
ramp.start[1] + (ramp.end[1] - ramp.start[1]) * t,
ramp.start[2] + dz * t + dx / length * lane];
});
for (let index = 1; index < points.length; index += 1) {
const detail = `${id}/${ramp.id}, lane ${lane}, sample ${index}`;
expect(allowed(points[index - 1], points[index]), detail).toBe(true);
expect(allowed(points[index], points[index - 1]), detail).toBe(true);
}
}
}
} finally {
world.free();
for (const group of [source, prepared]) group.traverse((node) => { if ((node as Mesh).isMesh) (node as Mesh).geometry.dispose(); });
}
}, 120000);
it("every generated seam matches actual shipping navigation vertices", async () => {
for (const [id] of packages) {
const definition = requireDungeonDefinition(id);
const ramps = definition.traversalRamps as readonly DungeonTraversalRamp[];
const bridges = ramps.reduce((count, ramp) => count + (ramp.navigationBridges?.length ?? 0), 0);
if (!bridges) continue;
const geometries = await readDungeonGeometry(path.join(process.cwd(), "public", definition.assets.navigation!.url!));
const geometry = geometries.sort((a, b) => b.getAttribute("position").count - a.getAttribute("position").count)[0];
try {
const originalCount = geometry.index!.count;
smoothDungeonStairGeometry(geometry, ramps, 0.05);
expect(() => bridgeDungeonStairNavigation(geometry, ramps, 0.05)).not.toThrow();
expect(geometry.index!.count).toBe(originalCount + bridges * 6);
} finally { geometries.forEach((entry) => entry.dispose()); }
}
}, 120000);
});
+59
View File
@@ -0,0 +1,59 @@
import { BufferGeometry, Float32BufferAttribute } from "three";
import { describe, expect, it } from "vitest";
import { bridgeDungeonStairNavigation, smoothDungeonStairGeometry } from "./dungeonTraversalRamps";
// The offline Node 24 pipeline uses native .ts specifiers; load it at runtime,
// without making those tool-only modules part of the browser TypeScript build.
const pipelineModule = "../../scripts/dungeon-pipeline/wow-stair-geometry.ts";
const { detectDungeonStairRamps, dungeonStairNavigationBridges, dungeonStairRisers } = await import(pipelineModule);
function staircase(steps: number, rotated = false) {
const vertices: number[] = [];
for (let step = 0; step < steps; step += 1) {
const x = step;
const y = step * 0.5;
const points = [[x, y, -2], [x, y + 0.5, -2], [x, y + 0.5, 2], [x, y, -2], [x, y + 0.5, 2], [x, y, 2]];
for (const point of points) vertices.push(...(rotated ? [-point[2], point[1], point[0]] : point));
}
const geometry = new BufferGeometry();
geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
return geometry;
}
describe("WoW shipped stair detection", () => {
it.each([false, true])("detects repeated risers, including rotated stairs (%s)", (rotated) => {
const geometry = staircase(7, rotated);
const ramps = detectDungeonStairRamps(dungeonStairRisers(geometry));
expect(ramps).toHaveLength(1);
expect(ramps[0].width).toBeCloseTo(4.02);
expect(ramps[0].end[1] - ramps[0].start[1]).toBeCloseTo(3.5);
geometry.dispose();
});
it("does not interpret a single ledge or tall wall as a staircase", () => {
const ledge = staircase(1);
expect(detectDungeonStairRamps(dungeonStairRisers(ledge))).toEqual([]);
const wall = staircase(4);
const p = wall.getAttribute("position");
for (let index = 0; index < p.count; index += 1) p.setY(index, p.getY(index) * 10);
expect(detectDungeonStairRamps(dungeonStairRisers(wall))).toEqual([]);
ledge.dispose(); wall.dispose();
});
it("fills separate stair portals using existing source vertices, without bridging an unrelated floor", () => {
const geometry = new BufferGeometry();
geometry.setAttribute("position", new Float32BufferAttribute([
-1, 0, 0, 1, 0, 0, -1, 0.5, 2, 1, 0.5, 2,
-1, 0.75, 3, 1, 0.75, 3, -1, 1.5, 6, 1, 1.5, 6,
-1, 8, 3, 1, 8, 3, -1, 8, 4,
], 3));
geometry.setIndex([0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6, 8, 9, 10]);
const ramps = dungeonStairNavigationBridges(geometry, [{ id: "flight", start: [0, 0, -0.01], end: [0, 1.5, 6.01], width: 3 }]);
expect(ramps[0].navigationBridges).toHaveLength(1);
smoothDungeonStairGeometry(geometry, ramps, 0.05);
expect(() => bridgeDungeonStairNavigation(geometry, ramps, 0.05)).not.toThrow();
expect(geometry.index!.count).toBe(21);
expect(geometry.getAttribute("position").getY(8)).toBe(8);
geometry.dispose();
});
});
+14 -5
View File
@@ -45,7 +45,8 @@ import {
} from "../game/mobRuntimeRegistry"; } from "../game/mobRuntimeRegistry";
import { combatHasLineOfSight } from "../game/combatSpatial"; import { combatHasLineOfSight } from "../game/combatSpatial";
import { registerDungeonRuntimeReset } from "../game/dungeonRuntimeReset"; import { registerDungeonRuntimeReset } from "../game/dungeonRuntimeReset";
import { scaledDungeonEnemyLevel } from "../game/dungeonLevelScaling"; import { dungeonEnemyHealthBaseline, scaledDungeonEnemyLevel } from "../game/dungeonLevelScaling";
import { requireDungeonDefinition } from "../game/dungeonRegistry";
import { stepFearedMobAway } from "../game/mobMotion"; import { stepFearedMobAway } from "../game/mobMotion";
import { import {
clusterStaticMobSpawns, clusterStaticMobSpawns,
@@ -884,6 +885,7 @@ function ProxyMob({
const selected = useCombatStore((state) => state.selectedTargetId === instanceId); const selected = useCombatStore((state) => state.selectedTargetId === instanceId);
const showAggroRanges = useCombatStore((state) => state.settings.showMobAggroRanges); const showAggroRanges = useCombatStore((state) => state.settings.showMobAggroRanges);
const gameMode = useGameStore((state) => state.gameMode); const gameMode = useGameStore((state) => state.gameMode);
const dungeonExpansion = useGameStore((state) => requireDungeonDefinition(state.activeDungeonId).expansion);
const characterLevel = useCombatStore((state) => state.level); const characterLevel = useCombatStore((state) => state.level);
const manastormLevel = useManastormStore((state) => state.level); const manastormLevel = useManastormStore((state) => state.level);
const manastormPartySize = useManastormStore((state) => state.partySize); const manastormPartySize = useManastormStore((state) => state.partySize);
@@ -923,16 +925,22 @@ function ProxyMob({
useEffect(() => { useEffect(() => {
const baseHealthMultiplier = definition.combat?.healthMultiplier ?? 1; const baseHealthMultiplier = definition.combat?.healthMultiplier ?? 1;
const baseDamageMultiplier = definition.combat?.damageMultiplier ?? 1; const baseDamageMultiplier = definition.combat?.damageMultiplier ?? 1;
const level = gameMode === "manastorm"
? definition.combat?.level
: scaledDungeonEnemyLevel(characterLevel, boss);
const healthMultiplier = baseHealthMultiplier * (manastormModifiers?.enemyStatMultiplier ?? 1);
const healthBaseline = gameMode === "dungeon"
? dungeonEnemyHealthBaseline(level ?? characterLevel, dungeonExpansion)
: undefined;
useCombatStore.getState().registerMob(instanceId, { useCombatStore.getState().registerMob(instanceId, {
name: definition.name, name: definition.name,
serverEntry: definition.combat?.serverEntry, serverEntry: definition.combat?.serverEntry,
boss, boss,
level: gameMode === "manastorm" level,
? definition.combat?.level maxHealth: healthBaseline === undefined ? undefined : healthBaseline * healthMultiplier,
: scaledDungeonEnemyLevel(characterLevel, boss),
hasLoot: Boolean((boss && bossHasLoot(definition.id)) || definition.hasLoot), hasLoot: Boolean((boss && bossHasLoot(definition.id)) || definition.hasLoot),
lootSourceId: boss ? definition.id : undefined, lootSourceId: boss ? definition.id : undefined,
healthMultiplier: baseHealthMultiplier * (manastormModifiers?.enemyStatMultiplier ?? 1), healthMultiplier,
damageMultiplier: baseDamageMultiplier * (manastormModifiers?.enemyStatMultiplier ?? 1), damageMultiplier: baseDamageMultiplier * (manastormModifiers?.enemyStatMultiplier ?? 1),
bonusLootChance: manastormModifiers?.bonusLootChance, bonusLootChance: manastormModifiers?.bonusLootChance,
moveSpeed: definition.combat?.moveSpeed, moveSpeed: definition.combat?.moveSpeed,
@@ -959,6 +967,7 @@ function ProxyMob({
definition.combat, definition.combat,
instanceId, instanceId,
gameMode, gameMode,
dungeonExpansion,
manastormLevel, manastormLevel,
manastormMapRewardMultiplier, manastormMapRewardMultiplier,
manastormModeId, manastormModeId,
+70
View File
@@ -0,0 +1,70 @@
import { DUNGEON_LEADERBOARD_PAGE_SIZE, type LeaderboardScope } from "../app/dungeonLeaderboardClient";
import { formatDungeonDuration, type DungeonClearFilter, type DungeonLeaderboard as LeaderboardData } from "../game/dungeonRunTypes";
import { ControllerButton } from "./ControllerButton";
import { DungeonRunDetails } from "./DungeonRunDetails";
import "./dungeonRuns.css";
export function DungeonLeaderboard({ dungeonTitle, data, scope, loading, filter, onFilter,
expanded, onExpand, offset, onPage, onRefresh, difficultyLabel, onDifficulty,
selectedId, select }: {
readonly dungeonTitle: string;
readonly data: LeaderboardData;
readonly scope: LeaderboardScope;
readonly loading: boolean;
readonly filter: DungeonClearFilter;
readonly onFilter: (filter: DungeonClearFilter) => void;
readonly expanded: ReadonlySet<string>;
readonly onExpand: (id: string) => void;
readonly offset: number;
readonly onPage: (offset: number) => void;
readonly onRefresh: () => void;
readonly difficultyLabel: string;
readonly onDifficulty?: () => void;
readonly selectedId: string;
readonly select: (id: string) => void;
}) {
const controls = { selectedId, select };
return <section className="dungeon-leaderboard" aria-label={`${dungeonTitle} leaderboard`} aria-busy={loading}>
<header>
<p className="front-kicker">{scope === "world" ? "World leaderboard" : "This device · offline leaderboard"}</p>
<h3>Fastest expeditions</h3>
<div className="dungeon-leaderboard__filters" aria-label="Clear type">
<ControllerButton {...controls} controlId="leaderboard-final" aria-pressed={filter === "final"}
onClick={() => onFilter("final")}>Final Boss clears <small>All entries</small></ControllerButton>
<ControllerButton {...controls} controlId="leaderboard-full" aria-pressed={filter === "full"}
onClick={() => onFilter("full")}>Full dungeon clears <small>All bosses</small></ControllerButton>
</div>
<div className="dungeon-leaderboard__meta">
{onDifficulty ? <ControllerButton {...controls} controlId="leaderboard-difficulty" onClick={onDifficulty}
aria-label={`Leaderboard difficulty: ${difficultyLabel}. Change difficulty`}>{difficultyLabel} ↻</ControllerButton>
: <span>{difficultyLabel}</span>}
<span>{data.total} {data.total === 1 ? "run" : "runs"}</span>
<ControllerButton {...controls} controlId="leaderboard-refresh" onClick={onRefresh}>Refresh</ControllerButton>
</div>
</header>
<div className="dungeon-leaderboard__entries">
{loading ? <p className="dungeon-leaderboard__empty" role="status">Loading run times…</p>
: data.entries.length === 0 ? <p className="dungeon-leaderboard__empty">No {filter === "full" ? "full dungeon" : "final boss"} clears yet. Complete a run to set the first time.</p>
: <ol>
{data.entries.map((entry) => <li key={entry.id}>
<ControllerButton {...controls} controlId={`leaderboard-run-${entry.id}`}
className="dungeon-leaderboard__run" aria-expanded={expanded.has(entry.id)}
aria-controls={`run-details-${entry.id}`} onClick={() => onExpand(entry.id)}>
<b>#{entry.rank}</b><span><strong>{entry.party.find((member) => !member.npc)?.name ?? entry.party[0]?.name ?? "Party"}</strong>
<small>{entry.fullClear ? "All bosses" : `${entry.killedBossIds.length} bosses`} · {new Date(entry.finishedAt).toLocaleDateString()}</small></span>
<time>{formatDungeonDuration(entry.durationMs)}</time><em aria-hidden="true">{expanded.has(entry.id) ? "−" : "+"}</em>
</ControllerButton>
{expanded.has(entry.id) ? <div id={`run-details-${entry.id}`}><DungeonRunDetails dungeonId={entry.dungeonId}
difficultyId={entry.difficultyId} party={entry.party} killedBossIds={entry.killedBossIds} /></div> : null}
</li>)}
</ol>}
</div>
{data.total > DUNGEON_LEADERBOARD_PAGE_SIZE ? <nav className="dungeon-leaderboard__pages" aria-label="Leaderboard pages">
<ControllerButton {...controls} controlId="leaderboard-prev" disabled={offset === 0 || loading}
onClick={() => onPage(Math.max(0, offset - DUNGEON_LEADERBOARD_PAGE_SIZE))}>Previous</ControllerButton>
<span>{offset + 1}–{Math.min(offset + DUNGEON_LEADERBOARD_PAGE_SIZE, data.total)} of {data.total}</span>
<ControllerButton {...controls} controlId="leaderboard-next" disabled={offset + DUNGEON_LEADERBOARD_PAGE_SIZE >= data.total || loading}
onClick={() => onPage(offset + DUNGEON_LEADERBOARD_PAGE_SIZE)}>Next</ControllerButton>
</nav> : null}
</section>;
}
+32
View File
@@ -0,0 +1,32 @@
import catalog from "../game/generated/dungeonLeaderboardCatalog.generated.json";
import type { DungeonRunMember } from "../game/dungeonRunTypes";
const className = (id: string) => catalog.classes.find((entry) => entry.id === id)?.name ?? id;
export function DungeonRunDetails({ dungeonId, difficultyId, party, killedBossIds }: {
readonly dungeonId: string;
readonly difficultyId: string;
readonly party: readonly DungeonRunMember[];
readonly killedBossIds: readonly string[];
}) {
const dungeon = catalog.dungeons.find((entry) => entry.id === dungeonId);
const ids = dungeon?.difficulties.find((entry) => entry.id === difficultyId)?.bossIds ?? [];
const bosses = dungeon?.bosses.filter((boss) => ids.includes(boss.id)) ?? [];
return <div className="dungeon-run-details">
<h4>Party</h4>
<ul className="dungeon-run-party">
{party.map((member, index) => <li key={`${member.name}-${index}`}>
<strong>{member.name}{member.npc ? <small> NPC</small> : null}</strong>
<span>Level {member.level} · {className(member.classId)}{member.secondaryClassId ? ` / ${className(member.secondaryClassId)}` : ""}</span>
<small>{member.role === "damage" ? "Damage" : member.role === "healer" ? "Healer" : "Tank"}</small>
</li>)}
</ul>
<h4>Bosses defeated · {killedBossIds.length}/{bosses.length}</h4>
<ul className="dungeon-run-bosses">
{bosses.map((boss) => <li key={boss.id} className={killedBossIds.includes(boss.id) ? "is-defeated" : ""}>
<span aria-hidden="true">{killedBossIds.includes(boss.id) ? "✓" : "—"}</span>
{boss.name}<small>{killedBossIds.includes(boss.id) ? "Defeated" : "Not defeated"}</small>
</li>)}
</ul>
</div>;
}
+103
View File
@@ -0,0 +1,103 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useShellStore } from "../app/shellStore";
import { awaitSharedDungeonRunPlacement, localDungeonRunPlacement, saveLocalDungeonRun, submitDungeonRun, type LeaderboardScope } from "../app/dungeonLeaderboardClient";
import { useOnlineSessionStore } from "../app/onlineSessionStore";
import { completedDungeonRun, useDungeonRunStore } from "../game/dungeonRunStore";
import { formatDungeonDuration, type DungeonRunPlacement, type DungeonRunProgress } from "../game/dungeonRunTypes";
import catalog from "../game/generated/dungeonLeaderboardCatalog.generated.json";
import { useGameStore } from "../game/store";
import { useMenuController } from "../input/useMenuController";
import { ControllerButton } from "./ControllerButton";
import { DungeonRunDetails } from "./DungeonRunDetails";
import "./dungeonRuns.css";
export interface RunPlacementState {
readonly scope: LeaderboardScope;
readonly placement: DungeonRunPlacement | null;
readonly loading: boolean;
}
export function DungeonRunResultsDialog({ progress, ranking, onFinish, onLoot, onRetry }: {
readonly progress: DungeonRunProgress;
readonly ranking: RunPlacementState;
readonly onFinish: () => void;
readonly onLoot: () => void;
readonly onRetry: () => void;
}) {
const definition = catalog.dungeons.find((dungeon) => dungeon.id === progress.dungeonId);
const fullClear = definition?.difficulties.find((entry) => entry.id === progress.difficultyId)?.bossIds
.every((id) => progress.killedBossIds.includes(id)) ?? false;
const controller = useMenuController([
{ id: "run-loot", run: onLoot }, { id: "run-finish", run: onFinish },
...(ranking.scope === "device" ? [{ id: "run-retry", run: onRetry }] : []),
], { initialId: "run-loot", onBack: onLoot });
const controls = { selectedId: controller.selectedId, select: controller.select };
const panel = useRef<HTMLElement>(null);
useEffect(() => {
const previous = document.activeElement;
panel.current?.focus();
return () => { if (previous instanceof HTMLElement && previous.isConnected) previous.focus(); };
}, []);
return <div className="modal-backdrop dungeon-results-backdrop">
<section ref={panel} tabIndex={-1} className="dungeon-results" role="dialog" aria-modal="true"
aria-labelledby="dungeon-results-title" onKeyDown={(event) => {
if (event.key !== "Tab") return;
const buttons = Array.from(panel.current?.querySelectorAll<HTMLButtonElement>("button:not(:disabled)") ?? []);
const first = buttons[0]; const last = buttons.at(-1);
if (event.shiftKey && (document.activeElement === first || document.activeElement === panel.current)) {
event.preventDefault(); last?.focus();
} else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
}}>
<header><p className="front-kicker">{fullClear ? "Full dungeon clear" : "Final boss clear"}</p>
<h2 id="dungeon-results-title">{definition?.title ?? progress.dungeonId} complete</h2>
<p>The final boss is defeated. Your expedition is complete.</p>
</header>
<div className="dungeon-results__score">
<div><small>Time to final boss</small><strong>{progress.timed && progress.durationMs !== null
? formatDungeonDuration(progress.durationMs) : "Untimed"}</strong></div>
<div aria-live="polite"><small>{ranking.scope === "world" ? "World leaderboard" : "This device leaderboard"}</small>
<strong>{ranking.loading ? "Recording…" : ranking.placement ? `#${ranking.placement.finalRank}` : "Unranked"}</strong>
{ranking.placement ? <span>of {ranking.placement.finalTotal} final boss clears</span> : null}
</div>
</div>
{ranking.placement?.fullRank ? <p className="dungeon-results__full-rank">Full dungeon clears: <strong>#{ranking.placement.fullRank}</strong> of {ranking.placement.fullTotal}</p> : null}
{!progress.timed ? <p className="dungeon-results__note">This resumed run has no saved timer. Start a new expedition to record a leaderboard time.</p> : null}
{ranking.scope === "device" ? <p className="dungeon-results__note">Your time is saved on this device. Reconnect to submit it to the world leaderboard.</p> : null}
<div className="dungeon-results__details"><DungeonRunDetails dungeonId={progress.dungeonId}
difficultyId={progress.difficultyId} party={progress.party} killedBossIds={progress.killedBossIds} /></div>
<footer>
<ControllerButton {...controls} controlId="run-loot" className="button" onClick={onLoot}>Stay and loot</ControllerButton>
<ControllerButton {...controls} controlId="run-finish" className="button button--primary" onClick={onFinish}>Return to main menu</ControllerButton>
{ranking.scope === "device" ? <ControllerButton {...controls} controlId="run-retry" className="button" onClick={onRetry}>Retry submission</ControllerButton> : null}
</footer>
</section>
</div>;
}
export function DungeonRunResults() {
const progress = useDungeonRunStore((state) => state.progress);
const overlay = useGameStore((state) => state.overlay);
const record = useMemo(() => progress ? completedDungeonRun(progress) : null, [progress]);
const [retry, setRetry] = useState(0);
const [ranking, setRanking] = useState<RunPlacementState>({ scope: "world", placement: null, loading: false });
useEffect(() => {
if (!record) { setRanking({ scope: "world", placement: null, loading: false }); return; }
let live = true;
saveLocalDungeonRun(record);
setRanking({ scope: "world", placement: null, loading: true });
const online = useOnlineSessionStore.getState().snapshot;
const submission = online?.activity.id === record.id && !online.authority
? awaitSharedDungeonRunPlacement(record.id) : submitDungeonRun(record, useShellStore.getState().session);
void submission
.then((placement) => { if (live) setRanking({ scope: "world", placement, loading: false }); })
.catch(() => { if (live) setRanking({ scope: "device", placement: localDungeonRunPlacement(record), loading: false }); });
return () => { live = false; };
}, [record, retry]);
if (overlay !== "dungeon-results" || !progress || progress.finishedAt === null) return null;
return <DungeonRunResultsDialog progress={progress} ranking={ranking} onRetry={() => setRetry((value) => value + 1)}
onLoot={() => useGameStore.getState().closeOverlay()} onFinish={() => {
useShellStore.getState().saveActiveDungeonRunCheckpoint(null);
useGameStore.getState().closeOverlay();
useShellStore.getState().returnToMainMenu();
}} />;
}
+35 -14
View File
@@ -21,7 +21,10 @@ import {
import { useMenuController, type MenuAction } from "../input/useMenuController"; import { useMenuController, type MenuAction } from "../input/useMenuController";
import { LazyLocalCompanionPanel } from "./LazyLocalCompanionPanel"; import { LazyLocalCompanionPanel } from "./LazyLocalCompanionPanel";
import { ControllerButton } from "./ControllerButton"; import { ControllerButton } from "./ControllerButton";
import { DungeonMapGraphic } from "./DungeonMapGraphic"; import { DungeonLeaderboard } from "./DungeonLeaderboard";
import { useDungeonLeaderboard } from "./useDungeonLeaderboard";
import type { DungeonClearFilter } from "../game/dungeonRunTypes";
import { DUNGEON_LEADERBOARD_PAGE_SIZE } from "../app/dungeonLeaderboardClient";
import { BrandMark, ControllerLegend, FrontSurface } from "./FrontSurface"; import { BrandMark, ControllerLegend, FrontSurface } from "./FrontSurface";
import { OnlineGroupPanel } from "./OnlineGroupPanel"; import { OnlineGroupPanel } from "./OnlineGroupPanel";
import { useOnlineGroupStore } from "../app/onlineGroupStore"; import { useOnlineGroupStore } from "../app/onlineGroupStore";
@@ -77,6 +80,20 @@ export function DungeonSelectScreen() {
?? firstCategoryDungeon ?? firstCategoryDungeon
?? null; ?? null;
const selectedDefinition = selectedDungeon ? dungeonDefinitionById(selectedDungeon.id) : null; const selectedDefinition = selectedDungeon ? dungeonDefinitionById(selectedDungeon.id) : null;
const [clearFilter, setClearFilter] = useState<DungeonClearFilter>("final");
const [difficultyId, setDifficultyId] = useState("");
const [expandedRuns, setExpandedRuns] = useState<ReadonlySet<string>>(new Set());
const leaderboardDifficulty = selectedDefinition?.difficultyVariants.find((variant) => variant.id === difficultyId)
?? selectedDefinition?.difficultyVariants.find((variant) => variant.id === selectedDefinition.defaultDifficultyId);
const leaderboard = useDungeonLeaderboard(selectedDungeon?.id ?? "", leaderboardDifficulty?.id ?? "normal", clearFilter);
const toggleRun = (id: string) => setExpandedRuns((current) => {
const next = new Set(current); if (next.has(id)) next.delete(id); else next.add(id); return next;
});
const cycleDifficulty = () => {
const variants = selectedDefinition?.difficultyVariants ?? [];
const index = variants.findIndex((variant) => variant.id === leaderboardDifficulty?.id);
if (variants.length) setDifficultyId(variants[(index + 1) % variants.length].id);
};
const selectedPackInstalled = selectedDungeon ? dungeonContentIsUsable(selectedDungeon.id) : false; const selectedPackInstalled = selectedDungeon ? dungeonContentIsUsable(selectedDungeon.id) : false;
const canStart = Boolean(selectedDungeon?.available && selectedPackInstalled); const canStart = Boolean(selectedDungeon?.available && selectedPackInstalled);
@@ -176,8 +193,17 @@ export function DungeonSelectScreen() {
id: `dungeon-${dungeon.id}`, id: `dungeon-${dungeon.id}`,
run: () => selectDungeon(dungeon.id), run: () => selectDungeon(dungeon.id),
enabled: true, enabled: true,
neighbors: index === 0 ? { up: `dungeon-category-${selectedCategory}` } : undefined, neighbors: { ...(index === 0 ? { up: `dungeon-category-${selectedCategory}` } : {}), right: "leaderboard-final" },
})), })),
{ id: "leaderboard-final", run: () => setClearFilter("final") },
{ id: "leaderboard-full", run: () => setClearFilter("full") },
{ id: "leaderboard-difficulty", run: cycleDifficulty, enabled: (selectedDefinition?.difficultyVariants.length ?? 0) > 1 },
{ id: "leaderboard-refresh", run: leaderboard.refresh },
...leaderboard.data.entries.map((entry) => ({ id: `leaderboard-run-${entry.id}`, run: () => toggleRun(entry.id) })),
{ id: "leaderboard-prev", run: () => leaderboard.setOffset(Math.max(0, leaderboard.offset - DUNGEON_LEADERBOARD_PAGE_SIZE)),
enabled: !leaderboard.loading && leaderboard.offset > 0 },
{ id: "leaderboard-next", run: () => leaderboard.setOffset(leaderboard.offset + DUNGEON_LEADERBOARD_PAGE_SIZE),
enabled: !leaderboard.loading && leaderboard.offset + DUNGEON_LEADERBOARD_PAGE_SIZE < leaderboard.data.total },
...(rolePickerOpen ...(rolePickerOpen
? availableRoles.map((role) => ({ ? availableRoles.map((role) => ({
id: `dungeon-role-${role}`, id: `dungeon-role-${role}`,
@@ -193,7 +219,7 @@ export function DungeonSelectScreen() {
run: () => setRolePickerOpen(false), run: () => setRolePickerOpen(false),
}] : []), }] : []),
{ id: "dungeon-back", run: returnToMainMenu }, { id: "dungeon-back", run: returnToMainMenu },
], [availableRoles, categoryDungeons, downloading, firstCategoryDungeon, pendingDownload, returnToMainMenu, rolePickerOpen, selectedCategory, selectedDungeon]); ], [availableRoles, categoryDungeons, downloading, firstCategoryDungeon, pendingDownload, returnToMainMenu, rolePickerOpen, selectedCategory, selectedDungeon, selectedDefinition, leaderboard, expandedRuns, leaderboardDifficulty]);
const controller = useMenuController(actions, { const controller = useMenuController(actions, {
initialId: firstAvailable ? `dungeon-${firstAvailable.id}` : "dungeon-back", initialId: firstAvailable ? `dungeon-${firstAvailable.id}` : "dungeon-back",
onBack: pendingDownload onBack: pendingDownload
@@ -289,17 +315,12 @@ export function DungeonSelectScreen() {
<main className="dungeon-select-detail" aria-live="polite"> <main className="dungeon-select-detail" aria-live="polite">
{selectedDungeon ? ( {selectedDungeon ? (
<> <>
<div className="dungeon-select-map"> <DungeonLeaderboard dungeonTitle={selectedDungeon.title} data={leaderboard.data} scope={leaderboard.scope}
{selectedDefinition ? ( loading={leaderboard.loading} filter={clearFilter} onFilter={setClearFilter}
<DungeonMapGraphic expanded={expandedRuns} onExpand={toggleRun} offset={leaderboard.offset} onPage={leaderboard.setOffset}
dungeonId={selectedDefinition.id} onRefresh={leaderboard.refresh} difficultyLabel={leaderboardDifficulty?.difficulty === "heroic" ? "Heroic" : "Normal"}
position={selectedDefinition.entrance.footPosition} onDifficulty={(selectedDefinition?.difficultyVariants.length ?? 0) > 1 ? cycleDifficulty : undefined}
yaw={selectedDefinition.entrance.yaw} selectedId={controller.selectedId} select={controller.select} />
/>
) : (
<div className="dungeon-select-map__placeholder" aria-hidden="true">HM</div>
)}
</div>
<section className="dungeon-select-copy"> <section className="dungeon-select-copy">
<p className="front-kicker">{canStart ? "Playable expedition" : selectedDungeon.available ? "Content required" : "In development"}</p> <p className="front-kicker">{canStart ? "Playable expedition" : selectedDungeon.available ? "Content required" : "In development"}</p>
<h2>{selectedDungeon.title}</h2> <h2>{selectedDungeon.title}</h2>
+18 -5
View File
@@ -37,6 +37,8 @@ import { ThreatMeterWidget } from "./ThreatMeterWidget";
import { BossLootWindow } from "./BossLootWindow"; import { BossLootWindow } from "./BossLootWindow";
import { EditableHudElement } from "./EditableHudElement"; import { EditableHudElement } from "./EditableHudElement";
import { DpsMeter } from "./DpsMeter"; import { DpsMeter } from "./DpsMeter";
import { useDungeonRunStore } from "../game/dungeonRunStore";
import { formatDungeonDuration } from "../game/dungeonRunTypes";
import { DesktopActionBars } from "./DesktopActionBars"; import { DesktopActionBars } from "./DesktopActionBars";
import { currentUiDevice, useUiLayoutStore } from "../game/uiLayoutStore"; import { currentUiDevice, useUiLayoutStore } from "../game/uiLayoutStore";
import { SummonFrames } from "./SummonFrames"; import { SummonFrames } from "./SummonFrames";
@@ -140,20 +142,28 @@ export function DefeatedPrompt({
export function DungeonCompletePrompt({ export function DungeonCompletePrompt({
dungeonTitle, dungeonTitle,
onFinish, onFinish,
onResults,
durationMs,
finalBossOnly = false,
}: { }: {
readonly dungeonTitle: string; readonly dungeonTitle: string;
readonly onFinish: () => void; readonly onFinish: () => void;
readonly onResults?: () => void;
readonly durationMs?: number | null;
readonly finalBossOnly?: boolean;
}) { }) {
return ( return (
<section className="dungeon-complete-banner" role="status" aria-live="polite"> <section className="dungeon-complete-banner" role="status" aria-live="polite">
<span aria-hidden="true">◆</span> <span aria-hidden="true">◆</span>
<p> <p>
<strong>{dungeonTitle} complete</strong> <strong>{dungeonTitle} complete</strong>
<small>Every required encounter is defeated. Loot the room or finish the run.</small> <small>{finalBossOnly ? "Final boss defeated." : "Every required encounter is defeated."} Loot the room or finish the run.</small>
{durationMs != null ? <small>Time to final boss: {formatDungeonDuration(durationMs)}</small> : null}
</p> </p>
<button type="button" className="button button--primary" onClick={onFinish}> <button type="button" className="button button--primary" onClick={onFinish}>
Finish dungeon Finish dungeon
</button> </button>
{onResults ? <button type="button" className="button" onClick={onResults}>Run results</button> : null}
</section> </section>
); );
} }
@@ -218,8 +228,9 @@ export function Hud() {
activeDungeonEncounterRevision, activeDungeonEncounterRevision,
activeDungeonEncounterRevision, activeDungeonEncounterRevision,
); );
const dungeonComplete = gameMode === "dungeon" const runProgress = useDungeonRunStore((state) => state.progress);
&& activeDungeonRunIsComplete(activeDungeonId); const finalBossDefeated = runProgress?.dungeonId === activeDungeonId && runProgress.finishedAt !== null;
const dungeonComplete = gameMode === "dungeon" && (finalBossDefeated || activeDungeonRunIsComplete(activeDungeonId));
useEffect(() => { useEffect(() => {
const timer = window.setInterval(() => setClock(Date.now()), 100); const timer = window.setInterval(() => setClock(Date.now()), 100);
@@ -384,8 +395,10 @@ export function Hud() {
<ShelvedHud /> <ShelvedHud />
<DpsMeter /> <DpsMeter />
<BossLootWindow /> <BossLootWindow />
<EditableHudElement id="completion">{dungeonComplete && health > 0 ? ( <EditableHudElement id="completion">{dungeonComplete ? (
<DungeonCompletePrompt dungeonTitle={dungeon.title} onFinish={finishDungeon} /> <DungeonCompletePrompt dungeonTitle={dungeon.title} onFinish={finishDungeon}
finalBossOnly={!activeDungeonRunIsComplete(activeDungeonId)} durationMs={runProgress?.timed ? runProgress.durationMs : null}
onResults={finalBossDefeated ? () => useGameStore.getState().openOverlay("dungeon-results") : undefined} />
) : null}</EditableHudElement> ) : null}</EditableHudElement>
<EditableHudElement id="loot">{feedback?.kind === "loot" ? ( <EditableHudElement id="loot">{feedback?.kind === "loot" ? (
<section className="loot-reward" role="status" aria-live="polite"> <section className="loot-reward" role="status" aria-live="polite">
+102
View File
@@ -0,0 +1,102 @@
.dungeon-leaderboard, .dungeon-results {
--run-gold: var(--front-gold, #d8ae57);
--run-green: var(--front-green-bright, #c8e28d);
--run-line: var(--front-line, rgba(204, 224, 180, .18));
--run-muted: #b1b7a3;
color: #f0ecdc;
}
.dungeon-leaderboard {
display: flex;
min-width: 0;
min-height: 0;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--run-line);
border-radius: 13px 4px 13px 4px;
background: rgba(4, 16, 11, .9);
}
.dungeon-leaderboard > header { padding: 15px 12px 10px; border-bottom: 1px solid var(--run-line); }
.dungeon-leaderboard h3 { margin: 6px 0 14px; color: var(--run-gold); font: 24px Georgia, serif; }
.dungeon-leaderboard__filters { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.dungeon-leaderboard button { color: inherit; cursor: pointer; }
.dungeon-leaderboard__filters button {
min-height: 48px;
padding: 6px;
border: 1px solid var(--run-line);
border-radius: 5px;
background: #0c1a12;
font-size: 11px;
}
.dungeon-leaderboard__filters button[aria-pressed="true"] { border-color: var(--run-gold); background: #27301a; color: #f2dfaa; }
.dungeon-leaderboard__filters small { display: block; margin-top: 3px; color: var(--run-muted); font-size: 9px; }
.dungeon-leaderboard__meta { display: flex; margin-top: 10px; align-items: center; justify-content: space-between; gap: 7px; color: var(--run-muted); font-size: 10px; }
.dungeon-leaderboard__meta button { padding: 5px 2px; border: 0; background: transparent; color: var(--run-green); font-size: 10px; }
.dungeon-leaderboard__entries { min-height: 0; flex: 1; overflow: auto; overscroll-behavior: contain; }
.dungeon-leaderboard__entries ol { margin: 0; padding: 0; list-style: none; }
.dungeon-leaderboard__entries > ol > li { border-bottom: 1px solid var(--run-line); }
.dungeon-leaderboard__run { display: grid; width: 100%; min-height: 63px; grid-template-columns: 31px minmax(0, 1fr) auto 10px; gap: 7px; padding: 10px; align-items: center; border: 0; background: transparent; text-align: left; }
.dungeon-leaderboard__run:hover, .dungeon-leaderboard__run[aria-expanded="true"] { background: rgba(143, 181, 92, .09); }
.dungeon-leaderboard__run > b { color: var(--run-gold); font: 16px Georgia, serif; }
.dungeon-leaderboard__run > span { display: flex; min-width: 0; flex-direction: column; gap: 4px; }
.dungeon-leaderboard__run strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
.dungeon-leaderboard__run small { color: var(--run-muted); font-size: 9px; }
.dungeon-leaderboard__run time { color: var(--run-green); font-size: 14px; font-variant-numeric: tabular-nums; }
.dungeon-leaderboard__run em { color: var(--run-gold); font-size: 16px; font-style: normal; }
.dungeon-leaderboard__empty { padding: 22px 15px; color: var(--run-muted); font-size: 12px; line-height: 1.7; }
.dungeon-leaderboard__pages { display: flex; padding: 8px; align-items: center; justify-content: space-between; gap: 5px; border-top: 1px solid var(--run-line); font-size: 9px; }
.dungeon-leaderboard__pages button { padding: 7px; border: 1px solid var(--run-line); border-radius: 4px; background: #122019; font-size: 10px; }
.dungeon-leaderboard button:disabled { opacity: .4; cursor: default; }
.dungeon-run-details { padding: 8px 12px 12px; }
.dungeon-run-details h4 { margin: 9px 0; color: var(--run-gold); font-size: 11px; font-weight: 500; }
.dungeon-run-details ul { margin: 0; padding: 0; list-style: none; }
.dungeon-run-party li { display: flex; padding: 6px 0; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 4px 9px; border-bottom: 1px solid rgba(204, 224, 180, .07); }
.dungeon-run-party strong { font-size: 11px; }
.dungeon-run-party strong small { color: var(--run-muted); font-size: 8px; font-weight: 400; }
.dungeon-run-party span { width: 100%; order: 3; color: #d6dcc9; font-size: 10px; }
.dungeon-run-party li > small { color: var(--run-muted); font-size: 9px; }
.dungeon-run-bosses li { display: flex; padding: 5px 0; align-items: center; gap: 7px; color: var(--run-muted); font-size: 10px; }
.dungeon-run-bosses li.is-defeated { color: var(--run-green); }
.dungeon-run-bosses small { margin-left: auto; color: var(--run-muted); font-size: 8px; }
.dungeon-results-backdrop { z-index: 110; padding: 16px; pointer-events: auto; }
.dungeon-results {
display: flex;
width: min(580px, calc(100vw - 32px));
max-height: calc(100dvh - 32px);
flex-direction: column;
padding: 23px;
border: 1px solid var(--run-gold);
border-radius: 12px;
outline: 0;
background: linear-gradient(145deg, #172319, #07100d);
box-shadow: 0 20px 65px #0009;
}
.dungeon-results > header { flex: 0 0 auto; }
.dungeon-results h2 { margin: 7px 0; color: #f3deb0; font: 29px Georgia, serif; }
.dungeon-results header > p:last-child { margin: 9px 0 16px; color: var(--run-muted); font-size: 12px; }
.dungeon-results__score { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; flex: 0 0 auto; }
.dungeon-results__score > div { display: flex; padding: 14px; flex-direction: column; gap: 6px; border: 1px solid var(--run-line); border-radius: 6px; background: #ffffff04; }
.dungeon-results__score small { color: var(--run-muted); font-size: 11px; }
.dungeon-results__score strong { color: var(--run-green); font: 31px Georgia, serif; font-variant-numeric: tabular-nums; }
.dungeon-results__score span { color: var(--run-muted); font-size: 10px; }
.dungeon-results__full-rank { margin: 12px 0 0; color: var(--run-gold); font-size: 12px; }
.dungeon-results__note { margin: 12px 0 0; color: var(--run-muted); font-size: 11px; line-height: 1.5; }
.dungeon-results__details { min-height: 40px; margin-top: 13px; overflow: auto; overscroll-behavior: contain; border-block: 1px solid var(--run-line); }
.dungeon-results__details .dungeon-run-details { padding-inline: 0; }
.dungeon-results > footer { display: flex; margin-top: 16px; flex: 0 0 auto; flex-wrap: wrap; gap: 8px; }
.dungeon-results > footer button { min-height: 38px; flex: 1; white-space: nowrap; }
@media (max-width: 960px) {
.dungeon-select-detail { grid-template-rows: minmax(145px, 1fr) minmax(120px, .8fr); gap: 9px; }
.dungeon-leaderboard > header { padding: 9px; }
.dungeon-leaderboard h3 { margin: 4px 0 8px; font-size: 19px; }
.dungeon-leaderboard__filters button { min-height: 39px; font-size: 10px; }
.dungeon-leaderboard__meta { margin-top: 5px; }
.dungeon-leaderboard__run { min-height: 52px; }
}
@media (max-height: 520px) {
.dungeon-results { padding: 13px; }
.dungeon-results h2 { font-size: 23px; }
.dungeon-results header > p:last-child { margin-bottom: 9px; }
.dungeon-results__score > div { padding: 8px 12px; }
.dungeon-results__score strong { font-size: 25px; }
.dungeon-results > footer { margin-top: 9px; }
}
+39
View File
@@ -0,0 +1,39 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { DungeonLeaderboard } from "./DungeonLeaderboard";
import { DungeonRunResultsDialog } from "./DungeonRunResults";
import catalog from "../game/generated/dungeonLeaderboardCatalog.generated.json";
import type { DungeonRunProgress } from "../game/dungeonRunTypes";
const caves = catalog.dungeons.find((entry) => entry.id === "barren-caves")!;
const progress: DungeonRunProgress = { id: "ui-caves-test", dungeonId: caves.id, difficultyId: "normal", timed: true,
startedAt: 1000, finishedAt: 13345, durationMs: 12345, killedBossIds: [caves.finalBossId],
party: [{ name: "Tester", classId: "rom-priest", level: 3, role: "healer", npc: false },
{ name: "Garrick", classId: "warrior", level: 3, role: "tank", npc: true }] };
const noop = () => undefined;
describe("dungeon results and leaderboard", () => {
it("announces the final boss, frozen time, both rankings, party levels, and explicit loot/menu choices", () => {
const html = renderToStaticMarkup(createElement(DungeonRunResultsDialog, { progress,
ranking: { scope: "world", loading: false, placement: { finalRank: 2, finalTotal: 10, fullRank: 1, fullTotal: 4 } },
onFinish: noop, onLoot: noop, onRetry: noop }));
for (const text of ["Barren Caves complete", "00:12.3", "#2", "#1", "Anglo", "Level 3", "Garrick", "Stay and loot", "Return to main menu"])
expect(html).toContain(text);
expect(html).toContain('aria-modal="true"');
});
it("labels disconnected rankings as device-only and offers submission retry", () => {
const html = renderToStaticMarkup(createElement(DungeonRunResultsDialog, { progress,
ranking: { scope: "device", loading: false, placement: { finalRank: 1, finalTotal: 1, fullRank: 1, fullTotal: 1 } },
onFinish: noop, onLoot: noop, onRetry: noop }));
expect(html).toContain("This device leaderboard"); expect(html).toContain("Retry submission");
});
it("offers both clear filters and expandable party/boss records in the dungeon picker", () => {
const html = renderToStaticMarkup(createElement(DungeonLeaderboard, { dungeonTitle: caves.title,
data: { entries: [{ ...progress, durationMs: progress.durationMs!, finishedAt: progress.finishedAt!, fullClear: true, rank: 1 }], total: 1 },
scope: "world", loading: false, filter: "full", onFilter: noop, expanded: new Set([progress.id]),
onExpand: noop, offset: 0, onPage: noop, onRefresh: noop, difficultyLabel: "Normal", selectedId: "", select: noop }));
for (const text of ["Final Boss clears", "All entries", "Full dungeon clears", "All bosses", "Anglo", "Level 3", "00:12.3"])
expect(html).toContain(text);
expect(html).toContain('aria-expanded="true"');
});
});
+32
View File
@@ -0,0 +1,32 @@
import { useEffect, useState } from "react";
import { fetchDungeonLeaderboard, localDungeonLeaderboard, subscribeDungeonLeaderboard,
type LeaderboardScope } from "../app/dungeonLeaderboardClient";
import type { DungeonClearFilter, DungeonLeaderboard } from "../game/dungeonRunTypes";
export function useDungeonLeaderboard(dungeonId: string, difficultyId: string, filter: DungeonClearFilter) {
const [offset, setOffset] = useState(0);
const [revision, setRevision] = useState(0);
const [state, setState] = useState<{ data: DungeonLeaderboard; scope: LeaderboardScope; loading: boolean }>({
data: { entries: [], total: 0 }, scope: "world", loading: true,
});
useEffect(() => { setOffset(0); }, [dungeonId, difficultyId, filter]);
useEffect(() => subscribeDungeonLeaderboard(() => setRevision((value) => value + 1)), []);
useEffect(() => {
const refresh = () => setRevision((value) => value + 1);
window.addEventListener("focus", refresh);
return () => window.removeEventListener("focus", refresh);
}, []);
useEffect(() => {
const controller = new AbortController();
let live = true;
const timeout = setTimeout(() => controller.abort(), 8000);
setState({ data: { entries: [], total: 0 }, scope: "world", loading: true });
if (dungeonId) void fetchDungeonLeaderboard(dungeonId, difficultyId, filter, offset, controller.signal)
.then((data) => { if (live) setState({ data, scope: "world", loading: false }); })
.catch(() => { if (live) setState({ data: localDungeonLeaderboard(dungeonId, difficultyId, filter, offset),
scope: "device", loading: false }); });
else setState({ data: { entries: [], total: 0 }, scope: "world", loading: false });
return () => { live = false; controller.abort(); clearTimeout(timeout); };
}, [dungeonId, difficultyId, filter, offset, revision]);
return { ...state, offset, setOffset, refresh: () => setRevision((value) => value + 1) };
}