Documentation

documentation/README.md

Reference for the systems that carry state. Each page documents a data file or a runtime contract, with the fields that actually exist in the code — not an aspiration.

Page Covers
architecture.md Module layout, the fixed-step loop, render pipeline
data/quests.md quests.json — objectives, gating, branching, journal
data/items.md items.json — types, stats, damage types, gear sets
data/enemies.md enemies.json — stats, ranged behaviour, resistances
data/structures.md structures.json — the prop format and the editor
save-schema.md Save v3, migration, export/import
performance.md How to measure the game on your own hardware
localisation.md The string table, t(), and adding a locale

Editing content

All gameplay content is data. Change a JSON file, run npm run build, and commit play/ with the change — CI fails if play/ is stale.

npm test          # 50 unit tests
npm run test:e2e  # headless Chrome: boot → play → save → continue
npm run build     # rebuild play/

Validate a data file by loading the game: a malformed entry throws at boot and the E2E smoke test catches it before Pages publishes.

Architecture

documentation/architecture.md

Layout

index.html                    landing page (static, not built)
play/                         built game — output of `npm run build`
game/
  index.html                  Vite entry
  public/assets/manifest.json loader manifest (empty = procedural everything)
  public/draco/               DRACO decoder drop-in
  public/basis/               KTX2 transcoder drop-in
  src/
    main.ts                   Game class: boot, loop, interaction, save/load
    core/Engine.ts            renderer, composer, resize, quality presets
    core/AssetManager.ts      GLTF/DRACO/KTX2/Meshopt + procedural rig fallback
    core/InputManager.ts      keyboard/mouse/gamepad/touch, rebindable actions
    core/EventBus.ts          typed pub/sub
    core/SaveSystem.ts        v2 schema, migrate(), corruption recovery
    world/Terrain.ts          heightfield, sampling, water shader
    world/WorldBuilder.ts     village, dungeon, forest LOD, colliders, spawns
    world/DayNight.ts         sun orbit, sky shader, fog lerp, lanterns
    entities/Entity.ts        transform, interpolation, disposal
    entities/Player.ts        controller, camera, animation state machine
    entities/NPC.ts           idle routine, quest marker
    entities/Enemy.ts         goblin FSM
    systems/CombatSystem.ts   hit queries, hit-stop, damage numbers
    systems/QuestSystem.ts    objectives, rewards
    systems/InventorySystem.ts
    ui/*.ts                   HUD, Dialogue, Inventory, QuestLog, MainMenu, LoadingScreen
    audio/AudioManager.ts     Howler + synthesised WAV data URIs
    data/*.json               items, quests, dialogue, enemies

Frame

requestAnimationFrame
  ├─ input.update()            poll gamepad, fold touch + keyboard into moveAxis
  ├─ engine.resetInfo()        clear draw-call counters (composer renders several passes)
  ├─ accumulator += dt * hitstopScale
  ├─ while (accumulator >= 1/60 && steps < 5) fixedUpdate(1/60)
  │    ├─ player.update()      look → timers → movement → actions → mixer → camera
  │    ├─ enemies.update()     FSM tick, terrain snap, collider push-out
  │    ├─ npcs.update()        idle clip + head look-around
  │    ├─ combat.update()      damage-number pool, hit-stop timer
  │    ├─ world.update()       re-bucket tree LOD when the player moved > 8 m
  │    ├─ dayNight.update()    sun orbit, sky/fog/lantern lerp
  │    ├─ updateInteraction()  nearest NPC / herb / lever within 3.2 m
  │    └─ input.endStep()      clear edge-triggered actions
  ├─ renderScene(alpha)        interpolate entity positions between steps
  └─ engine.render()           RenderPass → Bloom → Vignette → OutputPass → SMAA

Data flow

InputManager ──► Player ──► CombatSystem ──► Enemy.takeDamage ──► EventBus "enemy:killed"
                                                     │
                     ┌───────────────────────────────┼──────────────────────┐
                     ▼                               ▼                      ▼
              QuestSystem.advance()            HUD (xp bar)          Game (killedEnemyIds)
                     │
                     ▼
             "quest:completed" ──► rewards ──► InventorySystem ──► HUD hotbar
                              └──► Game.save()  (autosave on completion)

No system holds a reference to another system's entities. The only shared mutable objects are the terrain (read-only sampling) and the world's collider list.

Key decisions

Area Decision Reason
Physics Capsule + raycast ground snap, no engine Deterministic, ~0 cost, enough for one slope limit
Ground rays 32×32 invisible collisionProxy mesh 2k triangles per ray instead of 32k
Collision Circle-vs-AABB / circle-vs-cylinder push-out in XZ O(n) with a cheap vertical-span reject; ~500 colliders
Animation AnimationMixer over procedurally generated clips Same API as GLB clips, so a real rig drops in unchanged
Characters One merged SkinnedMesh, 12 bones, vertex colours 1 draw call each, no texture atlas needed
Static props Merged per group (village = 1 mesh, dungeon = 1 mesh) Draw-call budget with zero batching work at runtime
Foliage 3 InstancedMesh tiers, re-bucketed on movement 3 draw calls for 460 trees; rebuild only every 8 m
Camera Raycast pull-in with snap-in / ease-out Never clips; never lags through a wall
Damage numbers 24 pre-allocated sprites with their own canvas Zero allocation on hit
Save Versioned JSON, migrate() never throws Corrupt save → fresh game + toast
Assets Manifest-driven, procedural fallback Missing file can never break boot

Budget enforcement

Save schema

documentation/save-schema.md

Three slots in localStorage under eldervale:save:<slot>. The schema is v3 and additive changes stay at v3 — new optional fields are read with a fallback.

Shape

{
  version: 3,
  name?: string,            // slot label, set by Rename
  timestamp: number,
  player: {
    pos: [x, y, z], hp, stamina, level, xp,
    inventory: [{ id, count }],
    equipped: string | null,  // weapon
    armor?: string | null,
    trinket?: string | null
  },
  quests: {
    active: [{ id, progress: number[] }],
    completed: string[],
    tracked?: string | null,
    journal?: [{ id, at }]     // at = epoch ms
  },
  skills?: { points, unlocked: string[] },
  recipes?: string[],          // discovered recipe ids
  world: { timeOfDay, enemiesKilled: string[], herbsCollected: string[] },
  settings: {
    volume, sensitivity, invertY, quality,
    bindings: Record<string, string[]>,
    palette?: string, reducedMotion?: boolean
  }
}

Rules

Export and import

The slot picker offers Export (downloads <slot>.json) and Import on an empty slot. Import runs the file through migrate() first, so a save from an older build lands as a valid v3 record. Junk is rejected without touching the slot.

Testing

tests/save-system.test.ts covers the round trip, an old-file import and junk rejection. The E2E smoke test saves, opens a fresh page and continues, asserting hp, inventory and position survive.

`quests.json`

documentation/data/quests.md

Every quest is one object in game/src/data/quests.json. Quests are offered by an NPC, advanced by bus events, and closed when every objective counter reaches its target.

Fields

Field Type Required Meaning
id string yes Unique. Used by saves, dialogue action: "accept" and "turnin".
title string yes Shown in the tracker and the quest log.
description string yes One paragraph, shown in the log and the offer dialogue.
giver string yes Dialogue id of the NPC (elder, villager_a … villager_d).
requires string[] no Quest ids that must be completed before this one is offered.
excludes string[] no Mutually exclusive quests. Accepting this one closes the others for good.
objectives array yes See below. Progress is per-objective, clamped to count.
rewards object yes { xp: number, items: [{ id, count }] }, granted on completion.
journalNote string no The line written into the journal when the quest closes.

Objectives

{ "type": "kill", "targetId": "goblin", "count": 3 }
type targetId means Advanced by
kill enemy type from enemies.json enemy:killed
collect item id from items.json item:collected
talk NPC dialogue id npc:talked

Counters are saved per quest and clamped on load, so a hand-edited save cannot complete a quest by claiming 999 kills.

Branching

A pair of quests that list each other in excludes is a branch:

{ "id": "q_nest_burn", "excludes": ["q_nest_spare"], "journalNote": "You burned the nest out…" }

Taking one sets the other unavailable (QuestSystem.isAvailable returns false once the sibling is active or completed). The dialogue action accept returns false for the closed side and the game toasts "You already chose the other path". When the taken quest completes, the journal records the sibling it left undone under Left undone.

Completion

  1. completed gains the id.
  2. A journal entry is pushed: { id, at: Date.now(), note, skipped }.
  3. quest:completed fires (the shrine lights on q_vale).
  4. XP and items are granted through the deps passed to QuestSystem.

Related

`items.json`

documentation/data/items.md

Every item is one object in game/src/data/items.json. Items are shared by the inventory, crafting recipes, quest rewards and enemy drops.

Fields

Field Type Required Meaning
id string yes Unique. Referenced by recipes, quests and drop tables.
name string yes Shown in the bag, tooltips and toasts.
type weapon | armor | trinket | consumable | material yes Decides which slot it can occupy and whether it can be used.
stack number yes Maximum per inventory slot (1 for gear).
icon string yes Two-letter glyph drawn in the bag.
desc string yes Tooltip line.
stats object no { damage, hp, reduction, stamina }, summed across equipped gear.
damageType physical | fire | frost weapons only Chooses the rider: fire burns 3 dps for 3 s, frost slows to 55 %.
set string no Set id; see Gear sets.

Gear sets

GEAR_SETS in game/src/systems/InventorySystem.ts lists the sets and their bonus. A piece only counts while it is equipped, and the bonus applies only when every piece is worn.

Set Pieces Bonus
trophy — Trophy Kit leather_vest, tooth_charm +4 damage, +15 % stamina
drowned — Drowned Regalia warden_plate, bog_heart +25 max HP, +5 % reduction

InventorySystem.setProgress() returns { set, worn, complete } for the UI; the inventory shows a green "Set complete" row when complete is true.

Resistances

Damage types meet enemy resistances before the hit lands, so the number you see is the number that was dealt:

damage = max(1, round(baseDamage * enemy.damageMultiplier(type)))

physical is always 1. See enemies.md for the per-type table.

Armour visuals

Equipping armour or a trinket changes the player model: Player.setGearVisual attaches a plate to the chest bone (plus shoulder pads for warden_plate) and a glowing bead at the hips for trinkets. The mapping lives in Player.ts (ARMOUR, TRINKET) — add an entry there when you add gear that should show.

`enemies.json`

documentation/data/enemies.md

One object per enemy type in game/src/data/enemies.json. Spawns live in WorldBuilder and reference these keys.

Fields

Field Type Meaning
name string Boss bar label and kill messages.
hp number Pool. Elites scale this in the spawn table.
damage number Per hit.
speed number Metres per second while chasing.
xp number Granted on death.
attackRange number Melee reach, or firing range when ranged.
attackCooldown number Seconds between attacks.
windup number Seconds of telegraph before a hit lands. The ground ring closes over this window.
ranged boolean Fires projectiles instead of swinging.
volley number Projectiles per attack (ranged only).
resist { fire?, frost? } Damage multiplier per element. 1.5 = weak, 0.6 = resistant.

Resistances in play

Type Fire Frost Reads as
goblin, archer 1.0 1.25 thin blood, hates cold
hound, alpha 1.5 0.75 fears flame, thick fur
brute 0.8 1.3 shrugs off fire
cultist 1.3 0.4 made of cold
warden, bog, choir 0.6–1.4 0.5–0.7 bosses resist both

Behaviour

The FSM is patrol → alert → chase → attack → stagger → dead. Archers and cultists hold range and strafe perpendicular to the line of sight, flipping direction every 1.4–3 s. Bosses wake when the player enters their arena on the same level (the check is height-gated), play three phases as health drops, and seal their arena with a portcullis.

Drops

Drop tables live in main.ts under lootTable; a killed enemy rolls its type's entry. Bosses drop a unique item: bog_heart, choir_bell, warden_plate.

Visuals

AssetManager builds each type procedurally: a palette, a bulk factor and a scale. Add a type by extending CharacterId, giving it a palette branch, and mapping it in main.ts where spawn types become character ids.

`structures.json`

documentation/data/structures.md

Props the world builder reads at boot. One structure is a position plus a list of primitives; the builder merges the parts into one mesh (one draw call) and adds a collider per solid part.

Shape

{
  "id": "watchtower",
  "x": -44,
  "z": 104,
  "parts": [
    { "shape": "cyl", "size": [2.2, 2.8, 7.5, 8], "offset": [0, 3.75, 0], "colour": 8669507, "solid": true }
  ]
}
Field Meaning
id Mesh name in the scene graph — handy when debugging in ?debug=1.
x, z World position; the mesh sits on the terrain height at that point.
parts[].shape box, cyl or cone.
parts[].size box: [w, h, d] · cyl: [radiusTop, radiusBottom, height, segments] · cone: [radius, height, segments].
parts[].offset [x, y, z] from the structure origin, in metres.
parts[].colour Integer RGB (0x8a7256 = 9079160).
parts[].solid true adds an axis-aligned collider sized to the primitive's footprint.

Colliders

Solid parts produce a box collider spanning the part's footprint and from one metre below the ground to offset[1] + height. Steps stay walkable because the player's step-up tolerance is 0.35 m.

Editing

Open /editor/ — a plan-view tool that loads this file, lets you place, drag and edit parts, and exports the same JSON. Copy the download over game/src/data/structures.json, rebuild, commit.

The editor keeps its own seed copy at editor/structures.json; refresh it with cp game/src/data/structures.json editor/structures.json after changing the data.

Where structures differ from interiors

Cottage interiors are not in this file: they are built procedurally in WorldBuilder.buildInteriors because they need doorway colliders and a per-room light. Use structures.json for open-air props.

Performance on your hardware

documentation/performance.md

The acceptance target is 60 fps at 1080p on desktop and 30 fps or better on a phone. The sandbox that built this game renders through SwiftShader, so those two numbers cannot be measured here. Everything else about performance is: draw calls, triangles, bundle size and the adaptive ladder are all measured and gated in CI.

This page is the handoff for the last unmeasured claim.

1. Capture

Open the game with the stats flag:

https://drsamonline.github.io/eldervale/play/?stats=1

Play for about a minute — walk the village, cross the bridge, fight something. Then press F2. A CSV downloads: one row per frame with frame_ms, draw_calls, triangles, render_scale and quality.

F3 shows the live p50 / p95 beside the draw-call count.

2. Read it

Column What it tells you
frame_ms 16.7 is 60 fps. 33.3 is 30. The game targets the former.
render_scale If this sits below 1.0, the adaptive ladder is working: it drops resolution before it drops shadows.
quality Which preset was active when the row was written.
draw_calls Should stay near 60. A number in the hundreds means something is spawning meshes per frame.
triangles Should stay near 60 k in the village, under 300 k everywhere.

3. What to send back

The CSV, the device (e.g. "M1 MacBook Air, Safari" or "Pixel 7, Chrome"), and whether the number felt smooth. With that, the thresholds in game/src/main.ts (trackFrameTime) can be tuned to your hardware instead of guessed.

4. What is already guaranteed

Claim Where it is enforced
Bundle under 25 MB gzipped CI: Assert gzipped budget (currently ~300 KB)
Draw calls and triangles in budget ?debug=1 overlay, F3
Adaptive quality works ?stats=1 + F2, and the ladder is unit-reasoned in trackFrameTime
No leaks across reloads measured: 3 cycles, 0 geometry and 0 texture growth
The game boots and plays CI: headless E2E smoke on every push

Localisation

documentation/localisation.md

UI strings live in game/src/data/strings.json, keyed by screen and read through t() in game/src/core/i18n.ts.

import { t } from './core/i18n';

hud.setPrompt(t('prompt.door', { name: 'Cottage 3' }));  // "Enter Cottage 3"

Adding a locale

  1. Copy the en object in strings.json under a new key (hi, ta, …).
  2. Translate the values. Do not change the keys or the {placeholders}.
  3. Call setLocale('hi') at boot, or store the choice beside the other settings.

setLocale ignores a locale with no bundle and stays on English, so a partial translation can ship without breaking the game.

Rules

Markup

Elements carry data-i18n="key"; applyI18n() fills them at boot and whenever the language changes. A key with a variable uses data-i18n-key for the value:

<button id="inv-close" data-i18n="ui.closeKey" data-i18n-key="I">Close [I]</button>

Current coverage

English and Hindi ship complete for the chrome: menus, settings labels, panel titles, buttons, interaction prompts and toasts — 39 keys in each bundle, checked by a test that fails if a key exists in one bundle and not the other.

The language lives in the save's settings and is switchable in Settings → Language. Quest titles, item names and dialogue remain content and are localised by translating those data files.