Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(verse): realtime 3D decks with third-person, first-person and bird's-eye views, plus a 1v1 duel mode (#866)

Ruben Lütke4256ee85af95
diff --git a/art/verse/BRIEF.md b/art/verse/BRIEF.md
new file mode 100644
index 0000000000..d74bd003ae
--- /dev/null
+++ b/art/verse/BRIEF.md
@@ -0,0 +1,173 @@
+# Dodaios Verse — production brief (capital ship rebuild)
+
+Status: greenlit 2026-10-19. This brief is the contract between every team on
+the rebuild. If a document and this brief disagree, this brief wins until it is
+changed here.
+
+## 1. Vision
+
+The Verse is the interior of **Dodaios**, a 1.6 km wedge-hulled capital ship of
+a fleet navy, seen from above. It must read as a real place photographed, not as
+a game prototype: polished black decks that mirror the ceiling light panels,
+light-grey wall panelling with recessed light strips, gunmetal structure, cold
+5600–6500 K light, red and green indicator lights, immense symmetric halls. The
+art direction is "fleet-navy brutalist industrial": militaristic, sterile,
+monumental, ordered. The person is the ship's **commanding officer**; the
+agents are its **officers and crew**; coding panes are **engineering
+technicians**; the pet is the commander's **companion drone**.
+
+Everything is new. Nothing from the previous starship build (code, plans,
+figures, ranks, look) is reused; the old module is deleted.
+
+Legal: no film or franchise name, logo, crest, insignia, typeface, alien script
+or character is copied or named anywhere in the repository. Use generic words
+("fleet", "capital ship", "trooper", "officer"). The ship's emblem is original.
+
+## 2. Camera and framing (fixed)
+
+- Orthographic camera, **pitch 60° below the horizon, yaw 0**: the camera looks
+ toward −Z (three.js) and down. Screen right = +X. Each deck orients its own
+ layout (the bridge faces its viewports at the top of the screen); see
+ LEVELS.md.
+- The ship fills the whole viewport at every zoom. Nothing outside the hull is
+ ever rendered: the area of a deck plate around the rooms is hull structure
+ (frames, conduits, machinery voids, dim maintenance light), never stars.
+ Viewports in the bridge may show a dim star field *inside the window glass*.
+- Pan and zoom only (no orbit). Zoom-out stops where the plate covers the
+ viewport; zoom-in stops at 1.25× the plate's native density.
+- Decks are separate floors stacked in the hull, reached by turbolift. New
+ decks are added as modules without touching the stage.
+- Eye-level view (added 2026-10-20): a deck exported as a realtime 3D scene
+ is walked in third person from behind the commander's shoulder on the
+ full-size stage; the fixed plate camera above stays the bird's-eye view
+ and the compact (IDE panel) view. Contract: docs/verse/realtime.md.
+
+## 3. Rendering technique (fixed)
+
+Hybrid "pre-rendered plate + realtime actors", the technique of the classic
+isometric RPGs, done with a modern path tracer:
+
+1. Each deck is assembled in **Blender** from a modular kit and rendered with
+ **Cycles** (OptiX) through the fixed orthographic camera into a
+ high-resolution **plate** (full GI, glossy reflections, area lights, AO,
+ haze, bloom). This is our "lighting build".
+2. The same cook exports what the runtime needs to put live things *into* that
+ photograph: simplified **occluder** meshes (depth only), a **nav grid**,
+ **sockets** (screens, seats, standing spots, holo emitters, lights, doors,
+ spawn points), **stations**, **rooms**, an **environment map** and
+ **light probes** for the characters.
+3. The web runtime (three.js) draws the plate, writes the occluders into the
+ depth buffer, then draws characters, screens, holograms and light effects in
+ the same world space with the same camera, so they sit inside the picture
+ and disappear correctly behind walls and consoles.
+
+Blender is the level editor, the cook is the build, the browser is the engine.
+
+## 4. Coordinate system and units (fixed)
+
+- Metres. three.js axes: X = screen right, Y = up, Z = toward the camera
+ (screen bottom). Deck floor at Y = 0.
+- Blender axes: X = three X, Y = −(three Z), Z = three Y. The glTF exporter's
+ "+Y up" conversion does this; manifests are always written in **three.js
+ axes**.
+- The plate camera: centre `C`, right vector `R = (1, 0, 0)`, up vector
+ `U = (0, cos 60°, −sin 60°)`, view direction `D = (0, −sin 60°, −cos 60°)`.
+ A world point P maps to plate metres `u = (P−C)·R`, `v = (P−C)·U`.
+- Density: **192 px per metre** along u at full resolution (L0), served as a
+ tile pyramid (L0, mips at 1/2 and 1/4, overview L1 at 1/8).
+
+## 5. Cutaway rules (the look of a section drawing, fixed)
+
+- No ceiling is visible to the camera. Ceilings exist in the Cycles scene with
+ camera visibility off so they still light the room and mirror in the floor.
+- Walls running along X (east–west) that have walkable space on their −Z side
+ (behind them, seen from the camera) are cut at **1.1 m**; the cut face gets
+ the section cap material (dark steel, faint hatching). The outermost −Z hull
+ wall of a deck and any east–west wall with no walkable space behind it stand
+ at full height and show their panelling.
+- Walls running along Z are seen edge-on and may stand at full height.
+- The cut-away parts still exist above the cut as ceiling ghosts (invisible
+ to the plate camera and to shadow rays): they close the rooms for
+ reflections and probes, and the realtime export turns them into real
+ walls, so a deck's rooms are complete at eye level.
+- Consoles face +Z where possible so their screens face the camera (the crew
+ sits on their +Z side and is seen over the shoulder).
+
+## 6. Decks (first release)
+
+| # | id | Name | Purpose in the app |
+|---|---|---|---|
+| 1 | `bridge` | Command Bridge | Agents work at consoles in two sunken crew pits either side of the command walkway; forward viewports; the commander's station at the walkway's end; strategy holo-table; briefing room off the bridge (team rounds). |
+| 2 | `ops` | Operations Deck | Main corridor spine; mess hall (idle crew); crew quarters with bunks (paused agents); quartermaster (the commander's uniform); records hall (service record, rank board); simulator room (the games). |
+| 3 | `engineering` | Reactor Engineering | Reactor shaft with the core column and catwalks; engineering control room whose terminal banks are the coding panes (technicians at live terminals); power conduits. |
+| 4 | `hangar` | Main Hangar | Shuttle on the pad, cargo, gantry crane, control booth; new agents arrive here by shuttle. |
+
+Every deck has a turbolift lobby. Rooms are sized for the real crew: up to 16
+agent consoles on the bridge, 12 terminals in engineering.
+
+## 7. People
+
+- **Commanding officer** (the person): walks where clicked; uniform by rank tier.
+- **Officers and crew** (agents): fleet uniform, colour by rank tier, a personal
+ accent colour from the agent, a name plate; duty status shown by what they do
+ and a small status beacon.
+- **Technicians** (coding panes): black work uniform and helmet at a terminal.
+- **Companion drone** (the pet): a small drone at the commander's heel.
+- **Ship's company** (ambient, not agents): a few patrol troopers and utility
+ drones on fixed rounds, no name plates, never interactive.
+
+One shared human skeleton for all humans (shared animation clips). glTF 2.0
+binary, Y up, metres, origin at the feet, facing +Z.
+
+## 8. Ranks and duty status (new)
+
+Ladder (first level of each rank; the XP curve is unchanged):
+
+| Tier | Ranks |
+|---|---|
+| Deck (enlisted) | Recruit 1 · Deckhand 3 · Technician 5 · Senior Technician 8 |
+| Line (officers) | Ensign 11 · Lieutenant 14 · Senior Lieutenant 17 · Commander 21 · Captain 25 |
+| Command | Line Captain 29 · Commodore 33 |
+| Flag | Rear Admiral 37 · Vice Admiral 41 · Admiral 45 · Fleet Admiral 50 |
+
+Insignia: a chest **rank plate** (original design: a small steel plate with up
+to six inset tiles; tile colour by tier — steel, blue, red, gold). Uniform by
+tier: deck = charcoal work uniform, line = olive-grey tunic with cap, command =
+black tunic with cap, flag = white tunic with cap.
+
+Duty status (from the agent's real run state): **working** (seated at its
+console, typing, screen live), **waiting for you** (stands, turns to you, amber
+beacon), **idle** (seeded off-duty life: mess, corridor, viewports), **paused**
+(in its bunk), **error** (red beacon at its console).
+
+## 9. Production pipeline (see docs/verse/pipeline.md once written)
+
+- Asset naming: `SM_` static mesh, `SK_` skeletal mesh, `A_` animation,
+ `M_`/`MI_` material/instance, `T_` texture (`_BC`, `_N`, `_ORM`), `UCX_`
+ occluder/collision proxy, `SOCKET_` attachment points, `LV_` deck level,
+ `BP_` runtime actor.
+- Source of truth is **code**: Blender Python builders under `art/verse/`
+ (kit pieces, materials, decks, characters). `.blend` files and downloaded
+ textures are derived data in a git-ignored cache and are never committed.
+- Only CC0 third-party textures/HDRIs (e.g. Poly Haven), recorded in a license
+ ledger with URL and hash.
+- Cooked output lives in `dodaios/ui/web/frontend/public/verse/` (plates as
+ AVIF tiles, glb, json). Budget for the whole cooked Verse: **≤ 160 MB**
+ (up to 25 MB of it per deck for the eye-level export, docs/verse/realtime.md),
+ at most 16 MB of plate per deck.
+- Gates: asset validator (names, budgets, sockets, manifest schema), cook
+ reproducibility, runtime checks (draw calls, frame time), visual QA in Chrome
+ against the reference contact sheet.
+- Blender is driven headless for cooks and through the Blender MCP bridge for
+ interactive assembly and viewport checks.
+
+## 10. Quality bar ("photographed, not generated")
+
+- Every hard edge bevelled; no perfectly flat, perfectly clean surface;
+ roughness variation and subtle grime in crevices; real-world scale on
+ everything.
+- Light has a reason: every light source is a fixture you can point at.
+- Restraint: grey, black, white, gunmetal; colour only on indicators, screens
+ and the reactor. No neon, no random glowing lines, no clutter without purpose.
+- Symmetry and rhythm: panel modules, light panels and floor seams on a 1.2 m
+ grid.
diff --git a/art/verse/decks/bridge/build.py b/art/verse/decks/bridge/build.py
index c98564a09a..3b14136fac 100644
--- a/art/verse/decks/bridge/build.py
+++ b/art/verse/decks/bridge/build.py
@@ -8,7 +8,8 @@ room, the turbolift lobby and the commander's ready room.
Layout numbers live in ``layout.py``; the bespoke hero pieces in
``viewport.py`` (forward wall), ``pits.py``, ``hall.py`` and ``aft.py``;
-hull structure in ``fill.py``; ceilings and fixtures in ``lights.py``.
+hull structure in ``fill.py``; ceilings and fixtures in ``lights.py``; the
+upper parts of the cut-away walls (ceiling ghosts) in ``upper.py``.
Kit pieces (consoles, chairs, stairs, rails, hull bays, ceiling panels) come
from ``art/verse/kit``.
@@ -32,7 +33,18 @@ EXPOSURE = 0.0
def _modules():
- names = ("layout", "geo", "panels", "viewport", "hall", "pits", "aft", "fill", "lights")
+ names = (
+ "layout",
+ "geo",
+ "panels",
+ "viewport",
+ "hall",
+ "pits",
+ "aft",
+ "fill",
+ "lights",
+ "upper",
+ )
mods = {}
for name in names:
full = f"decks.bridge.{name}"
@@ -127,6 +139,7 @@ def build() -> None:
m["aft"].build_lobby()
m["aft"].build_ready(use_kit)
m["lights"].build()
+ m["upper"].build()
_waypoints(L)
_rooms(L)
if not use_kit:
diff --git a/art/verse/decks/bridge/upper.py b/art/verse/decks/bridge/upper.py
new file mode 100644
index 0000000000..e5a7b76e33
--- /dev/null
+++ b/art/verse/decks/bridge/upper.py
@@ -0,0 +1,121 @@
+"""The upper parts of the bridge's cut-away walls (BRIEF section 5).
+
+The plate camera sees the aft bulkhead and the aft hull wall cut at 1.1 m.
+Above the cut they still exist as ceiling ghosts: invisible to the plate
+camera and to shadow rays, they close the rooms for floor reflections, the
+environment map, the probes and the realtime (eye-level) export, which turns
+them into normal walls (docs/verse/realtime.md).
+
+Bulkhead: a solid wall from the cut up to the aft rooms' ceiling with door
+heads over the three passages and the lift shafts closed up to the same
+height; above the rooms the hall-side skin runs on up to the hall ceiling.
+Aft wall: closed up to the rooms' ceiling. Faces get the same light-grey
+panelling as the walls below the cut.
+"""
+
+from __future__ import annotations
+
+from lib import kit, scene
+
+from . import layout as L
+
+DOOR_H = 2.7 # passage and lift door head
+SKIN = 0.3 # hall-side skin of the double bulkhead
+PANEL = "M_Wall_PaintedLight"
+BODY = "M_Wall_PaintedMid"
+BAND = "M_Struct_Gunmetal"
+BAND_Z = (3.0, 3.18) # gunmetal band where the room ceilings meet the hall skin
+
+
+def _panels(
+ mb: kit.MeshBuilder, x0: float, x1: float, y_face: float, z0: float, z1: float, sign: int
+) -> None:
+ """Inset light-grey panels on the 1.2 m module standing proud of a face.
+
+ ``sign`` is the face's outward direction along Blender Y (+1 toward
+ Blender +Y, i.e. three -z).
+ """
+ n = max(1, round((x1 - x0) / L.M))
+ step = (x1 - x0) / n
+ y_a, y_b = sorted((y_face, y_face + sign * 0.02))
+ for i in range(n):
+ a, b = x0 + i * step, x0 + (i + 1) * step
+ mb.box((a + 0.006, y_a, z0 + 0.02), (b - 0.006, y_b, z1 - 0.02), PANEL)
+
+
+def _openings() -> list[tuple[float, float, str]]:
+ return [
+ (*L.BRIEF_DOOR_X, "door"),
+ (*L.LIFT_P_X, "lift"),
+ (*L.MAIN_DOOR_X, "door"),
+ (*L.LIFT_S_X, "lift"),
+ (*L.READY_DOOR_X, "door"),
+ ]
+
+
+def _solid_spans(x_lo: float, x_hi: float) -> list[tuple[float, float]]:
+ spans, x = [], x_lo
+ for a, b, _ in _openings():
+ spans.append((x, a))
+ x = b
+ spans.append((x, x_hi))
+ return spans
+
+
+def _bulkhead() -> None:
+ zf, zn = L.BULKHEAD_Z
+ y_hall, y_room = -zf, -zn # Blender Y of the hall face and the room face
+ x_lo, x_hi = L.SIDE_WALL_X[0] - L.SIDE_WALL_T, L.SIDE_WALL_X[1] + L.SIDE_WALL_T
+ body = kit.MeshBuilder()
+ faces = kit.MeshBuilder()
+ for a, b in _solid_spans(x_lo, x_hi):
+ body.box((a, y_room, L.CUT_H), (b, y_hall, L.ROOM_CEILING), BODY)
+ _panels(faces, a, b, y_room, L.CUT_H, L.ROOM_CEILING, -1)
+ _panels(faces, a, b, y_hall, L.CUT_H, BAND_Z[0], 1)
+ for a, b, kind in _openings():
+ # Door head across the whole thickness, with a gunmetal soffit.
+ body.box((a, y_room, DOOR_H), (b, y_hall, L.ROOM_CEILING), BODY)
+ faces.box((a, y_room - 0.01, DOOR_H - 0.03), (b, y_hall + 0.01, DOOR_H), BAND)
+ _panels(faces, a, b, y_room, DOOR_H, L.ROOM_CEILING, -1)
+ _panels(faces, a, b, y_hall, DOOR_H, BAND_Z[0], 1)
+ if kind == "door":
+ # Jambs carry on up to the door head.
+ for x, side in ((a, 1), (b, -1)):
+ j0, j1 = sorted((x, x + side * 0.22))
+ faces.box((j0, y_room + 0.05, L.CUT_H), (j1, y_hall - 0.05, DOOR_H), BAND)
+ else:
+ # Lift shaft walls up to the car ceiling, a lit car ceiling below the head.
+ t = 0.18
+ faces.box((a, y_room, L.CUT_H), (a + t, y_hall, DOOR_H), BODY)
+ faces.box((b - t, y_room, L.CUT_H), (b, y_hall, DOOR_H), BODY)
+ faces.box((a, y_hall - t, L.CUT_H), (b, y_hall, DOOR_H), BODY)
+ for x, side in ((a, 1), (b, -1)):
+ f0, f1 = sorted((x - side * 0.06, x + side * 0.32))
+ faces.box((f0, y_room - 0.08, L.CUT_H), (f1, y_room + 0.12, DOOR_H + 0.02), BAND)
+ # Above the rooms the hall-side skin runs on to the hall ceiling.
+ body.box((x_lo, y_hall - SKIN, L.ROOM_CEILING), (x_hi, y_hall, L.HALL_CEILING), BODY)
+ faces.box((x_lo, y_hall, BAND_Z[0]), (x_hi, y_hall + 0.04, BAND_Z[1]), BAND)
+ _panels(faces, x_lo, x_hi, y_hall, BAND_Z[1], L.HALL_CEILING - 0.3, 1)
+ faces.box(
+ (x_lo, y_hall, L.HALL_CEILING - 0.3), (x_hi, y_hall + 0.03, L.HALL_CEILING), "M_Recess_Dark"
+ )
+ body.build("SM_bulkhead_upper", bevel_width=0.004)
+ faces.build("SM_bulkhead_upper_faces", bevel_width=0.003)
+
+
+def _aft_wall() -> None:
+ zf, zn = L.AFT_WALL_Z
+ x_lo, x_hi = L.SIDE_WALL_X[0] - L.SIDE_WALL_T, L.SIDE_WALL_X[1] + L.SIDE_WALL_T
+ body = kit.MeshBuilder()
+ body.box((x_lo, -zn, L.CUT_H), (x_hi, -zf, L.ROOM_CEILING), BODY)
+ body.build("SM_aftwall_upper", bevel_width=0.004)
+ faces = kit.MeshBuilder()
+ for x0, x1 in (L.BRIEFING_X, L.LOBBY_X, L.READY_X):
+ _panels(faces, x0, x1, -zf, L.CUT_H, L.ROOM_CEILING - 0.1, 1)
+ faces.build("SM_aftwall_upper_faces", bevel_width=0.003)
+
+
+def build() -> None:
+ with kit.into(scene.collection("Ceiling")), kit.ghost(L.CUT_H):
+ _bulkhead()
+ _aft_wall()
diff --git a/art/verse/decks/engineering/build.py b/art/verse/decks/engineering/build.py
index 7fe4d26143..5643d195ba 100644
--- a/art/verse/decks/engineering/build.py
+++ b/art/verse/decks/engineering/build.py
@@ -24,6 +24,7 @@ import eng_common as c # noqa: E402
import eng_reactor # noqa: E402
import eng_rooms # noqa: E402
import eng_sockets # noqa: E402
+import eng_upper # noqa: E402
from lib import scene # noqa: E402
DECK_ID = "engineering"
@@ -43,6 +44,7 @@ def build() -> None:
architecture.load_all()
eng_arch.OCCLUDER_BOXES.clear()
eng_arch.build()
+ eng_upper.build()
eng_reactor.build()
eng_rooms.build()
eng_sockets.build()
diff --git a/art/verse/decks/engineering/eng_upper.py b/art/verse/decks/engineering/eng_upper.py
new file mode 100644
index 0000000000..69fa23890a
--- /dev/null
+++ b/art/verse/decks/engineering/eng_upper.py
@@ -0,0 +1,226 @@
+"""The engineering deck above its section cut: what the plate never shows but
+the eye-level view must (BRIEF section 5, docs/verse/realtime.md).
+
+All of it is built as ceiling ghosts: invisible to the plate camera and to
+shadow rays, it closes the rooms for floor reflections and probes, and the
+realtime export turns it into normal walls.
+
+- Near hull wall: cut at 1.1 m along the lobby, bay and gallery; closed up
+ to the room ceilings with the 1.2 m panelling of the walls below the cut.
+- Reactor hall (12 m) over its lower neighbours: the hall-side skin above
+ the gallery wall (4.5 m) and above the glass partition of the control
+ room run on up to the hall ceiling.
+- Lobby | bay and control | bay: the 0.6 m and 0.3 m slits between a lower
+ wall top and the taller bay ceiling.
+- The hall ceiling's ring opening over the reactor shaft: a ribbed collar
+ rising 4 m into an exhaust plenum with a dark cap.
+- Door heads over the full-height door slots of the lobby | bay and
+ bay | gallery walls.
+
+`cladding()` is ordinary Architecture: the plain walls the plate sees only
+edge-on (the west hull wall, lobby | bay, bay | gallery) get the deck's dark
+panelling with a rail, a recessed top and thin light strips, so at eye level
+they are no longer flat light-grey slabs.
+"""
+
+from __future__ import annotations
+
+import eng_common as c
+from eng_common import Geo, build_into
+from lib import kit
+
+WALL_DARK = "M_Wall_PaintedDark"
+CHARCOAL = "M_Wall_Charcoal"
+STRIP = "M_Light_WallStrip"
+STRIP_EVERY = 4 # a vertical light strip after every this many 1.2 m panels
+DOOR_HEAD = 2.7
+GUNMETAL = "M_Struct_Gunmetal"
+RECESS = "M_Recess_Dark"
+HULL = "M_Hull_Structure"
+CEILING = "M_Ceiling_Panel"
+PANEL_INSET = 0.02 # panels stand this far proud of the wall face
+PLENUM_H = 4.0 # height of the exhaust plenum over the shaft opening
+OPENING_R = c.SHAFT_R + 1.0 # radius of the hall ceiling's opening
+
+
+def _panel_mat(i: int) -> str:
+ """Panels alternate dark paint and charcoal enamel, so a long run reads
+ as panelling (and catches the light differently), never as one slab."""
+ return CHARCOAL if i % 3 == 1 else WALL_DARK
+
+
+def _panels_x(geo: Geo, x0: float, x1: float, z_face: float, y0: float, y1: float,
+ toward: int, lights: Geo | None = None) -> None: # fmt: skip
+ """1.2 m panels on a wall face at three z = `z_face` facing `toward` (+1/-1 in z);
+ with `lights`, a thin vertical light strip every `STRIP_EVERY` panels."""
+ n = max(1, round((x1 - x0) / c.MODULE))
+ step = (x1 - x0) / n
+ za, zb = sorted((z_face, z_face + toward * PANEL_INSET))
+ for i in range(n):
+ a, b = x0 + i * step, x0 + (i + 1) * step
+ geo.box3(a + 0.008, b - 0.008, za, zb, y0 + 0.02, y1 - 0.02, _panel_mat(i))
+ if lights is not None and i > 0 and i % STRIP_EVERY == 0:
+ la, lb = sorted((z_face, z_face + toward * (PANEL_INSET + 0.006)))
+ lights.box3(a - 0.02, a + 0.02, la, lb, y0 + 0.25, y1 - 0.25, STRIP)
+
+
+def _panels_z(geo: Geo, z0: float, z1: float, x_face: float, y0: float, y1: float,
+ toward: int, lights: Geo | None = None) -> None: # fmt: skip
+ """1.2 m panels on a wall face at three x = `x_face` facing `toward` (+1/-1 in x);
+ with `lights`, a thin vertical light strip every `STRIP_EVERY` panels."""
+ n = max(1, round((z1 - z0) / c.MODULE))
+ step = (z1 - z0) / n
+ xa, xb = sorted((x_face, x_face + toward * PANEL_INSET))
+ for i in range(n):
+ a, b = z0 + i * step, z0 + (i + 1) * step
+ geo.box3(xa, xb, a + 0.008, b - 0.008, y0 + 0.02, y1 - 0.02, _panel_mat(i))
+ if lights is not None and i > 0 and i % STRIP_EVERY == 0:
+ la, lb = sorted((x_face, x_face + toward * (PANEL_INSET + 0.006)))
+ lights.box3(la, lb, a - 0.02, a + 0.02, y0 + 0.25, y1 - 0.25, STRIP)
+
+
+def near_wall() -> None:
+ """The near hull wall above the cut, room face at z = SOUTH_HULL_Z[0] facing -z."""
+ z_face, z_back = c.SOUTH_HULL_Z[0], c.SOUTH_HULL_Z[0] + 0.3
+ x_in, x_out = c.WEST_HULL_X[1] - 0.3, c.EAST_HULL_X[0] + 0.3
+ top = max(c.GALLERY_H, c.BAY_H, c.LOBBY_H) + 0.1
+ body, faces, lights = Geo(), Geo(), Geo()
+ body.box3(x_in, x_out, z_face, z_back, c.CUT_H, top, WALL_DARK)
+ rooms = (
+ (c.LOBBY[0], c.LOBBY[1], c.LOBBY_H),
+ (c.BAY[0], c.BAY[1], c.BAY_H),
+ (c.GALLERY[0], c.GALLERY[1], c.GALLERY_H),
+ )
+ for x0, x1, height in rooms:
+ # A gunmetal rail at the cut line ties the panels to the wall below.
+ faces.box3(x0, x1, z_face - 0.04, z_face, c.CUT_H, c.CUT_H + 0.12, GUNMETAL)
+ _panels_x(faces, x0, x1, z_face, c.CUT_H + 0.12, height - 0.35, -1, lights)
+ faces.box3(x0, x1, z_face - 0.03, z_face, height - 0.35, height, RECESS)
+ build_into("Ceiling", body, "SM_Eng_NearWallUpper", bevel_width=0.004)
+ build_into("Ceiling", faces, "SM_Eng_NearWallUpperFaces", bevel_width=0.003)
+ build_into("Ceiling", lights, "SM_Eng_NearWallUpperStrips", bevel_width=0.0)
+
+
+def hall_skins() -> None:
+ """The reactor hall's walls above its lower neighbours, up to the hall ceiling."""
+ body, faces = Geo(), Geo()
+ # Over the gallery wall: hall face at z = GALLERY_NORTH_Z[0], facing -z.
+ z_face, z_back = c.GALLERY_NORTH_Z
+ x0, x1 = c.PARTITION_X[1], c.EAST_HULL_X[0]
+ y0 = c.CONTROL_H - 0.1 # the kit wall's ghost ends at its 4.5 m height
+ body.box3(x0, x1, z_face, z_back, y0, c.HALL_H, WALL_DARK)
+ faces.box3(x0, x1, z_face - 0.05, z_face, y0, y0 + 0.3, GUNMETAL)
+ _panels_x(faces, x0, x1, z_face, y0 + 0.3, c.HALL_H - 0.6, -1)
+ faces.box3(x0, x1, z_face - 0.03, z_face, c.HALL_H - 0.6, c.HALL_H, RECESS)
+ # Over the glass partition: hall face at x = PARTITION_X[1], facing +x.
+ xa, xb = c.PARTITION_X
+ z0, z1 = c.FAR_WALL_Z, c.GALLERY_NORTH_Z[1]
+ body.box3(xa, xb, z0, z1, c.CONTROL_H, c.HALL_H, WALL_DARK)
+ faces.box3(xb, xb + 0.05, z0, z1, c.CONTROL_H, c.CONTROL_H + 0.3, GUNMETAL)
+ _panels_z(faces, z0, z1, xb, c.CONTROL_H + 0.3, c.HALL_H - 0.6, 1)
+ faces.box3(xb, xb + 0.03, z0, z1, c.HALL_H - 0.6, c.HALL_H, RECESS)
+ build_into("Ceiling", body, "SM_Eng_HallSkins", bevel_width=0.004)
+ build_into("Ceiling", faces, "SM_Eng_HallSkinFaces", bevel_width=0.003)
+
+
+def slits() -> None:
+ """Close the gaps between lower wall tops and the bay's taller ceiling."""
+ geo = Geo()
+ xa, xb = c.LOBBY_BAY_X
+ geo.box3(xa, xb, c.CONTROL_SOUTH_Z[1], c.SOUTH_HULL_Z[0], c.LOBBY_H - 0.1, c.BAY_H + 0.1,
+ WALL_DARK) # fmt: skip
+ za, zb = c.CONTROL_SOUTH_Z
+ geo.box3(c.LOBBY_BAY_X[0], c.BAY_GALLERY_X[0], za, zb, c.CONTROL_H - 0.1, c.BAY_H + 0.1,
+ WALL_DARK) # fmt: skip
+ build_into("Ceiling", geo, "SM_Eng_WallTops", bevel_width=0.0)
+
+
+def shaft_plenum() -> None:
+ """A ribbed collar over the ceiling's ring opening and a dark plenum cap."""
+ geo = Geo()
+ top = c.HALL_H + PLENUM_H
+ geo.sector(OPENING_R, OPENING_R + 0.4, c.HALL_H, top, HULL, segments=96)
+ for k in range(24):
+ a = k * 15.0
+ geo.sector(OPENING_R - 0.35, OPENING_R, c.HALL_H + 0.2, top, GUNMETAL,
+ a0=a - 0.9, a1=a + 0.9, segments=2) # fmt: skip
+ for y in (c.HALL_H + 0.3, c.HALL_H + 2.0, top - 0.4):
+ geo.sector(OPENING_R - 0.45, OPENING_R, y, y + 0.22, GUNMETAL, segments=96)
+ geo.sector(0.0, OPENING_R + 0.4, top, top + 0.3, CEILING, segments=96)
+ geo.sector(0.0, c.CORE_R + 1.5, top - 0.6, top, RECESS, segments=64)
+ build_into("Ceiling", geo, "SM_Eng_ShaftPlenum", bevel_width=0.0)
+
+
+def _door_gaps(z0: float, z1: float, doors: list[float]) -> list[tuple[float, float]]:
+ """The wall spans between door slots (`_cut_wall_z`'s gaps) along z."""
+ edges = [z0]
+ for d in sorted(doors):
+ edges += [d - c.DOOR_W / 2, d + c.DOOR_W / 2]
+ edges.append(z1)
+ return [(a, b) for a, b in zip(edges[0::2], edges[1::2], strict=True) if b - a > 0.05]
+
+
+# The full-height north-south walls: (x range, z range, height, door centres on z).
+Z_WALLS = (
+ (c.LOBBY_BAY_X, (c.CONTROL_SOUTH_Z[1], c.SOUTH_HULL_Z[0]), c.LOBBY_H, [c.DOOR_LOBBY_BAY]),
+ (c.BAY_GALLERY_X, (c.CONTROL_SOUTH_Z[0], c.SOUTH_HULL_Z[0]), c.GALLERY_H,
+ [c.DOOR_BAY_GALLERY]),
+) # fmt: skip
+
+
+def door_heads() -> None:
+ """Heads over the door slots of the full-height walls, from the door
+ height up to the wall top, with a gunmetal lintel and jambs."""
+ body, trim = Geo(), Geo()
+ for (xa, xb), _, height, doors in Z_WALLS:
+ for d in doors:
+ a, b = d - c.DOOR_W / 2, d + c.DOOR_W / 2
+ body.box3(xa, xb, a, b, DOOR_HEAD, height, WALL_DARK)
+ trim.box3(xa - 0.06, xb + 0.06, a - 0.16, b + 0.16, DOOR_HEAD - 0.12, DOOR_HEAD,
+ GUNMETAL) # fmt: skip
+ for z in (a, b - 0.16):
+ trim.box3(xa - 0.06, xb + 0.06, z, z + 0.16, c.CUT_H, DOOR_HEAD, GUNMETAL)
+ build_into("Ceiling", body, "SM_Eng_DoorHeads", bevel_width=0.004)
+ build_into("Ceiling", trim, "SM_Eng_DoorHeadTrim", bevel_width=0.006)
+
+
+def _clad_z(faces: Geo, lights: Geo, x_face: float, toward: int, z0: float, z1: float,
+ height: float) -> None: # fmt: skip
+ """Kick plate, lower panels, rail, upper panels with strips and a recessed
+ top on a wall face at x = `x_face` facing `toward`."""
+ xa, xb = sorted((x_face, x_face + toward * 0.03))
+ faces.box3(xa, xb, z0, z1, 0.0, 0.15, RECESS)
+ _panels_z(faces, z0, z1, x_face, 0.15, c.CUT_H, toward)
+ xa, xb = sorted((x_face, x_face + toward * 0.05))
+ faces.box3(xa, xb, z0, z1, c.CUT_H, c.CUT_H + 0.12, GUNMETAL)
+ _panels_z(faces, z0, z1, x_face, c.CUT_H + 0.12, height - 0.35, toward, lights)
+ xa, xb = sorted((x_face, x_face + toward * 0.03))
+ faces.box3(xa, xb, z0, z1, height - 0.35, height, RECESS)
+
+
+def cladding() -> None:
+ """Panelling on the plain walls the plate sees only edge-on (Architecture)."""
+ faces, lights = Geo(), Geo()
+ # West hull wall: control room and lobby (the lift core lies between them).
+ x_face = c.WEST_HULL_X[1]
+ _clad_z(faces, lights, x_face, 1, c.FAR_WALL_Z + 0.3, c.LIFT_CORE_Z[0], c.CONTROL_H)
+ _clad_z(faces, lights, x_face, 1, c.CONTROL_SOUTH_Z[1], c.SOUTH_HULL_Z[0], c.LOBBY_H)
+ # Both faces of the lobby | bay and bay | gallery walls, around their doors.
+ for (xa, xb), (z0, z1), height, doors in Z_WALLS:
+ for a, b in _door_gaps(z0, z1, doors):
+ _clad_z(faces, lights, xa, -1, a, b, height)
+ _clad_z(faces, lights, xb, 1, a, b, height)
+ obj = build_into("Architecture", faces, "SM_Eng_WallCladding", bevel_width=0.003)
+ kit.tag(obj, nav="none")
+ obj = build_into("Architecture", lights, "SM_Eng_WallCladdingStrips", bevel_width=0.0)
+ kit.tag(obj, nav="none")
+
+
+def build() -> None:
+ cladding()
+ with kit.ghost(c.CUT_H):
+ near_wall()
+ hall_skins()
+ slits()
+ shaft_plenum()
+ door_heads()
diff --git a/art/verse/decks/hangar/build.py b/art/verse/decks/hangar/build.py
index da569cf636..c9f4b06203 100644
--- a/art/verse/decks/hangar/build.py
+++ b/art/verse/decks/hangar/build.py
@@ -28,6 +28,7 @@ import hangar_arch as arch # noqa: E402
import hangar_layout as L # noqa: E402
import hangar_light as light # noqa: E402
import hangar_props as props # noqa: E402
+import hangar_upper as upper # noqa: E402
from lib import kit, scene # noqa: E402
B = L.B
@@ -158,6 +159,7 @@ def build() -> None:
arch.launch_well(well_piece=well_piece)
arch.front_band()
arch.ceiling()
+ upper.build()
arch.occluders(well_piece=well_piece)
props.build_all()
light.build(mounts)
diff --git a/art/verse/decks/hangar/hangar_upper.py b/art/verse/decks/hangar/hangar_upper.py
new file mode 100644
index 0000000000..847ebe4244
--- /dev/null
+++ b/art/verse/decks/hangar/hangar_upper.py
@@ -0,0 +1,195 @@
+"""The hangar above its section cuts: what the plate never shows but the
+eye-level view must (BRIEF section 5, docs/verse/realtime.md).
+
+All of it is built as ceiling ghosts: invisible to the plate camera and to
+shadow rays, it closes the rooms for floor reflections and probes, and the
+realtime export turns it into normal walls.
+
+- Side hull walls over the flight deck: cut at 4.5 m; closed up to the 21 m
+ ceiling with hull frames on the ceiling girders' 7.2 m rhythm.
+- Front skin: the hangar's near wall above the front band's 4.7 m ceiling,
+ from the band's ceiling edge up to the hangar ceiling.
+- Front band (booth, crew bay, arrivals, lift lobby, armoury): the near hull
+ wall, the side walls and the room walls cut at 1.1 m, closed up to the
+ band ceiling, with door heads over the openings and the booth's window
+ wall glazed up to its head.
+
+The front band's upper walls are dark paint and charcoal enamel panels over
+a gunmetal rail at the cut, with thin light strips: the mid-grey wainscot
+below the cut stays as the plate shows it, and at eye level the rooms read
+as panelled walls instead of flat light-grey slabs.
+"""
+
+from __future__ import annotations
+
+import hangar_arch as arch
+import hangar_layout as L
+from hangar_arch import CEILING_H, HULL, PANEL_DARK, PANEL_MID, RECESS, STEEL, box
+from lib import kit
+
+BAND_CEILING = 4.7 # underside of the front band's ceiling slab
+DOOR_HEAD = 2.7
+PANEL_INSET = 0.02
+GLASS = "M_Glass_Viewport"
+CHARCOAL = "M_Wall_Charcoal"
+STRIP = "M_Light_WallStrip"
+STRIP_EVERY = 4 # a vertical light strip after every this many panels
+
+
+def _panel_mat(i: int, mat: str | None) -> str:
+ """`mat`, or dark paint alternating with charcoal enamel."""
+ if mat is not None:
+ return mat
+ return CHARCOAL if i % 3 == 1 else PANEL_DARK
+
+
+def _panels_x(mb: kit.MeshBuilder, x0, x1, z_face, h0, h1, toward, module=1.2, mat=None,
+ lights=None): # fmt: skip
+ """Inset panels on a face at plan z = z_face facing `toward` (+1 = toward +z);
+ with `lights`, a thin vertical light strip every `STRIP_EVERY` panels."""
+ n = max(1, round((x1 - x0) / module))
+ step = (x1 - x0) / n
+ za, zb = sorted((z_face, z_face + toward * PANEL_INSET))
+ la, lb = sorted((z_face, z_face + toward * (PANEL_INSET + 0.006)))
+ for i in range(n):
+ a, b = x0 + i * step, x0 + (i + 1) * step
+ box(mb, a + 0.008, b - 0.008, za, zb, h0 + 0.02, h1 - 0.02, _panel_mat(i, mat))
+ if lights is not None and i > 0 and i % STRIP_EVERY == 0:
+ box(lights, a - 0.02, a + 0.02, la, lb, h0 + 0.25, h1 - 0.25, STRIP)
+
+
+def _panels_z(mb: kit.MeshBuilder, z0, z1, x_face, h0, h1, toward, module=1.2, mat=None,
+ lights=None): # fmt: skip
+ """Inset panels on a face at plan x = x_face facing `toward` (+1 = toward +x);
+ with `lights`, a thin vertical light strip every `STRIP_EVERY` panels."""
+ n = max(1, round((z1 - z0) / module))
+ step = (z1 - z0) / n
+ xa, xb = sorted((x_face, x_face + toward * PANEL_INSET))
+ la, lb = sorted((x_face, x_face + toward * (PANEL_INSET + 0.006)))
+ for i in range(n):
+ a, b = z0 + i * step, z0 + (i + 1) * step
+ box(mb, xa, xb, a + 0.008, b - 0.008, h0 + 0.02, h1 - 0.02, _panel_mat(i, mat))
+ if lights is not None and i > 0 and i % STRIP_EVERY == 0:
+ box(lights, la, lb, a - 0.02, a + 0.02, h0 + 0.25, h1 - 0.25, STRIP)
+
+
+def _band_face_z(faces, lights, x_face, toward, z0, z1, h0, top):
+ """Rail at the cut, panels with strips, recessed top on a face at plan x = x_face."""
+ lo, hi = sorted((x_face, x_face + toward * 0.05))
+ box(faces, lo, hi, z0, z1, h0, h0 + 0.12, STEEL)
+ _panels_z(faces, z0, z1, x_face, h0 + 0.12, top - 0.3, toward, lights=lights)
+ lo, hi = sorted((x_face, x_face + toward * 0.03))
+ box(faces, lo, hi, z0, z1, top - 0.3, top, RECESS)
+
+
+def side_walls() -> None:
+ """Side hull walls from their 4.5 m cut up to the ceiling, over the flight deck."""
+ body, faces = kit.MeshBuilder(), kit.MeshBuilder()
+ top = CEILING_H + 0.4
+ girders = [3.6 + 7.2 * i for i in range(7)]
+ for x0, x1, x_face, s in (
+ (-2.0, L.SIDE_T, L.SIDE_T, 1),
+ (L.WIDTH - L.SIDE_T, L.WIDTH + 2.0, L.WIDTH - L.SIDE_T, -1),
+ ):
+ box(body, x0, x1, 0.0, L.FRONT_Z, arch.SIDE_CUT_H, top, HULL)
+ # Panels between the frames, in three tiers split by gunmetal bands.
+ edges = [L.WALL_FACE_Z, *girders, L.FRONT_Z]
+ for a, b in zip(edges, edges[1:], strict=False):
+ for h0, h1 in ((arch.SIDE_CUT_H, 9.6), (9.9, 15.0), (15.3, CEILING_H - 1.6)):
+ _panels_z(faces, a + 0.45, b - 0.45, x_face, h0, h1, s, module=2.4, mat=PANEL_MID)
+ for h in (arch.SIDE_CUT_H, 9.6, 15.0):
+ lo, hi = sorted((x_face, x_face + s * 0.12))
+ box(faces, lo, hi, L.WALL_FACE_Z, L.FRONT_Z, h, h + 0.3, STEEL)
+ # Frames: deep I-section posts under every ceiling girder.
+ for z in girders:
+ lo, hi = sorted((x_face, x_face + s * 0.6))
+ box(faces, lo, hi, z - 0.4, z + 0.4, arch.SIDE_CUT_H, CEILING_H, STEEL)
+ lo, hi = sorted((x_face + s * 0.6, x_face + s * 0.7))
+ box(faces, lo, hi, z - 0.25, z + 0.25, arch.SIDE_CUT_H, CEILING_H, STEEL)
+ arch._build(body, "SM_Hangar_SideWallsUpper", bevel=0.0, collection="Ceiling")
+ arch._build(faces, "SM_Hangar_SideWallsUpperFaces", bevel=0.004, collection="Ceiling")
+
+
+def front_skin() -> None:
+ """The hangar's near wall above the front band, facing the flight deck."""
+ body, faces = kit.MeshBuilder(), kit.MeshBuilder()
+ z_face = L.FRONT_Z
+ top = CEILING_H + 0.4
+ box(body, -2.0, L.WIDTH + 2.0, z_face, z_face + 0.3, BAND_CEILING, top, HULL)
+ # A deep fascia over the band's ceiling edge, then panels between frames.
+ box(faces, L.SIDE_T, L.WIDTH - L.SIDE_T, z_face - 0.3, z_face, BAND_CEILING - 0.05, 5.6, STEEL)
+ posts = [2.4 + 7.2 * i for i in range(14)]
+ edges = [L.SIDE_T, *[x for x in posts if L.SIDE_T < x < L.WIDTH - L.SIDE_T], L.WIDTH - L.SIDE_T]
+ for a, b in zip(edges, edges[1:], strict=False):
+ for h0, h1 in ((5.6, 9.6), (9.9, 15.0), (15.3, CEILING_H - 1.6)):
+ _panels_x(faces, a + 0.4, b - 0.4, z_face, h0, h1, -1, module=2.4, mat=PANEL_MID)
+ for h in (9.6, 15.0):
+ box(faces, L.SIDE_T, L.WIDTH - L.SIDE_T, z_face - 0.12, z_face, h, h + 0.3, STEEL)
+ for x in posts:
+ if L.SIDE_T < x < L.WIDTH - L.SIDE_T:
+ box(faces, x - 0.3, x + 0.3, z_face - 0.6, z_face, 5.6, CEILING_H, STEEL)
+ arch._build(body, "SM_Hangar_FrontSkin", bevel=0.0, collection="Ceiling")
+ arch._build(faces, "SM_Hangar_FrontSkinFaces", bevel=0.004, collection="Ceiling")
+
+
+def front_band() -> None:
+ """The front band's cut walls closed up to the band ceiling."""
+ cut = L.CUT_H
+ nz0, nz1 = L.NEAR_WALL_Z
+ body, faces, lights = kit.MeshBuilder(), kit.MeshBuilder(), kit.MeshBuilder()
+ # Near hull wall, room face at nz0 facing -z.
+ box(body, -2.0, L.WIDTH + 2.0, nz0, nz1, cut, BAND_CEILING + 0.3, PANEL_DARK)
+ box(faces, L.SIDE_T, L.WIDTH - L.SIDE_T, nz0 - 0.04, nz0, cut, cut + 0.12, STEEL)
+ _panels_x(faces, L.SIDE_T, L.WIDTH - L.SIDE_T, nz0, cut + 0.12, BAND_CEILING - 0.3, -1,
+ lights=lights) # fmt: skip
+ box(faces, L.SIDE_T, L.WIDTH - L.SIDE_T, nz0 - 0.03, nz0, BAND_CEILING - 0.3, BAND_CEILING,
+ RECESS) # fmt: skip
+ # Side walls in the band.
+ for x0, x1, x_face, s in (
+ (-2.0, L.SIDE_T, L.SIDE_T, 1),
+ (L.WIDTH - L.SIDE_T, L.WIDTH + 2.0, L.WIDTH - L.SIDE_T, -1),
+ ):
+ box(body, x0, x1, L.FRONT_Z, nz1, cut, BAND_CEILING + 0.3, PANEL_DARK)
+ _band_face_z(faces, lights, x_face, s, L.FRONT_Z, nz0, cut, BAND_CEILING)
+ # Booth: window wall glazed up to its head, side walls up to the ceiling.
+ bx0, bx1, bz0, _ = L.BOOTH
+ bf = L.BOOTH_FLOOR
+ head = BAND_CEILING - 0.35
+ box(body, bx0, bx1, bz0, bz0 + 0.35, head, BAND_CEILING, PANEL_DARK)
+ box(faces, bx0 + 0.3, bx1 - 0.3, bz0 + 0.12, bz0 + 0.2, bf + cut, head, GLASS)
+ for x in [bx0 + 0.3 + i * 2.4 for i in range(10)]:
+ box(faces, x - 0.06, x + 0.06, bz0 + 0.05, bz0 + 0.3, bf + cut, head, STEEL)
+ box(body, bx0, bx0 + 0.3, bz0, nz0, bf + cut, BAND_CEILING, PANEL_DARK)
+ box(body, bx1 - 0.3, bx1, bz0, 53.4, bf + cut, BAND_CEILING, PANEL_DARK)
+ box(body, bx1 - 0.3, bx1, 57.6, nz0, bf + cut, BAND_CEILING, PANEL_DARK)
+ box(body, bx1 - 0.3, bx1, 53.4, 57.6, bf + DOOR_HEAD - 0.3, BAND_CEILING, PANEL_DARK)
+ # The booth's east wall, crew bay side (the floor there is 1.2 m lower).
+ for z0, z1 in ((bz0, 53.4), (57.6, nz0)):
+ _band_face_z(faces, lights, bx1, 1, z0, z1, bf + cut, BAND_CEILING)
+ box(faces, bx1 - 0.35, bx1 + 0.05, 53.4, 57.6, bf + DOOR_HEAD - 0.36, bf + DOOR_HEAD - 0.3,
+ STEEL) # fmt: skip
+ # Armoury: north wall with its door head, west wall.
+ ax0, ax1, az0, _ = L.ARMOURY
+ for xa, xb in ((ax0, 78.6), (81.2, ax1)):
+ box(body, xa, xb, az0, az0 + 0.3, cut, BAND_CEILING, PANEL_DARK)
+ _panels_x(faces, xa, xb, az0, cut, BAND_CEILING - 0.3, -1)
+ box(body, 78.6, 81.2, az0, az0 + 0.3, DOOR_HEAD, BAND_CEILING, PANEL_DARK)
+ box(faces, 78.6, 81.2, az0 - 0.01, az0 + 0.31, DOOR_HEAD - 0.04, DOOR_HEAD, STEEL)
+ box(body, ax0, ax0 + 0.3, az0, nz0, cut, BAND_CEILING, PANEL_DARK)
+ _band_face_z(faces, lights, ax0, -1, az0, nz0, cut, BAND_CEILING) # lift lobby side
+ _band_face_z(faces, lights, ax0 + 0.3, 1, az0 + 0.3, nz0, cut, BAND_CEILING) # armoury side
+ # Lift lobby | arrivals divider.
+ x0, x1 = L.LOBBY[0] - 0.15, L.LOBBY[0] + 0.15
+ box(body, x0, x1, 52.8, nz0, cut, BAND_CEILING, PANEL_DARK)
+ _band_face_z(faces, lights, x0, -1, 52.8, nz0, cut, BAND_CEILING)
+ _band_face_z(faces, lights, x1, 1, 52.8, nz0, cut, BAND_CEILING)
+ arch._build(body, "SM_Hangar_FrontBandUpper", bevel=0.004, collection="Ceiling")
+ arch._build(faces, "SM_Hangar_FrontBandUpperFaces", bevel=0.003, collection="Ceiling")
+ arch._build(lights, "SM_Hangar_FrontBandUpperStrips", bevel=0.0, collection="Ceiling")
+
+
+def build() -> None:
+ with kit.ghost(L.CUT_H):
+ side_walls()
+ front_skin()
+ front_band()
diff --git a/art/verse/lib/lightmap.py b/art/verse/lib/lightmap.py
new file mode 100644
index 0000000000..f3d0e83d6d
--- /dev/null
+++ b/art/verse/lib/lightmap.py
@@ -0,0 +1,238 @@
+"""Lightmap atlas helpers for the realtime export (pure numpy, no bpy).
+
+Used inside Blender by `lib.realtime` (packing, denoising, gap filling) and
+outside it by `scripts/verse/package_realtime.py` (RGBM encoding) and the
+tests. Format details: docs/verse/realtime.md.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+
+import numpy as np
+
+# ---------------------------------------------------------------- packing
+
+
+@dataclass(frozen=True)
+class Placement:
+ page: int
+ x: int # texel of the rectangle's inner (unpadded) left edge
+ y: int # texel of the inner top edge, row 0 at the top
+ scale: float # 1, or < 1 when the rectangle had to shrink to fit a page
+
+
+def pack_skyline(
+ sizes: list[tuple[float, float]],
+ groups: list[int],
+ page_px: int,
+ pad: int,
+) -> list[Placement]:
+ """Place rectangles (w, h in texels) on square pages, skyline bottom-left.
+
+ Rectangles are taken by group (a room), the tallest first within a
+ group, so a room's surfaces share as few pages as possible. Each drops
+ to the lowest spot on a page's skyline that fits it, on the first page
+ with room for it (small ones fill holes on earlier pages): rectangles of
+ very different sizes (a 1600 texel floor next to key banks) fill about
+ 80 % of the pages, shelf packing about half. Every rectangle keeps `pad`
+ free texels on each side (neighbours are at least 2 * pad apart). A
+ rectangle larger than a page is shrunk to fit.
+ """
+ order = sorted(range(len(sizes)), key=lambda i: (groups[i], -sizes[i][1], -sizes[i][0]))
+ placements: list[Placement | None] = [None] * len(sizes)
+ usable = page_px - 2 * pad
+ skylines: list[list[list[int]]] = [] # per page: segments [x, top, width]
+ for i in order:
+ w, h = sizes[i]
+ scale = min(1.0, usable / max(w, h, 1e-9))
+ cw = math.ceil(w * scale) + 2 * pad
+ ch = math.ceil(h * scale) + 2 * pad
+ spot = None
+ for page, skyline in enumerate(skylines):
+ spot = _skyline_spot(skyline, cw, ch, page_px)
+ if spot is not None:
+ spot = (page, *spot)
+ break
+ if spot is None:
+ skylines.append([[0, 0, page_px]])
+ spot = (len(skylines) - 1, 0, 0)
+ page, x, y = spot
+ _skyline_add(skylines[page], x, y + ch, cw)
+ placements[i] = Placement(page, x + pad, y + pad, scale)
+ return [p for p in placements if p is not None]
+
+
+def _skyline_spot(
+ skyline: list[list[int]], cw: int, ch: int, page_px: int
+) -> tuple[int, int] | None:
+ """Lowest (then leftmost) (x, y) on the skyline where a cw x ch rectangle fits."""
+ best = None
+ for start in range(len(skyline)):
+ x = skyline[start][0]
+ if x + cw > page_px:
+ break
+ y, reach, k = 0, x, start
+ while reach < x + cw:
+ y = max(y, skyline[k][1])
+ reach = skyline[k][0] + skyline[k][2]
+ k += 1
+ if y + ch <= page_px and (best is None or (y + ch, x) < (best[1] + ch, best[0])):
+ best = (x, y)
+ return best
+
+
+def _skyline_add(skyline: list[list[int]], x: int, top: int, cw: int) -> None:
+ """Raise the skyline to `top` over [x, x + cw) and merge equal neighbours."""
+ end = x + cw
+ out: list[list[int]] = []
+ for sx, sy, sw in skyline:
+ se = sx + sw
+ if se <= x or sx >= end:
+ out.append([sx, sy, sw])
+ continue
+ if sx < x:
+ out.append([sx, sy, x - sx])
+ if se > end:
+ out.append([end, sy, se - end])
+ out.append([x, top, cw])
+ out.sort()
+ merged: list[list[int]] = []
+ for segment in out:
+ if merged and merged[-1][1] == segment[1] and merged[-1][0] + merged[-1][2] == segment[0]:
+ merged[-1][2] += segment[2]
+ else:
+ merged.append(segment)
+ skyline[:] = merged
+
+
+# ---------------------------------------------------------------- denoising
+
+DENOISE_BAND = 512 # rows per band (memory: ~1 GB peak on a 4096 px page)
+
+
+def denoise(
+ irradiance: np.ndarray,
+ normal: np.ndarray,
+ position: np.ndarray,
+ covered: np.ndarray,
+ texel_m: float,
+ passes: int,
+) -> np.ndarray:
+ """Edge-aware a-trous filter of baked irradiance (h, w, 3).
+
+ Guided by the baked normal and world position, so light never bleeds
+ across a corner, between islands or between surfaces that are far apart
+ in the world; uncovered texels neither contribute nor change. Steps 1,
+ 2, 4 ... texels, processed in bands of rows with a halo.
+ """
+ result = irradiance.astype(np.float32)
+ weight_of = covered.astype(np.float32)
+ height = result.shape[0]
+ for level in range(passes):
+ step = 1 << level
+ halo = 2 * step
+ out = result.copy()
+ for row0 in range(0, height, DENOISE_BAND):
+ row1 = min(height, row0 + DENOISE_BAND)
+ a, b = max(0, row0 - halo), min(height, row1 + halo)
+ band = _atrous(result[a:b], normal[a:b], position[a:b], weight_of[a:b], step, texel_m)
+ out[row0:row1] = band[row0 - a : row0 - a + (row1 - row0)]
+ result = out
+ return result
+
+
+def _atrous(
+ value: np.ndarray,
+ normal: np.ndarray,
+ position: np.ndarray,
+ covered: np.ndarray,
+ step: int,
+ texel_m: float,
+) -> np.ndarray:
+ kernel = (1 / 16, 1 / 4, 3 / 8, 1 / 4, 1 / 16)
+ sigma2 = 2.0 * (2.5 * texel_m) ** 2 * step
+ h, w = value.shape[:2]
+ pad = 2 * step
+
+ def padded(a: np.ndarray) -> np.ndarray:
+ widths = ((pad, pad), (pad, pad)) + ((0, 0),) * (a.ndim - 2)
+ return np.pad(a, widths, mode="edge")
+
+ pv, pn, pp, pc = padded(value), padded(normal), padded(position), padded(covered)
+ total = np.zeros_like(value)
+ weights = np.zeros((h, w), dtype=np.float32)
+ for dy, ky in zip(range(-2, 3), kernel, strict=True):
+ for dx, kx in zip(range(-2, 3), kernel, strict=True):
+ rows = slice(pad + dy * step, pad + dy * step + h)
+ cols = slice(pad + dx * step, pad + dx * step + w)
+ dn = np.einsum("ijk,ijk->ij", normal, pn[rows, cols])
+ np.clip(dn, 0.0, 1.0, out=dn)
+ dn **= 32
+ diff = position - pp[rows, cols]
+ dp = np.einsum("ijk,ijk->ij", diff, diff)
+ wgt = (ky * kx) * pc[rows, cols] * dn * np.exp(-dp / sigma2)
+ total += pv[rows, cols] * wgt[..., None]
+ weights += wgt
+ filtered = total / np.maximum(weights, 1e-6)[..., None]
+ keep = (weights > 1e-6) & (covered > 0)
+ return np.where(keep[..., None], filtered, value)
+
+
+def fill_gaps(image: np.ndarray, covered: np.ndarray) -> np.ndarray:
+ """Push-pull fill of uncovered texels from covered ones (smooth, for mips
+ and compression); covered texels are unchanged."""
+ levels = [(image * covered[..., None], covered.astype(np.float32))]
+ while min(levels[-1][1].shape) > 1:
+ colour, weight = levels[-1]
+ h, w = weight.shape
+ h2, w2 = (h + 1) // 2, (w + 1) // 2
+ c = np.zeros((h2 * 2, w2 * 2, colour.shape[2]), dtype=np.float32)
+ k = np.zeros((h2 * 2, w2 * 2), dtype=np.float32)
+ c[:h, :w], k[:h, :w] = colour, weight
+ c = c.reshape(h2, 2, w2, 2, -1).sum(axis=(1, 3))
+ k = k.reshape(h2, 2, w2, 2).sum(axis=(1, 3))
+ levels.append((c, k))
+ colour, weight = levels[-1]
+ filled = colour / np.maximum(weight, 1e-12)[..., None]
+ for colour, weight in reversed(levels[:-1]):
+ h, w = weight.shape
+ up = np.repeat(np.repeat(filled, 2, axis=0), 2, axis=1)[:h, :w]
+ own = colour / np.maximum(weight, 1e-12)[..., None]
+ blend = np.clip(weight, 0.0, 1.0)[..., None]
+ filled = own * blend + up * (1.0 - blend)
+ return np.where(covered[..., None], image, filled).astype(np.float32)
+
+
+# ---------------------------------------------------------------- RGBM
+
+RGBM_MAX_RANGE = 64.0
+
+
+def rgbm_range(peak: float) -> float:
+ """The power of two the encoding spans: at least the peak, at most 64."""
+ return float(min(RGBM_MAX_RANGE, 2.0 ** math.ceil(math.log2(max(1.0, peak)))))
+
+
+def rgbm_encode(radiance: np.ndarray, span: float) -> np.ndarray:
+ """Linear HDR RGB (h, w, 3) -> uint8 RGBA, the "rgbm2" encoding.
+
+ decode: m = a^2 * span, rgb = c^2 * m (a, c in 0..1). Both factors are
+ squared, so precision follows brightness: dark texels keep fine steps,
+ bright fixtures up to `span` never clip. Values above `span` clip.
+ """
+ value = np.clip(np.nan_to_num(radiance.astype(np.float32)), 0.0, span)
+ peak = value.max(axis=2)
+ a = np.ceil(np.sqrt(peak / span) * 255.0)
+ a = np.clip(a, 1.0, 255.0)
+ m = (a / 255.0) ** 2 * span
+ c = np.sqrt(value / m[..., None])
+ rgb = np.clip(np.round(c * 255.0), 0, 255)
+ return np.concatenate([rgb, a[..., None]], axis=2).astype(np.uint8)
+
+
+def rgbm_decode(rgba: np.ndarray, span: float) -> np.ndarray:
+ """uint8 RGBA "rgbm2" -> linear RGB float32 (the runtime shader's maths)."""
+ data = rgba.astype(np.float32) / 255.0
+ return data[..., :3] ** 2 * (data[..., 3:4] ** 2 * span)
diff --git a/art/verse/lib/realtime.py b/art/verse/lib/realtime.py
new file mode 100644
index 0000000000..59c73fbcfb
--- /dev/null
+++ b/art/verse/lib/realtime.py
@@ -0,0 +1,1407 @@
+"""Realtime export of a deck, Blender side: the deck as an eye-level 3D scene.
+
+The plate cook photographs a deck from one fixed angle. The realtime export
+turns the same scene into geometry a browser can walk through at eye level:
+
+1. every mesh instance of Architecture, Props and Ceiling (the ceiling ghosts
+ included, now as normal geometry that casts shadows) is realised into its
+ own object, so it can own a unique lightmap layout;
+2. a second UV set (``LM``) is unwrapped per object and packed into square
+ atlas pages, at a texel density weighted by how close people get to the
+ surface (floors and consoles high, hull voids and ceilings low);
+3. Cycles bakes per page the diffuse irradiance (direct and indirect), the
+ diffuse albedo, the emission, and the world normal and position used to
+ denoise the irradiance; the page stores the view-independent outgoing
+ radiance ``albedo * irradiance + emission`` (scene linear, HDR);
+4. a box-projected reflection panorama is rendered per room;
+5. the triangles are grouped by (material, room, page) into chunks with
+ world positions, normals and the lightmap UV.
+
+`scripts/verse/package.py` (outside Blender) encodes the pages and panoramas
+(RGBM WebP), writes the meshopt-compressed glTF and the manifest's
+``realtime`` block. Format and runtime: docs/verse/realtime.md.
+
+Raw outputs (all in `out_dir`):
+ lm_<page>.npy float16 (h, w, 3) radiance per page, gaps filled
+ probe_<room>.npy float16 (h, w, 3) equirect radiance, three.js layout
+ geometry.npz chunk arrays: <i>_pos, <i>_nrm (float32), <i>_uv, <i>_idx
+ realtime.json chunks, pages, probes, materials, stats
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+
+import bmesh
+import bpy
+import numpy as np
+from mathutils import Vector
+
+from lib import cook, lightmap, scene
+
+UV_NAME = "LM"
+ROLES = ("Architecture", "Props", "Ceiling", "Lights")
+# Faces never exported: the plate's section caps (a drawing convention),
+# decals cut out by their alpha (worn-through paint, stencils; they need an
+# alpha bake, docs/verse/realtime.md "Open work") and volume-only haze. A
+# material whose node tree is volume-only or alpha-cut is recognised as well
+# (`_unexportable`), so a deck's own decals and hazes need no entry here.
+EXCLUDED_MATERIALS = frozenset(
+ {
+ "M_Section_Cap",
+ "M_Deck_Hazard",
+ "M_Deck_Marking_White",
+ "M_Deck_Marking_Amber",
+ "M_Deck_Marking_Red",
+ "M_Deck_Marking_Dark",
+ "M_TMP_PropsInd_StencilAmber",
+ "M_TMP_PropsInd_StencilDark",
+ "M_TMP_PropsInd_StencilRed",
+ "M_TMP_PropsInd_StencilWhite",
+ "M_Haze_Volume",
+ "M_TMP_PropsInd_Haze",
+ "M_Eng_ShaftHaze",
+ "M_Hangar_WellFog",
+ }
+)
+
+
+@dataclass(frozen=True)
+class Preset:
+ page_px: int
+ density: float # lightmap texels per metre at weight 1
+ max_pages: int
+ samples: int # irradiance bake samples
+ probe_size: tuple[int, int]
+ probe_samples: int
+ margin_px: int
+ denoise_passes: int
+
+
+PRESETS = {
+ "final": Preset(4096, 48.0, 4, 512, (1024, 512), 256, 6, 4),
+ "preview": Preset(1024, 10.0, 2, 48, (256, 128), 48, 3, 2),
+}
+
+# How close people get to a surface: lightmap density relative to the base.
+DENSITY_WEIGHT = {
+ "M_Hull_Structure": 0.3,
+ "M_Hull_Pipe": 0.35,
+ "M_Hull_PipeInsulated": 0.35,
+ "M_Ceiling_Panel": 0.45,
+ "M_Recess_Dark": 0.4,
+ "M_Starfield": 0.6,
+ "M_Floor_GlossBlack": 0.75,
+ "M_Floor_SatinDark": 0.75,
+ "M_Floor_Grating": 0.75,
+ "M_Light_CeilingPanel": 0.5,
+ # Operations deck
+ "M_Ops_Floor_Satin": 0.75,
+ "M_Ops_Floor_SatinGrey": 0.75,
+ "M_Ops_Floor_WashTile": 0.75,
+ "M_Ops_Floor_WhiteTile": 0.75,
+ "M_Ops_Starfield": 0.6,
+ "M_Ops_Light_Corridor": 0.5,
+ "M_Ops_Light_Dim": 0.5,
+ "M_Ops_Light_Warm": 0.5,
+ "M_Ops_Light_MessCool": 0.5,
+ "M_Ops_Light_Night": 0.5,
+ "M_Ops_Light_Ring": 0.5,
+ "M_Ops_Light_Med": 0.5,
+ # Hangar deck: 4 200 m2 of flight deck, seen from 1.7 m
+ "M_Hangar_Deck": 0.6,
+ "M_Hangar_BankPanel": 0.4,
+ "M_Hangar_RoomStrip": 0.5,
+}
+
+
+@dataclass(frozen=True)
+class RtMaterial:
+ """What the runtime needs on top of the baked radiance: the specular layer.
+
+ The bake carries all diffuse light (and the diffuse albedo in it), so the
+ runtime material draws ``radiance + specular``. ``color`` is the specular
+ tint of metals (linear RGB); ``specular`` is Blender's Specular IOR Level
+ (0.5 = F0 4 %). ``detail`` picks a runtime close-up layer (see
+ docs/verse/realtime.md); ``collide`` says whether the camera stops at it.
+ """
+
+ roughness: float = 0.5
+ metalness: float = 0.0
+ color: tuple[float, float, float] = (0.0, 0.0, 0.0)
+ clearcoat: float = 0.0
+ clearcoat_roughness: float = 0.05
+ specular: float = 0.5
+ detail: str = "none"
+ transparent: bool = False
+ opacity: float = 1.0
+ collide: bool = True
+
+
+_GLASS = RtMaterial(roughness=0.02, specular=0.5, transparent=True, opacity=0.06, collide=False)
+_LAMP = RtMaterial(roughness=0.25, clearcoat=1.0, clearcoat_roughness=0.02, collide=False)
+_EMITTER = RtMaterial(roughness=0.6, specular=0.25, collide=False)
+
+MATERIALS: dict[str, RtMaterial] = {
+ "M_Floor_GlossBlack": RtMaterial(
+ roughness=0.3, clearcoat=1.0, clearcoat_roughness=0.06, specular=0.12, detail="deck_plates"
+ ),
+ "M_Floor_SatinDark": RtMaterial(
+ roughness=0.3, clearcoat=0.35, clearcoat_roughness=0.06, detail="deck_plates"
+ ),
+ "M_Floor_Grating": RtMaterial(roughness=0.46, metalness=1.0, color=(0.32, 0.33, 0.34)),
+ "M_Wall_PaintedLight": RtMaterial(
+ roughness=0.28, clearcoat=0.2, clearcoat_roughness=0.12, detail="painted"
+ ),
+ "M_Wall_PaintedMid": RtMaterial(roughness=0.41, detail="painted"),
+ "M_Wall_PaintedDark": RtMaterial(roughness=0.39, detail="painted"),
+ "M_Wall_Charcoal": RtMaterial(
+ roughness=0.32, clearcoat=0.25, clearcoat_roughness=0.12, detail="painted"
+ ),
+ "M_Struct_Gunmetal": RtMaterial(
+ roughness=0.38, metalness=1.0, color=(0.16, 0.165, 0.175), detail="metal"
+ ),
+ "M_Trim_BrushedSteel": RtMaterial(
+ roughness=0.22, metalness=1.0, color=(0.56, 0.565, 0.575), detail="metal"
+ ),
+ "M_Trim_Chrome": RtMaterial(roughness=0.07, metalness=1.0, color=(0.82, 0.83, 0.84)),
+ "M_Rubber_Black": RtMaterial(roughness=0.72, specular=0.35),
+ "M_Recess_Dark": RtMaterial(roughness=0.7),
+ "M_Ceiling_Panel": RtMaterial(roughness=0.47, detail="painted"),
+ "M_Console_Body": RtMaterial(
+ roughness=0.36, clearcoat=0.15, clearcoat_roughness=0.12, detail="painted"
+ ),
+ "M_Console_Deck": RtMaterial(roughness=0.43, detail="painted"),
+ "M_Console_Keys": RtMaterial(roughness=0.5),
+ "M_Screen": RtMaterial(roughness=0.3, clearcoat=1.0, clearcoat_roughness=0.03),
+ "M_Glass_Viewport": _GLASS,
+ "M_Glass_Clear": RtMaterial(
+ roughness=0.01, specular=0.5, transparent=True, opacity=0.04, collide=False
+ ),
+ "M_Starfield": RtMaterial(roughness=1.0, specular=0.0, collide=False),
+ "M_Plastic_BlackSatin": RtMaterial(roughness=0.48),
+ "M_Plastic_LampOff": RtMaterial(roughness=0.25, clearcoat=0.5, clearcoat_roughness=0.05),
+ "M_Plastic_MedWhite": RtMaterial(roughness=0.36),
+ "M_Fabric_BunkGrey": RtMaterial(roughness=0.9, specular=0.3),
+ "M_Paint_TrimRed": RtMaterial(roughness=0.3),
+ "M_Lacquer_BlackGloss": RtMaterial(roughness=0.07, clearcoat=1.0, clearcoat_roughness=0.03),
+ "M_Seat_Upholstery": RtMaterial(roughness=0.4),
+ "M_Crate_Paint": RtMaterial(roughness=0.46, detail="painted"),
+ "M_Hull_Structure": RtMaterial(roughness=0.5, metalness=0.75, color=(0.07, 0.075, 0.085)),
+ "M_Hull_Pipe": RtMaterial(roughness=0.41),
+ "M_Hull_PipeInsulated": RtMaterial(roughness=0.69),
+ "M_Section_Cap": RtMaterial(roughness=0.5),
+ "M_Light_CeilingPanel": _EMITTER,
+ "M_Light_WallStrip": _EMITTER,
+ "M_Light_Backlit": _EMITTER,
+ "M_Light_RedTrim": _EMITTER,
+ "M_Light_FloorInlay": _EMITTER,
+ "M_Light_Maint_Red": _EMITTER,
+ "M_Light_Maint_Amber": _EMITTER,
+ "M_Emit_BacklitPanel": _EMITTER,
+ "M_Indicator_Red": _LAMP,
+ "M_Indicator_Green": _LAMP,
+ "M_Indicator_Amber": _LAMP,
+ "M_Indicator_Blue": _LAMP,
+ "M_Indicator_White": _LAMP,
+ "M_Light_Warm": _EMITTER,
+ "M_Light_Flood": _EMITTER,
+ "M_Light_DimCold": _EMITTER,
+ "M_Light_CabinWarm": _EMITTER,
+ # Industrial kit stand-ins (temp names while lib.materials lacks them)
+ "M_TMP_PropsInd_LampFlood": _EMITTER,
+ "M_TMP_PropsInd_LampDim": _EMITTER,
+ "M_TMP_PropsInd_CabinGlow": _EMITTER,
+ "M_TMP_PropsInd_CoreHot": _EMITTER,
+ "M_TMP_PropsInd_ContainerGrey": RtMaterial(roughness=0.5, detail="painted"),
+ "M_TMP_PropsInd_ContainerGunmetal": RtMaterial(roughness=0.46, detail="painted"),
+ "M_TMP_PropsInd_ContainerOlive": RtMaterial(roughness=0.5, detail="painted"),
+ "M_TMP_PropsInd_HullPaint": RtMaterial(roughness=0.42, detail="painted"),
+ "M_TMP_PropsInd_GlassDark": RtMaterial(roughness=0.04, clearcoat=0.6, clearcoat_roughness=0.03),
+ "M_TMP_PropsInd_Tread": RtMaterial(
+ roughness=0.36, metalness=1.0, color=(0.3, 0.305, 0.31), detail="metal"
+ ),
+ "M_Container_Paint_Grey": RtMaterial(roughness=0.5, detail="painted"),
+ "M_Container_Paint_Gunmetal": RtMaterial(roughness=0.46, detail="painted"),
+ "M_Container_Paint_Olive": RtMaterial(roughness=0.5, detail="painted"),
+ "M_Hull_PaintWhite": RtMaterial(roughness=0.42, detail="painted"),
+ "M_Glass_Canopy": RtMaterial(roughness=0.04, clearcoat=0.6, clearcoat_roughness=0.03),
+ # Hologram projector lenses (bridge): small, glossy, never in the camera's way.
+ "TMP_M_Glass_HoloLens": RtMaterial(
+ roughness=0.04, clearcoat=1.0, clearcoat_roughness=0.02, collide=False
+ ),
+ "M_Glass_HoloLens": RtMaterial(
+ roughness=0.04, clearcoat=1.0, clearcoat_roughness=0.02, collide=False
+ ),
+ "M_Metal_TreadPlate": RtMaterial(
+ roughness=0.36, metalness=1.0, color=(0.3, 0.305, 0.31), detail="metal"
+ ),
+ "M_Reactor_CoreHot": _EMITTER,
+ "M_Eng_CoreHot": _EMITTER,
+ # Operations deck
+ "M_Ops_Floor_Satin": RtMaterial(
+ roughness=0.3, clearcoat=0.45, clearcoat_roughness=0.08, detail="deck_plates"
+ ),
+ "M_Ops_Floor_SatinGrey": RtMaterial(roughness=0.4, detail="painted"),
+ "M_Ops_Floor_WashTile": RtMaterial(roughness=0.26, clearcoat=0.3, clearcoat_roughness=0.08),
+ "M_Ops_Floor_WhiteTile": RtMaterial(roughness=0.3, clearcoat=0.2, clearcoat_roughness=0.1),
+ "M_Ops_Table_Top": RtMaterial(roughness=0.16, clearcoat=1.0, clearcoat_roughness=0.05),
+ "M_Ops_Table_Grey": RtMaterial(roughness=0.4, detail="painted"),
+ "M_Ops_Wall_White": RtMaterial(roughness=0.35, detail="painted"),
+ "M_Ops_Glass_Case": RtMaterial(
+ roughness=0.03, specular=0.5, transparent=True, opacity=0.05, collide=False
+ ),
+ "M_Ops_Glass_Slit": RtMaterial(
+ roughness=0.02, specular=0.15, transparent=True, opacity=0.04, collide=False
+ ),
+ "M_Ops_Starfield": RtMaterial(roughness=1.0, specular=0.0, collide=False),
+ "M_Ops_Light_Pip": _LAMP,
+ "M_Ops_Lamp_Warm": _LAMP,
+ "M_Ops_Light_Warm": _EMITTER,
+ "M_Ops_Light_Dim": _EMITTER,
+ "M_Ops_Light_Reading": _EMITTER,
+ "M_Ops_Light_Hatch": _EMITTER,
+ "M_Ops_Light_Ring": _EMITTER,
+ "M_Ops_Light_Med": _EMITTER,
+ "M_Ops_Light_Maint": _EMITTER,
+ "M_Ops_Light_SimBar": _EMITTER,
+ "M_Ops_Light_Corridor": _EMITTER,
+ "M_Ops_Light_Night": _EMITTER,
+ "M_Ops_Light_MessCool": _EMITTER,
+ "M_Ops_Fabric_Blanket": RtMaterial(roughness=0.92, specular=0.3),
+ "M_Ops_Fabric_Sheet": RtMaterial(roughness=0.88, specular=0.3),
+ "M_Fabric_Linen": RtMaterial(roughness=0.9, specular=0.3),
+ "M_Fabric_BlanketSlate": RtMaterial(roughness=0.92, specular=0.3),
+ "M_Fabric_UniformOlive": RtMaterial(roughness=0.9, specular=0.3),
+ "M_Ops_Enamel_Steel": RtMaterial(roughness=0.3, clearcoat=0.4, clearcoat_roughness=0.08),
+ "M_Ops_Enamel_Blue": RtMaterial(roughness=0.3, clearcoat=0.4, clearcoat_roughness=0.08),
+ "M_Ops_Enamel_Red": RtMaterial(roughness=0.3, clearcoat=0.4, clearcoat_roughness=0.08),
+ "M_Ops_Enamel_Gold": RtMaterial(roughness=0.3, clearcoat=0.4, clearcoat_roughness=0.08),
+ "TMP_M_Metal_RankGold": RtMaterial(roughness=0.3, metalness=1.0, color=(0.8, 0.56, 0.22)),
+ "TMP_M_Paint_RankBlue": RtMaterial(roughness=0.35),
+ "TMP_M_Paint_RankRed": RtMaterial(roughness=0.35),
+ "M_Metal_RankGold": RtMaterial(roughness=0.3, metalness=1.0, color=(0.8, 0.56, 0.22)),
+ "M_Paint_RankBlue": RtMaterial(roughness=0.35),
+ "M_Paint_RankRed": RtMaterial(roughness=0.35),
+ # Hangar deck
+ "M_Hangar_Deck": RtMaterial(
+ roughness=0.42, clearcoat=0.8, clearcoat_roughness=0.06, specular=0.3, detail="painted"
+ ),
+ "M_Hangar_BankPanel": _EMITTER,
+ "M_Hangar_RoomStrip": _EMITTER,
+ "M_Hangar_PierLight": _EMITTER,
+ "M_Hangar_FloodLens": _EMITTER,
+ "M_Hangar_DoorGlow": _EMITTER,
+ "M_Hangar_SignBacklit": _EMITTER,
+ "M_Hangar_ShaftLamp": _EMITTER,
+ "M_Hangar_FloorLamp": _LAMP,
+ # The launch well's containment field: a faint emissive sheet that dims
+ # what lies below it to about half (its transparent colour ~0.5).
+ "M_Hangar_FieldBlue": RtMaterial(
+ roughness=0.08, specular=0.2, transparent=True, opacity=0.48, collide=False
+ ),
+}
+
+
+class RealtimeError(RuntimeError):
+ """The deck scene cannot be exported for the realtime view."""
+
+
+@dataclass
+class Item:
+ """One realised mesh object of the export."""
+
+ obj: bpy.types.Object
+ weight: float
+ area: float # world surface area, m2
+ centre: tuple[float, float, float]
+ room: str | None = None
+ page: int = -1
+ z_range: tuple[float, float] = (0.0, 0.0) # world height of its lowest and highest point
+
+
+@dataclass
+class Stats:
+ timings: dict[str, float] = field(default_factory=dict)
+ objects: int = 0
+ triangles: int = 0
+ vertices: int = 0
+ chunks: int = 0
+ area_m2: float = 0.0
+ page_density: list[float] = field(default_factory=list)
+ hidden_objects: int = 0
+ hidden_area_m2: float = 0.0
+ far_split: int = 0
+ far_decimated_triangles: int = 0
+
+
+def export_realtime(deck_id: str, out_dir: Path, quality: str = "final") -> dict:
+ """Export deck `deck_id` (the current scene) for the realtime view into `out_dir`."""
+ if quality not in PRESETS:
+ raise ValueError(f"quality must be one of {sorted(PRESETS)}")
+ preset = PRESETS[quality]
+ info = scene.deck_info()
+ if info["deck_id"] != deck_id:
+ raise RealtimeError(f"scene holds deck {info['deck_id']!r}, not {deck_id!r}")
+ out_dir = out_dir.resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ bpy.context.view_layer.update()
+ stats = Stats()
+ rooms = cook._rooms()
+ with cook._stage("realise", stats.timings):
+ items = _realise()
+ _assign_rooms(items, rooms)
+ items = _split_tall(items, rooms, stats)
+ _weigh_by_distance(items, rooms, stats)
+ with cook._stage("visibility", stats.timings):
+ unseen = _unseen(items, rooms)
+ # Never seen from where people walk: still lit and casting light in the
+ # bake, never exported (no lightmap texels, no triangles).
+ hidden_area = sum(items[i].area for i in unseen)
+ items = [item for i, item in enumerate(items) if i not in unseen]
+ stats.objects = len(items)
+ stats.area_m2 = round(sum(item.area for item in items), 1)
+ stats.hidden_objects = len(unseen)
+ stats.hidden_area_m2 = round(hidden_area, 1)
+ print(
+ f"[verse] realtime {deck_id}: {len(items)} objects, {stats.area_m2} m2 "
+ f"({len(unseen)} objects, {hidden_area:.0f} m2 never seen from the rooms)",
+ flush=True,
+ )
+ with cook._stage("unwrap", stats.timings):
+ pages, density = _unwrap(items, preset)
+ with cook._stage("join", stats.timings):
+ _keep_object_space(items)
+ joined = _join_pages(items)
+ _patch_materials({m for _, obj in joined for m in obj.data.materials if m is not None})
+ with cook._stage("bake", stats.timings):
+ page_info = []
+ for page in range(pages):
+ objects = [obj for p, obj in joined if p == page]
+ radiance = _bake_page(page, objects, density, preset)
+ np.save(out_dir / f"lm_{page}.npy", radiance.astype(np.float16))
+ page_info.append(
+ {
+ "file": f"lm_{page}.npy",
+ "size": preset.page_px,
+ "density": round(density, 2),
+ "max": round(float(radiance.max()), 3),
+ }
+ )
+ stats.page_density.append(round(density, 2))
+ with cook._stage("probes", stats.timings):
+ probes = [_reflection_probe(room, preset, out_dir) for room in rooms]
+ with cook._stage("geometry", stats.timings):
+ chunks = _export_geometry(joined, out_dir / "geometry.npz", stats)
+ used = sorted({chunk["material"] for chunk in chunks})
+ result = {
+ "id": deck_id,
+ "quality": quality,
+ "pages": page_info,
+ "probes": probes,
+ "chunks": chunks,
+ "materials": {name: _material_json(name) for name in used},
+ "stats": {
+ "objects": stats.objects,
+ "triangles": stats.triangles,
+ "vertices": stats.vertices,
+ "chunks": stats.chunks,
+ "area_m2": stats.area_m2,
+ "hidden_objects": stats.hidden_objects,
+ "hidden_area_m2": stats.hidden_area_m2,
+ "far_split": stats.far_split,
+ "far_decimated_triangles": stats.far_decimated_triangles,
+ "density": stats.page_density,
+ "samples": preset.samples,
+ "blender": bpy.app.version_string,
+ **{key: round(value, 2) for key, value in stats.timings.items()},
+ },
+ }
+ (out_dir / "realtime.json").write_text(json.dumps(result, indent=1), encoding="utf-8")
+ return result
+
+
+# ---------------------------------------------------------------- realise
+
+
+def _realise() -> list[Item]:
+ """Every mesh instance of the deck as its own single-user object (modifiers
+ applied, materials kept, ghosts turned into normal shadow-casting geometry)
+ in a fresh collection; the original deck collections leave the render."""
+ roles = cook._deck_roles()
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ pending = []
+ for instance in depsgraph.object_instances:
+ obj = instance.object
+ if obj.type != "MESH":
+ continue
+ owner = (
+ instance.parent.original if instance.is_instance and instance.parent else obj.original
+ )
+ if roles.get(owner.name) not in ROLES:
+ continue
+ mesh = bpy.data.meshes.new_from_object(
+ obj, preserve_all_data_layers=True, depsgraph=depsgraph
+ )
+ original = obj.original
+ slots = [slot.material for slot in original.material_slots]
+ pending.append((original.name, mesh, instance.matrix_world.copy(), slots, original))
+ _exclude_originals()
+ target = bpy.data.collections.new("RT_realtime")
+ bpy.context.scene.collection.children.link(target)
+ items = []
+ for name, mesh, matrix, slots, original in pending:
+ # The evaluated mesh carries the object's materials in slot order; set
+ # them in place (clearing the list would reset every face to slot 0).
+ before = _faces_per_material(mesh)
+ for index, material in enumerate(slots):
+ if index < len(mesh.materials):
+ mesh.materials[index] = material
+ else:
+ mesh.materials.append(material)
+ if _faces_per_material(mesh) != before:
+ raise RealtimeError(f"{name}: realising changed which faces carry which material")
+ if not _drop_excluded_faces(mesh) or not _finite(mesh, name):
+ bpy.data.meshes.remove(mesh)
+ continue
+ obj = bpy.data.objects.new(f"RT_{name}", mesh)
+ obj.matrix_world = matrix
+ target.objects.link(obj)
+ ghost = bool(original.get("ceiling_ghost"))
+ obj.visible_camera = True
+ obj.visible_shadow = ghost or original.visible_shadow
+ obj.visible_diffuse = ghost or original.visible_diffuse
+ obj.visible_glossy = ghost or original.visible_glossy
+ obj.visible_transmission = ghost or original.visible_transmission
+ items.append(_item(obj))
+ if not items:
+ raise RealtimeError("deck has no mesh geometry to export")
+ bpy.context.view_layer.update()
+ return items
+
+
+def _exclude_originals() -> None:
+ root = scene.deck_root()
+ layer = _layer_collection(bpy.context.view_layer.layer_collection, root.name)
+ if layer is None:
+ raise RealtimeError(f"collection {root.name} is not in the view layer")
+ for child in layer.children:
+ if child.name in ("Architecture", "Props", "Ceiling"):
+ child.exclude = True
+ for obj in scene.objects_in("Lights"):
+ if obj.type == "MESH":
+ obj.hide_render = True
+
+
+def _layer_collection(layer, name: str):
+ if layer.collection.name == name:
+ return layer
+ for child in layer.children:
+ found = _layer_collection(child, name)
+ if found is not None:
+ return found
+ return None
+
+
+_UNEXPORTABLE: dict[str, str | None] = {}
+
+
+def _unexportable(material: bpy.types.Material | None) -> str | None:
+ """Why a material's faces stay out of the export, or None.
+
+ Listed in `EXCLUDED_MATERIALS`; volume-only (haze, fog: no surface to
+ bake); or cut out by alpha (decals and stencils: a Principled BSDF with a
+ linked or partial Alpha, or one mixed with a Transparent BSDF), which
+ would bake as opaque quads with black where the paint is missing.
+ """
+ if material is None:
+ return None
+ if material.name in _UNEXPORTABLE:
+ return _UNEXPORTABLE[material.name]
+ reason = None
+ if _base_name(material.name) in EXCLUDED_MATERIALS:
+ reason = "excluded"
+ elif material.node_tree is not None:
+ output = _material_output(material.node_tree)
+ if output is not None:
+ surface = output.inputs["Surface"].links
+ if not surface:
+ reason = "volume" if output.inputs["Volume"].links else None
+ else:
+ nodes = _upstream(surface[0].from_node)
+ types = {node.type for node in nodes}
+ for node in nodes:
+ alpha = node.inputs.get("Alpha") if node.type == "BSDF_PRINCIPLED" else None
+ if alpha is not None and (alpha.is_linked or alpha.default_value < 0.999):
+ reason = "alpha cut-out"
+ if {"BSDF_TRANSPARENT", "MIX_SHADER", "BSDF_PRINCIPLED"} <= types:
+ reason = "alpha cut-out"
+ _UNEXPORTABLE[material.name] = reason
+ return reason
+
+
+def _material_output(tree: bpy.types.NodeTree):
+ outputs = [node for node in tree.nodes if node.type == "OUTPUT_MATERIAL"]
+ active = [node for node in outputs if node.is_active_output]
+ return (active or outputs or [None])[0]
+
+
+def _upstream(node) -> list:
+ """`node` and every node feeding it."""
+ seen, stack = [], [node]
+ while stack:
+ current = stack.pop()
+ if current in seen:
+ continue
+ seen.append(current)
+ for socket in current.inputs:
+ stack.extend(link.from_node for link in socket.links)
+ return seen
+
+
+def _drop_excluded_faces(mesh: bpy.types.Mesh) -> bool:
+ """Remove faces of unexportable materials; False when nothing is left."""
+ excluded = {
+ index
+ for index, material in enumerate(mesh.materials)
+ if _unexportable(material) is not None
+ }
+ if excluded:
+ bm = bmesh.new()
+ bm.from_mesh(mesh)
+ doomed = [face for face in bm.faces if face.material_index in excluded]
+ bmesh.ops.delete(bm, geom=doomed, context="FACES")
+ bm.to_mesh(mesh)
+ bm.free()
+ return len(mesh.polygons) > 0
+
+
+def _finite(mesh: bpy.types.Mesh, name: str) -> bool:
+ co = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
+ mesh.vertices.foreach_get("co", co)
+ if not np.isfinite(co).all():
+ print(f"[verse] realtime: skipping {name} (non-finite vertices)", flush=True)
+ return False
+ return True
+
+
+def _faces_per_material(mesh: bpy.types.Mesh) -> dict[str, int]:
+ """Face count per material name (the realise step must keep it)."""
+ indices = np.empty(len(mesh.polygons), dtype=np.int32)
+ mesh.polygons.foreach_get("material_index", indices)
+ names = [m.name if m is not None else "" for m in mesh.materials] or [""]
+ counts: dict[str, int] = {}
+ for index, count in zip(*np.unique(indices, return_counts=True), strict=True):
+ key = names[min(int(index), len(names) - 1)]
+ counts[key] = counts.get(key, 0) + int(count)
+ return counts
+
+
+def _base_name(name: str) -> str:
+ return name.split(".")[0]
+
+
+def _item(obj: bpy.types.Object) -> Item:
+ mesh = obj.data
+ matrix = np.array(obj.matrix_world, dtype=np.float64)
+ co = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
+ mesh.vertices.foreach_get("co", co)
+ world = co.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
+ mesh.calc_loop_triangles()
+ tris = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("vertices", tris)
+ tris = tris.reshape(-1, 3)
+ a, b, c = world[tris[:, 0]], world[tris[:, 1]], world[tris[:, 2]]
+ area = float(0.5 * np.linalg.norm(np.cross(b - a, c - a), axis=1).sum())
+ weights = [DENSITY_WEIGHT.get(_base_name(m.name), 1.0) for m in mesh.materials if m is not None]
+ centre = world.mean(axis=0)
+ return Item(
+ obj=obj,
+ weight=max(weights, default=1.0),
+ area=area,
+ centre=(float(centre[0]), float(centre[1]), float(centre[2])),
+ z_range=(float(world[:, 2].min()), float(world[:, 2].max())),
+ )
+
+
+def _assign_rooms(items: list[Item], rooms: list[cook.Room]) -> None:
+ """The room each object belongs to (by its centre), for page grouping."""
+ for item in items:
+ x, y, _ = item.centre
+ item.room = cook._room_at(x, y, rooms) or _nearest_room(x, y, rooms)
+
+
+def _nearest_room(x: float, y: float, rooms: list[cook.Room]) -> str:
+ return min(rooms, key=lambda r: (r.centre[0] - x) ** 2 + (r.centre[1] - y) ** 2).id
+
+
+# ---------------------------------------------------------------- distance
+
+# People walk on the room floors with their eyes at 1.7 m: surfaces far above
+# (the upper walls of a 12 m hall, a 21 m hangar ceiling) or far below (a 52 m
+# reactor shaft) are only ever seen from a distance. Tall objects are split
+# into height bands, each band's lightmap density falls with its distance
+# from the eye band and far bands lose triangles.
+EYE_BAND_M = (-1.0, 4.0) # heights above the room floor seen up close
+TALL_M = 8.0 # objects taller than this (and big) are split into bands
+TALL_AREA_M2 = 150.0
+BAND_EDGES_M = (-24.0, -10.0, -3.0, 6.0, 12.0) # band limits above the room floor
+FAR_FALLOFF_M = 4.0 # density halves this far beyond the eye band
+FAR_DECIMATE_M = 4.0 # bands further than this lose triangles
+FAR_DECIMATE_RATE_M = 3.0 # and keep 1 / (1 + beyond / this) of them
+FAR_MIN_RATIO = 0.1
+FAR_MIN_TRIANGLES = 2000
+
+
+def _distance_beyond_eye_band(item: Item, floor: float) -> float:
+ low, high = item.z_range
+ return max(0.0, low - (floor + EYE_BAND_M[1]), (floor + EYE_BAND_M[0]) - high)
+
+
+def _split_tall(items: list[Item], rooms: list[cook.Room], stats: Stats) -> list[Item]:
+ """Split tall, big objects into height bands so each band can get its own
+ density and triangle budget (faces are first cut at the band limits)."""
+ floors = {room.id: room.z for room in rooms}
+ out = []
+ for item in items:
+ low, high = item.z_range
+ if high - low <= TALL_M or item.area < TALL_AREA_M2:
+ out.append(item)
+ continue
+ floor = floors.get(item.room or "", 0.0)
+ edges = [floor + edge for edge in BAND_EDGES_M]
+ _cut_at_heights(item.obj, [h for h in edges if low < h < high])
+ bands = _face_bands(item.obj, edges)
+ if len(bands) < 2:
+ out.append(item)
+ continue
+ first = min(bands)
+ copies = {band: item.obj if band == first else _copy_object(item.obj) for band in bands}
+ for band, faces in bands.items():
+ obj = copies[band]
+ _keep_faces(obj.data, faces)
+ part = _item(obj)
+ part.weight = item.weight
+ part.room = item.room
+ out.append(part)
+ stats.far_split += 1
+ return out
+
+
+def _face_bands(obj: bpy.types.Object, edges: list[float]) -> dict[int, np.ndarray]:
+ """Face indices per height band (band k lies between edges k-1 and k)."""
+ mesh = obj.data
+ centres = np.empty(len(mesh.polygons) * 3, dtype=np.float64)
+ mesh.polygons.foreach_get("center", centres)
+ matrix = np.array(obj.matrix_world, dtype=np.float64)
+ z = (centres.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3])[:, 2]
+ band = np.searchsorted(np.asarray(edges), z)
+ return {int(b): np.flatnonzero(band == b) for b in np.unique(band)}
+
+
+def _copy_object(obj: bpy.types.Object) -> bpy.types.Object:
+ copy = obj.copy()
+ copy.data = obj.data.copy()
+ for collection in obj.users_collection:
+ collection.objects.link(copy)
+ return copy
+
+
+def _cut_at_heights(obj: bpy.types.Object, heights: list[float]) -> None:
+ """Cut the object's faces along horizontal world planes (nothing removed)."""
+ if not heights:
+ return
+ inverse = obj.matrix_world.inverted()
+ normal = (obj.matrix_world.to_3x3().transposed() @ Vector((0.0, 0.0, 1.0))).normalized()
+ bm = bmesh.new()
+ bm.from_mesh(obj.data)
+ for height in heights:
+ geom = [*bm.verts, *bm.edges, *bm.faces]
+ bmesh.ops.bisect_plane(
+ bm, geom=geom, plane_co=inverse @ Vector((0.0, 0.0, height)), plane_no=normal, dist=1e-5
+ )
+ bm.to_mesh(obj.data)
+ bm.free()
+
+
+def _keep_faces(mesh: bpy.types.Mesh, keep: np.ndarray) -> None:
+ bm = bmesh.new()
+ bm.from_mesh(mesh)
+ bm.faces.index_update()
+ wanted = {int(i) for i in keep}
+ doomed = [face for face in bm.faces if face.index not in wanted]
+ bmesh.ops.delete(bm, geom=doomed, context="FACES")
+ loose = [vert for vert in bm.verts if not vert.link_faces]
+ bmesh.ops.delete(bm, geom=loose, context="VERTS")
+ bm.to_mesh(mesh)
+ bm.free()
+
+
+def _weigh_by_distance(items: list[Item], rooms: list[cook.Room], stats: Stats) -> None:
+ """Lower the density of far objects and decimate the far heavy ones."""
+ floors = {room.id: room.z for room in rooms}
+ for item in items:
+ distance = _distance_beyond_eye_band(item, floors.get(item.room or "", 0.0))
+ if distance <= 0.0:
+ continue
+ item.weight *= 1.0 / (1.0 + distance / FAR_FALLOFF_M)
+ if distance <= FAR_DECIMATE_M:
+ continue
+ mesh = item.obj.data
+ mesh.calc_loop_triangles()
+ before = len(mesh.loop_triangles)
+ if before < FAR_MIN_TRIANGLES:
+ continue
+ ratio = max(FAR_MIN_RATIO, 1.0 / (1.0 + (distance - FAR_DECIMATE_M) / FAR_DECIMATE_RATE_M))
+ modifier = item.obj.modifiers.new("RT_far", "DECIMATE")
+ modifier.decimate_type = "COLLAPSE"
+ modifier.ratio = ratio
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ reduced = bpy.data.meshes.new_from_object(
+ item.obj.evaluated_get(depsgraph), preserve_all_data_layers=True, depsgraph=depsgraph
+ )
+ item.obj.modifiers.remove(modifier)
+ old = item.obj.data
+ item.obj.data = reduced
+ bpy.data.meshes.remove(old)
+ reduced.calc_loop_triangles()
+ stats.far_decimated_triangles += before - len(reduced.loop_triangles)
+ refreshed = _item(item.obj)
+ item.area, item.centre, item.z_range = refreshed.area, refreshed.centre, refreshed.z_range
+ print(
+ f"[verse] realtime: {stats.far_split} tall objects split into height bands, "
+ f"{stats.far_decimated_triangles} triangles decimated far from the eye band",
+ flush=True,
+ )
+
+
+# ---------------------------------------------------------------- visibility
+
+VIEW_GRID_M = 1.2 # eye points on this grid inside every room
+VIEW_HEIGHTS_M = (0.9, 1.7, 2.5) # above the room's floor: a crouch, the head, the camera
+VIEW_RAYS = 256
+
+
+def _unseen(items: list[Item], rooms: list[cook.Room]) -> set[int]:
+ """Indices of objects no ray from any eye point in the rooms reaches.
+
+ Eye points sit on a grid inside every room polygon at a few heights; rays
+ go out in evenly spread directions and the first surface each hits counts
+ as seen. Hull voids behind full walls never are.
+ """
+ from mathutils.bvhtree import BVHTree
+
+ vertex_chunks, triangle_chunks, owner_chunks, offset = [], [], [], 0
+ for index, item in enumerate(items):
+ mesh = item.obj.data
+ matrix = np.array(item.obj.matrix_world, dtype=np.float64)
+ co = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
+ mesh.vertices.foreach_get("co", co)
+ mesh.calc_loop_triangles()
+ tris = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("vertices", tris)
+ vertex_chunks.append(co.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3])
+ triangle_chunks.append(tris.reshape(-1, 3) + offset)
+ owner_chunks.append(np.full(len(tris) // 3, index, dtype=np.int32))
+ offset += len(mesh.vertices)
+ vertices = np.concatenate(vertex_chunks)
+ triangles = np.concatenate(triangle_chunks)
+ owner = np.concatenate(owner_chunks)
+ tree = BVHTree.FromPolygons(vertices.tolist(), triangles.tolist(), all_triangles=True)
+ golden = math.pi * (3.0 - math.sqrt(5.0))
+ directions = []
+ for k in range(VIEW_RAYS):
+ y = 1.0 - 2.0 * (k + 0.5) / VIEW_RAYS
+ r = math.sqrt(max(0.0, 1.0 - y * y))
+ directions.append(Vector((math.cos(golden * k) * r, math.sin(golden * k) * r, y)))
+ seen = np.zeros(len(items), dtype=bool)
+ for room in rooms:
+ xs = [p[0] for p in room.polygon]
+ ys = [p[1] for p in room.polygon]
+ gx = np.arange(min(xs) + VIEW_GRID_M / 2, max(xs), VIEW_GRID_M)
+ gy = np.arange(min(ys) + VIEW_GRID_M / 2, max(ys), VIEW_GRID_M)
+ px, py = np.meshgrid(gx, gy)
+ px, py = px.ravel(), py.ravel()
+ inside = _points_in_polygon(px, py, room.polygon)
+ for x, y in zip(px[inside], py[inside], strict=True):
+ for height in VIEW_HEIGHTS_M:
+ origin = Vector((float(x), float(y), room.z + height))
+ for direction in directions:
+ _, _, index, _ = tree.ray_cast(origin, direction, 200.0)
+ if index is not None:
+ seen[owner[index]] = True
+ return {i for i in range(len(items)) if not seen[i]}
+
+
+# ---------------------------------------------------------------- lightmap UVs
+
+
+PAGE_FILL = 0.75 # share of a page the skyline packer fills (rectangles of mixed sizes)
+# Texels between the islands inside one object: enough for bilinear
+# filtering and the first mip levels. Objects of panels and greebles have
+# thousands of islands; the full page padding (`margin_px`) on each would
+# leave them a few percent of their own rectangle. The rectangles keep the
+# full padding from each other.
+ISLAND_GAP_TEXELS = 2.5
+# Smart UV's island margin (a fraction of the object's own square) never
+# exceeds this: an object only a few texels wide keeps its islands touching.
+MAX_ISLAND_MARGIN = 0.03
+# An object whose islands cover less of its square than this (thousands of
+# slivers, all margins) is sized as if they covered this much: it gets fewer
+# texels per metre instead of taking a page of margins from everyone else.
+MIN_LAYOUT_FILL = 0.3
+
+
+@dataclass(frozen=True)
+class Layout:
+ bbox: tuple[float, float, float, float] # u0, v0, u1, v1 of the object's own layout
+ uv_area: float
+
+
+def _unwrap(items: list[Item], preset: Preset) -> tuple[int, float]:
+ """Unwrap every object's LM UVs and pack them into pages.
+
+ Returns (page count, texels per metre at weight 1). Every object gets its
+ own Smart UV Project layout with island margins sized for the expected
+ density, and goes whole, as one rectangle, onto skyline-packed pages
+ (`lightmap.pack_skyline`, room by room). Rectangles are sized by the
+ object's weighted area; when they do not fit into `max_pages` pages the
+ density steps down until they do.
+
+ (Packing every island of a page with Blender's Pack Islands instead
+ wasted most of each page: a decimated shaft wall or a beveled key bank
+ has thousands of islands, each paying a full margin, so Pack Islands
+ shrank whole pages to 2-18 % coverage.)
+ """
+ size = preset.page_px
+ pad = preset.margin_px + 1
+ weighted = sum(item.area * item.weight**2 for item in items)
+ estimate = min(
+ preset.density, math.sqrt(preset.max_pages * size * size * PAGE_FILL / max(weighted, 1e-9))
+ )
+ layouts = [_project(item, estimate) for item in items]
+ rooms = sorted({item.room or "" for item in items})
+ groups = [rooms.index(item.room or "") for item in items]
+ density = preset.density
+ while True:
+ sizes = [_rect(item, layout, density) for item, layout in zip(items, layouts, strict=True)]
+ placements = lightmap.pack_skyline(sizes, groups, size, pad)
+ pages = max((p.page for p in placements), default=-1) + 1
+ if pages <= preset.max_pages:
+ break
+ density *= 0.97
+ used = sum(w * h for w, h in sizes) / (pages * size * size)
+ print(
+ f"[verse] realtime: {pages} page(s) at {density:.1f} px/m, {len(items)} objects, "
+ f"{used:.0%} of the pages in rectangles",
+ flush=True,
+ )
+ for item, layout, (w, h), place in zip(items, layouts, sizes, placements, strict=True):
+ item.page = place.page
+ _place_layout(item.obj, layout.bbox, w, h, place, size)
+ return pages, density
+
+
+def _rect(item: Item, layout: Layout, density: float) -> tuple[float, float]:
+ """Size in texels of an object's whole layout at its weighted density."""
+ u0, v0, u1, v1 = layout.bbox
+ covered = max(layout.uv_area, MIN_LAYOUT_FILL * (u1 - u0) * (v1 - v0), 1e-12)
+ k = density * item.weight * math.sqrt(item.area / covered)
+ return (u1 - u0) * k, (v1 - v0) * k
+
+
+def _place_layout(
+ obj: bpy.types.Object,
+ bbox: tuple[float, float, float, float],
+ w: float,
+ h: float,
+ place: lightmap.Placement,
+ size: int,
+) -> None:
+ """Move an object's whole layout into its page rectangle."""
+ layer = obj.data.uv_layers[UV_NAME]
+ uv = np.empty(len(layer.data) * 2, dtype=np.float64)
+ layer.data.foreach_get("uv", uv)
+ uv = uv.reshape(-1, 2)
+ bw, bh = max(bbox[2] - bbox[0], 1e-9), max(bbox[3] - bbox[1], 1e-9)
+ # Blender UV: v grows upward; the packer counts rows from the top.
+ u = (place.x + (uv[:, 0] - bbox[0]) / bw * w * place.scale) / size
+ top = place.y + h * place.scale
+ v = 1.0 - (top - (uv[:, 1] - bbox[1]) / bh * h * place.scale) / size
+ layer.data.foreach_set("uv", np.stack([u, v], axis=1).ravel().astype(np.float32))
+
+
+def _project(item: Item, density: float) -> Layout:
+ """Smart UV Project of one object into its own unit square, islands
+ `ISLAND_GAP_TEXELS` apart at `density` (Smart UV packs them itself)."""
+ obj = item.obj
+ mesh = obj.data
+ layer = mesh.uv_layers.get(UV_NAME) or mesh.uv_layers.new(name=UV_NAME)
+ mesh.uv_layers.active = layer # an existing render UV map (screens) stays active_render
+ expected = math.sqrt(item.area) * density * item.weight # texels across the square
+ margin = min(MAX_ISLAND_MARGIN, ISLAND_GAP_TEXELS / max(expected, 1.0))
+ if expected < 8.0 * ISLAND_GAP_TEXELS:
+ margin = 0.0 # a few texels wide: islands touch, the rectangle's padding keeps it apart
+ _edit_objects([obj])
+ try:
+ bpy.ops.mesh.select_all(action="SELECT")
+ bpy.ops.uv.smart_project(
+ angle_limit=math.radians(66.0),
+ margin_method="FRACTION",
+ island_margin=margin,
+ area_weight=0.0,
+ correct_aspect=True,
+ scale_to_bounds=False,
+ )
+ finally:
+ bpy.ops.object.mode_set(mode="OBJECT")
+ layer = mesh.uv_layers[UV_NAME] # edit mode reallocated the layers
+ uv = np.empty(len(layer.data) * 2, dtype=np.float64)
+ layer.data.foreach_get("uv", uv)
+ uv = uv.reshape(-1, 2)
+ mesh.calc_loop_triangles()
+ loops = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("loops", loops)
+ tri = uv[loops].reshape(-1, 3, 2)
+ e1, e2 = tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]
+ area = float(0.5 * np.abs(e1[:, 0] * e2[:, 1] - e1[:, 1] * e2[:, 0]).sum())
+ bbox = (
+ float(uv[:, 0].min()),
+ float(uv[:, 1].min()),
+ float(uv[:, 0].max()),
+ float(uv[:, 1].max()),
+ )
+ return Layout(bbox=bbox, uv_area=area)
+
+
+def _edit_objects(objects: list[bpy.types.Object]) -> None:
+ for obj in bpy.context.view_layer.objects:
+ obj.select_set(False)
+ for obj in objects:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = objects[0]
+ bpy.ops.object.mode_set(mode="EDIT")
+
+
+# ---------------------------------------------------------------- join
+
+
+OBJECT_SPACE_ATTR = "rt_orco"
+RANDOM_ATTR = "rt_random"
+
+
+def _keep_object_space(items: list[Item]) -> None:
+ """Store each object's own texture space before the objects are joined.
+
+ The kit's materials read Object coordinates and Object Info > Random;
+ joined objects share one space, so the original local coordinates and a
+ per-object random go into point attributes the patched materials read
+ (`_patch_materials`).
+ """
+ for index, item in enumerate(items):
+ mesh = item.obj.data
+ co = np.empty(len(mesh.vertices) * 3, dtype=np.float32)
+ mesh.vertices.foreach_get("co", co)
+ orco = mesh.attributes.new(OBJECT_SPACE_ATTR, "FLOAT_VECTOR", "POINT")
+ orco.data.foreach_set("vector", co)
+ rnd = mesh.attributes.new(RANDOM_ATTR, "FLOAT", "POINT")
+ value = ((index * 2654435761) % 4294967296) / 4294967296.0
+ rnd.data.foreach_set("value", np.full(len(mesh.vertices), value, dtype=np.float32))
+
+
+def _join_pages(items: list[Item]) -> list[tuple[int, bpy.types.Object]]:
+ """Join each page's objects into one object per set of ray visibility flags.
+
+ Cycles syncs the whole scene for every object it bakes, so a page bakes
+ as one or a few objects instead of hundreds.
+ """
+ groups: dict[tuple, list[bpy.types.Object]] = {}
+ for item in items:
+ obj = item.obj
+ flags = (
+ obj.visible_shadow,
+ obj.visible_diffuse,
+ obj.visible_glossy,
+ obj.visible_transmission,
+ )
+ groups.setdefault((item.page, flags), []).append(obj)
+ joined = []
+ for (page, _), objects in sorted(groups.items(), key=lambda kv: (kv[0][0], str(kv[0][1]))):
+ for obj in bpy.context.view_layer.objects:
+ obj.select_set(False)
+ for obj in objects:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = objects[0]
+ if len(objects) > 1:
+ bpy.ops.object.join()
+ target = bpy.context.view_layer.objects.active
+ target.name = f"RT_page{page}_{len(joined)}"
+ mesh = target.data
+ render_uv = mesh.uv_layers.get("UVMap")
+ if render_uv is not None:
+ render_uv.active_render = True
+ mesh.uv_layers.active = mesh.uv_layers[UV_NAME]
+ joined.append((page, target))
+ return joined
+
+
+def _patch_materials(materials: set[bpy.types.Material]) -> None:
+ """Point Object coordinates and Object Info > Random at the stored
+ attributes, and light the plate-only emitters (`light_glossy_emitters`)."""
+ light_glossy_emitters(materials)
+ for material in materials:
+ tree = material.node_tree
+ if tree is None:
+ continue
+ for link in list(tree.links):
+ node, socket = link.from_node, link.from_socket.name
+ if node.type == "TEX_COORD" and socket == "Object":
+ attr = tree.nodes.new("ShaderNodeAttribute")
+ attr.attribute_type = "GEOMETRY"
+ attr.attribute_name = OBJECT_SPACE_ATTR
+ tree.links.new(attr.outputs["Vector"], link.to_socket)
+ elif node.type == "OBJECT_INFO" and socket == "Random":
+ attr = tree.nodes.new("ShaderNodeAttribute")
+ attr.attribute_type = "GEOMETRY"
+ attr.attribute_name = RANDOM_ATTR
+ tree.links.new(attr.outputs["Fac"], link.to_socket)
+
+
+def light_glossy_emitters(materials) -> int:
+ """Make emitters that only the plate's floor mirror shows visible at eye level.
+
+ Some fixtures emit only for glossy (and camera) rays, so the plate shows
+ them in the floor mirror while spot lights do the lighting. The bake, the
+ probes and the eye-level camera must see them lit; the room's light must
+ not change: "Is Glossy Ray" and "Is Camera Ray" become "not a diffuse
+ ray". Returns how many links were rewired.
+ """
+ count = 0
+ for material in materials:
+ tree = material.node_tree
+ if tree is None:
+ continue
+ for link in list(tree.links):
+ node, socket = link.from_node, link.from_socket.name
+ if node.type == "LIGHT_PATH" and socket in ("Is Glossy Ray", "Is Camera Ray"):
+ lit = tree.nodes.new("ShaderNodeMath")
+ lit.operation = "SUBTRACT"
+ lit.inputs[0].default_value = 1.0
+ tree.links.new(node.outputs["Is Diffuse Ray"], lit.inputs[1])
+ tree.links.new(lit.outputs[0], link.to_socket)
+ count += 1
+ return count
+
+
+# ---------------------------------------------------------------- bake
+
+
+def _bake_page(
+ page: int, objects: list[bpy.types.Object], density: float, preset: Preset
+) -> np.ndarray:
+ """Bake one page; returns its radiance (h, w, 3) float32, gaps filled."""
+ size = preset.page_px
+ image = bpy.data.images.new(f"LM_bake_{page}", size, size, alpha=True, float_buffer=True)
+ image.colorspace_settings.name = "Non-Color"
+ materials = {m for obj in objects for m in obj.data.materials if m is not None}
+ nodes = []
+ for material in materials:
+ tree = material.node_tree
+ if tree is None:
+ continue
+ node = tree.nodes.new("ShaderNodeTexImage")
+ node.image = image
+ node.select = True
+ tree.nodes.active = node
+ nodes.append((tree, node))
+ for obj in bpy.context.view_layer.objects:
+ obj.select_set(False)
+ for obj in objects:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = objects[0]
+ bpy_scene = bpy.context.scene
+ bake = bpy_scene.render.bake
+ bake.target = "IMAGE_TEXTURES"
+ bake.use_selected_to_active = False
+ saved_samples = bpy_scene.cycles.samples
+ margin = preset.margin_px
+ try:
+ passes = {}
+ for name, kind, filters, samples, pad in (
+ ("normal", "NORMAL", set(), 1, margin),
+ ("position", "POSITION", set(), 1, margin),
+ ("albedo", "DIFFUSE", {"COLOR"}, 16, margin),
+ ("emit", "EMIT", set(), 16, margin),
+ ("irradiance", "DIFFUSE", {"DIRECT", "INDIRECT"}, preset.samples, margin),
+ ):
+ started = time.monotonic()
+ bpy_scene.cycles.samples = samples
+ bpy.ops.object.bake(
+ type=kind,
+ pass_filter=filters,
+ uv_layer=UV_NAME,
+ margin=pad,
+ margin_type="EXTEND",
+ use_clear=True,
+ normal_space="OBJECT",
+ target="IMAGE_TEXTURES",
+ )
+ pixels = np.empty(size * size * 4, dtype=np.float32)
+ image.pixels.foreach_get(pixels)
+ passes[name] = pixels.reshape(size, size, 4)[::-1, :, :3].copy()
+ print(
+ f"[verse] realtime page {page}: {name} {time.monotonic() - started:.1f} s",
+ flush=True,
+ )
+ finally:
+ bpy_scene.cycles.samples = saved_samples
+ for tree, node in nodes:
+ tree.nodes.remove(node)
+ bpy.data.images.remove(image)
+ guided = np.abs(passes["normal"]).sum(axis=2) > 0.05
+ normal = passes.pop("normal") * 2.0 - 1.0
+ texel_m = 1.0 / density
+ started = time.monotonic()
+ irradiance = lightmap.denoise(
+ passes.pop("irradiance"),
+ normal,
+ passes.pop("position"),
+ guided,
+ texel_m,
+ preset.denoise_passes,
+ )
+ print(f"[verse] realtime page {page}: denoise {time.monotonic() - started:.1f} s", flush=True)
+ radiance = passes["albedo"] * irradiance + passes["emit"]
+ radiance = np.where(np.isfinite(radiance), np.maximum(radiance, 0.0), 0.0)
+ return lightmap.fill_gaps(radiance, guided)
+
+
+# ---------------------------------------------------------------- probes
+
+
+def _reflection_probe(room: cook.Room, preset: Preset, out_dir: Path) -> dict:
+ """An equirect panorama of the room at eye height and the box it is projected on."""
+ position = cook._eye_point(room)
+ path = out_dir / f"probe_{room.id}.exr"
+ cook._render_panorama(
+ bpy.context.scene, position, preset.probe_size, preset.probe_samples, path
+ )
+ radiance = cook._load_linear_rgb(path)
+ path.unlink()
+ np.save(out_dir / f"probe_{room.id}.npy", radiance.astype(np.float16))
+ xs = [p[0] for p in room.polygon]
+ ys = [p[1] for p in room.polygon]
+ ceiling = _room_ceiling(room)
+ box_min = scene.to_three((min(xs), max(ys), room.z))
+ box_max = scene.to_three((max(xs), min(ys), ceiling))
+ return {
+ "room": room.id,
+ "file": f"probe_{room.id}.npy",
+ "w": preset.probe_size[0],
+ "h": preset.probe_size[1],
+ "position": scene.to_three(position),
+ "box_min": box_min,
+ "box_max": box_max,
+ }
+
+
+def _room_ceiling(room: cook.Room) -> float:
+ """Height of the room's ceiling: the median of upward hits over a grid of
+ points in the room (one ray at the probe point can find a fixture, a
+ gantry or an opening instead)."""
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ xs = [p[0] for p in room.polygon]
+ ys = [p[1] for p in room.polygon]
+ gx = np.linspace(min(xs), max(xs), 9)[1:-1]
+ gy = np.linspace(min(ys), max(ys), 9)[1:-1]
+ px, py = (a.ravel() for a in np.meshgrid(gx, gy))
+ inside = _points_in_polygon(px, py, room.polygon)
+ heights = []
+ for x, y in zip(px[inside], py[inside], strict=True):
+ origin = Vector((float(x), float(y), room.z + 1.4))
+ hit, location, *_ = bpy.context.scene.ray_cast(depsgraph, origin, Vector((0.0, 0.0, 1.0)))
+ if hit:
+ heights.append(float(location.z))
+ return float(np.median(heights)) if heights else room.z + 4.0
+
+
+# ---------------------------------------------------------------- geometry
+
+
+def _export_geometry(
+ joined: list[tuple[int, bpy.types.Object]], path: Path, stats: Stats
+) -> list[dict]:
+ """Group every triangle by (material, room, page) and write the chunks."""
+ rooms = cook._rooms()
+ corners: dict[tuple[str, str, int], list[tuple[np.ndarray, np.ndarray, np.ndarray]]] = {}
+ for page, obj in joined:
+ for key, arrays in _object_corners(obj, page, rooms).items():
+ corners.setdefault(key, []).append(arrays)
+ arrays: dict[str, np.ndarray] = {}
+ chunks = []
+ for index, key in enumerate(sorted(corners)):
+ material, room, page = key
+ pos = np.concatenate([c[0] for c in corners[key]])
+ nrm = np.concatenate([c[1] for c in corners[key]])
+ uv = np.concatenate([c[2] for c in corners[key]])
+ vertices, indices = _weld(pos, nrm, uv)
+ arrays[f"{index}_pos"] = vertices[:, 0:3].astype(np.float32)
+ arrays[f"{index}_nrm"] = vertices[:, 3:6].astype(np.float32)
+ arrays[f"{index}_uv"] = vertices[:, 6:8].astype(np.float32)
+ arrays[f"{index}_idx"] = indices.astype(np.uint32)
+ chunks.append(
+ {
+ "index": index,
+ "material": material,
+ "room": room,
+ "page": page,
+ "vertices": int(len(vertices)),
+ "triangles": int(len(indices) // 3),
+ }
+ )
+ stats.vertices += len(vertices)
+ stats.triangles += len(indices) // 3
+ stats.chunks = len(chunks)
+ np.savez(path, **arrays)
+ return chunks
+
+
+def _object_corners(obj: bpy.types.Object, page: int, rooms: list[cook.Room]) -> dict:
+ """Per (material, room, page): world positions, normals and LM UVs per triangle corner."""
+ mesh = obj.data
+ mesh.calc_loop_triangles()
+ n = len(mesh.loop_triangles)
+ if n == 0:
+ return {}
+ loops = np.empty(n * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("loops", loops)
+ verts = np.empty(n * 3, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("vertices", verts)
+ mat_index = np.empty(n, dtype=np.int32)
+ mesh.loop_triangles.foreach_get("material_index", mat_index)
+ co = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
+ mesh.vertices.foreach_get("co", co)
+ normals = np.empty(len(mesh.loops) * 3, dtype=np.float64)
+ mesh.corner_normals.foreach_get("vector", normals)
+ uv = np.empty(len(mesh.loops) * 2, dtype=np.float64)
+ mesh.uv_layers[UV_NAME].data.foreach_get("uv", uv)
+ matrix = np.array(obj.matrix_world, dtype=np.float64)
+ linear = matrix[:3, :3]
+ normal_matrix = np.linalg.inv(linear).T
+ pos = co.reshape(-1, 3)[verts] @ linear.T + matrix[:3, 3]
+ nrm = normals.reshape(-1, 3)[loops] @ normal_matrix.T
+ nrm /= np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-12)
+ tex = uv.reshape(-1, 2)[loops]
+ # Room per triangle: the side its face looks into.
+ tri = pos.reshape(n, 3, 3)
+ face_n = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
+ face_n /= np.maximum(np.linalg.norm(face_n, axis=1, keepdims=True), 1e-12)
+ probe = tri.mean(axis=1) + face_n * 0.08
+ room_of = _rooms_of(probe[:, 0], probe[:, 1], rooms)
+ names = [_base_name(m.name) if m is not None else "M_Default" for m in mesh.materials]
+ out: dict = {}
+ for m in np.unique(mat_index):
+ material = names[min(int(m), len(names) - 1)] if names else "M_Default"
+ for room in np.unique(room_of[mat_index == m]):
+ sel = np.repeat((mat_index == m) & (room_of == room), 3)
+ key = (material, rooms[int(room)].id, page)
+ out[key] = (_to_three(pos[sel]), _to_three(nrm[sel]), tex[sel])
+ return out
+
+
+def _to_three(v: np.ndarray) -> np.ndarray:
+ """Blender (x, y, z) -> three.js (x, z, -y)."""
+ return np.stack([v[:, 0], v[:, 2], -v[:, 1]], axis=1)
+
+
+def _rooms_of(x: np.ndarray, y: np.ndarray, rooms: list[cook.Room]) -> np.ndarray:
+ """Index of the room polygon containing each point (Blender XY); the nearest centre outside."""
+ result = np.full(len(x), -1, dtype=np.int32)
+ for index, room in enumerate(rooms):
+ inside = _points_in_polygon(x, y, room.polygon)
+ result[(result < 0) & inside] = index
+ missing = result < 0
+ if missing.any():
+ centres = np.array([room.centre for room in rooms])
+ d = (x[missing, None] - centres[None, :, 0]) ** 2 + (
+ y[missing, None] - centres[None, :, 1]
+ ) ** 2
+ result[missing] = d.argmin(axis=1)
+ return result
+
+
+def _points_in_polygon(x: np.ndarray, y: np.ndarray, polygon) -> np.ndarray:
+ inside = np.zeros(len(x), dtype=bool)
+ pts = list(polygon)
+ for (x0, y0), (x1, y1) in zip(pts, pts[1:] + pts[:1], strict=True):
+ crosses = (y0 > y) != (y1 > y)
+ with np.errstate(divide="ignore", invalid="ignore"):
+ at = x0 + (y - y0) * (x1 - x0) / (y1 - y0)
+ inside ^= crosses & (x < at)
+ return inside
+
+
+def _weld(pos: np.ndarray, nrm: np.ndarray, uv: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Merge identical corners into shared vertices; returns (vertices (v, 8), indices)."""
+ key = np.concatenate(
+ [np.round(pos * 1e4), np.round(nrm * 1e3), np.round(uv * 2e6)], axis=1
+ ).astype(np.int64)
+ _, first, inverse = np.unique(key, axis=0, return_index=True, return_inverse=True)
+ vertices = np.concatenate([pos, nrm, uv], axis=1)[first]
+ return vertices, inverse.reshape(-1).astype(np.uint32)
+
+
+# ---------------------------------------------------------------- materials
+
+
+def _material_json(name: str) -> dict:
+ material = MATERIALS.get(name)
+ if material is None:
+ material = _fallback_material(name)
+ print(
+ f"[verse] realtime: material {name} is not in MATERIALS; read off its nodes: "
+ f"{material}",
+ flush=True,
+ )
+ data = asdict(material)
+ data["color"] = [round(c, 4) for c in data["color"]]
+ return data
+
+
+def _fallback_material(name: str) -> RtMaterial:
+ """Specular parameters read off the material's nodes: an emission-only
+ surface is an emitter, otherwise the Principled BSDF's defaults."""
+ material = bpy.data.materials.get(name)
+ tree = material.node_tree if material is not None else None
+ output = _material_output(tree) if tree is not None else None
+ surface = output.inputs["Surface"].links if output is not None else []
+ if surface and surface[0].from_node.type == "EMISSION":
+ return _EMITTER
+ bsdf = next((n for n in tree.nodes if n.type == "BSDF_PRINCIPLED"), None) if tree else None
+ if bsdf is None:
+ return RtMaterial()
+
+ def value(socket: str, default: float) -> float:
+ inp = bsdf.inputs.get(socket)
+ if inp is None or inp.is_linked:
+ return default
+ v = inp.default_value
+ return float(v) if isinstance(v, float) else default
+
+ metal = value("Metallic", 0.0)
+ colour = bsdf.inputs["Base Color"].default_value
+ transmission = value("Transmission Weight", 0.0)
+ return RtMaterial(
+ roughness=value("Roughness", 0.5),
+ metalness=metal,
+ color=(float(colour[0]), float(colour[1]), float(colour[2])) if metal > 0.5 else (0, 0, 0),
+ clearcoat=value("Coat Weight", 0.0),
+ clearcoat_roughness=value("Coat Roughness", 0.05),
+ transparent=transmission > 0.5,
+ opacity=0.1 if transmission > 0.5 else 1.0,
+ collide=transmission <= 0.5,
+ )
diff --git a/art/verse/schema/deck.schema.json b/art/verse/schema/deck.schema.json
index d0c284b88f..9969d6d029 100644
--- a/art/verse/schema/deck.schema.json
+++ b/art/verse/schema/deck.schema.json
@@ -186,6 +186,90 @@
"bytes": { "type": "integer" },
"plate_bytes": { "type": "integer" }
}
+ },
+ "realtime": {
+ "description": "Optional: the deck as an eye-level 3D scene (docs/verse/realtime.md). Written by `cook.py deck <id> --realtime`; absent on decks never exported.",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["version", "quality", "scene", "lightmaps", "probes", "materials", "bytes", "stats"],
+ "properties": {
+ "version": { "const": 1 },
+ "quality": { "enum": ["preview", "final"] },
+ "scene": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["url", "vertices", "triangles", "chunks"],
+ "properties": {
+ "url": { "type": "string", "pattern": "^realtime/[^/]+\\.glb$", "description": "Meshopt-compressed glTF 2.0 (EXT_meshopt_compression, KHR_mesh_quantization); one node per (material, room, page) chunk with extras {material, room, page}; TEXCOORD_0 is the lightmap UV." },
+ "vertices": { "type": "integer", "minimum": 1 },
+ "triangles": { "type": "integer", "minimum": 1 },
+ "chunks": { "type": "integer", "minimum": 1 }
+ }
+ },
+ "lightmaps": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["encoding", "range", "pages"],
+ "properties": {
+ "encoding": { "const": "rgbm2", "description": "RGBA8: m = a^2 * range, rgb = c^2 * m (linear scene radiance, albedo and emission included)." },
+ "range": { "type": "number", "exclusiveMinimum": 0 },
+ "pages": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["url", "size", "density"],
+ "properties": {
+ "url": { "type": "string", "pattern": "^realtime/[^/]+\\.webp$" },
+ "size": { "type": "integer", "minimum": 64, "maximum": 8192 },
+ "density": { "type": "number", "exclusiveMinimum": 0, "description": "Texels per metre at density weight 1." }
+ }
+ }
+ }
+ }
+ },
+ "probes": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["room", "url", "w", "h", "range", "position", "box_min", "box_max"],
+ "properties": {
+ "room": { "type": "string" },
+ "url": { "type": "string", "pattern": "^realtime/[^/]+\\.webp$" },
+ "w": { "type": "integer", "minimum": 1 },
+ "h": { "type": "integer", "minimum": 1 },
+ "range": { "type": "number", "exclusiveMinimum": 0 },
+ "position": { "$ref": "#/$defs/vec3" },
+ "box_min": { "$ref": "#/$defs/vec3" },
+ "box_max": { "$ref": "#/$defs/vec3" }
+ }
+ }
+ },
+ "materials": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["roughness", "metalness", "color", "clearcoat", "clearcoat_roughness", "specular", "detail", "transparent", "opacity", "collide"],
+ "properties": {
+ "roughness": { "type": "number", "minimum": 0, "maximum": 1 },
+ "metalness": { "type": "number", "minimum": 0, "maximum": 1 },
+ "color": { "$ref": "#/$defs/vec3" },
+ "clearcoat": { "type": "number", "minimum": 0, "maximum": 1 },
+ "clearcoat_roughness": { "type": "number", "minimum": 0, "maximum": 1 },
+ "specular": { "type": "number", "minimum": 0, "maximum": 1 },
+ "detail": { "enum": ["none", "deck_plates", "painted", "metal"] },
+ "transparent": { "type": "boolean" },
+ "opacity": { "type": "number", "minimum": 0, "maximum": 1 },
+ "collide": { "type": "boolean" }
+ }
+ }
+ },
+ "bytes": { "type": "integer", "minimum": 0 },
+ "stats": { "type": "object" }
+ }
}
},
"$defs": {
diff --git a/docs/verse/README.md b/docs/verse/README.md
index 11c1190328..21314f1507 100644
--- a/docs/verse/README.md
+++ b/docs/verse/README.md
@@ -17,6 +17,8 @@ on engineering).
| [`art/verse/LEVELS.md`](../../art/verse/LEVELS.md) | The level design of every deck: rooms, sockets, station kinds. |
| [`art/verse/ART_DIRECTION.md`](../../art/verse/ART_DIRECTION.md) | The art director's standing notes. |
| [`pipeline.md`](pipeline.md) | The production pipeline: stages, naming, budgets, cook, validation, Blender MCP. |
+| [`realtime.md`](realtime.md) | The eye-level view: realtime export of a deck (lightmaps, probes, glTF), its manifest block, the runtime and the over-the-shoulder camera. |
+| [`combat.md`](combat.md) | The optional reactor duel: the combat core (simulation, netcode, bot, balance) and how it plays in the 3D view (start, controls, camera, effects, HUD, sound). |
| [`../agent-society/level-system.md`](../agent-society/level-system.md) | Ranks, XP rules, rewards and the service record. |
## How it is made
@@ -47,9 +49,18 @@ framing at its own size; a low, wide one still shows at least 5 m of floor top
to bottom. The camera never comes closer than the plate is sharp: an older
deck cooked at 96 px/m, or a HiDPI screen, stops a little further out.
-**V** (or the bird's-eye button on the tool rail) pulls the camera back over
-the whole deck; there WASD pans the map. V again returns to the commander at
-the close zoom. In both views a click on the floor walks there, a click on a
+**Duel.** At any of the four consoles on the reactor's control ring (Reactor
+Engineering) E offers *Start a duel*; the **Duel** button on the tool rail does
+the same from any deck (the turbolift rides down first). Choose normal, hard
+or elite and fight a 1v1 blaster duel against a bot, best of three; Esc pauses,
+Esc again leaves and puts the commander back on the deck. See
+[`combat.md`](combat.md).
+
+**Views.** The tool rail's switch offers the **bird's-eye** view, **third
+person** and **first person**; 1, 2 and 3 pick one and V cycles them (the last
+choice is remembered). The bird's-eye view pulls the camera back over the
+whole deck; there WASD pans the map. Choosing third or first person returns
+to the commander at the close zoom. In both views a click on the floor walks there, a click on a
crew member selects them, a drag looks around (the camera picks the commander
up again when they walk) and the wheel or +/- zooms between the whole deck and
the closest view the plate allows.
@@ -63,9 +74,19 @@ a shared budget (`engine/tiles.ts`, `engine/tileStreamer.ts`,
`engine/plateLayer.ts`). Older decks without mips stream the overview and L0
as before.
-The deck stays a pre-rendered plate seen from one fixed angle, so the third
-person camera follows from above, not from behind the shoulder; a camera
-behind the commander would need the decks as real-time 3D scenes.
+A deck exported as a real-time 3D scene ([`realtime.md`](realtime.md); the
+bridge so far) is walked at eye level instead on the full-size stage: the
+camera sits behind the commander's shoulder (the commander stands in the
+lower right third of the frame) or, in first person, at their eyes. Both play
+like a shooter: a click on the view takes the mouse, moving it turns the view,
+the left button or E works what the crosshair is on, Esc gives the mouse back
+so the HUD's buttons work. WASD walk relative to the view (A/D strafe) and the
+commander faces it while walking. The wheel moves the third-person camera
+between 1.2 and 5 m; scrolling in past that is first person, scrolling out of
+first person comes back. The camera never passes through walls. The view
+settings set mouse sensitivity, inverted look and the field of view of each
+person. The IDE side panel keeps the plate. Details: [`realtime.md`](realtime.md)
+("Views").
## Decks
diff --git a/docs/verse/combat.md b/docs/verse/combat.md
new file mode 100644
index 0000000000..ea97ce8c4a
--- /dev/null
+++ b/docs/verse/combat.md
@@ -0,0 +1,907 @@
+# Verse combat: the reactor duel
+
+Status: **combat core built, tested and through an adversarial pass,
+2026-10-20; playable in the 3D view since 2026-10-26** (see "In the 3D view"). The Verse stays a workspace first. Combat is optional: the person
+starts a 1v1 blaster duel at any time from the control ring in the middle of
+the **Reactor Shaft** hall on the engineering deck, against a bot today and
+against another person later. Leaving is always one key away.
+
+Code: `dodaios/ui/web/frontend/src/components/society/verse/combat/`
+(TypeScript, no React, no three.js). This document covers the architecture,
+the arena, the rules and their tuned numbers, the bot, the balance results
+and what the integrator has to do.
+
+| File | What it is |
+|---|---|
+| `sim.ts` | The deterministic fixed-tick simulation: `createMatch`, `step(state, inputs, ctx)`. |
+| `types.ts`, `input.ts`, `tuning.ts` | InputCommand, MatchState, CombatEvent; control state to input; every balance number. |
+| `arena.ts`, `arenaReactor.ts` | Arena description and runtime (movement grid, raycasts, cover); the Reactor Shaft arena. |
+| `raycast.ts`, `rng.ts`, `math.ts` | Segment sweeps; seeded randomness; small math. |
+| `observe.ts` | What a player can know (line of sight, view cone, sounds). The bot reads only this. |
+| `protocol.ts`, `transport.ts` | Versioned wire messages; Channel, in-process LocalNetwork, WebSocket adapter. |
+| `server.ts`, `client.ts` | Authoritative MatchServer; MatchClient with prediction, reconciliation, interpolation. |
+| `view.ts`, `camera.ts` | Per-frame ViewState and HUD; shoulder-camera rigs and crosshair convergence. |
+| `session.ts`, `index.ts` | `createLocalDuel()`: the one object the 3D view needs; the public surface. |
+| `bot/` | `BotBrain` (tactics and reflexes), `AimController`, route finding, difficulty tiers. |
+| `harness/` | Headless duels, person models and scripted exploit strategies, balance runs (`cli.ts` for big runs, in parallel). |
+| `*.test.ts` | Unit, netcode and adversarial tests (`exploits.test.ts`, `netcodeAdversarial.test.ts`, `harness/exploits.test.ts`). |
+
+## Architecture
+
+Multiplayer from day one: even the duel against the bot runs as a server
+with two clients. The bot is just another client.
+
+```
+ +-------------------------------------------+
+ | MatchServer (authoritative) |
+ | MatchState --step(state, inputs)--> ... |
+ | 60 Hz fixed tick, input queue per player |
+ +-----------+-------------------+-----------+
+ snapshots, events | | snapshots, events
+ (full state, ack) | |
+ +-----------v-----+ +-----v-----------+
+ Transport --> | Channel | | Channel | <-- Transport
+ (LocalNetwork +-----------+-----+ +-----+-----------+ (LocalNetwork
+ now, WebSocket | InputCommands | today)
+ for PvP) +-----------v-----+ +-----v-----------+
+ | MatchClient | | MatchClient |
+ | prediction | | prediction |
+ | reconciliation | | reconciliation |
+ | interpolation | | interpolation |
+ +-----------+-----+ +-----+-----------+
+ | |
+ keys + mouse observe(view) -> BotBrain
+ ViewState, events (same information a person has)
+```
+
+### The simulation
+
+`step(state, inputs, ctx) -> { state, events }` is pure and deterministic:
+
+- **Fixed tick**, 60 Hz. Every duration is in ticks.
+- **No clock, no `Math.random`.** Random draws are *counter-based*: the spread
+ of shot N of player P is `hash(matchSeed, P, N, salt)`, a deflection angle
+ is `hash(matchSeed, boltId, tick, salt)`. A client predicting its own shot
+ gets exactly the server's spread without sharing an RNG stream. Bots and the
+ harness use their own seeded generators (`Rng`).
+- **Plain JSON state** (`MatchState`): players, bolts, scores, phase, a short
+ pose history for lag compensation. No classes, no maps.
+- **Quantised every step**: positions to 1 mm, aim to 1e-4 rad, health/heat/
+ energy to 1e-3. The wire format uses the same grid, so a snapshot carries
+ the server's state *exactly* and a client's replay matches it bit for bit.
+- **Inputs, not actions**: `inputs[slot]` is an InputCommand or `null` (the
+ player's last input repeats: held buttons stay held, presses do not repeat).
+- **Nothing from a client is trusted**: every command goes through
+ `sanitizeInput` inside the step. A legal command (anything `makeInput`
+ builds) passes unchanged, so prediction still matches; anything else is made
+ legal: the move stick is clamped to length 1 (a diagonal is never faster),
+ non-numbers become 0 or the previous aim, pitch is clamped, unknown button
+ bits are dropped.
+- Order inside a tick: aim and presses, then dodge/shield/vent/sights/sprint,
+ movement, every player's trigger, then the lag-compensation rewind of the
+ new bolts (so a rewound bolt can never stop the other player's shot of the
+ same tick), bolts, regeneration and timers, round rules.
+
+An `InputCommand` is everything a player ever sends:
+
+| Field | Meaning |
+|---|---|
+| `seq` | Per-player sequence number, +1 per tick (acknowledged back for reconciliation). |
+| `mx`, `my` | Strafe right / forward, -1..1, in the aim frame (WASD). Sent as 1/127. |
+| `yaw`, `pitch` | Absolute aim, radians (yaw 0 faces +Z like the deck sockets). Sent as 1e-4. |
+| `buttons` | FIRE, ADS, SHIELD, SPRINT (held), DODGE, VENT, FORFEIT (pressed). |
+| `viewTick` | The server tick the client was displaying (its interpolation time), for lag compensation; -1 = none. |
+
+### Server, clients, transport
+
+- **MatchServer** accepts Channels; a duel starts when two players said hello
+ with the same protocol version and the same **rules hash** (`rulesHash`:
+ the tuning and the arena, so a client built for a re-laid-out room is
+ rejected instead of mispredicting every wall). It runs the fixed step on its
+ own clock (`update(nowMs)`), applies one queued input per player per tick
+ (a late player's last input repeats; a queue longer than 6 is trimmed so a
+ player who fell behind catches up, and the presses of the dropped inputs
+ carry over into the next one, so a roll or vent is never lost), and every
+ `snapshotEvery` ticks sends each player the full state, the last input it
+ applied for them (`ackSeq`) and every event since the snapshot that client
+ last confirmed (each input message names it; at least two snapshot periods,
+ at most 1.5 s), so lost snapshots lose no effect. Malformed messages are
+ ignored. A leave or a closed channel ends the match for the other player;
+ the end message is reliable and carries the final snapshot, so the last
+ kill, round end and match end always arrive.
+- **MatchClient** turns the control state into one InputCommand per tick,
+ sends it together with the previous two (loss), and steps its own copy of
+ the match with it at once (**prediction**). On a snapshot it takes the
+ server's state, drops the acknowledged inputs and replays the rest
+ (**reconciliation**). The opponent is drawn from the snapshots, a little in
+ the past (**snapshot interpolation**), never from guesses. Own actions
+ (shots, rolls, shield, vents) play from the prediction at once; everything
+ else from the server; each event plays once (`eventKey`). It also counts how
+ often its prediction was wrong (`prediction`), for a debug overlay.
+- **Lag compensation hook**: the server keeps 32 ticks of poses. A shot's
+ `viewTick` says what the shooter saw; the server flies the new bolt through
+ the ticks between that and now against the poses of those ticks (projectile
+ fast-forward, at most 15 ticks = 250 ms), then on as usual. On in the local
+ duel (it makes the person's shots land on the opponent they see), and the
+ switch for PvP.
+- **Transport**: server and clients only see a `Channel`. `LocalNetwork` links
+ them in-process on a virtual clock and, for tests or practice, adds seeded
+ latency, jitter and loss (reliable messages are never dropped and stay in
+ order among themselves). Messages pass through JSON like on a real wire.
+ `socketChannel(ws)` adapts a browser or Node WebSocket for the PvP server.
+
+### Wire protocol, version 2
+
+JSON arrays with a one-letter tag; numbers in states and inputs are integers
+on the quantisation grid. Version 2 (the adversarial pass): the hello carries
+the rules hash, snapshots carry the events since the client's last confirmed
+snapshot, and the end message carries the final snapshot.
+
+| Direction | Message | Reliable |
+|---|---|---|
+| C to S | `["h", version, playerId, name, rulesHash]` hello | yes |
+| C to S | `["i", lastSnapshotTick, [[seq, mx*127, my*127, yaw*1e4, pitch*1e4, buttons, viewTick], ...]]` newest inputs, repeated; `lastSnapshotTick` confirms what the client has | no |
+| C to S | `["l"]` leave (forfeit) | yes |
+| C to S | `["p", clientMs]` ping | no |
+| S to C | `["w", version, slot, matchId, seed, rulesHash, arenaId, snapshotEvery, config, playerIds]` welcome | yes |
+| S to C | `["s", tick, ackSeq, state, events]` snapshot (full state, about 0.5 kB) and the events since the client's confirmed snapshot | no |
+| S to C | `["e", winner, reason, scores, tick, ackSeq, state, events]` match over, with the final snapshot | yes |
+| S to C | `["o", clientMs, serverTick]` pong | no |
+| S to C | `["r", reason]` rejected (version, tuning or arena, bad id, full, duplicate) | yes |
+
+Measured at 30 Hz snapshots over a 50 ms link: about 18 kB/s down (snapshots
+of about 0.5 kB) and 6 kB/s up (inputs of about 95 B, sent 60 times a second
+with the two before) per player, uncompressed. A binary encoding of the same
+arrays is a drop-in later.
+
+### Why this is ready for PvP
+
+To play another person: run `MatchServer` in Node behind a WebSocket server,
+give each person a `MatchClient` over `socketChannel`, set `snapshotEvery: 2`
+and `lagCompensation: true`. Nothing in the simulation, the client, the view
+or the protocol changes. Open items for real PvP are listed at the end.
+
+## The arena: Reactor Shaft
+
+The duel happens in the reactor hall of the engineering deck (manifest room
+`reactor`), in the deck's own frame: x to the right, z toward the camera, y
+up, metres. The arena overlays the deck one to one.
+
+```
+ far wall (z 2): heat stacks O, machinery bays [##]
+ x 33 +--------------------------------------------------+ x 82
+ | O O [##][###][##] O O O |
+ | . N . |
+ | . | . [=] || | [=] coolant run (1 m high)
+ | . | . | || power conduit (to ceiling)
+ W 0 >- - - - - -( ( core ) )- - - - - - < 1 [=] || | E
+ | . | . |
+ | . | . [=] || |
+ | . S . |
+ +-------- door ---------- door ---------- door -----+ z 38.1
+ 0, 1: spawns (sides swap every round). The circle is the drop (r 13);
+ the core stands on a control ring (r 5..6.5) reached by four catwalks.
+```
+
+| Element | Where (deck metres) | Movement | Bolts |
+|---|---|---|---|
+| Hall | x 33..82, z 2..38.1, ceiling 12 | inside | walls stop them; doorways let them out |
+| Shaft (drop) | centre (54, 22), r 13 | blocked (no falling) | fly over it, fall in |
+| Control ring | r 5..6.5 around the axis | walkable | floor |
+| Catwalks N, E, S, W | 1.2 m wide, ring to rim | walkable | floor |
+| Core containment | r 3.75, up to 1.9 m | blocked | stops them (cover); shots over 1.9 m pass |
+| Heat stacks | x 35.4, 41.4, 66.6, 72.6, 78.6; z 3.35; r 1.35 | blocked | stop them |
+| Machinery bays | x 45.6..50.8, 52.6..55.6, 57.2..62.4 on the far wall | blocked | stop them |
+| Power conduits | x 78.0..79.4, z 12/22/32 +-1.15, to the ceiling | blocked | stop them (hard cover) |
+| Coolant runs | x 70.8..75.6, z 12/22/32 +-0.7, 1.0 m high | blocked | stop low bolts only |
+| Spawns | side 0 (38.8, 22) facing +X; side 1 (69.2, 22) facing -X | | out of each other's sight (the core) |
+| Duel terminals | ring consoles `reactor_ring__ring_1..4` (58.24, 17.76), (49.76, 17.76), (49.76, 26.24), (58.24, 26.24) | | |
+
+Derived from the deck sources (`art/verse/decks/engineering/eng_common.py`,
+`eng_reactor.py`, `eng_dressing.py`, `art/verse/kit/props/industrial/reactor.py`).
+`arena.test.ts` checks it against the cooked deck: the room outline and the
+ring consoles match the manifest, and away from the rim band the walkable
+area agrees with `nav.png` to more than 95% both ways. One deliberate
+difference: the cooked nav grid marks most of the 2.4 m rim band around the
+drop as blocked (plate seams and bolt strips); the arena treats it as floor up
+to the kerb, as it reads on screen, so the narrow south passage between the
+drop and the gallery wall stays open. The arena's movement grid is 0.1 m,
+eroded by the body radius (0.3 m).
+
+Spawns are mirrored about the shaft axis and the players swap sides every
+round (the first round's sides come from the seed), so the room's east/west
+differences even out: over 20,051 balance rounds side 0 won 50.6% (see below).
+
+## Rules and tuned numbers
+
+A match is best of three rounds (first to 2, at most 5 rounds with draws).
+Each round: a 3 s countdown (aim only), then live play until a player dies or
+90 s pass (then the higher health wins the round), then a 2.5 s pause. Forfeit
+works at any moment. 40 s into a round the **reactor surges**: health stops
+regenerating and both players' positions are pinged on the HUD every 1.5 s,
+so no round can stall in a hide-and-seek between people.
+
+### Blaster
+
+| | Value |
+|---|---|
+| Rate of fire | 5 bolts/s (12 ticks), full-auto while held |
+| Bolt | travels at 60 m/s (visible, dodgeable at range), 6 cm radius, 90 m range |
+| Damage | 15 up to 12 m, falling to 9 at 32 m; headshots (>= 1.5 m high) x1.5 |
+| Time to kill, all hits | 7 bolts = 1.2 s close, about 2.2 s at 30 m; 0.8 s with headshots |
+| Heat | +9 per shot; cools 35/s after 0.3 s without firing |
+| Overheat | at 100 (the 12th bolt in a row): locked 2.5 s; a vent press 0.9..1.25 s into the lock ends it at once |
+| Manual vent | press when heat >= 5: 0.5 s + 0.01 s per heat point; a second press in the window (30..52% of the vent) finishes it at once; one try per vent |
+| Spread (cone half-angle) | hip 1.6 deg, sights 0.3 deg; +1.0 / +0.3 deg at full run speed |
+| Bloom | +0.45 deg per shot hip (max 3.5), +0.2 in sights (max 1.5); recovers 5 deg/s after 0.1 s |
+| Recoil | kicks the aim up 0.55 deg (hip) / 0.35 deg (sights) and +-0.2 deg sideways per shot; settles 9 deg/s by itself |
+| Sights | 0.18 s in, 0.12 s out; 60% move speed |
+| Not while | shield up, rolling (and 0.2 s after), venting, sprinting (and 0.15 s after) |
+
+### Energy shield
+
+| | Value |
+|---|---|
+| Energy | 100; raising needs 20 and costs 6; drains 8/s while up |
+| Coverage | a front arc of +-60 deg around the aim, 0.8 m out, 2 m high |
+| Normal block | absorbs the bolt for 0.9 energy per point of its damage; 40% of blocked bolts glance off at a seeded angle (+-40 deg about the mirror direction) with half damage, as the blocker's bolt |
+| Perfect parry | a bolt meeting the shield within 0.15 s (9 ticks) of raising it goes straight back at whoever sent it (+-1.2 deg), 1.2x faster, full damage, no energy cost; up to 3 reflections per bolt (rallies) |
+| Whiff penalty | a raise whose parry window met no bolt turns the parry window off for raises in the next 1.0 s; timed parries stay strong, flicking earns nothing |
+| Re-raise lockout | 0.4 s after lowering |
+| Break | at 0 energy: down for 3 s, then regenerates from 0; the key must be pressed again |
+| Regeneration | 20/s after 0.9 s lowered |
+| While up | 50% move speed, no firing, no sights, no sprint |
+
+### Movement and health
+
+| | Value |
+|---|---|
+| Run | 4.8 m/s (78% straight back), acceleration 34 m/s2, braking 42 m/s2 |
+| Sprint | 7.0 m/s, input within 50 deg of forward, ends on fire/sights/shield |
+| Dodge roll | 4 m in 0.4 s in the move direction (back if none), 2.0 s cooldown, **no invulnerability frames**, blaster back 0.2 s after |
+| Health | 100; regenerates 10/s after 5 s without damage (not during the surge) |
+| Bodies | 0.3 m radius on the grid; bolt hit capsule 0.34 m (+0.06 bolt) from 0.34 to 1.46 m; heads from 1.5 m |
+
+## The bot
+
+`BotBrain` is a client like any other: each tick it gets an `Observation`
+and returns a `ControlState`, which becomes an InputCommand through the same
+`makeInput` as a person's keys.
+
+**Fair perception (`observe.ts`).** It sees what the person's screen would
+show: the opponent inside the hip camera's view (+-55 deg from the camera
+behind the right shoulder: 70 deg vertical at 16:9 shows +-51 deg, so close
+by it sees far to the sides, as the screen does) or within 3 m, with a clear
+line to the opponent's head, chest or hips from its eyes or from the camera
+(the shoulder view looks round a right-hand corner before the body leaves
+cover, for people and bots alike; the camera is pulled in at walls). It sees
+bolts the same way, hears shots (where from), running footsteps within 9 m
+(16 m sprinting) and the surge pings, and knows which way a hit came from.
+Health bars are on both HUDs, so it knows health. A test runs whole duels and
+checks that every shot it fires follows a real sighting.
+
+**Human-like timing.** A new sighting is acted on after a sampled reaction
+time; while tracking, it acts on what it saw 95..150 ms ago (extrapolated);
+incoming bolts are answered after their own reaction delay. It decides a few
+times a second, not every frame.
+
+**Aim (`bot/aim.ts`).** It leads with its read of the target's motion: the
+velocity it sees, or, once the target has turned its running round twice
+within 0.7 s (A-D strafing), the average over the last 200..300 ms, so a
+wobbling target is aimed at the middle of its wobble instead of chased, as a
+practised player does. A speed-limited, stiffness-settled mouse with a
+wandering error (Ornstein-Uhlenbeck) and a larger error right after acquiring
+a target that fades; partial lead on a moving target with noise in its speed
+read; partial recoil compensation; it aims where a roll will end and holds
+fire into rolls; fires only when the aim is within a tier-set multiple of the
+target's width.
+
+**Tactics (utility, with hysteresis).** Fight in the open (strafe with
+changing rhythm, hold a range, close in without a line of sight; a far
+opponent is approached only with a reason, when it vents or its shield is
+broken, when the bot leads by 25 health or beyond 34 m, otherwise the bot
+trades from where it is and drifts in slowly, because walking straight at a
+shooter makes the easiest target there is), take cover
+and peek (cover spots are precomputed next to every tall solid: core, stacks,
+machinery, conduits; it picks one hidden from the opponent with a peek point
+that has a line), retreat to regenerate when losing, push an overheated,
+venting, shield-broken or weak opponent, flank (to the opponent's side or
+back), hunt (last sighting, sounds, then an approach lane chosen per round
+through the middle or round either side, then search on).
+
+**Reflexes.** Per seen incoming bolt: a timed parry (raise half a window
+before impact, with a timing error), a dodge roll sideways toward open floor,
+or a block. A steady stream is read by its rhythm and the next bolt parried.
+Under pressure and losing the trade it blocks for a moment, then answers.
+Vents are timed with an error (larger under fire). A freshly raised shield is
+baited (it holds fire to not feed a parry) and its drop punished during the
+0.4 s re-raise lockout.
+
+**Tiers.** All parameters live in `bot/tiers.ts`; `createLocalDuel({ difficulty, bot })` takes a tier and optional overrides.
+
+| | normal | hard | elite |
+|---|---|---|---|
+| Reaction (mean, sd) | 305 +- 60 ms | 255 +- 50 ms | 215 +- 40 ms |
+| Tracking latency | 150 ms | 120 ms | 95 ms |
+| Aim error (wandering) | 1.6 deg | 1.15 deg | 0.92 deg |
+| Mouse speed | 380 deg/s | 520 deg/s | 720 deg/s |
+| Lead / recoil control | 60% / 35% | 80% / 70% | 90% / 85% |
+| Reads A-D strafing (motion window) | never | 200 ms | 300 ms |
+| Heat cap | never stops (overheats) | 86 | 80 |
+| Vent timing error | 160 ms | 85 ms | 50 ms |
+| Parry tries / timing error | 25% / 110 ms | 45% / 65 ms | 65% / 42 ms |
+| Block / dodge use | 42% / 12% | 60% / 25% | 75% / 35% |
+| Cover / flank / aggression | 0.4 / 0.2 / 0.5 | 0.65 / 0.45 / 0.6 | 0.85 / 0.7 / 0.7 |
+| Bait and punish | never | 55% | 90% |
+| Head aim | never | 15% | 25% |
+| Decides every | 320 ms | 220 ms | 160 ms |
+
+## Balance
+
+The harness (`harness/`) runs headless duels: two controllers observe the
+authoritative state through `observe` and step the simulation directly (the
+same duels over the full client/server stack play out the same; see
+"Netcode under attack" below). It has three kinds of players:
+
+- **The bot tiers.**
+- **Two person models** (`harness/strategies.ts`), to estimate how people
+ fare. *Skilled*: reactions 225 +- 18 ms (nearly all within 200..250 ms), a
+ 110 ms tracking delay, aim error 1.0 deg (elite 0.92), fast flicks
+ (900 deg/s), heads 30% of the time, vents and parries timed by eye
+ (sd 60 / 55 ms), reads A-D strafing. *Average*: 270 +- 40 ms, looser aim
+ (1.45 deg), overheats now and then, parries rarely. They play by the same
+ rules and perception as the bots. They are estimates, not measurements;
+ a playtest calibrates them.
+- **One-trick strategies**: a base player (the hard bot unless named,
+ `skilled+trick` for a skilled person) with one behaviour forced, so a
+ result shows what the trick itself is worth.
+
+| Strategy | Behaviour |
+|---|---|
+| spam | holds the trigger whenever it sees the opponent, never vents, never shields |
+| turtle | shield up all the time, never fires |
+| blocker | raises the shield at every bolt it sees (no planned parries), fires otherwise |
+| camper | sits in cover near its spawn and waits |
+| dodger | rolls whenever the roll is ready |
+| flicker | flicks the shield for parries as fast as the lockout allows |
+| rusher | runs straight at the opponent |
+| circle | closes in and orbits the opponent at about 2 m, firing (point-blank circle strafing) |
+| jiggle | reverses its strafe every 140..300 ms (A-D spam) |
+| hider | once ahead on health, breaks off and hides (plays for the clock and the health tiebreak) |
+| edge | fires 11 bolts (heat 99, one short of an overheat), then vents at once with a timed press |
+| parrier | tries to parry every bolt it sees; never holds a block, never rolls |
+| watcher | holds the cover spot nearest its spawn that sees the other spawn, pre-aimed in sights |
+| kiter | keeps 28 m away (across the shaft) and fights in sights |
+| brawler | fights at 6 m |
+
+### Results (300 duels per pairing, best of 3, seed 2026)
+
+56 pairings: 16,800 duels, 40,623 rounds, 9 of them timed out. "A won" is the
+first-named side; slots alternate every duel. TTK is from the first hit on a
+full-health player to the kill (misses, blocks and regeneration included).
+Accuracy, parry rate (share of the bolts reaching a player that it parried)
+and perfect vents are A / B. With 300 duels a win rate is good to about
++-3 points (one standard error); repeat runs with other seeds moved single
+pairings by up to 7 points.
+
+**Skill ladder**
+
+| Pairing | A won duels | A won rounds | Round | TTK | Accuracy | Parry rate | Perfect vents |
+|---|---|---|---|---|---|---|---|
+| hard vs normal | 80% | 73% | 11.3 s | 5.8 s | 33 / 26% | 18 / 14% | 80 / 51% |
+| elite vs hard | 86% | 76% | 10.4 s | 5.0 s | 39 / 30% | 26 / 18% | 92 / 76% |
+| elite vs normal | 98% | 89% | 10.1 s | 4.7 s | 42 / 26% | 26 / 13% | 93 / 50% |
+| normal vs normal | 50% | 50% | 13.0 s | 6.8 s | 26 / 26% | 11 / 11% | 50 / 55% |
+| hard vs hard | 46% | 48% | 11.3 s | 5.5 s | 31 / 32% | 18 / 19% | 78 / 77% |
+| elite vs elite | 48% | 49% | 10.8 s | 5.2 s | 34 / 35% | 25 / 26% | 93 / 93% |
+
+(Over four seed sets the mirrors average 46..50% of duels and 48..50% of rounds.)
+
+**People against the bots** (the person models; duels / rounds won by the person)
+
+| | vs normal | vs hard | vs elite |
+|---|---|---|---|
+| skilled | 91 / 82% | 72 / 65% | 40 / 43% |
+| average | 66 / 61% | 31 / 36% | 7 / 16% |
+
+Skilled against elite on the final code: 40% (above) and 37..38% in two more
+runs of 400 duels; about 42% of rounds. How it moves with the person
+(400 duels each):
+
+| Skilled person | vs elite (duels / rounds) | vs hard |
+|---|---|---|
+| reactions 200 ms | 44 / 46% | |
+| reactions 225 ms | 37 / 40% | |
+| reactions 250 ms | 31 / 37% | |
+| aim error 0.85 deg / 1.2 deg | 42 / 45%, 34 / 38% | |
+| 200 ms and 0.85 deg (a very good player) | 47 / 47% | 80 / 70% |
+| 250 ms and 1.2 deg (a good player) | 24 / 33% | 62 / 59% |
+
+So: **normal** is for learning (an average player wins two duels in three),
+**hard** is a fair fight for a good player and a real challenge for an
+average one, **elite** is hard for a skilled player but beatable: it wins
+about 6 duels in 10.
+
+**One-trick strategies against the hard bot** (the trick on the hard bot's aim
+and movement; a trick that ties means it is worth as much as the bot's mixed
+play, a trick that wins would be an exploit)
+
+| Trick | Hard won duels | Hard won rounds | Round | TTK | Notes |
+|---|---|---|---|---|---|
+| spam | 92% | 84% | 8.8 s | 4.0 s | overheats 0.8 times a round |
+| turtle | 100% | 100% | 8.0 s | 3.1 s | the shield breaks, then nothing is left |
+| blocker | 41% | 45% | 10.1 s | 4.7 s | parries 29% by reacting in time (45..48% over three more seeds) |
+| camper | 94% | 87% | 9.8 s | 5.7 s | |
+| dodger | 55% | 55% | 12.5 s | 6.3 s | 4.4 rolls a round |
+| flicker | 59% | 56% | 11.3 s | 5.7 s | the whiff lock holds its parries to 19% |
+| rusher | 80% | 70% | 8.0 s | 3.1 s | |
+| circle | 82% | 73% | 7.8 s | 3.0 s | point blank the hard bot hits 53% |
+| jiggle | 65% | 60% | 9.9 s | 4.6 s | wobbling barely moves you; see below |
+| hider | 61% | 58% | 13.8 s | 6.4 s | 6 rounds went to the clock |
+| edge | 50% | 50% | 10.5 s | 5.1 s | 99% perfect vents; heat mastery is worth exactly the bot's own heat play |
+| parrier | 57% | 55% | 10.0 s | 4.7 s | |
+| watcher | 57% | 54% | 13.4 s | 7.5 s | side 0 won only 39% of these rounds: the east side's hold is behind a conduit |
+| kiter | 59% | 54% | 13.6 s | 7.6 s | was 38% before the bots stopped walking at far shooters |
+| brawler | 58% | 56% | 10.3 s | 4.6 s | |
+
+**A skilled person playing one trick against the elite bot** (elite's win
+rate; against plain skilled play the elite bot wins 60%. A trick that pushes
+this below 60% would be a cheap way to beat the bot.)
+
+| Trick | Elite won duels | Elite won rounds |
+|---|---|---|
+| spam | 98% | 91% |
+| blocker | 62% | 59% |
+| camper | 99% | 94% |
+| dodger | 65% | 60% |
+| flicker | 70% | 63% |
+| rusher | 89% | 81% |
+| circle | 92% | 81% |
+| jiggle | 56% | 54% |
+| hider | 74% | 66% |
+| edge | 59% | 56% |
+| parrier | 63% | 59% |
+| watcher | 66% | 61% |
+| kiter | 63% | 58% |
+| brawler | 72% | 66% |
+
+No trick helps a skilled player much: jiggle (A-D spam) is the best at
++4 points, edge +1, everything else costs. (The turtle is left out; it
+cannot win a round.)
+
+**Tricks against each other** (A won duels): spam vs blocker 10%, spam vs
+flicker 25%, dodger vs spam 89%, rusher vs camper 67%, flicker vs rusher 83%,
+dodger vs blocker 36%, dodger vs flicker 63%, blocker vs flicker 65%,
+blocker vs rusher 73%, kiter vs brawler 48%, kiter vs dodger 57%, edge vs
+blocker 56%, jiggle vs kiter 32%, normal vs spam 63%, normal vs turtle 100%.
+They beat each other in circles (blocker beats dodger, flicker and rusher;
+edge beats blocker; dodger beats spam and flicker; kiter beats jiggle), and
+none beats the bots.
+
+### The adversarial pass (2026-10-20)
+
+A second agent tried to break the core and to beat the bots cheaply. What it
+found and what changed:
+
+**Bugs, all fixed and covered by tests**
+
+| # | Found | Fix |
+|---|---|---|
+| 1 | Lag compensation favoured slot 0: a rewound bolt of slot 0 could kill slot 1 before slot 1's own shot of the same tick was fired. | Every trigger first, then the rewinds (`exploits.test.ts`). |
+| 2 | A modified client could run at 12 m/s (a 10x move stick), send strings or NaN as aim, set unknown button bits; a malformed message could throw inside the server. | `sanitizeInput` inside the step (legal commands unchanged), shape checks in the server; `makeInput` never sends a diagonal longer than 1 (`netcodeAdversarial.test.ts`). |
+| 3 | When the server trimmed a backed-up input queue, a roll, vent or forfeit in a dropped input was lost (the client had already played it). | Presses of dropped inputs carry over into the next one. |
+| 4 | The end message (reliable) could overtake the final snapshot (unreliable) under jitter: the last kill, round end and match end were never shown, and the client's last state was stale. | The end message carries the final snapshot (protocol v2). |
+| 5 | Events rode along for only two snapshot periods: at 10% loss about 1% of all events (hits, deaths, round ends) never reached a client. | Each snapshot carries the events since the client's last confirmed snapshot; 0 of 1,748 lost at 10% loss, 0 in a whole duel at 15% loss and 40 ms jitter. |
+| 6 | The handshake compared only the tuning: a client built for a re-laid-out arena would mispredict every wall. | `rulesHash` covers tuning and arena. |
+| 7 | The bot saw +-75 deg round its body; the hip camera shows +-51 deg at 16:9, but more to the sides up close and round a right-hand corner. | Bot perception from the camera point (see The bot). |
+| 8 | A non-array frame crashed the in-process transport and the client. | Guards. |
+
+**Exploits**
+
+- **Keeping your distance won.** Holding 28 m beat the hard bot 62%, the
+ elite bot's own clone at 28 m beat it 70%, and kiting lifted the skilled
+ person from 35% to 48% against elite; any preferred range from 16 m up
+ beat the default bot. The cause was the bots: they walked straight in on a
+ far opponent (a body walking along the line of fire is the easiest target
+ there is, and here the way in goes round the open shaft). Now they close in
+ only with a reason (the opponent vents or its shield is broken, they lead
+ by 25 health, or it is beyond 34 m) and otherwise trade from where they are
+ and drift in. The new bot beats the old one 61%; kiting now loses
+ (above). Fights moved a little longer: rounds about 11 s instead of 10,
+ TTK about 5 s instead of 4.
+- **A-D strafing beat a good leader.** The bots led with the velocity of
+ the moment, which a wobbling target turns into a guess: skilled+jiggle won
+ 48% against elite (plain skilled 38%), elite+jiggle beat elite 56%. Against
+ a poor leader it is the opposite (normal+jiggle beat normal 5%: a wobbling
+ target barely moves). Hard and elite now read it (above); the edge fell to
+ about 4 points, which is about what the technique should be worth.
+- **Tried and harmless:** turtling, shield flicking and parry spam (the
+ whiff lock and the re-raise lockout), roll chaining (no invulnerability),
+ firing to the overheat edge with timed vents (ties the bot; skill, not an
+ exploit), point-blank circle strafing (at 2 m bots hit 53..60%; the shield
+ arc does not save the orbiter either), camping, spawn watching, playing for
+ the clock (the surge pings both).
+- **Spawns:** never in sight of each other, mirrored, swapped every round:
+ side 0 won 49.4% of 40,623 rounds. A pre-aimed hold behind the east
+ conduits is stronger than any hold on the west floor (side 0 won 34..39%
+ of the watcher's rounds), but holding is not a winning plan, and sides swap
+ each round.
+
+### Netcode under attack
+
+Whole bot duels through MatchServer, LocalNetwork and two MatchClients:
+
+- With no loss, a client predicts its own movement exactly; the only
+ corrections come from what it cannot know (the opponent's newest hits and
+ deaths): about 6..7% of snapshots at 60 ms with 30 ms jitter. At 70 ms,
+ 40 ms jitter and 15% loss it stays under 30%, worst about 1 m (a death
+ learnt a round trip late).
+- Every event reaches both clients exactly once, and the final state is the
+ server's, at 15% loss and 40 ms jitter (`netcodeAdversarial.test.ts`).
+- The same seeds replay the same networked duel, event for event.
+- 17.7 kB/s down and 5.9 kB/s up per player at 30 Hz snapshots over 50 ms.
+
+### Findings and decisions
+
+- **Higher skill wins more, and never always.** The ladder is ordered
+ (hard over normal 80%, elite over hard 86%, elite over normal 98%), mirrors
+ are even, and the skill shows where it should: accuracy 26, 31..33,
+ 34..42%; parry rate 11, 18, 25%; perfect vents 50, 78, 93%.
+- **No strategy dominates.** Every one-trick strategy loses to or ties the
+ hard bot, and none lets a skilled person beat elite cheaply.
+- **Heat is a real resource.** Holding the trigger overheats 0.8 times a
+ round and loses to every tier, even normal (63% for normal). Firing to the
+ edge with timed vents is exactly as good as the bots' own heat play.
+- **Parries are skill, not spam.** Without the whiff lock, flicking the
+ shield parried 42% of bolts and beat the hard bot 64% (measured before the
+ adversarial pass); with it a whiffed raise costs the next second of
+ parries. The window is 0.15 s: a reacted raise at mid range (15..25 m,
+ where a bolt flies 0.25..0.4 s) lands in it; up close only anticipation
+ (the stream's rhythm) parries.
+- **The roll has no invulnerability.** Bolts travel, so stepping out of their
+ path is the evasion and it reads on screen. With the first 1.6 s cooldown,
+ 0.15 s of invulnerability turned roll spam into the best trick (61% against
+ hard); at 2.0 s cooldown and 0.2 s recovery the roll is a deliberate tool.
+- **Range is a choice, not a win.** Long range is slow (TTK 7..8 s at 28 m)
+ and dodge-heavy, close range fast; neither wins by itself once the bots
+ stopped walking into fire.
+- **Pace.** Real time to kill is about 5 s (1.2 s if every bolt hits up
+ close), a round 10..13 s, a match about 25..30 s of play plus countdowns.
+ The reactor surge trims rare stalemates (9 timeouts in 40,623 rounds).
+
+### Running it
+
+```
+# the suite, with the balance and exploit smoke tests (about 5 s)
+npx vitest run src/components/society/verse/combat
+# full matrix inside vitest (single process, slow)
+COMBAT_BALANCE=full npx vitest run src/components/society/verse/combat/harness
+# fast, from a shell: bundle once, then every pairing in its own process
+npx esbuild src/components/society/verse/combat/harness/cli.ts --bundle --platform=node --format=esm --outfile=$TMP/balance.mjs
+node $TMP/balance.mjs 300 all 2026 - 15 # 56 pairings x 300 duels, 15 processes: about 1.5 min
+node $TMP/balance.mjs 300 elite:skilled+kiter # one pairing
+# try a change against the defaults
+node $TMP/balance.mjs 300 hard:dodger,hard:hard 1 '{"dodge":{"iframeTicks":9}}' 2
+```
+
+Sets: `ladder`, `humans`, `exploits`, `elite` (skilled+trick vs elite),
+`cross`, `all`. Strategy ids: `normal`, `hard`, `elite`, `skilled`, `average`,
+a trick (on the hard bot) or `base+trick`; for experiments also
+`base+rangeN` (fight at N m), `base+approachN` (walk in at N/10 without a
+reason), `base+mwN` (motion read window N ms).
+
+## For the integrator
+
+### Start, play, leave
+
+```ts
+import { createLocalDuel, idleControl, resolveAim, cameraRigFor, cameraPose } from "./combat";
+
+const duel = createLocalDuel({ difficulty: "hard", seed: Date.now() >>> 0 });
+// every animation frame:
+const { view, events } = duel.frame(dtMs, control); // control: ControlState
+// view.players / view.bolts / view.hud / view.match -> draw; events -> effects and sounds
+// keep calling until duel.finished, then read duel.result and duel.dispose()
+duel.forfeit(); // the leave key, any time
+```
+
+1. **Entry.** Offer "Start duel" (with a normal / hard / elite choice) at the
+ four control-ring consoles (`REACTOR_ARENA.terminals`, the manifest's
+ `reactor_ring__ring_N` stand sockets, E to use) and from a menu anywhere on
+ the engineering deck. Build the arena early (`buildArena(REACTOR_ARENA, 0.3)`,
+ about 20 ms) when the deck loads.
+2. **On start.** Fade, place the commander and a bot figure at the positions
+ in the first `view.players` (spawns swap each round: follow `view.players`
+ every frame, they are authoritative), switch the stage into combat mode
+ (combat camera, HUD, crosshair), keep crew in the hall as non-colliding
+ bystanders or send them out, disable station interactions in the hall.
+3. **On end.** Show `duel.result` (won/lost, rounds, stats), return control
+ to the deck's walking (snap the commander onto the deck nav grid with its
+ `nearestWalkable`: the arena's rim band is wider than the cooked grid's).
+
+### Input mapping (suggested)
+
+| Key | ControlState |
+|---|---|
+| W A S D | `moveY` / `moveX` (-1..1, camera frame) |
+| Mouse | `yaw`, `pitch` (pass through `resolveAim`, below) |
+| Left button (hold) | `fire` |
+| Right button (hold) | `ads` |
+| Q (hold) | `shield` |
+| Space (press) | `dodge` (direction from WASD, backward if none) |
+| R (press) | `vent`; press again inside the window for a perfect vent |
+| Shift (hold) | `sprint` |
+| Esc then confirm | `duel.forfeit()` |
+
+Presses are latched by the client until the next tick, so a quick tap on a
+144 Hz frame is never lost.
+
+### Camera and aim
+
+- `cameraRigFor(player)` gives the over-the-shoulder rig for the player's
+ state: hip (0.55 m right, 1.68 m up, 2.5 m back, 70 deg), sights (0.42,
+ 1.62, 1.3, 50 deg; blended by `player.ads`), sprint (2.9 m back, 76 deg),
+ shield (2.75 m back, 68 deg). Ease between rigs over about 0.15 s; keep the
+ existing camera collision.
+- `cameraPose(player, rig)` places the camera behind the right shoulder and
+ orbits the pivot with the pitch.
+- `resolveAim(ctx, view, cameraPosition, cameraDirection)` converges the
+ blaster on whatever is under the crosshair (the muzzle sits right of and
+ below the camera); feed its `yaw` and `pitch` into the ControlState. Bolts
+ then land on the crosshair.
+- Crosshair: `crosshairRadiusPx(view.hud.spreadDeg, fovDeg, viewportHeight)`.
+ Recoil: `hud.recoilPitchDeg` / `recoilYawDeg` (the crosshair kicks and
+ settles; add a small camera shake on `shot` for the local player).
+
+### Drawing
+
+- `view.players[i]`: position, `yaw` (body), `aimYaw`/`aimPitch` (blaster,
+ with recoil), `speed`, `sprinting`, `ads`, `shieldUp`, `shieldEnergy`,
+ `parrying` (window open: flash the shield), `shieldBroken`, `dodging` and
+ `dodgeProgress` (roll animation), `venting`/`overheated`/`heat` (vents glow,
+ steam), `alive`. The local player is already smoothed between ticks; the
+ opponent is interpolated.
+- `view.bolts[i]`: position, unit direction, speed, `kind` (`shot`,
+ `deflect`, `parry`), `owner`. Draw a stretched emissive capsule about 1.2 m
+ long and 5 cm thick along the direction with a short trail; colour by owner
+ (the person's and the opponent's), brighter for a parried bolt.
+- The shield: a curved energy panel 0.8 m in front, +-60 deg, 2 m high,
+ facing the aim yaw; opacity from `shieldEnergy`.
+
+### Effects and sounds (events)
+
+| Event | Play |
+|---|---|
+| `shot` | muzzle flash and blaster sound at `x,y,z`; local camera kick |
+| `hit` | sparks at the hit point; hit marker for `owner` (headshot variant); damage indicator from `fromX,fromZ` and a hurt sound for `target` |
+| `impact` | scorch and sparks on the `surface` along the normal |
+| `block` / `deflect` | shield ripple at the point; glance sound and sparks for a deflection |
+| `parry` | bright flash, a sharp parry sound, a short hit-pause if wanted |
+| `bolt_expire` | end the bolt's trail (left the room or fell into the shaft) |
+| `shield_up` / `shield_down` / `shield_break` / `shield_ready` | shield hum on/off, break shatter, ready ping |
+| `overheat`, `vent_start`, `vent_perfect`, `vent_miss`, `vent_end` | overheat alarm and steam; vent hiss; perfect-vent chime; miss buzz |
+| `dodge` | roll animation and whoosh |
+| `death` | collapse; kill banner |
+| `countdown`, `round_start`, `round_end`, `match_end` | announcer and banners (`round_end.reason`: kill, time, trade) |
+| `surge` | reactor alarm, a red pulse in the hall's lights |
+| `ping` | a HUD marker on the opponent for about a second |
+
+### HUD
+
+`view.hud` (the local player): `health`/`healthMax`, `heat` (0..1),
+`overheated`, `venting` with `ventProgress` and `ventWindow` (draw the vent bar
+with its sweet spot), `ventAttempted`, `shieldEnergy`, `shieldUp`,
+`shieldBroken` with `shieldBrokenLeft`, `shieldCanRaise`, `parryReady`
+(whiff lock), `dodgeReady` and `dodgeCooldown`, `spreadDeg`, `ads`,
+`sprinting`, `canFire`, `enemyHealth`. `view.match`: `phase`, `round`,
+`scores` (by slot; `view.slot` is the person's), `roundsToWin`, `countdown`,
+`roundTimeLeft`, `surge`, `winner`, `endReason`.
+
+## In the 3D view
+
+Code: `src/components/society/verse/duel/` (controller, input, camera, HUD
+model, sound, figures, blaster, effects, shield, `DuelLayer.tsx`) and
+`hud/DuelHud.tsx`, `hud/DuelPanel.tsx`, `hud/duel.css`. Strings:
+`verse.duel.*` in `src/i18n/locales/ship/verse.<lang>.json`.
+
+### Start and leave
+
+- **Ring consoles.** In third person on Reactor Engineering, standing within
+ 2.2 m of a control-ring console (`REACTOR_ARENA.terminals`) shows *Duel
+ terminal: Start a duel [E]*; E opens the start panel.
+- **Tool rail.** The **Duel** button opens the same panel on any deck. Off
+ engineering, choosing an opponent rides the turbolift down first and starts
+ the match once the deck's eye-level scene is on screen.
+- **Start panel** (`DuelPanel`): what the duel is, normal / hard / elite as
+ three rows (no native select), the controls. A choice starts the match at
+ once and asks for the pointer lock (the click is the user gesture).
+- **Leaving.** Esc releases the pointer and pauses the match (the duel's clock
+ stands still while paused); Esc again, or *Leave the duel*, forfeits and
+ returns to the deck. After the match the result screen offers *Rematch* and
+ *Back to the ship*. On leaving, the commander stands where they finished
+ (snapped onto the deck's nav grid) and the shoulder camera snaps behind them.
+- A stage that goes out of sight pauses a running match.
+
+`DuelController` (React-free) owns the phases `off -> running <-> paused ->
+result -> running | off`, the `LocalDuel`, the input, the camera, the HUD feed
+and the sound; `VerseStage` holds one per stage and renders `DuelLayer` (in
+the Canvas, eye-level view only) and `DuelHud` while a duel is on. During a
+duel the stage's own keys, pointer picking, labels, crew card and tool rail
+are off, the commander's deck body is hidden (`runtime.duelActive`), and crew
+standing in the reactor hall are not drawn (`runtime.duelArea`), so nobody
+stands in the line of fire.
+
+### Controls
+
+| Key | Control |
+|---|---|
+| W A S D (or arrows) | move (strafe / forward in the aim frame) |
+| Shift | sprint (forward only) |
+| Mouse (pointer lock) | aim; unlocked, movement over the stage aims too |
+| Left button | fire (hold) |
+| Right button | aim down the sights (hold): the camera closes in over the shoulder and narrows its field of view |
+| Q | energy shield (hold) |
+| Space | dodge roll in the move direction |
+| R | vent; again inside the gold window: perfect vent |
+| Esc | pause; again: leave |
+
+Presses are latched until the next frame reads them. Keys the duel uses never
+reach the stage's handlers. A click while the pointer is not locked locks it
+again (*Click to aim* shows under the crosshair).
+
+### Camera
+
+`DuelCamera` turns with the eye-level views' mouse look (`mouseLook.ts`:
+the same rate per pixel, sensitivity and inverted axis; the pointer lock asks
+for raw movement), so aiming feels the same in and out of a match. The duel
+is always fought over the shoulder: first person on the deck switches to the
+duel's camera for the match and back afterwards. It eases the core's rigs
+(`cameraRigFor`: hip, sights, sprint, shield; about 0.15 s) and adds 0.2 m to the side (less in the sights) so the
+body clears the crosshair. The camera's vertical field of view is the rig's
+(70 deg hip, the angle the bot's perception assumes). It is pulled in front of
+the deck's geometry with the eye view's BVH (`runtime.eye.test`) and eases
+back out. The view follows the blaster's recoil (the screen kicks with every
+shot and settles with it) while the aim sent to the simulation is the mouse's;
+`resolveAim` converges the muzzle on whatever the crosshair covers. Shots, hits
+taken and parries add a short shake. Each round starts facing the spawn's
+direction. `RealtimeBackdrop` renders from `runtime.cameraOverride` while it
+is set.
+
+### Bodies, blaster, effects
+
+- **Figures** (`figure.ts`): the commander's own officer body and look for the
+ person, the trooper body in gunmetal armour with red accents and a red visor
+ for the bot. The legs walk the way the body moves (the walk plays backwards
+ when it backs off, the hips turn at most 80 deg off the aim), spine and chest
+ twist and bend toward the aim, the head follows it, and both arms reach the
+ blaster by two-bone IK (`solveElbow`): right hand on the grip, left on the
+ shroud, or palm forward behind a raised shield. Sprinting carries the
+ blaster low, venting tips it up. A dodge is a tucked roll along the move
+ direction; a knocked-out body falls backwards.
+- **Blaster** (`blaster.ts`): procedural, graphite and brushed gold, energy
+ cells along the receiver (amber for the person, red for the bot), heat vents
+ on the shroud glowing blue to amber to red with the heat and pulsing while
+ venting, an emitter ring at the muzzle.
+- **Bolts** (`effects.ts`): a white-hot core in a coloured glow with a tapering
+ trail, HDR so the eye view's bloom catches them and additive so they read on
+ the low tier too; amber (person), red (bot), near white and thicker when
+ parried. Pooled.
+- **Impacts**: sparks with gravity, a flash, a scorch mark that glows hot for
+ 1.6 s and fades after 24 s. **Hits**: sparks and a flash on the body.
+ **Muzzle**: a star flash. **Overheat / vent**: steam from the muzzle.
+- **Shield** (`shield.ts`): a translucent curved panel, +-60 deg, 0.8 m out,
+ 2 m high, with a hex lattice, bright edges and a scan line; strength follows
+ energy, the parry window shows as a hot rim, a block ripples blue-white from
+ the strike point, a parry flashes the panel gold-white, a break flickers red.
+
+Shader note: the trail's alpha clamps its varying before `pow`; MSAA samples
+varyings just outside a triangle, and one NaN in the HDR target is spread over
+the whole frame by the bloom (a black screen).
+
+### HUD
+
+`buildHudModel(view, feed, now, camYaw)` (pure, tested) turns the view and the
+frame's events into what `DuelHud` draws: score and round clock top centre
+with round pips and the opponent's health; a spread-aware crosshair
+(`crosshairRadiusPx`), red over the opponent, dimmed while the blaster cannot
+fire, with hit markers (white, gold headshot, red knockout); damage arcs
+around it pointing where hits came from (relative to the camera); a red edge
+flash on hits taken and a pulse at low health; call-outs (parry, parried,
+deflected, perfect vent, vent missed, overheated, shield broken); health,
+shield (parry ready / cooling / down with its countdown) and roll cooldown
+bottom left; heat with the vent's gold window and a sweeping marker bottom
+right; the countdown, *Fight* and round banners; the surge warning and the
+opponent's pinged position; the pause and result screens (accuracy, damage,
+headshots, parries, blocks, perfect vents). Key hints show for the first
+seconds of a match.
+
+### Sound
+
+`DuelSound` synthesises everything with WebAudio (no recorded assets): the
+blaster's zap, impacts, body hits and the shooter's marker tick, block,
+deflection whine, parry bell, shield hum up and down, shield break, overheat
+alarm, vent hiss, perfect / missed vent chimes, roll whoosh, death, countdown
+ticks, round start and end chords, surge alarm. The opponent's sounds are
+panned and attenuated by where they happen relative to the camera; a
+compressor keeps bursts from clipping. The AudioContext starts on the start
+click.
+
+### QA hooks
+
+`window.__verseDuel` (built bundles too, like `__verseStats`): `start(tier)`
+on the deck on screen, `leave()`, `look(dx, dy)`, `hold({fire, ads, shield,
+moveX, moveY, sprint})`, `press("dodge" | "vent")`, `place(x, z, yaw)` (put the
+commander somewhere, e.g. at a ring console), `state()` (phase, HUD model,
+view, result, crosshair target, camera pose). `localStorage["verse.duel.anyDeck"]
+= "1"` lets the duel start on any deck without the lift ride (the arena's
+coordinates stay engineering's), for testing a deck whose eye-level export is
+missing.
+
+Measured (headless Chrome, RTX 5070 Ti, 2560 x 1392, tier high, engineering
+preview export): 60 fps (vsync) through a whole match, 160..250 draw calls,
+CPU 1.5..3.8 ms per frame.
+
+### Open
+
+- The bodies have no aiming, firing, hit-reaction or roll clips; the upper
+ body and the roll are procedural. Proper clips would look better.
+- Pointer lock in the desktop app's WebView is untested here (headless runs
+ aim through the QA hook).
+- No settings for the duel's volume or a separate mouse sensitivity (it uses
+ the eye view's).
+
+## Testing
+
+```
+cd dodaios/ui/web/frontend
+npx tsc -p tsconfig.json --noEmit
+npx vitest run src/components/society/verse/combat
+```
+
+Duel integration: `duel/duel.test.ts` (input mapping, camera, HUD model, the
+start / pause / Escape / leave / result / rematch flow against the real local
+duel) and `hud/duelHud.test.tsx` (start panel, HUD, pause and result screens).
+
+87 tests in 10 files, about 5 s (the files declare the node environment; the
+frontend's default jsdom made the same suite take 10..20 s). The full balance
+matrix is one more test, opt-in with `COMBAT_BALANCE=full`.
+
+| File | Covers |
+|---|---|
+| `sim.test.ts` | match flow, rate of fire and bolt speed, falloff and headshots, overheat, timed vents, sights and spread, shield block/back/parry/break/lockout, run/sprint/sights/shield speeds, drop and catwalks, dodge, rounds and side swap, forfeit, regeneration, determinism, JSON round trip, purity |
+| `exploits.test.ts` | no tunnelling at 5 m per tick (bodies, wall pipes, coolant runs), no hits through the core, low bolts stopped by waist-high cover, the shield at point blank (front holds, flank does not), parry rallies stop after three reflections, a bolt never hits its owner, deflections never hit the deflector; same-tick lag-compensated one-shots trade, mirrored duels are mirrored; double knock-outs, five trades make a draw, a drawn time-out, the dead cannot act, shields and presses across a round change, forfeit in the countdown and the pause; eleven bolts and a timed vent never overheat, holding or spamming the vent key |
+| `arena.test.ts` | spawns out of sight, walkways and drop, solids, bolts over the drop and through doorways, cover spots; against the cooked deck: room outline, ring consoles, nav grid agreement over 95% |
+| `raycast.test.ts` | box, cylinder, capsule and sphere sweeps; seeded randomness |
+| `netcode.test.ts` | exact state and input round trip, snapshot size; latency, jitter, loss and reliable order; WebSocket adapter; handshake; exact self-prediction (0 corrections); prediction under 70 ms, jitter and 8% loss; smooth opponent; leave and disconnect; rejected tuning or third player; lag-compensated shot |
+| `netcodeAdversarial.test.ts` | a modified client (10x move stick, strings and huge numbers as aim, unknown buttons, malformed messages); legal inputs pass the sanitising unchanged; a press inside a trimmed burst survives; another arena is rejected; whole bot duels at 70 ms, 40 ms jitter and 15% loss: every event exactly once on both clients, the final state arrives, corrections stay small, the same seeds replay the same duel |
+| `bot/bot.test.ts` | never fires without a recent real sighting (whole duels); reaction time per tier; leads a running target; parries and blocks a marksman's bolts; routes round and over the shaft |
+| `session.test.ts` | a whole match against the bot through the full stack; forfeit at any time; over a laggy link; crosshair convergence hits; crosshair size |
+| `harness/balance.test.ts` | elite beats normal, tricks lose to hard, duels reproduce from their seed |
+| `harness/exploits.test.ts` | kiting, point-blank orbiting and rushing lose; playing for the clock and spawn watching are no walkover; a skilled person beats normal and finds elite hard but beatable |
+
+## Later, for PvP
+
+- A Node host: `MatchServer` per duel behind a WebSocket server, matchmaking
+ and accounts outside this module. Inputs are already sanitised and messages
+ shape-checked; add rate limits per connection there.
+- Clock drift and jitter: the server's input queue absorbs them (late inputs
+ repeat the last one, a backed-up queue is trimmed without losing presses),
+ at the cost of a rare one-tick correction; for real networks add client
+ time dilation (run a little faster or slower to keep the queue at 2).
+- Lag-compensation trust: a client says which tick it saw (`viewTick`), so a
+ cheater can claim the full 250 ms rewind for every shot. The cap bounds it;
+ the server could also bound the rewind by its own round-trip measurement.
+ For the victim, a rewound bolt appears partway along its flight.
+- Interest management: today every client gets the full state, including a
+ hidden opponent; for competitive play send the opponent only when visible.
+- Parry fairness under latency: judge the parry window on the defender's
+ input tick (favour the defender) as the shot side already is. Over a
+ network everyone sees incoming bolts a round trip into their flight, which
+ makes reacted parries and rolls harder than in the local duel.
+- Prediction shows the opponent's held trigger: when the opponent let go
+ within the last round trip, a bolt can show for a few ticks and vanish
+ (1 in 80 opponent bolts at 70 ms).
+- Different browsers may round `Math.sin` and friends differently in the
+ last bit. The server is authoritative and the state is quantised, so that
+ only causes a rare correction, never a lasting desync.
+- A binary encoding of the same arrays; delta snapshots if bandwidth matters.
diff --git a/docs/verse/pipeline.md b/docs/verse/pipeline.md
index 03fdab657d..ed8330d150 100644
--- a/docs/verse/pipeline.md
+++ b/docs/verse/pipeline.md
@@ -29,12 +29,14 @@ under `dodaios/ui/web/frontend/public/verse/` are committed.
art/verse/
BRIEF.md TEAM.md LEVELS.md style-bible.md LICENSES.md
lib/ scene.py cook.py naming.py textures.py (pipeline)
+ realtime.py lightmap.py (realtime export)
kit.py materials.py (kit)
kit/ modular pieces lookdev/ material tests
decks/<id>/ build.py (+ helpers) characters/ character builders
schema/ deck.schema.json
.cache/ blend/ cook/ textures/ logs/ mcp/ notes/ gpu.lock (git-ignored)
scripts/verse/ blender.py cook.py package.py validate.py closeup.py mcp_bridge.py textures.py avif_test.py
+ package_realtime.py meshopt_pack.mjs _realtime_entry.py (realtime export)
tests/verse/ test_verse_content.py
dodaios/ui/web/frontend/public/verse/decks/<id>/ cooked deck (committed)
dodaios/ui/web/frontend/src/components/society/verse/content/manifest.ts
@@ -130,6 +132,10 @@ and `plate_camera(scene, Bounds(...), px_per_m)`.
## Cook
+The plate cook below; the eye-level (realtime) export of a deck is its own
+stage, `cook.py deck <id> --realtime`, documented in [`realtime.md`](realtime.md).
+A plate cook keeps a deck's `realtime/` folder and manifest block.
+
```
python scripts/verse/cook.py deck <id> [--quality preview|final] [--keep-blend] [--device auto|optix|cuda|cpu]
```
@@ -271,7 +277,8 @@ No other file changes: the engine discovers decks by id and manifest.
| Gate | Limit | Checked by |
|---|---|---|
-| Whole `public/verse` | ≤ 90 MB | validator, pytest |
+| Whole `public/verse` | ≤ 160 MB | validator, pytest |
+| Realtime export per deck (`realtime/`: glb, lightmap pages, probes) | ≤ 25 MB | validator |
| Plate per deck (L0 + M2 + M4 + L1) | ≤ 16 MB | validator |
| Character `.glb` | ≤ 2 MB each, `SK_`/`SM_`/`A_`/`T_` prefix | validator |
| Manifest | JSON Schema, ids match folders, tile count and sizes of every level (mips per the contract, no stray files), nav size, occluders without materials and named `UCX_*`, env is Radiance HDR | validator |
diff --git a/docs/verse/realtime.md b/docs/verse/realtime.md
new file mode 100644
index 0000000000..a3d2ecb05c
--- /dev/null
+++ b/docs/verse/realtime.md
@@ -0,0 +1,349 @@
+# Verse realtime decks: the eye-level view
+
+Status: all four decks exported (bridge 2026-10-20; engineering, hangar and
+ops 2026-10-26, when the lightmap packing was rebuilt and the bridge
+re-exported with it).
+
+The plate pipeline photographs a deck from one fixed angle. The realtime
+export turns the same Blender scene into a 3D scene the browser walks through
+at eye level, so the person steers the commander in third person from behind
+their shoulder or in first person through their eyes, with shooter mouse look,
+as in a game. The plate stays: it is the bird's-eye view (key 1) and the IDE
+side panel's view.
+
+| | Plate (bird's-eye, compact panel) | Realtime (full-size stage, third or first person) |
+|---|---|---|
+| Camera | orthographic, 60° down, fixed | perspective, over the shoulder or at eye height, shooter mouse look |
+| Light | Cycles path tracing, baked into the photograph | Cycles bake of the diffuse light into lightmaps + live reflections |
+| Ceilings, upper walls | hidden (cutaway, BRIEF §5) | real geometry |
+| Content | `plate/`, `occluders.glb`, `nav.png`, `env.hdr` | `realtime/scene.glb`, `realtime/lm_*.webp`, `realtime/probe_*.webp` |
+
+Both share the manifest, nav grid, sockets, stations, rooms, light probes and
+the live people, screens, holograms and beacons.
+
+## Pipeline
+
+```
+python scripts/verse/cook.py deck <id> --realtime [--quality preview|final] [--keep-blend]
+```
+
+Runs in headless Blender under the GPU lock (`scripts/verse/_realtime_entry.py`
+→ `art/verse/lib/realtime.py`), then packages (`scripts/verse/package_realtime.py`,
+outside Blender, needs `node` and the frontend's `node_modules` for the meshopt
+encoder) and validates. The deck must have been cooked once (its manifest
+exists); the plate is not touched, and a later plate cook keeps the
+`realtime/` folder and block. `--keep-blend` saves the baked scene to
+`art/verse/.cache/blend/RT_<id>.blend`.
+
+| Quality | Pages | Density (weight 1) | Irradiance samples | Probes | Use |
+|---|---|---|---|---|---|
+| preview | ≤ 2 × 1024² | ≤ 10 px/m | 48 | 256 × 128 | iteration (~2 min) |
+| final | ≤ 4 × 4096² | ≤ 48 px/m | 512 | 1024 × 512 | committed content (~15 min for the bridge) |
+
+Stages (`lib/realtime.py`, timings in `realtime.stats`):
+
+1. **Realise.** Every mesh instance of Architecture, Props and Ceiling (kit
+ instances included) becomes its own object with modifiers applied (the
+ per-material face counts are checked to survive this step).
+ Ceiling ghosts (`ceiling_ghost`, the cut-away upper walls) and ceilings
+ become normal geometry: visible, casting shadows. Faces of
+ `EXCLUDED_MATERIALS` are dropped: `M_Section_Cap` (the cut plane is a
+ drawing convention) and the floor decals with worn-through transparency
+ (`M_Deck_Hazard`, `M_Deck_Marking_White`; they need an alpha bake, see
+ "Open work").
+2. **Visibility.** Eye points on a 1.2 m grid in every room polygon, at 0.9,
+ 1.7 and 2.5 m above its floor, cast 256 rays each; objects no ray reaches
+ (hull voids behind full walls, pipe runs inside double walls, the dark
+ boxes behind the star fields) stay in the scene for the lighting but are
+ neither unwrapped nor exported. On the bridge: 646 of 1395 objects,
+ 7400 m², 236k triangles.
+3. **Unwrap.** Each object gets a second UV set `LM` from Smart UV Project
+ into its own square, its islands `ISLAND_GAP_TEXELS` (2.5) apart at the
+ expected density, and goes whole, as one rectangle sized by its weighted
+ area, onto skyline-packed pages (`lib/lightmap.pack_skyline`; rectangles
+ `2 × (margin_px + 1)` texels apart, grouped by room so a room shares few
+ pages; about 80 % of a page ends up in rectangles). An object whose
+ islands cover less than `MIN_LAYOUT_FILL` (0.3) of its square (thousands
+ of slivers, a decimated shaft wall) is sized as if they covered that
+ much: it gets fewer texels instead of taking space from everyone else.
+ Texel density follows `DENSITY_WEIGHT` (how close people get: hull voids
+ 0.3, ceilings 0.45, floors 0.75, walls and consoles 1.0); the base density
+ steps down until everything fits into `max_pages`.
+ Until 2026-10-26 the pages were packed island by island with Blender's
+ Pack Islands, a full page margin per island: objects of panels, bevels
+ and greebles have thousands of islands, so the margins alone overflowed
+ the pages and Pack Islands shrank everything; the bridge's four pages
+ held only 3-15 % surface (its reported 38.6 px/m was nominal, the real
+ density about a third of it). Measure with `realtime.json`'s chunks:
+ the summed LM UV area per page is the share of the page in use.
+4. **Join.** Cycles re-syncs the whole scene for every object it bakes, so
+ each page's objects are joined (one object per set of ray-visibility
+ flags). The kit's materials read Object coordinates and Object Info >
+ Random; before joining, each object's local coordinates and a random go
+ into the point attributes `rt_orco` / `rt_random`, and the materials are
+ rewired to read them, so joined surfaces bake exactly as instanced ones.
+5. **Bake** per page (Cycles, OptiX): world normal and position (guides),
+ diffuse colour (albedo), emission, and diffuse direct + indirect light
+ (irradiance, `samples`). The irradiance is denoised with an edge-aware
+ à-trous filter guided by normal and position (`lib/lightmap.denoise`:
+ light never crosses a corner or jumps between islands), then
+ `radiance = albedo × irradiance + emission` (scene linear, HDR) and the
+ gaps between islands are filled by push-pull (`fill_gaps`) so mip levels
+ and compression never pull black into an island.
+6. **Probes.** One equirect reflection panorama per room at its probe point
+ (the light probe's point, eye height), with the real ceilings, and the
+ room's box (polygon bounds, floor to the ceiling hit straight up) for
+ parallax correction.
+7. **Geometry.** Triangles are grouped into chunks by (material, room, page):
+ the room is the one the face looks into (centroid moved 8 cm along the
+ normal), so each chunk reflects its own room's probe. World positions,
+ normals and the LM UV per chunk, welded.
+
+## Files and manifest block
+
+```
+public/verse/decks/<id>/realtime/
+ scene.glb meshopt glTF, one node per chunk
+ lm_<page>.webp lightmap pages, RGBA, "rgbm2"
+ probe_<room>.webp reflection panoramas, RGBA, "rgbm2", three.js equirect layout
+```
+
+`scene.glb`: glTF 2.0 with `EXT_meshopt_compression` (vertex codec v0,
+vertex-cache and vertex-fetch optimised) and `KHR_mesh_quantization`.
+Per chunk one node, `extras: {material, room, page}`, translation and one
+uniform scale (positions are int16; a uniform scale keeps world normals
+right), `NORMAL` int8 normalised, `TEXCOORD_0` = the lightmap UV, uint16
+normalised, glTF orientation (v = 0 is the page's top row). Materials in the
+file carry only names; the runtime builds them from the manifest.
+
+**rgbm2** (lightmaps and probes): RGBA8, lossy colour, lossless alpha (WebP
+`alpha_quality=100`). Decode: `m = a² · range`, `rgb = c² · m` (a, c in
+0..1). Both factors are squared, so precision follows brightness: dark
+texels keep fine steps, fixtures up to `range` (a power of two, ≤ 64) never
+clip. `lib/lightmap.rgbm_encode` / `rgbm_decode`; the shader decodes the
+same way. Decode images with `premultiplyAlpha: "none"` and
+`colorSpaceConversion: "none"`.
+
+Manifest (`verse.deck/1`, optional, backwards compatible; schema in
+`art/verse/schema/deck.schema.json`, runtime parser in `content/manifest.ts`):
+
+```json
+"realtime": {
+ "version": 1,
+ "quality": "final",
+ "scene": { "url": "realtime/scene.glb", "vertices": 1319724, "triangles": 1023325, "chunks": 295 },
+ "lightmaps": { "encoding": "rgbm2", "range": 32,
+ "pages": [{ "url": "realtime/lm_0.webp", "size": 4096, "density": 38.61 }] },
+ "probes": [{ "room": "bridge", "url": "realtime/probe_bridge.webp", "w": 1024, "h": 512, "range": 32,
+ "position": [36, 1.4, 16.12], "box_min": [3.6, 0, 3.6], "box_max": [68.4, 7.2, 31.2] }],
+ "materials": { "M_Floor_GlossBlack": { "roughness": 0.3, "metalness": 0, "color": [0, 0, 0],
+ "clearcoat": 1, "clearcoat_roughness": 0.06, "specular": 0.12,
+ "detail": "deck_plates", "transparent": false, "opacity": 1, "collide": true } },
+ "bytes": 16500000,
+ "stats": { "objects": 749, "hidden_objects": 646, "density": [38.61], "bake_s": 816 }
+}
+```
+
+Materials: the bake holds all diffuse light with the albedo in it, so a
+realtime material is only the **specular layer** on top: roughness,
+metalness, metal tint (`color`), clear coat, specular level (Blender's
+Specular IOR Level, 0.5 = F0 4 %), transparency (glass), whether the camera
+collides with it, and a close-up `detail` layer. `MATERIALS` in
+`lib/realtime.py` lists them per kit material; a material missing there is
+read off its Principled BSDF defaults. **Add new kit materials to that table.**
+
+A runtime that does not read `version` ignores the block and shows the plate.
+
+## Runtime
+
+Code: `src/components/society/verse/engine/realtime/`.
+
+| File | Role |
+|---|---|
+| `realtimeScene.ts` | Loads the glb (GLTFLoader + MeshoptDecoder), the pages (ImageBitmap, flipY off) and the probes (decoded on the GPU into half-float equirects, PMREM); builds one material per chunk key; builds the collision BVH (three-mesh-bvh) over chunks whose material collides. |
+| `deckMaterial.ts` | `makeDeckMaterial`: MeshStandardMaterial, or MeshPhysicalMaterial where a coat, a specular level or glass needs it. `patchDeckShader` adds the baked radiance (`totalEmissiveRadiance += decode(lightMap)`), removes lightmap irradiance and environment diffuse, box-projects reflections into the room's box, and for `deck_plates` draws the 2.4 × 1.2 m plate joints and bolts and the smudged, wiped coat close up. Glass blends `ONE, ONE_MINUS_SRC_ALPHA` (its reflection plus what is behind it). |
+| `shoulderRig.ts` | The camera, third and first person (below). Pure. |
+| `viewMode.ts` | The three views and their keys, the wheel's hand-over between third and first person (`zoomStep`), which way the body faces while walking in a shooter view (`bodyFacing`). Pure. |
+| `mouseLook.ts` | Shooter mouse look shared with the duel: the turn rate per pointer-lock pixel, sensitivity and inverted axis (`lookDelta`), taking the mouse with raw movement where the browser allows it (`requestMouseLook`). |
+| `RealtimeBackdrop.tsx` | Loads the scene into the stage's scene on `REALTIME_LAYER`, owns the frame while active: rig → camera → post chain → stats → `afterFrame`. Publishes `runtime.eye` (camera + collider) for the HUD and the pointer. |
+| `orbitInput.ts` | Mouse: a click on the view takes the mouse (pointer lock); then movement turns the view and the left button works what the crosshair is on; Esc gives it back (the HUD's buttons work again). A drag still turns the view where the lock is refused. Touch and pen: drag turns, pinch zooms, a tap picks. The wheel zooms through the stage, which hands over between third and first person. |
+| `viewSettings.ts` | The person's settings, kept in this browser: sensitivity, inverted look, field of view per person, quality, and the view they last chose. |
+| `eyePick.ts` | Pointer picking at eye level: bodies as upright cylinders (only in front of the deck's geometry), stations near the deck point hit, floor points to walk to. |
+
+The stage (`VerseStage.tsx`) shows the realtime view when the stage is
+full size, the deck has a realtime block and the view is third or first
+person; the bird's-eye view is the plate (the realtime scene stays loaded,
+the plate idles while hidden). A deck whose realtime scene fails to load
+falls back to the plate. `runtime.toScreen` and `runtime.ray` project through
+the eye-level camera while it is on screen, so name plates, station labels,
+crew cards and clicks work in both views. In the realtime view the keys are
+camera-relative (`CommanderControl.directionFrom`), beacons get world sizes
+and depth, and the plate-only lamp sprites (LightsLayer) are off.
+
+People: the same actors as on the plate, lit by the room's SH light probe
+and the deck's environment map (`actors/roomLight.ts`), with AgX at the
+plate's exposure; the baked room light and the people match because both
+come from the same Cycles scene.
+
+Post chain (tier "high"): HDR half-float target with 4× MSAA, bloom
+(UnrealBloom, threshold 1.5, strength 0.035, radius 0.3, scene linear before
+the exposure; UnrealBloom sums five blur levels, so more veils the dark deck
+in grey), output pass with AgX and `toneMappingExposure = 2^exposure`. The
+eye view clears to true black (AgX lifts the plate view's near-black clear
+colour to a visible grey). Deck materials are double-sided: Cycles renders
+both sides of a face, and builders leave open quads (star fields, decals)
+facing either way.
+Tier "low" (a GPU that stays slower than ~45 fps for 2.5 s at "high"):
+direct render, no bloom, pixel ratio at most 1. `runtime.stats.tier` shows
+the tier; `window.__verseStats` exposes the frame numbers in every build.
+
+QA hook: `window.__verseTune = { bloomStrength, bloomRadius, bloomThreshold,
+envGain, bakedGain, coatBias, exposureBias, materials: { <name prefix>:
+{ <numeric material property>: value } } }` overrides the look while a run
+measures it (read every frame; unset, the built-in values apply). Tune
+against Cycles renders from the same camera (`SHOULDER` numbers; ceiling
+ghosts visible), then move the values into the code.
+
+### Views
+
+Three views (`viewMode.ts`), switched on the tool rail's three-part control
+(bird's-eye, third person, first person; the one on screen pressed and
+named, the others an icon and their key) or from the keyboard. The last view
+chosen is kept in this browser (`viewSettings`, `view`). First person needs
+the eye-level scene; where there is none (the IDE panel, decks not exported)
+its button is disabled and a remembered first person shows third person.
+
+| Input | Bird's-eye | Third person | First person |
+|---|---|---|---|
+| 1 / 2 / 3 | pick the view (top row or keypad) | | |
+| V | cycle bird's-eye → third → first → bird's-eye | | |
+| Mouse | drag pans, click walks / selects / uses | shooter look (pointer lock): X turns, Y pitches | same |
+| Click on the view | walk / select / use | takes the mouse (when free) | same |
+| Left button (mouse taken) | | works what the crosshair is on: a crew member (again: their record), a station; never walks | same |
+| E | station within reach | what the crosshair is on, else the station within reach | same |
+| Esc | closes card / panel | gives the mouse back (HUD usable), then closes card / panel | same |
+| L | | takes or gives back the mouse | same |
+| W A S D | pan the map | walk relative to the view (A/D strafe), Shift hurries | same |
+| Wheel, + / − | zoom the plate | shoulder distance 1.2–5 m, eased; one notch past 1.2 m goes to first person | a notch out returns to third person at 1.2 m |
+
+Choosing third or first person with a click or a key takes the mouse at once
+(the browser needs that gesture); the bird's-eye view gives it back. With the
+mouse free the crosshair dims and *Click to look around* shows under it.
+Pointer lock asks for raw movement (`unadjustedMovement`) and falls back to a
+plain lock. Touch and pen keep drag-to-turn and tap-to-pick.
+
+While walking in a shooter view the commander faces the view, leaning at
+most 45° into a strafe; walking backwards they keep facing it and the walk
+clip plays in reverse (`bodyFacing`, `Actor.drive`). Standing still they turn
+freely. The camera never turns on its own (no recentring). The duel uses the
+same mouse look (`lookDelta`, `requestMouseLook`; see combat.md).
+
+### Camera
+
+`SHOULDER` in `shoulderRig.ts`; the third-person framing copies the reference
+shot the person gave: the commander in the lower right third, seen from about
+mid-thigh up, the room at eye level in depth.
+
+| | Value |
+|---|---|
+| Horizontal field of view | third person 70°, first person 85° (each 55–110° in the view settings; vertical from the aspect, at least 40°); blends with the person |
+| Mouse look | 0.0022 rad per pointer-lock pixel × sensitivity (0.25–3), the duel's rate too; drag 0.0042 rad/px |
+| Pivot | 1.74 m above the feet (top of the head), 0.47 m to the camera's left of the commander, so they stand right of centre (~0.63 of the width) |
+| Distance | 2.4 m behind the pivot (wheel: 1.2–5 m, eased with 0.09 s); the commander fills the frame from mid-thigh up, head top at ~0.48 of the height, as in the reference |
+| Pitch | third person 7° down by default, −35° (up) to 60° (down); first person ±80° |
+| Height | ~2.03 m at the default pitch (a little above the commander's head, looking slightly down on their shoulders); the horizon sits a little above the middle of the frame |
+| First person | eyes 1.65 m above the feet, 0.1 m in front of the body's axis, no sideways lag, the pivot's vertical lag; a segment test keeps them 0.12 m short of a wall in front; the commander's body is hidden past 30 % of the blend |
+| Hand-over | third ↔ first blends position and field of view in about 0.2 s (time constant 0.07 s, smoothstep) |
+| Follow | pivot lags 0.07 s horizontally, 0.16 s vertically (no head bob; the pivot ignores the walk cycle) |
+| Collision | segment tests head → shoulder → camera against the BVH; in at once with 0.24 m clearance, back out at 3.2 m/s |
+| Keys | W away from the camera, S toward it, A/D strafe; the commander faces the view while walking (9 rad/s) with the shared clips; Shift hurries |
+
+QA hook (every build): `window.__verseView = { set(view), look(dx, dy),
+zoom(factor), state() }` switches views, turns and zooms without a mouse
+(headless browsers cannot lock the pointer); `state()` reports the view, the
+person, distances, the blend, field of view, yaw, pitch and whether the mouse
+is taken.
+
+## Measured (bridge slice, RTX 5070 Ti, 2560 × 1392)
+
+Headless Chrome against an isolated instance of the built app, tier "high":
+
+| | Value |
+|---|---|
+| Frame rate | 60 fps (vsync) standing, walking and looking around; uncapped (`--disable-gpu-vsync --disable-frame-rate-limit`) ~600 fps, frame ~2 ms, CPU ~1.5–2.3 ms |
+| Draw calls | 200–290 (deck chunks, crew, effects) |
+| Triangles drawn | 0.6–0.95 M |
+| Content | 1.02 M triangles in 295 chunks; `realtime/` ~16.5 MB (glb 11.2 MB, 4 lightmap pages 4.7 MB, 6 probes ~0.6 MB) of the 25 MB budget |
+| Export | ~15 min on the GPU (bake 13.6 min of it), package ~2.5 min |
+
+The look was tuned against Cycles renders from the rig's exact camera with
+the ceiling ghosts visible (`window.__verseTune`): baked deck levels match
+the Cycles render; the floor's coat reflections, bloom and the windows were
+corrected until the dark areas matched.
+
+## Decks (final quality, 2026-10-26)
+
+| Deck | Export | `realtime/` | Triangles / chunks | Density (weight 1) | Pages in use |
+|---|---|---|---|---|---|
+| bridge | 21 min (bake 16 min) | 18.8 MB | 1.02 M / 323 | 42.5 px/m | 37-51 % surface, 86 % in rectangles |
+| engineering | 11 min (bake 7.5 min) | 21.2 MB | 1.56 M / 206 | 29.5 px/m | 25-41 % surface, 82 % in rectangles |
+| hangar | 12 min (bake 9 min) | 18.7 MB | 1.09 M / 197 | 27.7 px/m | 21-54 % surface, 80 % in rectangles |
+| ops | 17 min (bake 11 min) | 16.2 MB | 0.91 M / 441 | 29.5 px/m | 38-53 % surface |
+
+Closing the rooms at eye level (step 1 below), besides the ceiling ghosts:
+engineering's plain full-height walls (west hull wall, lobby | bay,
+bay | gallery) carry dark panelling with a rail and thin light strips
+(`eng_upper.cladding`, Architecture), the door slots in them have heads,
+and the near hull wall's upper panels are dark paint and charcoal instead
+of flat mid grey; the hangar's front band (booth, crew bay, arrivals, lift
+lobby, armoury) got the same upper panelling (`hangar_upper`).
+
+"Surface" is the share of each page the lightmap UVs cover; before the
+packing rebuild the bridge's pages held 3-15 %. The bridge numbers in
+"Measured" above are from the first slice (2026-10-20, old packing).
+
+## Exporting another deck
+
+1. Close the rooms at eye level. Everything the plate's cutaway removes must
+ exist above the cut as ceiling ghosts: build the upper parts of cut walls
+ with `kit.ghost(L.CUT_H)` into the `Ceiling` collection (see
+ `art/verse/decks/bridge/upper.py`; kit `*_Cut` pieces already carry their
+ ghosts). Door openings need heads and jambs up to the door height.
+ Ghosts stay invisible to the plate camera and to shadow rays, so the
+ committed plate does not change until the deck is recooked (then they
+ show only in floor reflections, as BRIEF §5 asks).
+2. Check the eye-level look before baking: render a few Cycles views from
+ walkable spots with ceilings visible (perspective camera ~1.9 m high,
+ 72° HFOV) and look for black voids above walls, missing ceilings and hull
+ gaps.
+3. Add every new material to `MATERIALS` (and `DENSITY_WEIGHT` if people
+ never get close to it) in `lib/realtime.py`.
+4. `python scripts/verse/cook.py deck <id> --realtime --quality preview`,
+ check it in the app (isolated instance), then `--quality final`.
+5. `python scripts/verse/validate.py` and `pytest tests/verse` must pass;
+ the realtime folder of a deck has a 25 MB budget, the whole
+ `public/verse` 160 MB.
+
+## Open work
+
+- First person has no view-model hands or blaster; the body is simply hidden.
+ Duels stay over the shoulder (the duel's own camera) whatever view is on.
+- There are no strafe or backwards clips: strafing leans the walk up to 45°,
+ backwards plays the walk in reverse.
+
+- Engineering's reactor shaft and the hangar are tall open volumes with one
+ probe each; the probe box runs from the room floor to its ceiling, so the
+ 52 m shaft below the reactor hall's floor reflects as if it ended there.
+- Floor markings with worn-through paint (`M_Deck_Hazard`,
+ `M_Deck_Marking_White`) are left out: bake their paint coverage as alpha
+ (an extra EMIT bake of the `keep` mask) and draw them alpha-tested.
+- Planar reflections for the main floors would add the crew and consoles to
+ the black deck's mirror; the box-projected probes show the room only.
+- The x-ray silhouettes of the plate view are off at eye level.
+- The bridge's side hull walls are large plain panels; at eye level they
+ want the panelling, light strips and structure the other walls have
+ (a level-design pass for the deck-bridge builder).
+- Lightmap texels are 2.6–3.5 cm: crisp enough with the live reflections and
+ the floor's plate detail, soft on small console details up close. Tiling
+ detail normals per material (`detail` "painted"/"metal" today only break
+ up the roughness) would sharpen walls and consoles further.
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_0.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_0.webp
new file mode 100644
index 0000000000..c3f5f45d52
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_1.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_1.webp
new file mode 100644
index 0000000000..817ba7900b
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_2.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_2.webp
new file mode 100644
index 0000000000..16e8ee2cf5
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_3.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_3.webp
new file mode 100644
index 0000000000..3fb8dd3039
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_bridge.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_bridge.webp
new file mode 100644
index 0000000000..9a723e9aa8
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_bridge.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_briefing.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_briefing.webp
new file mode 100644
index 0000000000..d35310e7ee
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_briefing.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_lobby.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_lobby.webp
new file mode 100644
index 0000000000..0da48dbff2
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_lobby.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_pit_p.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_pit_p.webp
new file mode 100644
index 0000000000..469ae27c7f
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_pit_p.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_pit_s.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_pit_s.webp
new file mode 100644
index 0000000000..c4e1f80181
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_pit_s.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_ready.webp b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_ready.webp
new file mode 100644
index 0000000000..9a6f6baa09
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/probe_ready.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/bridge/realtime/scene.glb b/dodaios/ui/web/dist/verse/decks/bridge/realtime/scene.glb
new file mode 100644
index 0000000000..9b66f31436
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/bridge/realtime/scene.glb differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_0.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_0.webp
new file mode 100644
index 0000000000..fcdf8cf16b
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_1.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_1.webp
new file mode 100644
index 0000000000..540ed63485
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_2.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_2.webp
new file mode 100644
index 0000000000..332aa39e43
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_3.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_3.webp
new file mode 100644
index 0000000000..a4786deeaa
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_bay.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_bay.webp
new file mode 100644
index 0000000000..04ee3fc0cf
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_bay.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_control.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_control.webp
new file mode 100644
index 0000000000..801e1a0b66
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_control.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_gallery.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_gallery.webp
new file mode 100644
index 0000000000..4eeadb5150
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_gallery.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_lobby.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_lobby.webp
new file mode 100644
index 0000000000..8e8a275e6f
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_lobby.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_reactor.webp b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_reactor.webp
new file mode 100644
index 0000000000..15b8c48cd1
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/probe_reactor.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/engineering/realtime/scene.glb b/dodaios/ui/web/dist/verse/decks/engineering/realtime/scene.glb
new file mode 100644
index 0000000000..5b7b9e6a0e
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/engineering/realtime/scene.glb differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_0.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_0.webp
new file mode 100644
index 0000000000..3ffb3bda46
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_1.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_1.webp
new file mode 100644
index 0000000000..f392574349
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_2.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_2.webp
new file mode 100644
index 0000000000..ae673012cf
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_3.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_3.webp
new file mode 100644
index 0000000000..d7c25235af
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_armoury.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_armoury.webp
new file mode 100644
index 0000000000..35904c6488
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_armoury.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_arrivals.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_arrivals.webp
new file mode 100644
index 0000000000..717a48093d
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_arrivals.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_booth.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_booth.webp
new file mode 100644
index 0000000000..05f8caff90
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_booth.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_crew_bay.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_crew_bay.webp
new file mode 100644
index 0000000000..075a2ac2d3
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_crew_bay.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_flight_deck.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_flight_deck.webp
new file mode 100644
index 0000000000..b902adc6d6
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_flight_deck.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_lift_lobby.webp b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_lift_lobby.webp
new file mode 100644
index 0000000000..d8e9213eba
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/probe_lift_lobby.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/hangar/realtime/scene.glb b/dodaios/ui/web/dist/verse/decks/hangar/realtime/scene.glb
new file mode 100644
index 0000000000..07c1829cf7
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/hangar/realtime/scene.glb differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_0.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_0.webp
new file mode 100644
index 0000000000..cd98de44b4
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_1.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_1.webp
new file mode 100644
index 0000000000..08af540c63
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_2.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_2.webp
new file mode 100644
index 0000000000..43e194fde6
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_3.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_3.webp
new file mode 100644
index 0000000000..9fd2a18bc1
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_corridor.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_corridor.webp
new file mode 100644
index 0000000000..414b5b27d8
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_corridor.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_lobby.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_lobby.webp
new file mode 100644
index 0000000000..65bc7295f4
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_lobby.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_medbay.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_medbay.webp
new file mode 100644
index 0000000000..d6b72a2b57
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_medbay.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_mess.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_mess.webp
new file mode 100644
index 0000000000..611873ab1c
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_mess.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_quartermaster.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_quartermaster.webp
new file mode 100644
index 0000000000..e76bbcdb62
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_quartermaster.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_quarters.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_quarters.webp
new file mode 100644
index 0000000000..c2b7468eca
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_quarters.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_records.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_records.webp
new file mode 100644
index 0000000000..778e8b4a32
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_records.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_simulator.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_simulator.webp
new file mode 100644
index 0000000000..2abba257a4
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_simulator.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_storage.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_storage.webp
new file mode 100644
index 0000000000..4d5c034d96
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_storage.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_team_a.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_team_a.webp
new file mode 100644
index 0000000000..c1ed04a5cd
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_team_a.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_team_b.webp b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_team_b.webp
new file mode 100644
index 0000000000..aaecc34d2b
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/probe_team_b.webp differ
diff --git a/dodaios/ui/web/dist/verse/decks/ops/realtime/scene.glb b/dodaios/ui/web/dist/verse/decks/ops/realtime/scene.glb
new file mode 100644
index 0000000000..15cfe264da
Binary files /dev/null and b/dodaios/ui/web/dist/verse/decks/ops/realtime/scene.glb differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/manifest.json b/dodaios/ui/web/frontend/public/verse/decks/bridge/manifest.json
index e48d89f255..f29cace2f9 100644
--- a/dodaios/ui/web/frontend/public/verse/decks/bridge/manifest.json
+++ b/dodaios/ui/web/frontend/public/verse/decks/bridge/manifest.json
@@ -3656,6 +3656,847 @@
"blender_s": 693.5,
"package_s": 96.94,
"plate_bytes": 2811653,
- "bytes": 3291549
+ "bytes": 22060431
+ },
+ "realtime": {
+ "version": 1,
+ "quality": "final",
+ "scene": {
+ "url": "realtime/scene.glb",
+ "vertices": 1320074,
+ "triangles": 1022265,
+ "chunks": 323
+ },
+ "lightmaps": {
+ "encoding": "rgbm2",
+ "range": 32.0,
+ "pages": [
+ {
+ "url": "realtime/lm_0.webp",
+ "size": 4096,
+ "density": 42.49
+ },
+ {
+ "url": "realtime/lm_1.webp",
+ "size": 4096,
+ "density": 42.49
+ },
+ {
+ "url": "realtime/lm_2.webp",
+ "size": 4096,
+ "density": 42.49
+ },
+ {
+ "url": "realtime/lm_3.webp",
+ "size": 4096,
+ "density": 42.49
+ }
+ ]
+ },
+ "probes": [
+ {
+ "room": "bridge",
+ "url": "realtime/probe_bridge.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 36.0,
+ 1.4,
+ 16.1225
+ ],
+ "box_min": [
+ 3.6,
+ 0.0,
+ 3.6
+ ],
+ "box_max": [
+ 68.4,
+ 7.2,
+ 31.2
+ ]
+ },
+ {
+ "room": "briefing",
+ "url": "realtime/probe_briefing.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 15.9,
+ 1.4,
+ 38.4
+ ],
+ "box_min": [
+ 3.6,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 28.2,
+ 3.6,
+ 43.2
+ ]
+ },
+ {
+ "room": "lobby",
+ "url": "realtime/probe_lobby.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 36.0,
+ 1.4,
+ 38.4
+ ],
+ "box_min": [
+ 30.6,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 41.4,
+ 3.6,
+ 43.2
+ ]
+ },
+ {
+ "room": "pit_p",
+ "url": "realtime/probe_pit_p.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 18.0685,
+ 0.0,
+ 18.268
+ ],
+ "box_min": [
+ 3.6,
+ -1.4,
+ 7.2
+ ],
+ "box_max": [
+ 31.8,
+ 7.2,
+ 28.8
+ ]
+ },
+ {
+ "room": "pit_s",
+ "url": "realtime/probe_pit_s.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 53.9315,
+ 0.0,
+ 18.268
+ ],
+ "box_min": [
+ 40.2,
+ -1.4,
+ 7.2
+ ],
+ "box_max": [
+ 68.4,
+ 7.2,
+ 28.8
+ ]
+ },
+ {
+ "room": "ready",
+ "url": "realtime/probe_ready.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 56.1,
+ 1.4,
+ 38.4
+ ],
+ "box_min": [
+ 43.8,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 68.4,
+ 3.6,
+ 43.2
+ ]
+ }
+ ],
+ "materials": {
+ "M_Ceiling_Panel": {
+ "roughness": 0.47,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Body": {
+ "roughness": 0.36,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.15,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Deck": {
+ "roughness": 0.43,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Keys": {
+ "roughness": 0.5,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Emit_BacklitPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Floor_GlossBlack": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.12,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_Grating": {
+ "roughness": 0.46,
+ "metalness": 1.0,
+ "color": [
+ 0.32,
+ 0.33,
+ 0.34
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_SatinDark": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.35,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.5,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Glass_Clear": {
+ "roughness": 0.01,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.04,
+ "collide": false
+ },
+ "M_Hull_Pipe": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_PipeInsulated": {
+ "roughness": 0.69,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_Structure": {
+ "roughness": 0.5,
+ "metalness": 0.75,
+ "color": [
+ 0.07,
+ 0.075,
+ 0.085
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Indicator_Amber": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Blue": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Green": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Red": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_White": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Lacquer_BlackGloss": {
+ "roughness": 0.07,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Light_Backlit": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_CeilingPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_FloorInlay": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_RedTrim": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_WallStrip": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Paint_TrimRed": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_BlackSatin": {
+ "roughness": 0.48,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_LampOff": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.5,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Recess_Dark": {
+ "roughness": 0.7,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Rubber_Black": {
+ "roughness": 0.72,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.35,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Screen": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Seat_Upholstery": {
+ "roughness": 0.4,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Starfield": {
+ "roughness": 1.0,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.0,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Struct_Gunmetal": {
+ "roughness": 0.38,
+ "metalness": 1.0,
+ "color": [
+ 0.16,
+ 0.165,
+ 0.175
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Trim_BrushedSteel": {
+ "roughness": 0.22,
+ "metalness": 1.0,
+ "color": [
+ 0.56,
+ 0.565,
+ 0.575
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Trim_Chrome": {
+ "roughness": 0.07,
+ "metalness": 1.0,
+ "color": [
+ 0.82,
+ 0.83,
+ 0.84
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_Charcoal": {
+ "roughness": 0.32,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.25,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedDark": {
+ "roughness": 0.39,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedLight": {
+ "roughness": 0.28,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.2,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedMid": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "TMP_M_Glass_HoloLens": {
+ "roughness": 0.04,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "TMP_M_Metal_RankGold": {
+ "roughness": 0.3,
+ "metalness": 1.0,
+ "color": [
+ 0.8,
+ 0.56,
+ 0.22
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ }
+ },
+ "bytes": 18753386,
+ "stats": {
+ "objects": 751,
+ "triangles": 1022265,
+ "vertices": 1320074,
+ "chunks": 323,
+ "area_m2": 28524.2,
+ "hidden_objects": 646,
+ "hidden_area_m2": 7403.6,
+ "far_split": 2,
+ "far_decimated_triangles": 1108,
+ "density": [
+ 42.49,
+ 42.49,
+ 42.49,
+ 42.49
+ ],
+ "samples": 512,
+ "blender": "5.0.1",
+ "realise_s": 6.45,
+ "visibility_s": 21.8,
+ "unwrap_s": 36.22,
+ "join_s": 2.64,
+ "bake_s": 945.31,
+ "probes_s": 25.34,
+ "geometry_s": 6.39,
+ "blender_s": 1048.5,
+ "package_s": 215.34
+ }
}
}
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_0.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_0.webp
new file mode 100644
index 0000000000..c3f5f45d52
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_1.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_1.webp
new file mode 100644
index 0000000000..817ba7900b
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_2.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_2.webp
new file mode 100644
index 0000000000..16e8ee2cf5
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_3.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_3.webp
new file mode 100644
index 0000000000..3fb8dd3039
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_bridge.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_bridge.webp
new file mode 100644
index 0000000000..9a723e9aa8
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_bridge.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_briefing.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_briefing.webp
new file mode 100644
index 0000000000..d35310e7ee
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_briefing.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_lobby.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_lobby.webp
new file mode 100644
index 0000000000..0da48dbff2
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_lobby.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_pit_p.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_pit_p.webp
new file mode 100644
index 0000000000..469ae27c7f
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_pit_p.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_pit_s.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_pit_s.webp
new file mode 100644
index 0000000000..c4e1f80181
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_pit_s.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_ready.webp b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_ready.webp
new file mode 100644
index 0000000000..9a6f6baa09
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/probe_ready.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/scene.glb b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/scene.glb
new file mode 100644
index 0000000000..9b66f31436
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/bridge/realtime/scene.glb differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json b/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json
index 9b0422e41e..e1dbbfbbfc 100644
--- a/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json
+++ b/dodaios/ui/web/frontend/public/verse/decks/engineering/manifest.json
@@ -3188,6 +3188,841 @@
"blender_s": 1257.8,
"package_s": 141.53,
"plate_bytes": 3740702,
- "bytes": 4225303
+ "bytes": 25480107
+ },
+ "realtime": {
+ "version": 1,
+ "quality": "final",
+ "scene": {
+ "url": "realtime/scene.glb",
+ "vertices": 1751115,
+ "triangles": 1559785,
+ "chunks": 206
+ },
+ "lightmaps": {
+ "encoding": "rgbm2",
+ "range": 32.0,
+ "pages": [
+ {
+ "url": "realtime/lm_0.webp",
+ "size": 4096,
+ "density": 29.48
+ },
+ {
+ "url": "realtime/lm_1.webp",
+ "size": 4096,
+ "density": 29.48
+ },
+ {
+ "url": "realtime/lm_2.webp",
+ "size": 4096,
+ "density": 29.48
+ },
+ {
+ "url": "realtime/lm_3.webp",
+ "size": 4096,
+ "density": 29.48
+ }
+ ]
+ },
+ "probes": [
+ {
+ "room": "bay",
+ "url": "realtime/probe_bay.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 23.7,
+ 1.4,
+ 46.7
+ ],
+ "box_min": [
+ 15.4,
+ 0.0,
+ 41.4
+ ],
+ "box_max": [
+ 32.0,
+ 4.8,
+ 52.0
+ ]
+ },
+ {
+ "room": "control",
+ "url": "realtime/probe_control.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 17.0,
+ 1.4,
+ 21.3
+ ],
+ "box_min": [
+ 2.0,
+ 0.0,
+ 2.0
+ ],
+ "box_max": [
+ 32.0,
+ 4.5,
+ 40.6
+ ]
+ },
+ {
+ "room": "gallery",
+ "url": "realtime/probe_gallery.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 58.0,
+ 1.4,
+ 45.2
+ ],
+ "box_min": [
+ 34.0,
+ 0.0,
+ 38.4
+ ],
+ "box_max": [
+ 82.0,
+ 4.8,
+ 52.0
+ ]
+ },
+ {
+ "room": "lobby",
+ "url": "realtime/probe_lobby.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 8.3,
+ 1.4,
+ 46.7
+ ],
+ "box_min": [
+ 2.0,
+ 0.0,
+ 41.4
+ ],
+ "box_max": [
+ 14.6,
+ 4.2,
+ 52.0
+ ]
+ },
+ {
+ "room": "reactor",
+ "url": "realtime/probe_reactor.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 57.5,
+ 1.4,
+ 20.05
+ ],
+ "box_min": [
+ 33.0,
+ 0.0,
+ 2.0
+ ],
+ "box_max": [
+ 82.0,
+ 12.0,
+ 38.1
+ ]
+ }
+ ],
+ "materials": {
+ "M_Ceiling_Panel": {
+ "roughness": 0.47,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Body": {
+ "roughness": 0.36,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.15,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Deck": {
+ "roughness": 0.43,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Crate_Paint": {
+ "roughness": 0.46,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Emit_BacklitPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Floor_GlossBlack": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.12,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_Grating": {
+ "roughness": 0.46,
+ "metalness": 1.0,
+ "color": [
+ 0.32,
+ 0.33,
+ 0.34
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_SatinDark": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.35,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.5,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Glass_Viewport": {
+ "roughness": 0.02,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.06,
+ "collide": false
+ },
+ "M_Hull_Pipe": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_PipeInsulated": {
+ "roughness": 0.69,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_Structure": {
+ "roughness": 0.5,
+ "metalness": 0.75,
+ "color": [
+ 0.07,
+ 0.075,
+ 0.085
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Indicator_Amber": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Blue": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Green": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Red": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_White": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_Backlit": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_CeilingPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_Maint_Red": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_WallStrip": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Paint_TrimRed": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_BlackSatin": {
+ "roughness": 0.48,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_LampOff": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.5,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Recess_Dark": {
+ "roughness": 0.7,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Rubber_Black": {
+ "roughness": 0.72,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.35,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Screen": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Seat_Upholstery": {
+ "roughness": 0.4,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Struct_Gunmetal": {
+ "roughness": 0.38,
+ "metalness": 1.0,
+ "color": [
+ 0.16,
+ 0.165,
+ 0.175
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_ContainerGrey": {
+ "roughness": 0.5,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_ContainerGunmetal": {
+ "roughness": 0.46,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_ContainerOlive": {
+ "roughness": 0.5,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_CoreHot": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_TMP_PropsInd_LampDim": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_TMP_PropsInd_LampFlood": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_TMP_PropsInd_Tread": {
+ "roughness": 0.36,
+ "metalness": 1.0,
+ "color": [
+ 0.3,
+ 0.305,
+ 0.31
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Trim_BrushedSteel": {
+ "roughness": 0.22,
+ "metalness": 1.0,
+ "color": [
+ 0.56,
+ 0.565,
+ 0.575
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_Charcoal": {
+ "roughness": 0.32,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.25,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedDark": {
+ "roughness": 0.39,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedLight": {
+ "roughness": 0.28,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.2,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedMid": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ }
+ },
+ "bytes": 21239242,
+ "stats": {
+ "objects": 794,
+ "triangles": 1559785,
+ "vertices": 1751115,
+ "chunks": 206,
+ "area_m2": 84514.3,
+ "hidden_objects": 675,
+ "hidden_area_m2": 9681.0,
+ "far_split": 8,
+ "far_decimated_triangles": 1125147,
+ "density": [
+ 29.48,
+ 29.48,
+ 29.48,
+ 29.48
+ ],
+ "samples": 512,
+ "blender": "5.0.1",
+ "realise_s": 23.39,
+ "visibility_s": 16.06,
+ "unwrap_s": 23.16,
+ "join_s": 1.42,
+ "bake_s": 452.3,
+ "probes_s": 27.89,
+ "geometry_s": 12.53,
+ "blender_s": 561.7,
+ "package_s": 92.39
+ }
}
}
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_0.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_0.webp
new file mode 100644
index 0000000000..fcdf8cf16b
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_1.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_1.webp
new file mode 100644
index 0000000000..540ed63485
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_2.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_2.webp
new file mode 100644
index 0000000000..332aa39e43
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_3.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_3.webp
new file mode 100644
index 0000000000..a4786deeaa
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_bay.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_bay.webp
new file mode 100644
index 0000000000..04ee3fc0cf
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_bay.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_control.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_control.webp
new file mode 100644
index 0000000000..801e1a0b66
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_control.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_gallery.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_gallery.webp
new file mode 100644
index 0000000000..4eeadb5150
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_gallery.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_lobby.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_lobby.webp
new file mode 100644
index 0000000000..8e8a275e6f
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_lobby.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_reactor.webp b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_reactor.webp
new file mode 100644
index 0000000000..15b8c48cd1
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/probe_reactor.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/scene.glb b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/scene.glb
new file mode 100644
index 0000000000..5b7b9e6a0e
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/engineering/realtime/scene.glb differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/manifest.json b/dodaios/ui/web/frontend/public/verse/decks/hangar/manifest.json
index 6a09767132..30248e70af 100644
--- a/dodaios/ui/web/frontend/public/verse/decks/hangar/manifest.json
+++ b/dodaios/ui/web/frontend/public/verse/decks/hangar/manifest.json
@@ -2174,6 +2174,943 @@
"blender_s": 1628.0,
"package_s": 166.91,
"plate_bytes": 3615652,
- "bytes": 4053963
+ "bytes": 22806769
+ },
+ "realtime": {
+ "version": 1,
+ "quality": "final",
+ "scene": {
+ "url": "realtime/scene.glb",
+ "vertices": 1076985,
+ "triangles": 1086962,
+ "chunks": 197
+ },
+ "lightmaps": {
+ "encoding": "rgbm2",
+ "range": 64.0,
+ "pages": [
+ {
+ "url": "realtime/lm_0.webp",
+ "size": 4096,
+ "density": 27.74
+ },
+ {
+ "url": "realtime/lm_1.webp",
+ "size": 4096,
+ "density": 27.74
+ },
+ {
+ "url": "realtime/lm_2.webp",
+ "size": 4096,
+ "density": 27.74
+ },
+ {
+ "url": "realtime/lm_3.webp",
+ "size": 4096,
+ "density": 27.74
+ }
+ ]
+ },
+ "probes": [
+ {
+ "room": "armoury",
+ "url": "realtime/probe_armoury.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 89.0,
+ 1.4,
+ 52.4
+ ],
+ "box_min": [
+ 77.0,
+ 0.0,
+ 47.5
+ ],
+ "box_max": [
+ 97.5,
+ 4.7,
+ 61.6
+ ]
+ },
+ {
+ "room": "arrivals",
+ "url": "realtime/probe_arrivals.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 50.0,
+ 1.4,
+ 55.5
+ ],
+ "box_min": [
+ 40.0,
+ 0.0,
+ 46.0
+ ],
+ "box_max": [
+ 62.0,
+ 4.7,
+ 61.6
+ ]
+ },
+ {
+ "room": "booth",
+ "url": "realtime/probe_booth.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 16.0,
+ "position": [
+ 14.0,
+ 2.6,
+ 51.6
+ ],
+ "box_min": [
+ 3.0,
+ 1.2,
+ 47.2
+ ],
+ "box_max": [
+ 25.0,
+ 4.7,
+ 61.6
+ ]
+ },
+ {
+ "room": "crew_bay",
+ "url": "realtime/probe_crew_bay.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 36.0,
+ 1.4,
+ 51.0
+ ],
+ "box_min": [
+ 25.0,
+ 0.0,
+ 46.0
+ ],
+ "box_max": [
+ 40.0,
+ 4.7,
+ 61.6
+ ]
+ },
+ {
+ "room": "flight_deck",
+ "url": "realtime/probe_flight_deck.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 64.0,
+ "position": [
+ 33.0,
+ 1.4,
+ 24.5
+ ],
+ "box_min": [
+ 2.5,
+ 0.0,
+ 1.5
+ ],
+ "box_max": [
+ 97.5,
+ 21.0,
+ 46.0
+ ]
+ },
+ {
+ "room": "lift_lobby",
+ "url": "realtime/probe_lift_lobby.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 70.0,
+ 1.4,
+ 56.5
+ ],
+ "box_min": [
+ 62.0,
+ 0.0,
+ 46.0
+ ],
+ "box_max": [
+ 77.0,
+ 4.7,
+ 61.6
+ ]
+ }
+ ],
+ "materials": {
+ "M_Ceiling_Panel": {
+ "roughness": 0.47,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Body": {
+ "roughness": 0.36,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.15,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Deck": {
+ "roughness": 0.43,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Crate_Paint": {
+ "roughness": 0.46,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Emit_BacklitPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Floor_GlossBlack": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.12,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_Grating": {
+ "roughness": 0.46,
+ "metalness": 1.0,
+ "color": [
+ 0.32,
+ 0.33,
+ 0.34
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_SatinDark": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.35,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.5,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Glass_Viewport": {
+ "roughness": 0.02,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.06,
+ "collide": false
+ },
+ "M_Hangar_BankPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Hangar_Deck": {
+ "roughness": 0.42,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.8,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.3,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hangar_FieldBlue": {
+ "roughness": 0.08,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.2,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.48,
+ "collide": false
+ },
+ "M_Hangar_FloodLens": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Hangar_FloorLamp": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Hangar_PierLight": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Hangar_RoomStrip": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Hangar_SignBacklit": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Hull_Pipe": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_Structure": {
+ "roughness": 0.5,
+ "metalness": 0.75,
+ "color": [
+ 0.07,
+ 0.075,
+ 0.085
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Indicator_Amber": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Blue": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Green": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Red": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_White": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_FloorInlay": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_WallStrip": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Paint_TrimRed": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_BlackSatin": {
+ "roughness": 0.48,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_LampOff": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.5,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Recess_Dark": {
+ "roughness": 0.7,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Rubber_Black": {
+ "roughness": 0.72,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.35,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Screen": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Seat_Upholstery": {
+ "roughness": 0.4,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Struct_Gunmetal": {
+ "roughness": 0.38,
+ "metalness": 1.0,
+ "color": [
+ 0.16,
+ 0.165,
+ 0.175
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_CabinGlow": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_TMP_PropsInd_ContainerGrey": {
+ "roughness": 0.5,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_ContainerGunmetal": {
+ "roughness": 0.46,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_ContainerOlive": {
+ "roughness": 0.5,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_GlassDark": {
+ "roughness": 0.04,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.6,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_HullPaint": {
+ "roughness": 0.42,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_Tread": {
+ "roughness": 0.36,
+ "metalness": 1.0,
+ "color": [
+ 0.3,
+ 0.305,
+ 0.31
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Trim_BrushedSteel": {
+ "roughness": 0.22,
+ "metalness": 1.0,
+ "color": [
+ 0.56,
+ 0.565,
+ 0.575
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_Charcoal": {
+ "roughness": 0.32,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.25,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedDark": {
+ "roughness": 0.39,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedLight": {
+ "roughness": 0.28,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.2,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedMid": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ }
+ },
+ "bytes": 18735354,
+ "stats": {
+ "objects": 290,
+ "triangles": 1086962,
+ "vertices": 1076985,
+ "chunks": 197,
+ "area_m2": 80049.9,
+ "hidden_objects": 9,
+ "hidden_area_m2": 6906.1,
+ "far_split": 13,
+ "far_decimated_triangles": 24646,
+ "density": [
+ 27.74,
+ 27.74,
+ 27.74,
+ 27.74
+ ],
+ "samples": 512,
+ "blender": "5.0.1",
+ "realise_s": 2.64,
+ "visibility_s": 28.61,
+ "unwrap_s": 4.73,
+ "join_s": 0.36,
+ "bake_s": 531.26,
+ "probes_s": 32.99,
+ "geometry_s": 10.14,
+ "blender_s": 613.8,
+ "package_s": 114.74
+ }
}
}
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_0.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_0.webp
new file mode 100644
index 0000000000..3ffb3bda46
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_1.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_1.webp
new file mode 100644
index 0000000000..f392574349
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_2.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_2.webp
new file mode 100644
index 0000000000..ae673012cf
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_3.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_3.webp
new file mode 100644
index 0000000000..d7c25235af
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_armoury.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_armoury.webp
new file mode 100644
index 0000000000..35904c6488
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_armoury.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_arrivals.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_arrivals.webp
new file mode 100644
index 0000000000..717a48093d
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_arrivals.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_booth.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_booth.webp
new file mode 100644
index 0000000000..05f8caff90
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_booth.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_crew_bay.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_crew_bay.webp
new file mode 100644
index 0000000000..075a2ac2d3
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_crew_bay.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_flight_deck.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_flight_deck.webp
new file mode 100644
index 0000000000..b902adc6d6
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_flight_deck.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_lift_lobby.webp b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_lift_lobby.webp
new file mode 100644
index 0000000000..d8e9213eba
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/probe_lift_lobby.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/scene.glb b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/scene.glb
new file mode 100644
index 0000000000..07c1829cf7
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/hangar/realtime/scene.glb differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/manifest.json b/dodaios/ui/web/frontend/public/verse/decks/ops/manifest.json
index d502f1061e..0e4a9b743f 100644
--- a/dodaios/ui/web/frontend/public/verse/decks/ops/manifest.json
+++ b/dodaios/ui/web/frontend/public/verse/decks/ops/manifest.json
@@ -8618,6 +8618,1245 @@
"blender_s": 1592.0,
"package_s": 177.73,
"plate_bytes": 3847194,
- "bytes": 4458833
+ "bytes": 20691418
+ },
+ "realtime": {
+ "version": 1,
+ "quality": "final",
+ "scene": {
+ "url": "realtime/scene.glb",
+ "vertices": 923535,
+ "triangles": 913270,
+ "chunks": 441
+ },
+ "lightmaps": {
+ "encoding": "rgbm2",
+ "range": 32.0,
+ "pages": [
+ {
+ "url": "realtime/lm_0.webp",
+ "size": 4096,
+ "density": 29.48
+ },
+ {
+ "url": "realtime/lm_1.webp",
+ "size": 4096,
+ "density": 29.48
+ },
+ {
+ "url": "realtime/lm_2.webp",
+ "size": 4096,
+ "density": 29.48
+ },
+ {
+ "url": "realtime/lm_3.webp",
+ "size": 4096,
+ "density": 29.48
+ }
+ ]
+ },
+ "probes": [
+ {
+ "room": "corridor",
+ "url": "realtime/probe_corridor.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 48.0,
+ 1.4,
+ 30.0
+ ],
+ "box_min": [
+ 4.2,
+ 0.0,
+ 27.6
+ ],
+ "box_max": [
+ 91.8,
+ 4.2,
+ 32.4
+ ]
+ },
+ {
+ "room": "lobby",
+ "url": "realtime/probe_lobby.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 76.0,
+ 1.4,
+ 39.8
+ ],
+ "box_min": [
+ 71.0,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 81.0,
+ 4.6,
+ 46.0
+ ]
+ },
+ {
+ "room": "medbay",
+ "url": "realtime/probe_medbay.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 82.0,
+ 1.4,
+ 52.5
+ ],
+ "box_min": [
+ 71.0,
+ 0.0,
+ 47.0
+ ],
+ "box_max": [
+ 93.0,
+ 4.6,
+ 58.0
+ ]
+ },
+ {
+ "room": "mess",
+ "url": "realtime/probe_mess.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 17.0,
+ 1.4,
+ 14.2
+ ],
+ "box_min": [
+ 3.0,
+ 0.0,
+ 2.0
+ ],
+ "box_max": [
+ 31.0,
+ 4.6,
+ 26.4
+ ]
+ },
+ {
+ "room": "quartermaster",
+ "url": "realtime/probe_quartermaster.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 84.0,
+ 1.4,
+ 14.2
+ ],
+ "box_min": [
+ 75.0,
+ 0.0,
+ 2.0
+ ],
+ "box_max": [
+ 93.0,
+ 4.6,
+ 26.4
+ ]
+ },
+ {
+ "room": "quarters",
+ "url": "realtime/probe_quarters.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 16.0,
+ "position": [
+ 20.0,
+ 1.4,
+ 45.8
+ ],
+ "box_min": [
+ 3.0,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 37.0,
+ 4.6,
+ 58.0
+ ]
+ },
+ {
+ "room": "records",
+ "url": "realtime/probe_records.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 42.0,
+ 1.4,
+ 14.2
+ ],
+ "box_min": [
+ 33.0,
+ 0.0,
+ 2.0
+ ],
+ "box_max": [
+ 51.0,
+ 4.6,
+ 26.4
+ ]
+ },
+ {
+ "room": "simulator",
+ "url": "realtime/probe_simulator.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 63.0,
+ 1.4,
+ 14.2
+ ],
+ "box_min": [
+ 53.0,
+ 0.0,
+ 2.0
+ ],
+ "box_max": [
+ 73.0,
+ 4.6,
+ 26.4
+ ]
+ },
+ {
+ "room": "storage",
+ "url": "realtime/probe_storage.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 32.0,
+ "position": [
+ 88.0,
+ 1.4,
+ 39.8
+ ],
+ "box_min": [
+ 83.0,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 93.0,
+ 4.6,
+ 46.0
+ ]
+ },
+ {
+ "room": "team_a",
+ "url": "realtime/probe_team_a.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 16.0,
+ "position": [
+ 46.0,
+ 1.4,
+ 45.8
+ ],
+ "box_min": [
+ 39.0,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 53.0,
+ 4.6,
+ 58.0
+ ]
+ },
+ {
+ "room": "team_b",
+ "url": "realtime/probe_team_b.webp",
+ "w": 1024,
+ "h": 512,
+ "range": 16.0,
+ "position": [
+ 62.0,
+ 1.4,
+ 45.8
+ ],
+ "box_min": [
+ 55.0,
+ 0.0,
+ 33.6
+ ],
+ "box_max": [
+ 69.0,
+ 4.6,
+ 58.0
+ ]
+ }
+ ],
+ "materials": {
+ "M_Ceiling_Panel": {
+ "roughness": 0.47,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Body": {
+ "roughness": 0.36,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.15,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Deck": {
+ "roughness": 0.43,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Console_Keys": {
+ "roughness": 0.5,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Crate_Paint": {
+ "roughness": 0.46,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Emit_BacklitPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Fabric_BlanketSlate": {
+ "roughness": 0.92,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.3,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Fabric_BunkGrey": {
+ "roughness": 0.9,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.3,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Fabric_Linen": {
+ "roughness": 0.9,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.3,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Fabric_UniformOlive": {
+ "roughness": 0.9,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.3,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_GlossBlack": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.12,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_Grating": {
+ "roughness": 0.46,
+ "metalness": 1.0,
+ "color": [
+ 0.32,
+ 0.33,
+ 0.34
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Floor_SatinDark": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.35,
+ "clearcoat_roughness": 0.06,
+ "specular": 0.5,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Glass_Clear": {
+ "roughness": 0.01,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.04,
+ "collide": false
+ },
+ "M_Hull_Pipe": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_PipeInsulated": {
+ "roughness": 0.69,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Hull_Structure": {
+ "roughness": 0.5,
+ "metalness": 0.75,
+ "color": [
+ 0.07,
+ 0.075,
+ 0.085
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Indicator_Amber": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Blue": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Green": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_Red": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Indicator_White": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Lacquer_BlackGloss": {
+ "roughness": 0.07,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Light_CeilingPanel": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_FloorInlay": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Light_WallStrip": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Floor_Satin": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.45,
+ "clearcoat_roughness": 0.08,
+ "specular": 0.5,
+ "detail": "deck_plates",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Ops_Floor_SatinGrey": {
+ "roughness": 0.4,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Ops_Floor_WashTile": {
+ "roughness": 0.26,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.3,
+ "clearcoat_roughness": 0.08,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Ops_Glass_Case": {
+ "roughness": 0.03,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.05,
+ "collide": false
+ },
+ "M_Ops_Glass_Slit": {
+ "roughness": 0.02,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.15,
+ "detail": "none",
+ "transparent": true,
+ "opacity": 0.04,
+ "collide": false
+ },
+ "M_Ops_Light_Corridor": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_Dim": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_Hatch": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_MessCool": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_Night": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_Pip": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.02,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_Ring": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Light_Warm": {
+ "roughness": 0.6,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.25,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": false
+ },
+ "M_Ops_Table_Top": {
+ "roughness": 0.16,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Paint_TrimRed": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_BlackSatin": {
+ "roughness": 0.48,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_LampOff": {
+ "roughness": 0.25,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.5,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Plastic_MedWhite": {
+ "roughness": 0.36,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Recess_Dark": {
+ "roughness": 0.7,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Rubber_Black": {
+ "roughness": 0.72,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.35,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Screen": {
+ "roughness": 0.3,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 1.0,
+ "clearcoat_roughness": 0.03,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Seat_Upholstery": {
+ "roughness": 0.4,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Struct_Gunmetal": {
+ "roughness": 0.38,
+ "metalness": 1.0,
+ "color": [
+ 0.16,
+ 0.165,
+ 0.175
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_TMP_PropsInd_ContainerGunmetal": {
+ "roughness": 0.46,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Trim_BrushedSteel": {
+ "roughness": 0.22,
+ "metalness": 1.0,
+ "color": [
+ 0.56,
+ 0.565,
+ 0.575
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "metal",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Trim_Chrome": {
+ "roughness": 0.07,
+ "metalness": 1.0,
+ "color": [
+ 0.82,
+ 0.83,
+ 0.84
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedDark": {
+ "roughness": 0.39,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedLight": {
+ "roughness": 0.28,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.2,
+ "clearcoat_roughness": 0.12,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "M_Wall_PaintedMid": {
+ "roughness": 0.41,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "painted",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "TMP_M_Metal_RankGold": {
+ "roughness": 0.3,
+ "metalness": 1.0,
+ "color": [
+ 0.8,
+ 0.56,
+ 0.22
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "TMP_M_Paint_RankBlue": {
+ "roughness": 0.35,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ },
+ "TMP_M_Paint_RankRed": {
+ "roughness": 0.35,
+ "metalness": 0.0,
+ "color": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "clearcoat": 0.0,
+ "clearcoat_roughness": 0.05,
+ "specular": 0.5,
+ "detail": "none",
+ "transparent": false,
+ "opacity": 1.0,
+ "collide": true
+ }
+ },
+ "bytes": 16209942,
+ "stats": {
+ "objects": 785,
+ "triangles": 913270,
+ "vertices": 923535,
+ "chunks": 441,
+ "area_m2": 75101.8,
+ "hidden_objects": 598,
+ "hidden_area_m2": 10153.0,
+ "far_split": 0,
+ "far_decimated_triangles": 0,
+ "density": [
+ 29.48,
+ 29.48,
+ 29.48,
+ 29.48
+ ],
+ "samples": 512,
+ "blender": "5.0.1",
+ "realise_s": 2.78,
+ "visibility_s": 12.95,
+ "unwrap_s": 50.62,
+ "join_s": 3.47,
+ "bake_s": 675.16,
+ "probes_s": 65.25,
+ "geometry_s": 6.69,
+ "blender_s": 821.5,
+ "package_s": 178.31
+ }
}
}
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_0.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_0.webp
new file mode 100644
index 0000000000..cd98de44b4
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_0.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_1.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_1.webp
new file mode 100644
index 0000000000..08af540c63
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_1.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_2.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_2.webp
new file mode 100644
index 0000000000..43e194fde6
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_2.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_3.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_3.webp
new file mode 100644
index 0000000000..9fd2a18bc1
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/lm_3.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_corridor.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_corridor.webp
new file mode 100644
index 0000000000..414b5b27d8
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_corridor.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_lobby.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_lobby.webp
new file mode 100644
index 0000000000..65bc7295f4
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_lobby.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_medbay.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_medbay.webp
new file mode 100644
index 0000000000..d6b72a2b57
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_medbay.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_mess.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_mess.webp
new file mode 100644
index 0000000000..611873ab1c
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_mess.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_quartermaster.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_quartermaster.webp
new file mode 100644
index 0000000000..e76bbcdb62
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_quartermaster.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_quarters.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_quarters.webp
new file mode 100644
index 0000000000..c2b7468eca
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_quarters.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_records.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_records.webp
new file mode 100644
index 0000000000..778e8b4a32
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_records.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_simulator.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_simulator.webp
new file mode 100644
index 0000000000..2abba257a4
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_simulator.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_storage.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_storage.webp
new file mode 100644
index 0000000000..4d5c034d96
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_storage.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_team_a.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_team_a.webp
new file mode 100644
index 0000000000..c1ed04a5cd
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_team_a.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_team_b.webp b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_team_b.webp
new file mode 100644
index 0000000000..aaecc34d2b
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/probe_team_b.webp differ
diff --git a/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/scene.glb b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/scene.glb
new file mode 100644
index 0000000000..15cfe264da
Binary files /dev/null and b/dodaios/ui/web/frontend/public/verse/decks/ops/realtime/scene.glb differ
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx b/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
index 3d7a0601d8..ed8804fe0f 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
@@ -3,13 +3,18 @@
*
* Each deck is a photograph rendered offline (the plate); the stage puts the
* live crew, their screens and the ship's small lights into it with a camera
- * that matches the photograph exactly (BRIEF §3). The person is the
- * commanding officer, steered in third person (the keys walk them, the camera
+ * that matches the photograph exactly (BRIEF §3). Decks exported as eye-level
+ * scenes (docs/verse/realtime.md) are walked on the full-size stage in third
+ * person (over the commander's shoulder) or first person (through their
+ * eyes), both with shooter mouse look; the plate stays the bird's-eye view
+ * and the IDE panel's view. V cycles the three views, 1/2/3 pick one, and
+ * the wheel hands third person over to first. The person is the commanding
+ * officer, steered in third or first person (the keys walk them, the camera
* follows) or sent by clicks from a bird's-eye view; the agents are officers
* at the bridge consoles; coding panes are technicians at engineering's
* terminals; stations turn places of the ship into the app's actions.
*/
-import { Component, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { Component, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { Canvas } from "@react-three/fiber";
import { useReducedMotion } from "framer-motion";
import { CanvasActivity, useCanvasAwake } from "@/hooks/useCanvasAwake";
@@ -32,6 +37,13 @@ import { DeckBackdrop } from "./engine/DeckBackdrop";
import { DeckEnvironment } from "./engine/DeckEnvironment";
import { DebugOverlay } from "./engine/DebugOverlay";
import { attachPointerInput } from "./engine/pointerInput";
+import { RealtimeBackdrop } from "./engine/realtime/RealtimeBackdrop";
+import { attachOrbitInput } from "./engine/realtime/orbitInput";
+import { hasMouseLook, releaseMouseLook, requestMouseLook } from "./engine/realtime/mouseLook";
+import { controlModeOf, cycleView, isShooterView, resolveView, viewForKey, type Person, type VerseView } from "./engine/realtime/viewMode";
+import { eyePick } from "./engine/realtime/eyePick";
+import { useViewSettings } from "./engine/realtime/viewSettings";
+import { eyeCapable as canWalkAtEyeLevel } from "./engine/stageView";
import { pickBody, pickStation } from "./engine/picking";
import { worldToPlate } from "./engine/plateMath";
import { screenToPlate } from "./engine/view";
@@ -41,7 +53,7 @@ import { useCharacterLibrary } from "./actors/useCharacterLibrary";
import type { Look } from "./actors/look";
import { buildCast, COMMANDER_ID, type CommanderState } from "./life/cast";
import { commanderTarget, type CommanderOrders } from "./life/commander";
-import { stationWithin, type ControlMode } from "./life/control";
+import { stationWithin } from "./life/control";
import { useCrewLife } from "./life/useCrewLife";
import { useWorldActions } from "./life/useWorldActions";
import { useDevDuty } from "./life/devOverrides";
@@ -58,7 +70,14 @@ import { LiftPanel } from "./hud/LiftPanel";
import { DeckTitle, StatsReadout, Toolbar } from "./hud/DeckBar";
import { LauncherPanel } from "./hud/LauncherPanel";
import { SimulatorPanel } from "./hud/SimulatorPanel";
+import { ViewSettingsPanel } from "./hud/ViewSettingsPanel";
import { StageRuntime } from "./runtime";
+import { REACTOR_ARENA } from "./combat/arenaReactor";
+import { DuelController, type DuelDifficulty } from "./duel/duelController";
+import { attachDuelInput } from "./duel/duelInput";
+import { DuelLayer } from "./duel/DuelLayer";
+import { DuelHud } from "./hud/DuelHud";
+import { DuelPanel } from "./hud/DuelPanel";
import "./verse.css";
export interface VerseStageProps {
@@ -86,11 +105,28 @@ const PAN_KEYS: Record<string, PanKey> = {
/** How long the off-duty crew stays in the mess when called. */
const MESS_CALL_MS = 90_000;
const NOTICE_MS = 4200;
+/** The help text is long: it stays up long enough to read. */
+const HELP_MS = 15_000;
const DOORS_MS = 460;
const DOORS_GIVE_UP_MS = 5000;
type Hover = { kind: "crew"; id: string } | { kind: "station"; id: string } | null;
-type Panel = "lift" | "launcher" | "games" | null;
+type Panel = "lift" | "launcher" | "games" | "settings" | "duel" | null;
+
+/** The deck the duel arena overlays (Reactor Engineering). */
+const ARENA_DECK = REACTOR_ARENA.deck as DeckId;
+
+/**
+ * Testing switch: `localStorage["verse.duel.anyDeck"] = "1"` starts a duel on whatever deck is loaded (the arena's
+ * coordinates are engineering's), for checking the duel on a deck whose eye-level export is not there yet.
+ */
+function duelAnyDeck(): boolean {
+ try {
+ return window.localStorage.getItem("verse.duel.anyDeck") === "1";
+ } catch {
+ return false;
+ }
+}
function typesText(target: EventTarget | null): boolean {
const el = target as HTMLElement | null;
@@ -111,13 +147,23 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const webgl = useWebglSupported();
const runtime = useMemo(() => new StageRuntime(), []);
runtime.view.reduced = reduced;
+ // The duel (docs/verse/combat.md): one controller per stage; its phase drives the HUD and the input.
+ const duel = useMemo(() => new DuelController(), []);
+ useEffect(() => () => duel.dispose(), [duel]);
+ const duelPhase = useSyncExternalStore(duel.subscribe, duel.getPhase);
+ /** Stage actions the duel input calls back into (filled once the stage's callbacks exist). */
+ const duelActions = useRef({ lockAim: () => undefined as void });
+ const dueling = duelPhase !== "off";
+ runtime.duelActive = dueling;
const [deckId, setDeckId] = useState<DeckId>(initialDeck ?? "bridge");
const deckState = useDeck(deckId);
const deck = deckState.deck;
/** The deck whose plate is on screen. */
const [shownDeck, setShownDeck] = useState<Deck | null>(null);
- const plateReady = !!deck && shownDeck === deck;
+ /** The deck whose eye-level scene is loaded, and the decks whose eye-level scene failed here (they fall back to the plate). */
+ const [eyeDeck, setEyeDeck] = useState<Deck | null>(null);
+ const [eyeFailed, setEyeFailed] = useState<ReadonlySet<string>>(() => new Set());
const [failure, setFailure] = useState<Error | null>(null);
const [debug, setDebug] = useState(false);
const [hover, setHover] = useState<Hover>(null);
@@ -146,6 +192,8 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const lifeRef = useRef(life);
lifeRef.current = life;
useEffect(() => {
+ // The frame numbers are read by QA runs against built bundles too; the handle with the stage itself stays development-only.
+ Object.assign(window, { __verseStats: runtime.stats });
if (!import.meta.env.DEV) return;
const handle = {
runtime,
@@ -154,7 +202,7 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
setDuty: useDevDuty.getState().setDuty,
get life() { return lifeRef.current; },
};
- Object.assign(window, { __verse: handle, __verseStats: runtime.stats });
+ Object.assign(window, { __verse: handle });
}, [runtime]);
// The IDE tab always opens on its deck; another host keeps where the person last was.
@@ -174,18 +222,48 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
runtime.control.reframe = true;
}, [deck, runtime]);
- // Third person (the keys walk the commander, the camera follows) or bird's-eye (the keys pan over the whole deck).
- const [mode, setMode] = useState<ControlMode>(runtime.control.mode);
- const switchMode = useCallback((next: ControlMode) => {
+ // The view (viewMode.ts): bird's-eye (the keys pan over the whole deck), third or first person (the keys walk the
+ // commander, the camera follows). The person's last choice is kept in this browser.
+ const chosenView = useViewSettings((s) => s.view);
+ // The full-size stage walks an exported deck at eye level; the plate stays the bird's-eye view and the compact view.
+ const eyeCapable = !!deck && canWalkAtEyeLevel({ compact, realtime: !!deck.realtime, failed: eyeFailed.has(deck.id) });
+ const view = resolveView(chosenView, eyeCapable);
+ const mode = controlModeOf(view);
+ const eyeOn = eyeCapable && mode === "follow";
+ /** Shooter mouse look (pointer lock, a centre crosshair): third and first person at eye level. */
+ const shooter = isShooterView(view, eyeCapable);
+ const plateReady = !!deck && (eyeOn ? eyeDeck === deck : shownDeck === deck);
+ const viewRef = useRef(view);
+ viewRef.current = view;
+ // The view on screen steers the commander (or the map) and picks the eye-level camera's person.
+ useEffect(() => {
const control = runtime.control;
- if (control.mode === next) return;
- control.mode = next;
- control.clearKeys();
- runtime.view.clearKeys();
- if (next === "overview") runtime.view.overview();
- else control.reframe = true;
- setMode(next);
- }, [runtime]);
+ const next = controlModeOf(view);
+ if (control.mode !== next) {
+ control.mode = next;
+ control.clearKeys();
+ runtime.view.clearKeys();
+ if (next === "overview") runtime.view.overview();
+ else control.reframe = true;
+ }
+ if (view !== "overview") runtime.shoulder.setPerson(view);
+ }, [view, runtime]);
+ const chooseView = useCallback((next: VerseView) => useViewSettings.getState().set({ view: next }), []);
+
+ // The person's mouse settings turn the eye-level camera; the quality goes to its renderer.
+ const sensitivity = useViewSettings((s) => s.sensitivity);
+ const invertY = useViewSettings((s) => s.invertY);
+ const quality = useViewSettings((s) => s.quality);
+ const fovThird = useViewSettings((s) => s.fovThird);
+ const fovFirst = useViewSettings((s) => s.fovFirst);
+ useEffect(() => {
+ runtime.shoulder.sensitivity = sensitivity;
+ runtime.shoulder.invertY = invertY;
+ runtime.shoulder.fovThird = fovThird;
+ runtime.shoulder.fovFirst = fovFirst;
+ duel.camera.sensitivity = sensitivity;
+ duel.camera.invertY = invertY;
+ }, [runtime, duel, sensitivity, invertY, fovThird, fovFirst]);
// The doors open once the car has arrived and the new deck is on screen (or after a moment, whatever happens).
useEffect(() => {
@@ -198,9 +276,9 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
useEffect(() => () => { for (const timer of timers.current) clearTimeout(timer); }, []);
const later = useCallback((fn: () => void, ms: number) => { timers.current.push(setTimeout(fn, ms)); }, []);
- const say = useCallback((text: string) => {
+ const say = useCallback((text: string, ms: number = NOTICE_MS) => {
setNotice(text);
- later(() => setNotice((n) => (n === text ? null : n)), NOTICE_MS);
+ later(() => setNotice((n) => (n === text ? null : n)), ms);
}, [later]);
const quickCreate = useQuickCreateAgent();
@@ -276,19 +354,48 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
}
}, [walkTo, onOpenLedger, onOpenGroup, teamAtTable, say, t, messUntil, life.crew, later, createAgent]);
- const toggleView = useCallback(() => {
- const next: ControlMode = runtime.control.mode === "follow" ? "overview" : "follow";
- switchMode(next);
- say(t(next === "overview" ? "verse.notice.view_overview" : "verse.notice.view_follow"));
- }, [runtime, switchMode, say, t]);
-
- // The use key works the station the commander stands at.
- const workNearStation = useCallback(() => {
+ // Choosing a view (the switch, V, 1/2/3) is a click or a key press: third and first person take the mouse for
+ // shooter look at once, the bird's-eye view gives it back.
+ const showView = useCallback((wanted: VerseView) => {
+ const next = resolveView(wanted, eyeCapable);
+ if (next !== viewRef.current) {
+ chooseView(next);
+ say(t(next === "overview" ? "verse.notice.view_overview" : !eyeCapable ? "verse.notice.view_follow" : next === "first" ? "verse.notice.view_first" : "verse.notice.view_follow_eye"));
+ }
+ const el = surfaceRef.current;
+ if (!el || runtime.duelActive) return;
+ if (isShooterView(next, eyeCapable)) requestMouseLook(el);
+ else releaseMouseLook(el);
+ }, [eyeCapable, chooseView, say, t, runtime]);
+ const cycle = useCallback(() => showView(cycleView(viewRef.current, eyeCapable)), [showView, eyeCapable]);
+ // The wheel pushed third person into first (or pulled first back out): the switch follows, the mouse stays as it is.
+ const zoomEye = useCallback((factor: number) => {
+ const changed: Person | null = runtime.shoulder.zoom(factor);
+ if (changed) chooseView(changed);
+ }, [runtime, chooseView]);
+
+ // The station within the commander's reach, the one in front preferred: where the eye-level camera looks, else where
+ // the commander faces.
+ // The duel terminals: the four consoles on the reactor's control ring (engineering only, or anywhere for testing).
+ const duelTerminals = useMemo<Station[]>(() => {
+ if (!deck || (deck.id !== ARENA_DECK && !duelAnyDeck())) return [];
+ const floor = deck.rooms.find((r) => r.id === REACTOR_ARENA.room)?.floorY ?? 0;
+ return REACTOR_ARENA.terminals.map((tm) => ({ id: `duel:${tm.id}`, kind: "games" as const, room: REACTOR_ARENA.room, x: tm.x, y: floor, z: tm.z, sockets: {} }));
+ }, [deck]);
+ const stationAtHand = useCallback((): Station | null => {
const d = runtime.deck;
const pose = runtime.poses.get(COMMANDER_ID);
- const station = d && pose ? stationWithin(d.stations, pose.x, pose.z) : null;
+ if (!d || !pose) return null;
+ const facing = runtime.eye ? runtime.shoulder.forward() : { x: Math.sin(pose.yaw), z: Math.cos(pose.yaw) };
+ return stationWithin(duelTerminals.length ? [...d.stations, ...duelTerminals] : d.stations, pose.x, pose.z, undefined, facing);
+ }, [runtime, duelTerminals]);
+
+ // The use key works the station at hand.
+ const workNearStation = useCallback(() => {
+ const station = stationAtHand();
+ if (station?.id.startsWith("duel:")) { setPanel("duel"); return; }
if (station) activateStation(station);
- }, [runtime, activateStation]);
+ }, [stationAtHand, activateStation]);
// Third person: which station is within the commander's reach (checked a few times a second), offered with its key.
const [nearStation, setNearStation] = useState<string | null>(null);
@@ -299,32 +406,62 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const now = performance.now();
if (now - last < 200) return;
last = now;
- const d = runtime.deck;
- const pose = runtime.poses.get(COMMANDER_ID);
- const id = d && pose && runtime.control.mode === "follow" ? stationWithin(d.stations, pose.x, pose.z)?.id ?? null : null;
+ const id = runtime.control.mode === "follow" && !runtime.duelActive ? stationAtHand()?.id ?? null : null;
setNearStation((prev) => (prev === id ? prev : id));
};
runtime.afterFrame.add(check);
return () => { runtime.afterFrame.delete(check); };
- }, [awake, runtime]);
+ }, [awake, runtime, stationAtHand]);
// Pointer: hover labels, taps on crew, stations and the floor.
+ const eyeHit = useCallback((sx: number, sy: number) => {
+ const d = runtime.deck;
+ const ray = runtime.ray(sx, sy);
+ if (!d || !ray || !runtime.eye) return null;
+ return eyePick(ray.ray, d.stations, runtime.poses.values(), (id) => life.crew.has(id), runtime.eye.collider);
+ }, [runtime, life.crew]);
const hit = useCallback((sx: number, sy: number): Hover => {
const d = runtime.deck;
if (!d) return null;
+ if (runtime.eye) {
+ const h = eyeHit(sx, sy);
+ return h && h.kind !== "floor" ? h : null;
+ }
const p = screenToPlate(runtime.view.current, runtime.view.vp, sx, sy);
const body = pickBody(d.camera, runtime.poses.values(), p, (id) => life.crew.has(id));
if (body) return { kind: "crew", id: body };
const station = pickStation(d, p);
return station ? { kind: "station", id: station.id } : null;
- }, [runtime, life.crew]);
+ }, [runtime, life.crew, eyeHit]);
- const handlers = useRef({ hover: (_x: number, _y: number) => undefined as void, tap: (_x: number, _y: number) => undefined as void });
+ const handlers = useRef({
+ hover: (_x: number, _y: number) => undefined as void,
+ tap: (_x: number, _y: number) => undefined as void,
+ aim: (_x: number, _y: number) => false as boolean,
+ });
handlers.current.hover = (sx, sy) => {
const h = hit(sx, sy);
setHover((prev) => (sameHover(prev, h) ? prev : h));
if (surfaceRef.current) surfaceRef.current.dataset.cursor = h ? "pointer" : "";
};
+ // Shooter look: the left button (or E) works what the centre crosshair is on, a crew member or a station; never the
+ // floor (that would send the commander off with every press of the button). Returns whether something was there.
+ handlers.current.aim = (sx, sy) => {
+ const d = runtime.deck;
+ if (!d) return false;
+ const h = hit(sx, sy);
+ if (h?.kind === "crew") {
+ if (selected === h.id) openCrew(h.id);
+ else setSelected(h.id);
+ return true;
+ }
+ if (h?.kind === "station") {
+ const station = d.stations.find((s) => s.id === h.id);
+ if (station) activateStation(station);
+ return !!station;
+ }
+ return false;
+ };
handlers.current.tap = (sx, sy) => {
const d = runtime.deck;
if (!d) return;
@@ -341,6 +478,12 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
return;
}
setSelected(null);
+ if (runtime.eye) {
+ const at = eyeHit(sx, sy);
+ const floor = at?.kind === "floor" ? nearestWalkable(d.nav, { x: at.x, z: at.z }, 1.2) : null;
+ if (floor) walkTo(floor.x, floor.z);
+ return;
+ }
const p = screenToPlate(runtime.view.current, runtime.view.vp, sx, sy);
const floor = pickFloor(d.camera, d.nav, p.u, p.v);
if (floor) walkTo(floor.x, floor.z);
@@ -349,6 +492,33 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
useEffect(() => {
const el = surfaceRef.current;
if (!el) return;
+ // A duel: the mouse aims and fires, the keys fight (duel/duelInput.ts).
+ if (dueling) {
+ return attachDuelInput(el, duel.input, {
+ look: (dx, dy) => duel.camera.look(dx, dy),
+ escape: () => {
+ if (document.pointerLockElement === el) document.exitPointerLock?.();
+ duel.escape();
+ },
+ relock: () => duelActions.current.lockAim(),
+ live: () => duel.live,
+ });
+ }
+ // Third and first person: shooter mouse look (a click takes the mouse), the wheel zooms and hands over between them.
+ if (eyeOn) {
+ return attachOrbitInput(el, runtime.shoulder, {
+ tap: (x, y) => handlers.current.tap(x, y),
+ hover: (x, y) => handlers.current.hover(x, y),
+ leave: () => setHover(null),
+ moved: () => setHover(null),
+ aim: (x, y) => { handlers.current.aim(x, y); },
+ capture: () => {
+ hostRef.current?.focus({ preventScroll: true });
+ requestMouseLook(el);
+ },
+ zoom: (factor) => keyActions.current.zoomEye(factor),
+ });
+ }
return attachPointerInput(el, runtime.view, {
tap: (x, y) => handlers.current.tap(x, y),
hover: (x, y) => handlers.current.hover(x, y),
@@ -362,7 +532,7 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
return pose ? runtime.toScreen(pose.x, pose.y + pose.height * 0.5, pose.z) : null;
},
});
- }, [runtime, webgl, generation]);
+ }, [runtime, webgl, generation, eyeOn, dueling, duel]);
// Opening the full-size stage hands it the keyboard, so the movement keys work at once (unless someone is typing;
// the IDE's side panel never takes focus from the terminal beside it).
@@ -375,8 +545,47 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
// Keyboard: WASD/arrows walk the commander (third person) or pan (bird's-eye), Shift hurries, V switches the view,
// E works the station at hand, +/- zoom, Escape closes, F9 the alignment overlay (development).
- const keyActions = useRef({ toggleView, workNearStation });
- keyActions.current = { toggleView, workNearStation };
+ const lockPointer = useCallback(() => {
+ const el = surfaceRef.current;
+ if (!el || !runtime.eye) return;
+ if (hasMouseLook(el)) { releaseMouseLook(el); return; }
+ requestMouseLook(el);
+ say(t("verse.notice.mouse_look"));
+ }, [runtime, say, t]);
+ // E: what the crosshair is on (at eye level), else the station within reach.
+ const interact = useCallback(() => {
+ const el = surfaceRef.current;
+ if (runtime.eye && el && handlers.current.aim(el.clientWidth / 2, el.clientHeight / 2)) return;
+ workNearStation();
+ }, [runtime, workNearStation]);
+ // The bird's-eye view (or a deck without an eye-level scene) gives the mouse back; so does leaving the stage.
+ useEffect(() => { if (!eyeOn && !dueling) releaseMouseLook(surfaceRef.current); }, [eyeOn, dueling]);
+ useEffect(() => {
+ const surface = surfaceRef.current;
+ return () => releaseMouseLook(surface);
+ }, []);
+ // Mouse look is on while the surface holds the pointer lock: a reticle marks what a click works.
+ const [locked, setLocked] = useState(false);
+ useEffect(() => {
+ const changed = () => {
+ const now = !!surfaceRef.current && document.pointerLockElement === surfaceRef.current;
+ setLocked(now);
+ // The browser released the mouse (Escape): the duel pauses rather than playing on without aim.
+ if (now) duel.hadLock = true;
+ else if (duel.phase === "running" && duel.hadLock) duel.pause();
+ };
+ document.addEventListener("pointerlockchange", changed);
+ return () => document.removeEventListener("pointerlockchange", changed);
+ }, [duel]);
+ // A dialog needs the pointer: opening one ends mouse look.
+ useEffect(() => {
+ if (panel && surfaceRef.current && document.pointerLockElement === surfaceRef.current) document.exitPointerLock();
+ }, [panel]);
+ const keyActions = useRef({ cycle, showView, interact, lockPointer, zoomEye });
+ keyActions.current = { cycle, showView, interact, lockPointer, zoomEye };
+ /** What Escape closes first: a selected crew member or an open panel. */
+ const closable = useRef(false);
+ closable.current = selected !== null || panel !== null;
useEffect(() => {
if (!awake) return;
const owns = (e: KeyboardEvent) => {
@@ -384,7 +593,20 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const focused = document.activeElement;
return !focused || focused === document.body || !!hostRef.current?.contains(focused);
};
+ // Escape ends mouse look, or closes the crew card or a panel, and nothing else: claimed before the Agents view sees
+ // it (it would leave the ship). With nothing open it goes through and leaves as before.
+ const escape = (e: KeyboardEvent) => {
+ if (e.code !== "Escape" || runtime.duelActive) return;
+ const surface = surfaceRef.current;
+ const looking = !!surface && document.pointerLockElement === surface;
+ if (!(looking || closable.current) || !owns(e)) return;
+ e.preventDefault();
+ if (looking) { document.exitPointerLock?.(); return; }
+ setPanel(null);
+ setSelected(null);
+ };
const down = (e: KeyboardEvent) => {
+ if (runtime.duelActive) return;
if (e.key === "Shift") runtime.control.run = true;
if (!owns(e)) return;
const key = PAN_KEYS[e.code];
@@ -395,11 +617,13 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
else v.setKey(key, true, e.shiftKey);
return;
}
- if (e.code === "Equal" || e.code === "NumpadAdd") v.zoomAt(v.vp.width / 2, v.vp.height / 2, 1.25);
- else if (e.code === "Minus" || e.code === "NumpadSubtract") v.zoomAt(v.vp.width / 2, v.vp.height / 2, 0.8);
- else if (e.code === "KeyV" && !e.repeat) keyActions.current.toggleView();
- else if (e.code === "KeyE" && !e.repeat) keyActions.current.workNearStation();
- else if (e.code === "Escape") { setPanel(null); setSelected(null); }
+ const direct = e.repeat ? null : viewForKey(e.code);
+ if (direct) { e.preventDefault(); keyActions.current.showView(direct); return; }
+ if (e.code === "Equal" || e.code === "NumpadAdd") { if (runtime.eye) keyActions.current.zoomEye(0.85); else v.zoomAt(v.vp.width / 2, v.vp.height / 2, 1.25); }
+ else if (e.code === "Minus" || e.code === "NumpadSubtract") { if (runtime.eye) keyActions.current.zoomEye(1.18); else v.zoomAt(v.vp.width / 2, v.vp.height / 2, 0.8); }
+ else if (e.code === "KeyV" && !e.repeat) keyActions.current.cycle();
+ else if (e.code === "KeyE" && !e.repeat) keyActions.current.interact();
+ else if (e.code === "KeyL" && !e.repeat) keyActions.current.lockPointer();
else if (e.code === "F9" && import.meta.env.DEV) setDebug((d) => !d);
};
const up = (e: KeyboardEvent) => {
@@ -410,10 +634,12 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
runtime.control.setKey(key, false, e.shiftKey);
};
const blur = () => { runtime.view.clearKeys(); runtime.control.clearKeys(); };
+ window.addEventListener("keydown", escape, true);
window.addEventListener("keydown", down);
window.addEventListener("keyup", up);
window.addEventListener("blur", blur);
return () => {
+ window.removeEventListener("keydown", escape, true);
window.removeEventListener("keydown", down);
window.removeEventListener("keyup", up);
window.removeEventListener("blur", blur);
@@ -421,10 +647,114 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
};
}, [awake, runtime]);
+ // The duel: start it (riding down to engineering first when the commander is elsewhere), lock the mouse for aiming,
+ // pause when the stage goes out of sight, and give the commander back to the deck where the duel ended.
+ const [duelChoice, setDuelChoice] = useState<DuelDifficulty>("hard");
+ const [pendingDuel, setPendingDuel] = useState<DuelDifficulty | null>(null);
+ // The duel aims with the same mouse look as third and first person.
+ duelActions.current.lockAim = () => {
+ const el = surfaceRef.current;
+ if (el) requestMouseLook(el);
+ };
+ const beginDuel = useCallback((difficulty: DuelDifficulty) => {
+ const d = runtime.deck;
+ if (!d) return;
+ // The duel is fought over the shoulder (its own camera); from the bird's-eye view the stage goes to third person.
+ if (viewRef.current === "overview") chooseView("third");
+ runtime.control.mode = "follow";
+ runtime.control.clearKeys();
+ duel.floorY = d.rooms.find((r) => r.id === REACTOR_ARENA.room)?.floorY ?? 0;
+ runtime.duelArea = REACTOR_ARENA.bounds;
+ setSelected(null);
+ setHover(null);
+ duel.start(difficulty);
+ }, [runtime, duel, chooseView]);
+ const startDuel = useCallback((difficulty: DuelDifficulty) => {
+ setPanel(null);
+ setDuelChoice(difficulty);
+ if (deckId !== ARENA_DECK && !duelAnyDeck()) {
+ // Down to Reactor Engineering first; the match starts once its eye-level scene is on screen.
+ setPendingDuel(difficulty);
+ rideTo(ARENA_DECK);
+ return;
+ }
+ if (!eyeCapable) { say(t("verse.duel.notice.needs_eye")); return; }
+ beginDuel(difficulty);
+ duelActions.current.lockAim();
+ }, [deckId, eyeCapable, rideTo, beginDuel, say, t]);
+ useEffect(() => {
+ if (!pendingDuel || doors || !deck || deck.id !== ARENA_DECK) return;
+ if (!eyeCapable) { setPendingDuel(null); say(t("verse.duel.notice.needs_eye")); return; }
+ if (eyeDeck !== deck) return;
+ setPendingDuel(null);
+ beginDuel(pendingDuel);
+ }, [pendingDuel, doors, deck, eyeCapable, eyeDeck, beginDuel, say, t]);
+ useEffect(() => {
+ duel.onExit = (at) => {
+ if (surfaceRef.current && document.pointerLockElement === surfaceRef.current) document.exitPointerLock?.();
+ if (at) runtime.placeCommander = { x: at.x, z: at.z, yaw: at.yaw };
+ runtime.duelArea = null;
+ runtime.control.clearKeys();
+ runtime.control.reframe = true;
+ };
+ return () => { duel.onExit = null; };
+ }, [duel, runtime]);
+ // The pause and result screens need the pointer; a hidden stage pauses the match.
+ useEffect(() => {
+ if (duelPhase !== "paused" && duelPhase !== "result") return;
+ if (surfaceRef.current && document.pointerLockElement === surfaceRef.current) document.exitPointerLock?.();
+ }, [duelPhase]);
+ useEffect(() => { if (!awake && duel.phase === "running") duel.pause(); }, [awake, duel]);
+ const leaveDuel = useCallback(() => {
+ const midMatch = duel.phase === "running" || duel.phase === "paused";
+ duel.leave();
+ if (midMatch) say(t("verse.duel.notice.left"));
+ }, [duel, say, t]);
+ // QA hook (built bundles too, like __verseStats): start a duel on the deck on screen and drive it without a mouse.
+ const beginRef = useRef(beginDuel);
+ beginRef.current = beginDuel;
+ useEffect(() => {
+ const hook = {
+ start: (difficulty: DuelDifficulty = "hard") => beginRef.current(difficulty),
+ leave: () => duel.leave(),
+ /** Put the commander somewhere on the deck (a ring console, to check the start prompt). */
+ place: (x: number, z: number, yaw = 0) => { runtime.placeCommander = { x, z, yaw }; runtime.control.reframe = true; },
+ look: (dx: number, dy: number) => duel.camera.look(dx, dy),
+ hold: (c: Parameters<DuelController["hold"]>[0]) => duel.hold(c),
+ press: (name: "dodge" | "vent") => duel.press(name),
+ state: () => ({ phase: duel.phase, hud: duel.hud(), view: duel.view, result: duel.result, aim: duel.aimTarget, pose: duel.pose }),
+ };
+ Object.assign(window, { __verseDuel: hook });
+ return () => { if ((window as unknown as { __verseDuel?: unknown }).__verseDuel === hook) delete (window as unknown as { __verseDuel?: unknown }).__verseDuel; };
+ }, [duel, runtime]);
+
+ // QA hook (built bundles too): switch views, look and zoom without a mouse (headless browsers cannot lock the pointer).
+ const viewActions = useRef({ showView, zoomEye });
+ viewActions.current = { showView, zoomEye };
+ useEffect(() => {
+ const hook = {
+ set: (v: VerseView) => viewActions.current.showView(v),
+ look: (dx: number, dy: number) => runtime.shoulder.look(dx, dy, true),
+ zoom: (factor: number) => viewActions.current.zoomEye(factor),
+ state: () => ({
+ view: viewRef.current, person: runtime.shoulder.person, distance: runtime.shoulder.distance, actual: runtime.shoulder.actual,
+ firstShare: runtime.shoulder.firstShare, hfov: runtime.shoulder.hfov(), yaw: runtime.shoulder.yaw, pitch: runtime.shoulder.pitch,
+ commanderHidden: runtime.commanderHidden, locked: hasMouseLook(surfaceRef.current),
+ }),
+ };
+ Object.assign(window, { __verseView: hook });
+ return () => { if ((window as unknown as { __verseView?: unknown }).__verseView === hook) delete (window as unknown as { __verseView?: unknown }).__verseView; };
+ }, [runtime]);
+
const focusOn = useCallback((id: string) => {
const pose = runtime.poses.get(id);
const d = runtime.deck;
if (!pose || !d) return;
+ const me = runtime.poses.get(COMMANDER_ID);
+ if (runtime.eye && me) {
+ runtime.shoulder.faceToward(me.x, me.z, pose.x, pose.z);
+ return;
+ }
const p = worldToPlate(d.camera, pose.x, pose.y, pose.z);
runtime.view.focus(p.u, p.v);
}, [runtime]);
@@ -476,9 +806,11 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
if (!deck) return null;
const pointed = hover?.kind === "station";
const id = pointed ? hover.id : nearStation;
+ const terminal = id ? duelTerminals.find((s) => s.id === id) : undefined;
+ if (terminal) return { station: terminal, name: t("verse.duel.terminal"), action: t("verse.duel.start"), key: "E" };
const station = id ? deck.stations.find((s) => s.id === id) : undefined;
return station ? { station, name: t(`verse.station.${station.kind}.name`), action: t(`verse.station.${station.kind}.action`), key: pointed ? null : "E" } : null;
- }, [hover, nearStation, deck, t]);
+ }, [hover, nearStation, deck, t, duelTerminals]);
const card = useMemo<CrewCardInfo | null>(() => {
const m = selected ? life.crew.get(selected) : undefined;
if (!m) return null;
@@ -500,6 +832,13 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
const onPlateReady = useCallback((shown: Deck) => setShownDeck(shown), []);
const onFailure = useCallback((error: Error) => { console.error("Verse deck failed", error); setFailure(error); }, []);
+ const onEyeReady = useCallback((shown: Deck) => setEyeDeck(shown), []);
+ // A deck whose eye-level scene cannot load is still walked on its plate.
+ const onEyeFailure = useCallback((error: Error) => {
+ console.error("Verse eye-level view failed; showing the plate", error);
+ const failed = runtime.deck?.id;
+ if (failed) setEyeFailed((prev) => (prev.has(failed) ? prev : new Set(prev).add(failed)));
+ }, [runtime]);
const problem = failure ?? deckState.error;
const fallback = <div className="verse-fallback" role="status">{chunkReady ? t("verse.stage.unavailable") : null}</div>;
@@ -518,13 +857,19 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
gl={{ antialias: true, alpha: false, stencil: false, powerPreference: "high-performance" }}
onCreated={({ gl }) => gl.setClearColor(0x050607, 1)}
>
+ {deck && !problem && eyeCapable && (
+ <RealtimeBackdrop runtime={runtime} deck={deck} active={eyeOn} commanderId={COMMANDER_ID} quality={quality} onReady={onEyeReady} onError={onEyeFailure} />
+ )}
+ {deck && !problem && eyeCapable && dueling && (
+ <DuelLayer runtime={runtime} controller={duel} deck={deck} library={library} commanderId={COMMANDER_ID} commanderLook={commanderLook} />
+ )}
{deck && !problem && (
- <DeckBackdrop runtime={runtime} deck={deck} debug={debug} awake={awake} onReady={onPlateReady} onError={onFailure}>
+ <DeckBackdrop runtime={runtime} deck={deck} debug={debug} awake={awake} active={!eyeOn} onReady={onPlateReady} onError={onFailure}>
<DeckEnvironment url={deck.envUrl} />
{library && <ActorsLayer runtime={runtime} deck={deck} library={library} cast={cast} commanderId={COMMANDER_ID} reduced={reduced} saluteAt={saluteAt} />}
<ScreensLayer deck={deck} faces={faces} />
<HoloLayer sockets={holos} lit={litHolos} reduced={reduced} />
- <LightsLayer deck={deck} alarm={alarm} reduced={reduced} />
+ <LightsLayer deck={deck} alarm={alarm} reduced={reduced} runtime={runtime} />
<BeaconsLayer runtime={runtime} statuses={deckStatuses} reduced={reduced} />
{import.meta.env.DEV && debug && <DebugOverlay deck={deck} />}
</DeckBackdrop>
@@ -536,22 +881,35 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
)}
{chunkReady && (
<div className="verse-hud">
- <FloatingLabels runtime={runtime} plates={plates} station={labelledStation} deck={deck} />
- <DeckTitle deck={deckId} t={t} counts={counts} rankCard={<RankCard compact={compact} />} />
- <Toolbar
+ {!dueling && <FloatingLabels runtime={runtime} plates={plates} station={labelledStation} deck={deck} />}
+ {!dueling && <DeckTitle deck={deckId} t={t} counts={counts} rankCard={<RankCard compact={compact} />} />}
+ {!dueling && <Toolbar
t={t}
- mode={mode}
- onToggleView={toggleView}
+ view={view}
+ firstAvailable={eyeCapable}
+ onView={showView}
onLift={() => setPanel("lift")}
onCommander={() => { if (runtime.control.mode === "follow") runtime.control.reframe = true; else focusOn(COMMANDER_ID); }}
- onHelp={() => say(t("verse.stage.help"))}
- />
+ onSettings={eyeCapable ? () => setPanel("settings") : undefined}
+ onDuel={compact ? undefined : () => setPanel("duel")}
+ onHelp={() => say(t(eyeOn ? "verse.stage.help_eye" : "verse.stage.help"), HELP_MS)}
+ />}
+ {shooter && !dueling && <div className="verse-reticle" data-locked={locked} data-on={hover ? "" : undefined} aria-hidden />}
+ {shooter && !dueling && !locked && !panel && plateReady && (
+ <div className="verse-look-hint" aria-hidden>{t("verse.tools.click_to_look")}</div>
+ )}
+ {dueling && (
+ <DuelHud runtime={runtime} controller={duel} phase={duelPhase} locked={locked} t={t}
+ onResume={() => { duel.resume(); duelActions.current.lockAim(); }}
+ onLeave={leaveDuel}
+ onRematch={() => { duel.rematch(); duelActions.current.lockAim(); }} />
+ )}
{(!plateReady || problem) && (
<div className="verse-status" role="status" data-tone={problem ? "error" : "quiet"}>
{problem ? t("verse.stage.deck_missing") : t("verse.stage.loading")}
</div>
)}
- {card && (
+ {card && !dueling && (
<CrewCard info={card} t={t} onOpen={() => openCrew(card.id)} onShow={() => focusOn(card.id)} onClose={() => setSelected(null)}
onWalk={() => {
const pose = runtime.poses.get(card.id);
@@ -564,6 +922,10 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
<LauncherPanel t={t} say={say} onClose={() => setPanel(null)} onOpenIde={() => { setPanel(null); useEventStore.getState().setActiveSection("agentic-ide"); }} />
)}
{panel === "games" && <SimulatorPanel t={t} onClose={() => setPanel(null)} />}
+ {panel === "duel" && !dueling && (
+ <DuelPanel t={t} ride={deckId !== ARENA_DECK && !duelAnyDeck()} last={duelChoice} onStart={startDuel} onClose={() => setPanel(null)} />
+ )}
+ {panel === "settings" && <ViewSettingsPanel t={t} tier={eyeOn ? runtime.stats.tier : ""} onClose={() => setPanel(null)} />}
<RanksOverlay active={awake} crew={officers} companionName={lead?.name} />
{import.meta.env.DEV && <StatsReadout runtime={runtime} />}
<div className="verse-doors" data-shut={doors !== null} aria-hidden><i /><i /></div>
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/actors/ActorsLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/actors/ActorsLayer.tsx
index 2475c81810..facb4e1cfd 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/actors/ActorsLayer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/actors/ActorsLayer.tsx
@@ -14,6 +14,7 @@ import type { Deck } from "../content/deck";
import type { StageRuntime } from "../runtime";
import { seatedCrew } from "../../crewFeeds/seated";
import { worldToPlate } from "../engine/plateMath";
+import { bodyFacing } from "../engine/realtime/viewMode";
import { floorHeight, nearestWalkable } from "../nav/pathfind";
import { hash32 } from "../life/crew";
import { Actor, socketPose, type ActorContext, type Goal, type Pose } from "./actor";
@@ -65,6 +66,21 @@ function liftPoint(deck: Deck): Pose | null {
return lift ? { x: lift.x, y: lift.y, z: lift.z, yaw: lift.yaw } : null;
}
+/**
+ * Which way a body placed at (x, z) faces: the spawn or lift it stands at
+ * (a spawn's own facing; out of the lift doors), else toward −Z, the deck's
+ * forward. Pure.
+ */
+export function arrivalYaw(deck: Pick<Deck, "sockets">, x: number, z: number): number {
+ let best: { yaw: number; d: number } | null = null;
+ for (const s of deck.sockets) {
+ if (s.kind !== "spawn" && s.kind !== "lift") continue;
+ const d = Math.hypot(s.x - x, s.z - z);
+ if (d <= 2.5 && (!best || d < best.d)) best = { yaw: s.yaw, d };
+ }
+ return best ? best.yaw : Math.PI;
+}
+
function spawnPoint(deck: Deck, entry: CastMember["entry"]): Pose | null {
if (entry === "spawn") {
const spawn = deck.sockets.find((s) => s.kind === "spawn" && s.id.startsWith("arrival")) ?? deck.sockets.find((s) => s.kind === "spawn");
@@ -112,7 +128,7 @@ export function ActorsLayer({ runtime, deck, library, cast, commanderId, reduced
const start = arrive ? null : spawnPoint(deck, now.entry);
if (start) actor.place(start);
else if (now.goal.kind === "socket") actor.place(socketPose(deck, now.goal.socket, now.goal.activity, actor.seatHeight));
- else if (now.goal.kind === "point") actor.place({ x: now.goal.x, y: 0, z: now.goal.z, yaw: 0 });
+ else if (now.goal.kind === "point") actor.place({ x: now.goal.x, y: 0, z: now.goal.z, yaw: arrivalYaw(deck, now.goal.x, now.goal.z) });
else if (now.goal.kind === "follow") {
// At the leader's heel: where the leader stands, or is about to.
const leaderId = now.goal.leaderId;
@@ -180,6 +196,9 @@ export function ActorsLayer({ runtime, deck, library, cast, commanderId, reduced
},
poseOf: (id) => actors.current.get(id) ?? null,
}), [deck, reduced, commanderId]);
+ // The commander's walking direction, refilled every frame (the actor reads it within the same frame).
+ const steering = useMemo(() => ({ x: 0, z: 0 }), []);
+ const facing = useMemo(() => ({ yaw: 0, reverse: false }), []);
useFrame((_, dt) => {
// A slow frame still moves people at their pace; a stall (a hidden tab) does not teleport them.
@@ -188,9 +207,23 @@ export function ActorsLayer({ runtime, deck, library, cast, commanderId, reduced
// Third person: the held movement keys walk the commander.
const control = runtime.control;
const lead = actors.current.get(commanderId);
- lead?.drive(control.mode === "follow" ? control.direction() : null, control.run);
+ const steer = control.mode !== "follow" || runtime.duelActive ? null : runtime.eye ? control.directionFrom(runtime.shoulder, steering) : control.direction(steering);
+ // At eye level the commander faces the view while walking (shooter strafing); on the plate, the way they walk.
+ lead?.drive(steer, control.run, steer && runtime.eye ? bodyFacing(runtime.shoulder.yaw, steer, facing) : null);
+ // A duel ended: the commander stands where they finished it, on the deck's walkable floor.
+ const placed = runtime.placeCommander;
+ if (lead && placed) {
+ runtime.placeCommander = null;
+ const at = nearestWalkable(deck.nav, { x: placed.x, z: placed.z }, 3) ?? placed;
+ lead.halt();
+ lead.place({ x: at.x, y: floorHeight(deck.nav, at.x, at.z), z: at.z, yaw: placed.yaw });
+ }
+ // In a duel the duellist's own body stands in for the commander's.
+ if (lead) lead.group.visible = !runtime.duelActive && !(runtime.eye && runtime.commanderHidden);
+ const area = runtime.duelActive ? runtime.duelArea : null;
for (const actor of actors.current.values()) {
actor.update(dtS, ctx);
+ if (actor !== lead) actor.group.visible = !area || actor.x < area.x0 || actor.x > area.x1 || actor.z < area.z0 || actor.z > area.z1;
if (actor.gone) {
const member = castRef.current.find((m) => m.id === actor.id);
if (member) departed.current.add(`${member.id}|${member.goalKey}`);
@@ -203,9 +236,9 @@ export function ActorsLayer({ runtime, deck, library, cast, commanderId, reduced
}
const pose = runtime.poses.get(actor.id);
if (pose) {
- pose.x = actor.x; pose.y = actor.y; pose.z = actor.z; pose.height = actor.height; pose.moving = actor.moving;
+ pose.x = actor.x; pose.y = actor.y; pose.z = actor.z; pose.yaw = actor.yaw; pose.height = actor.height; pose.moving = actor.moving;
} else {
- runtime.poses.set(actor.id, { id: actor.id, x: actor.x, y: actor.y, z: actor.z, height: actor.height, moving: actor.moving });
+ runtime.poses.set(actor.id, { id: actor.id, x: actor.x, y: actor.y, z: actor.z, yaw: actor.yaw, height: actor.height, moving: actor.moving });
}
const at = actor.settledAt;
if (at && at.kind === "seat" && screenSeats.has(at.id)) seatedCrew.add(actor.id);
@@ -216,7 +249,7 @@ export function ActorsLayer({ runtime, deck, library, cast, commanderId, reduced
// them when they stop; a drag looks around until they walk again.
const view = runtime.view;
if (lead?.moving) control.looking = false;
- if (lead && !lead.gone && control.mode === "follow" && view.measured && (!control.looking || control.reframe || view.leading)) {
+ if (lead && !lead.gone && !runtime.eye && control.mode === "follow" && view.measured && (!control.looking || control.reframe || view.leading)) {
const p = worldToPlate(deck.camera, lead.x, lead.y + lead.height * 0.5, lead.z);
if (control.reframe) {
control.reframe = false;
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/actors/actor.ts b/dodaios/ui/web/frontend/src/components/society/verse/actors/actor.ts
index cdee5e50bc..8bb155ec02 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/actors/actor.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/actors/actor.ts
@@ -135,6 +135,8 @@ export class Actor {
private lastPlan = 0;
private steer: Point | null = null;
private steerRun = false;
+ /** Shooter views: the way the body faces while driven (the view, `viewMode.bodyFacing`), and a walk played backwards. */
+ private steerFace: { yaw: number; reverse: boolean } | null = null;
private readonly clipNames: ReadonlySet<string>;
private readonly shadow: Mesh<PlaneGeometry, MeshBasicMaterial>;
@@ -182,10 +184,25 @@ export class Actor {
this.oneShotUntil = this.playOnce("salute");
}
- /** Direct control: walk toward `direction` (unit length, on the floor) from the next update on; null lets go. */
- drive(direction: Point | null, run = false): void {
+ /**
+ * Direct control: walk toward `direction` (unit length, on the floor) from
+ * the next update on; null lets go. `face` turns the body that way instead
+ * of along the walk (a shooter view: strafing, walking backwards).
+ */
+ drive(direction: Point | null, run = false, face: { yaw: number; reverse: boolean } | null = null): void {
this.steer = direction;
this.steerRun = run;
+ this.steerFace = direction ? face : null;
+ }
+
+ /** Stop whatever walk or settle is in progress and stand where the body is (until the next goal). */
+ halt(): void {
+ this.steer = null;
+ this.follower = null;
+ this.settle = null;
+ this.phase = "settled";
+ this.speed = 0;
+ this.play(this.isDrone ? "hover" : "idle");
}
/** Put the body somewhere at once (spawn, or a pose it already holds). */
@@ -318,9 +335,11 @@ export class Actor {
this.settle = null;
this.oneShotUntil = 0;
}
- const heading = Math.atan2(direction.x, direction.z);
+ const face = this.steerFace;
+ const heading = face ? face.yaw : Math.atan2(direction.x, direction.z);
this.yaw = turnToward(this.yaw, heading, DRIVE_TURN_RATE, dtS);
const pace = this.pace * (this.steerRun ? RUN_FACTOR : 1) * turnPace(this.yaw, heading);
+ const stride = face?.reverse ? -1 : 1;
const from = { x: this.x, z: this.z };
const near = ctx.neighbours(this);
// Nobody walks through a person; drones are small enough to pass.
@@ -344,7 +363,7 @@ export class Actor {
const walking = this.motion === "walk" || this.motion === "drive";
if (this.speed > DRIVE_WALK_ABOVE || (walking && this.speed > DRIVE_STAND_BELOW)) {
this.play("walk");
- if (this.action) this.action.timeScale = Math.max(0.3, this.speed / Math.max(0.1, this.instance.walkSpeed));
+ if (this.action) this.action.timeScale = stride * Math.max(0.3, this.speed / Math.max(0.1, this.instance.walkSpeed));
} else {
this.play(this.isDrone ? "hover" : "idle");
if (this.action) this.action.timeScale = 1;
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/arena.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/arena.test.ts
new file mode 100644
index 0000000000..dd964fa7f2
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/arena.test.ts
@@ -0,0 +1,170 @@
+// @vitest-environment node
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { inflateSync } from "node:zlib";
+import { describe, expect, it } from "vitest";
+import { buildArena, hasFloor, isWalkable, lineOfSight, raycastWorld, walkableSegment, COVER_HEIGHT } from "./arena";
+import { REACTOR_ARENA } from "./arenaReactor";
+import { DEFAULT_TUNING } from "./tuning";
+
+const arena = buildArena(REACTOR_ARENA, DEFAULT_TUNING.body.radius);
+const SHAFT = REACTOR_ARENA.centre;
+
+describe("reactor arena", () => {
+ it("spawns on opposite sides of the shaft, out of each other's sight", () => {
+ const [a, b] = REACTOR_ARENA.spawns;
+ expect(isWalkable(arena, a.x, a.z)).toBe(true);
+ expect(isWalkable(arena, b.x, b.z)).toBe(true);
+ expect(Math.hypot(a.x - b.x, a.z - b.z)).toBeGreaterThan(25);
+ // The core blocks the straight line at standing height.
+ expect(lineOfSight(arena, a.x, 1.6, a.z, b.x, 1.6, b.z)).toBe(false);
+ // Mirrored about the shaft axis.
+ expect(a.x + b.x).toBeCloseTo(2 * SHAFT.x, 6);
+ expect(a.z).toBe(b.z);
+ });
+
+ it("walks the catwalks and the ring but not into the drop", () => {
+ expect(walkableSegment(arena, 38.8, 22, 48.6, 22)).toBe(true); // west catwalk to the ring
+ expect(walkableSegment(arena, 54, 8.0, 54, 15.6)).toBe(true); // north catwalk
+ for (let a = 0; a < 360; a += 10) {
+ const r = 5.75;
+ expect(isWalkable(arena, SHAFT.x + Math.sin((a * Math.PI) / 180) * r, SHAFT.z + Math.cos((a * Math.PI) / 180) * r)).toBe(true);
+ }
+ expect(isWalkable(arena, 46, 17)).toBe(false); // over the shaft
+ expect(walkableSegment(arena, 40, 14, 50, 14)).toBe(false);
+ expect(isWalkable(arena, 54, 22)).toBe(false); // the core
+ });
+
+ it("has the east floor's cover and the far wall's stacks as solids", () => {
+ expect(isWalkable(arena, 78.6, 22)).toBe(false);
+ expect(isWalkable(arena, 73, 12)).toBe(false);
+ expect(isWalkable(arena, 72.6, 3.4)).toBe(false);
+ expect(isWalkable(arena, 76.5, 22)).toBe(true);
+ });
+
+ it("lets bolts fly over the drop, stops them at the core, walls and cover, and lets them out through doorways", () => {
+ // Across the shaft north of the core: nothing in the way.
+ expect(raycastWorld(arena, 41, 1.4, 14, 67, 1.4, 14)).toBeNull();
+ // Diving into the shaft: no floor there.
+ expect(raycastWorld(arena, 46, 1.4, 24.5, 46, -2, 24.5)).toBeNull();
+ // ...but there is floor on the rim.
+ expect(raycastWorld(arena, 36, 1.4, 22, 36, -1, 22)?.surface).toBe("floor");
+ const core = raycastWorld(arena, 40, 1.4, 22, 68, 1.4, 22);
+ expect(core?.surface).toBe("prop");
+ expect(core?.collider).toBe("core");
+ // Over the core's cap.
+ expect(raycastWorld(arena, 46, 2.4, 22.2, 62, 2.4, 22.2)).toBeNull();
+ const conduit = raycastWorld(arena, 70, 1.4, 22, 81, 1.4, 22);
+ expect(conduit?.collider).toBe("conduit_1");
+ expect(raycastWorld(arena, 60, 1.4, 30, 60, 1.4, 45)?.surface).toBe("wall");
+ expect(raycastWorld(arena, 54, 1.4, 36, 54, 1.4, 45)?.surface).toBe("exit");
+ // Waist-high coolant runs stop low bolts only.
+ expect(raycastWorld(arena, 70, 0.6, 12, 77, 0.6, 12)?.collider).toBe("coolant_0");
+ expect(raycastWorld(arena, 70, 1.4, 12, 77, 1.4, 12)).toBeNull();
+ });
+
+ it("finds cover spots next to tall solids, all on walkable floor", () => {
+ expect(arena.cover.length).toBeGreaterThan(40);
+ for (const c of arena.cover) {
+ expect(isWalkable(arena, c.x, c.z)).toBe(true);
+ const solid = REACTOR_ARENA.colliders.find((k) => k.id === c.collider);
+ expect(solid && solid.y1).toBeGreaterThanOrEqual(COVER_HEIGHT);
+ }
+ // Some cover sits on the ring, behind the core.
+ expect(arena.cover.some((c) => c.collider === "core")).toBe(true);
+ });
+
+ it("has floor exactly where the deck has it", () => {
+ expect(hasFloor(REACTOR_ARENA, 54, 12)).toBe(true); // north catwalk
+ expect(hasFloor(REACTOR_ARENA, 50, 12)).toBe(false); // drop
+ expect(hasFloor(REACTOR_ARENA, 30, 22)).toBe(false); // outside the hall
+ });
+});
+
+// ---------------------------------------------------------------- against the cooked deck
+
+const deckDir = resolve(process.cwd(), "public/verse/decks/engineering");
+
+function decodeGreyPng(buf: Buffer): { w: number; h: number; px: Uint8Array } {
+ let p = 8;
+ let w = 0;
+ let h = 0;
+ const idat: Buffer[] = [];
+ while (p < buf.length) {
+ const len = buf.readUInt32BE(p);
+ const type = buf.toString("ascii", p + 4, p + 8);
+ const data = buf.subarray(p + 8, p + 8 + len);
+ if (type === "IHDR") { w = data.readUInt32BE(0); h = data.readUInt32BE(4); if (data[8] !== 8 || data[9] !== 0) throw new Error("not 8-bit grey"); }
+ if (type === "IDAT") idat.push(data);
+ p += 12 + len;
+ }
+ const raw = inflateSync(Buffer.concat(idat));
+ const px = new Uint8Array(w * h);
+ let prev = new Uint8Array(w);
+ for (let y = 0; y < h; y++) {
+ const f = raw[y * (w + 1)];
+ const cur = new Uint8Array(w);
+ for (let x = 0; x < w; x++) {
+ const a = x > 0 ? cur[x - 1] : 0;
+ const b = prev[x];
+ const c = x > 0 ? prev[x - 1] : 0;
+ let v = raw[y * (w + 1) + 1 + x];
+ if (f === 1) v += a;
+ else if (f === 2) v += b;
+ else if (f === 3) v += (a + b) >> 1;
+ else if (f === 4) { const pp = a + b - c; const pa = Math.abs(pp - a); const pb = Math.abs(pp - b); const pc = Math.abs(pp - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }
+ cur[x] = v & 255;
+ }
+ px.set(cur, y * w);
+ prev = cur;
+ }
+ return { w, h, px };
+}
+
+const cooked = existsSync(resolve(deckDir, "manifest.json")) && existsSync(resolve(deckDir, "nav.png"));
+
+describe.skipIf(!cooked)("reactor arena against the cooked engineering deck", () => {
+ const manifest = cooked ? JSON.parse(readFileSync(resolve(deckDir, "manifest.json"), "utf8")) : null;
+
+ it("matches the reactor room's outline and its ring consoles", () => {
+ const room = manifest.rooms.find((r: { id: string }) => r.id === REACTOR_ARENA.room);
+ expect(room).toBeTruthy();
+ const xs = room.polygon.map((p: number[]) => p[0]);
+ const zs = room.polygon.map((p: number[]) => p[1]);
+ const b = REACTOR_ARENA.bounds;
+ expect(Math.abs(Math.min(...xs) - b.x0)).toBeLessThan(0.6);
+ expect(Math.abs(Math.max(...xs) - b.x1)).toBeLessThan(0.6);
+ expect(Math.abs(Math.min(...zs) - b.z0)).toBeLessThan(0.6);
+ expect(Math.abs(Math.max(...zs) - b.z1)).toBeLessThan(0.6);
+ for (const t of REACTOR_ARENA.terminals) {
+ const s = manifest.sockets.find((k: { id: string; kind: string }) => k.id === t.id && k.kind === "stand");
+ expect(s, t.id).toBeTruthy();
+ expect(Math.hypot(s.position[0] - t.x, s.position[2] - t.z)).toBeLessThan(0.2);
+ }
+ });
+
+ it("agrees with the nav grid away from the rim band it deliberately opens", () => {
+ const nav = manifest.nav;
+ const { w, h, px } = decodeGreyPng(readFileSync(resolve(deckDir, "nav.png")));
+ expect([w, h]).toEqual([nav.w, nav.h]);
+ const b = REACTOR_ARENA.bounds;
+ let navWalk = 0, navAndMine = 0, mineWalk = 0, mineAndNav = 0;
+ for (let r = 0; r < h; r++) {
+ for (let c = 0; c < w; c++) {
+ const x = nav.origin_x + (c + 0.5) * nav.cell;
+ const z = nav.origin_z + (r + 0.5) * nav.cell;
+ // Inside the hall, away from its walls (the clearances differ) and outside the rim band.
+ if (x < b.x0 + 0.6 || x > b.x1 - 0.6 || z < b.z0 + 0.6 || z > b.z1 - 0.6) continue;
+ const d = Math.hypot(x - SHAFT.x, z - SHAFT.z);
+ if (d > 12.6 && d < 16.0) continue;
+ const theirs = px[r * w + c] !== 0;
+ const mine = isWalkable(arena, x, z);
+ if (theirs) { navWalk++; if (mine) navAndMine++; }
+ if (mine) { mineWalk++; if (theirs) mineAndNav++; }
+ }
+ }
+ expect(navWalk).toBeGreaterThan(20000);
+ expect(navAndMine / navWalk).toBeGreaterThan(0.95);
+ expect(mineAndNav / mineWalk).toBeGreaterThan(0.95);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/arena.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/arena.ts
new file mode 100644
index 0000000000..f885d9a3bd
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/arena.ts
@@ -0,0 +1,388 @@
+/**
+ * The duel arena: a compact, renderer-independent description of a room
+ * (bounds, solid colliders, drops and the walkways across them) and the
+ * runtime built from it once: a fine movement grid eroded by the body radius,
+ * world raycasts for bolts and sight lines, and cover spots for the bot.
+ *
+ * Coordinates are the deck's world frame (x right, z toward the camera,
+ * y up, metres), so an arena overlays its deck one to one.
+ */
+import { sweepBox, sweepCylinder, sweepOut, type SweepOut } from "./raycast";
+import type { Surface } from "./types";
+
+export interface ArenaBox { kind: "box"; id: string; x0: number; x1: number; z0: number; z1: number; y0: number; y1: number }
+export interface ArenaCylinder { kind: "cyl"; id: string; x: number; z: number; r: number; y0: number; y1: number }
+export type ArenaCollider = ArenaBox | ArenaCylinder;
+
+/** A round drop in the floor (a shaft). Bolts fly over it; bodies cannot enter it. */
+export interface ArenaVoid { x: number; z: number; r: number }
+
+/** Floor across a void: a ring around its axis, or a radial walkway. */
+export type ArenaBridge =
+ | { kind: "annulus"; x: number; z: number; r0: number; r1: number }
+ /** `yawDeg`: direction from the axis, 0 = +Z, 90 = +X. */
+ | { kind: "spoke"; x: number; z: number; yawDeg: number; r0: number; r1: number; halfWidth: number };
+
+/** A doorway in the bounds: bolts leave through it without an impact. */
+export interface ArenaOpening { x0: number; x1: number; z0: number; z1: number; y1: number }
+
+export interface ArenaPoint { x: number; z: number; yaw: number }
+
+export interface ArenaDef {
+ id: string;
+ name: string;
+ /** The deck and room it overlays. */
+ deck: string;
+ room: string;
+ bounds: { x0: number; x1: number; z0: number; z1: number; ceiling: number };
+ colliders: readonly ArenaCollider[];
+ voids: readonly ArenaVoid[];
+ bridges: readonly ArenaBridge[];
+ openings: readonly ArenaOpening[];
+ /** Spawn of side 0 and side 1 (players swap sides every round). */
+ spawns: readonly [ArenaPoint, ArenaPoint];
+ /** Where a duel can be started from (consoles in the room). */
+ terminals: readonly (ArenaPoint & { id: string })[];
+ centre: { x: number; z: number };
+}
+
+export interface MoveGrid {
+ cell: number;
+ x0: number;
+ z0: number;
+ cols: number;
+ rows: number;
+ /** 1 = a body centre may stand here (already eroded by the body radius). */
+ walk: Uint8Array;
+}
+
+export interface CoverSpot {
+ x: number;
+ z: number;
+ /** The collider that gives the cover, and the direction from it to the spot. */
+ collider: string;
+ nx: number;
+ nz: number;
+}
+
+export interface Arena {
+ def: ArenaDef;
+ bodyRadius: number;
+ grid: MoveGrid;
+ cover: readonly CoverSpot[];
+}
+
+/** Colliders at least this tall hide a standing body. */
+export const COVER_HEIGHT = 1.7;
+const GRID_CELL = 0.1;
+
+// ---------------------------------------------------------------- floor
+
+export function inVoid(def: ArenaDef, x: number, z: number): boolean {
+ for (const v of def.voids) {
+ const dx = x - v.x;
+ const dz = z - v.z;
+ if (dx * dx + dz * dz < v.r * v.r) return true;
+ }
+ return false;
+}
+
+export function onBridge(def: ArenaDef, x: number, z: number): boolean {
+ for (const b of def.bridges) {
+ const dx = x - b.x;
+ const dz = z - b.z;
+ if (b.kind === "annulus") {
+ const d2 = dx * dx + dz * dz;
+ if (d2 >= b.r0 * b.r0 && d2 <= b.r1 * b.r1) return true;
+ } else {
+ const a = (b.yawDeg * Math.PI) / 180;
+ const along = dx * Math.sin(a) + dz * Math.cos(a);
+ const lateral = dx * Math.cos(a) - dz * Math.sin(a);
+ if (along >= b.r0 && along <= b.r1 && Math.abs(lateral) <= b.halfWidth) return true;
+ }
+ }
+ return false;
+}
+
+/** True where there is deck under (x, z) (bounds, not over a drop unless on a walkway). */
+export function hasFloor(def: ArenaDef, x: number, z: number): boolean {
+ const b = def.bounds;
+ if (x < b.x0 || x > b.x1 || z < b.z0 || z > b.z1) return false;
+ return !inVoid(def, x, z) || onBridge(def, x, z);
+}
+
+function blocksBody(c: ArenaCollider): boolean {
+ return c.y0 < 1.0 && c.y1 > 0.15;
+}
+
+function insideFootprint(c: ArenaCollider, x: number, z: number): boolean {
+ if (c.kind === "box") return x >= c.x0 && x <= c.x1 && z >= c.z0 && z <= c.z1;
+ const dx = x - c.x;
+ const dz = z - c.z;
+ return dx * dx + dz * dz <= c.r * c.r;
+}
+
+// ---------------------------------------------------------------- build
+
+const cache = new WeakMap<ArenaDef, Map<number, Arena>>();
+
+/** The runtime arena for a body radius (memoised per definition). */
+export function buildArena(def: ArenaDef, bodyRadius: number): Arena {
+ let byRadius = cache.get(def);
+ if (!byRadius) { byRadius = new Map(); cache.set(def, byRadius); }
+ const hit = byRadius.get(bodyRadius);
+ if (hit) return hit;
+ const grid = rasterise(def, bodyRadius);
+ const partial: Arena = { def, bodyRadius, grid, cover: [] };
+ const arena: Arena = { ...partial, cover: findCover(partial) };
+ byRadius.set(bodyRadius, arena);
+ return arena;
+}
+
+function rasterise(def: ArenaDef, radius: number): MoveGrid {
+ const b = def.bounds;
+ const cell = GRID_CELL;
+ const cols = Math.ceil((b.x1 - b.x0) / cell);
+ const rows = Math.ceil((b.z1 - b.z0) / cell);
+ const raw = new Uint8Array(cols * rows);
+ const blockers = def.colliders.filter(blocksBody);
+ for (let r = 0; r < rows; r++) {
+ const z = b.z0 + (r + 0.5) * cell;
+ for (let c = 0; c < cols; c++) {
+ const x = b.x0 + (c + 0.5) * cell;
+ if (!hasFloor(def, x, z)) continue;
+ let free = true;
+ for (const k of blockers) if (insideFootprint(k, x, z)) { free = false; break; }
+ if (free) raw[r * cols + c] = 1;
+ }
+ }
+ // Erode by the body radius: a centre is walkable when every cell within
+ // `radius` of it is floor. Cells beyond the grid count as walls.
+ const k = Math.ceil(radius / cell);
+ const offsets: number[] = [];
+ for (let dr = -k; dr <= k; dr++) {
+ for (let dc = -k; dc <= k; dc++) {
+ if ((dc * dc + dr * dr) * cell * cell <= radius * radius + 1e-9) offsets.push(dc, dr);
+ }
+ }
+ const walk = new Uint8Array(cols * rows);
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ if (!raw[r * cols + c]) continue;
+ let ok = true;
+ for (let i = 0; i < offsets.length; i += 2) {
+ const cc = c + offsets[i];
+ const rr = r + offsets[i + 1];
+ if (cc < 0 || rr < 0 || cc >= cols || rr >= rows || !raw[rr * cols + cc]) { ok = false; break; }
+ }
+ if (ok) walk[r * cols + c] = 1;
+ }
+ }
+ return { cell, x0: b.x0, z0: b.z0, cols, rows, walk };
+}
+
+// ---------------------------------------------------------------- queries
+
+export function cellOf(grid: MoveGrid, x: number, z: number): number {
+ const c = Math.floor((x - grid.x0) / grid.cell);
+ const r = Math.floor((z - grid.z0) / grid.cell);
+ if (c < 0 || r < 0 || c >= grid.cols || r >= grid.rows) return -1;
+ return r * grid.cols + c;
+}
+
+export function isWalkable(arena: Arena, x: number, z: number): boolean {
+ const i = cellOf(arena.grid, x, z);
+ return i >= 0 && arena.grid.walk[i] === 1;
+}
+
+/** Nearest walkable point within `maxM` metres (ring search), or null. */
+export function nearestWalkable(arena: Arena, x: number, z: number, maxM = 6): { x: number; z: number } | null {
+ if (isWalkable(arena, x, z)) return { x, z };
+ const g = arena.grid;
+ const c0 = Math.floor((x - g.x0) / g.cell);
+ const r0 = Math.floor((z - g.z0) / g.cell);
+ const maxRing = Math.ceil(maxM / g.cell);
+ for (let ring = 1; ring <= maxRing; ring++) {
+ let best = -1;
+ let bestD = Infinity;
+ for (let dr = -ring; dr <= ring; dr++) {
+ const edge = Math.abs(dr) === ring;
+ for (let dc = -ring; dc <= ring; dc += edge ? 1 : 2 * ring) {
+ const c = c0 + dc;
+ const r = r0 + dr;
+ if (c < 0 || r < 0 || c >= g.cols || r >= g.rows || !g.walk[r * g.cols + c]) continue;
+ const d = dc * dc + dr * dr;
+ if (d < bestD) { bestD = d; best = r * g.cols + c; }
+ }
+ }
+ if (best >= 0) {
+ const c = best % g.cols;
+ const r = (best - c) / g.cols;
+ return { x: g.x0 + (c + 0.5) * g.cell, z: g.z0 + (r + 0.5) * g.cell };
+ }
+ }
+ return null;
+}
+
+/** A body can walk the straight line a → b. */
+export function walkableSegment(arena: Arena, ax: number, az: number, bx: number, bz: number): boolean {
+ const len = Math.hypot(bx - ax, bz - az);
+ const n = Math.max(1, Math.ceil(len / (arena.grid.cell * 0.5)));
+ for (let i = 0; i <= n; i++) {
+ const t = i / n;
+ if (!isWalkable(arena, ax + (bx - ax) * t, az + (bz - az) * t)) return false;
+ }
+ return true;
+}
+
+export interface MoveResult { x: number; z: number; blockedX: boolean; blockedZ: boolean }
+
+/**
+ * Move a body by (dx, dz) over the grid in half-cell steps; a blocked step
+ * slides along the free axis. `free` vetoes points (other bodies).
+ */
+export function moveBody(
+ arena: Arena, x: number, z: number, dx: number, dz: number, free?: (x: number, z: number) => boolean,
+): MoveResult {
+ const len = Math.hypot(dx, dz);
+ const out: MoveResult = { x, z, blockedX: false, blockedZ: false };
+ if (len < 1e-9) return out;
+ if (!isWalkable(arena, x, z)) {
+ const p = nearestWalkable(arena, x, z, 2);
+ if (p) { out.x = p.x; out.z = p.z; }
+ return out;
+ }
+ const ok = (px: number, pz: number) => isWalkable(arena, px, pz) && (!free || free(px, pz));
+ const steps = Math.max(1, Math.ceil(len / (arena.grid.cell * 0.5)));
+ const sx = dx / steps;
+ const sz = dz / steps;
+ let px = x;
+ let pz = z;
+ for (let i = 0; i < steps; i++) {
+ if (ok(px + sx, pz + sz)) { px += sx; pz += sz; continue; }
+ if (Math.abs(sx) > 1e-12 && ok(px + sx, pz)) { px += sx; out.blockedZ = true; continue; }
+ if (Math.abs(sz) > 1e-12 && ok(px, pz + sz)) { pz += sz; out.blockedX = true; continue; }
+ out.blockedX = out.blockedX || Math.abs(sx) > 1e-12;
+ out.blockedZ = out.blockedZ || Math.abs(sz) > 1e-12;
+ break;
+ }
+ out.x = px;
+ out.z = pz;
+ return out;
+}
+
+// ---------------------------------------------------------------- raycasts
+
+export interface WorldHit {
+ t: number;
+ /** "exit": the segment leaves through a doorway; no impact to draw. */
+ surface: Surface | "exit";
+ collider: string | null;
+ nx: number;
+ ny: number;
+ nz: number;
+}
+
+const sw: SweepOut = sweepOut();
+
+/**
+ * The first thing the segment a → b meets: a collider, the floor (not over
+ * a drop), the ceiling or a wall (or a doorway). Null when it is clear.
+ */
+export function raycastWorld(
+ arena: Arena, ax: number, ay: number, az: number, bx: number, by: number, bz: number,
+): WorldHit | null {
+ const def = arena.def;
+ const dx = bx - ax;
+ const dy = by - ay;
+ const dz = bz - az;
+ let best: WorldHit | null = null;
+ const take = (t: number, surface: WorldHit["surface"], collider: string | null, nx: number, ny: number, nz: number) => {
+ if (t >= 0 && t <= 1 && (!best || t < best.t)) best = { t, surface, collider, nx, ny, nz };
+ };
+ for (const c of def.colliders) {
+ const t = c.kind === "box"
+ ? sweepBox(ax, ay, az, dx, dy, dz, c.x0, c.y0, c.z0, c.x1, c.y1, c.z1, sw)
+ : sweepCylinder(ax, ay, az, dx, dy, dz, c.x, c.z, c.r, c.y0, c.y1, sw);
+ if (t >= 0) take(t, "prop", c.id, sw.nx, sw.ny, sw.nz);
+ }
+ // Floor (y = 0) where there is deck.
+ if (dy < 0 && ay >= 0 && by < 0) {
+ const t = ay / (ay - by);
+ if (hasFloor(def, ax + dx * t, az + dz * t)) take(t, "floor", null, 0, 1, 0);
+ }
+ const bd = def.bounds;
+ if (dy > 0 && ay <= bd.ceiling && by > bd.ceiling) take((bd.ceiling - ay) / dy, "ceiling", null, 0, -1, 0);
+ // Walls: the bounds rectangle.
+ if (bx < bd.x0 || bx > bd.x1 || bz < bd.z0 || bz > bd.z1) {
+ let tw = 1;
+ let nx = 0;
+ let nz = 0;
+ if (bx < bd.x0 && dx < 0) { const t = (bd.x0 - ax) / dx; if (t < tw) { tw = t; nx = 1; nz = 0; } }
+ if (bx > bd.x1 && dx > 0) { const t = (bd.x1 - ax) / dx; if (t < tw) { tw = t; nx = -1; nz = 0; } }
+ if (bz < bd.z0 && dz < 0) { const t = (bd.z0 - az) / dz; if (t < tw) { tw = t; nx = 0; nz = 1; } }
+ if (bz > bd.z1 && dz > 0) { const t = (bd.z1 - az) / dz; if (t < tw) { tw = t; nx = 0; nz = -1; } }
+ tw = Math.max(0, tw);
+ const px = ax + dx * tw;
+ const py = ay + dy * tw;
+ const pz = az + dz * tw;
+ let exit = false;
+ for (const o of def.openings) {
+ if (px >= o.x0 - 1e-6 && px <= o.x1 + 1e-6 && pz >= o.z0 - 1e-6 && pz <= o.z1 + 1e-6 && py <= o.y1) { exit = true; break; }
+ }
+ take(tw, exit ? "exit" : "wall", null, nx, 0, nz);
+ }
+ return best;
+}
+
+/** True when nothing in the world blocks a → b. */
+export function lineOfSight(arena: Arena, ax: number, ay: number, az: number, bx: number, by: number, bz: number): boolean {
+ const h = raycastWorld(arena, ax, ay, az, bx, by, bz);
+ return h === null || h.surface === "exit";
+}
+
+// ---------------------------------------------------------------- cover
+
+function findCover(arena: Arena): CoverSpot[] {
+ const spots: CoverSpot[] = [];
+ const r = arena.bodyRadius;
+ const push = (x: number, z: number, id: string, nx: number, nz: number) => {
+ if (!isWalkable(arena, x, z)) return false;
+ for (const s of spots) if (Math.hypot(s.x - x, s.z - z) < 0.8) return true;
+ spots.push({ x, z, collider: id, nx, nz });
+ return true;
+ };
+ for (const c of arena.def.colliders) {
+ if (c.y1 < COVER_HEIGHT || c.y0 > 0.5) continue;
+ if (c.kind === "cyl") {
+ const n = Math.max(8, Math.round((2 * Math.PI * (c.r + 1)) / 1.0));
+ for (let i = 0; i < n; i++) {
+ const a = (i / n) * Math.PI * 2;
+ const nx = Math.sin(a);
+ const nz = Math.cos(a);
+ for (const off of [0.35, 0.8, 1.4, 2.0, 2.6]) {
+ const d = c.r + r + off;
+ if (push(c.x + nx * d, c.z + nz * d, c.id, nx, nz)) break;
+ }
+ }
+ } else {
+ const sides: [number, number, number, number, number, number][] = [
+ // x, z start, x, z end, normal x, normal z
+ [c.x0, c.z0, c.x1, c.z0, 0, -1],
+ [c.x0, c.z1, c.x1, c.z1, 0, 1],
+ [c.x0, c.z0, c.x0, c.z1, -1, 0],
+ [c.x1, c.z0, c.x1, c.z1, 1, 0],
+ ];
+ for (const [x0, z0, x1, z1, nx, nz] of sides) {
+ const len = Math.hypot(x1 - x0, z1 - z0);
+ const n = Math.max(1, Math.round(len / 1.0));
+ for (let i = 0; i <= n; i++) {
+ const t = i / n;
+ const d = r + 0.35;
+ push(x0 + (x1 - x0) * t + nx * d, z0 + (z1 - z0) * t + nz * d, c.id, nx, nz);
+ }
+ }
+ }
+ }
+ return spots;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/arenaReactor.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/arenaReactor.ts
new file mode 100644
index 0000000000..f32749a572
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/arenaReactor.ts
@@ -0,0 +1,93 @@
+/**
+ * The Reactor Shaft hall of the engineering deck as a duel arena.
+ *
+ * Derived from the deck's sources (art/verse/decks/engineering/eng_common.py,
+ * eng_reactor.py, eng_dressing.py and the kit's industrial reactor) and
+ * checked against the cooked manifest and nav grid by arena.test.ts:
+ *
+ * room "reactor" x 33..82, z 2..38.1, ceiling 12 m
+ * shaft axis (54, 22), drop r 13, control ring r 5..6.5 around a
+ * core of r 3 (containment cage to r ~3.75, ~1.9 m tall)
+ * catwalks N, E, S, W, 1.2 m wide, ring to rim
+ * far wall heat-exchanger stacks (x 35.4/41.4/66.6/72.6/78.6) and
+ * three machinery bays between them
+ * east floor three power-conduit columns (x 78.6) behind three
+ * waist-high coolant runs (x 70.8..75.6)
+ *
+ * One deliberate difference from the nav grid: the 2.4 m rim band around the
+ * drop is cooked as mostly blocked (plate seams and bolt strips); here it is
+ * floor up to the kerb, as it reads on screen, so the south passage between
+ * the drop and the gallery wall stays open.
+ *
+ * far wall (z 2): stacks and machinery
+ * x 33 +--------------------------------------------------+ x 82
+ * | O O [##][###][##] O O O |
+ * | . . N . . |
+ * | . . [=] || |
+ * | . | . |
+ * W 0 > - - - - - - ( ( core ) ) - - - - - - < 1 [=] || | E
+ * | . | . |
+ * | . . [=] || |
+ * | . . S . . |
+ * +-------- door ---------- door ---------- door -----+ z 38.1
+ * 0, 1: spawns (sides swap each round) [=] coolant (1 m) || conduit
+ */
+import type { ArenaCollider, ArenaDef } from "./arena";
+
+const SHAFT = { x: 54, z: 22 };
+const STACK_X = [35.4, 41.4, 66.6, 72.6, 78.6];
+const UNIT_Z = [12, 22, 32];
+
+const colliders: ArenaCollider[] = [
+ // Core containment: blocks bolts up to its cap.
+ { kind: "cyl", id: "core", x: SHAFT.x, z: SHAFT.z, r: 3.75, y0: -64, y1: 1.9 },
+ // Heat-exchanger stacks on the far wall, on plinths.
+ ...STACK_X.map((x, i): ArenaCollider => ({ kind: "cyl", id: `stack_${i}`, x, z: 3.35, r: 1.35, y0: 0, y1: 11.6 })),
+ ...STACK_X.map((x, i): ArenaCollider => ({ kind: "box", id: `plinth_${i}`, x0: x - 1.5, x1: x + 1.5, z0: 2.0, z1: 4.8, y0: 0, y1: 0.5 })),
+ // Coolant lines along the far wall at chest height (either side of the machinery bays).
+ { kind: "box", id: "wall_pipes_w", x0: 33.0, x1: 45.4, z0: 2.0, z1: 2.75, y0: 0.9, y1: 2.3 },
+ { kind: "box", id: "wall_pipes_e", x0: 62.6, x1: 82.0, z0: 2.0, z1: 2.75, y0: 0.9, y1: 2.3 },
+ // Machinery bays between the stacks.
+ { kind: "box", id: "machinery_0", x0: 45.6, x1: 50.8, z0: 2.0, z1: 3.1, y0: 0, y1: 7.2 },
+ { kind: "box", id: "machinery_1", x0: 52.6, x1: 55.6, z0: 2.0, z1: 3.6, y0: 0, y1: 7.2 },
+ { kind: "box", id: "machinery_2", x0: 57.2, x1: 62.4, z0: 2.0, z1: 3.1, y0: 0, y1: 7.2 },
+ // East floor: power conduits to the ceiling, coolant runs at waist height.
+ ...UNIT_Z.map((z, i): ArenaCollider => ({ kind: "box", id: `conduit_${i}`, x0: 78.0, x1: 79.4, z0: z - 1.15, z1: z + 1.15, y0: 0, y1: 12 })),
+ ...UNIT_Z.map((z, i): ArenaCollider => ({ kind: "box", id: `coolant_${i}`, x0: 70.8, x1: 75.6, z0: z - 0.7, z1: z + 0.7, y0: 0, y1: 1.0 })),
+];
+
+export const REACTOR_ARENA: ArenaDef = {
+ id: "engineering.reactor",
+ name: "Reactor Shaft",
+ deck: "engineering",
+ room: "reactor",
+ bounds: { x0: 33.0, x1: 82.0, z0: 2.0, z1: 38.1, ceiling: 12 },
+ colliders,
+ voids: [{ x: SHAFT.x, z: SHAFT.z, r: 13.0 }],
+ bridges: [
+ { kind: "annulus", x: SHAFT.x, z: SHAFT.z, r0: 5.0, r1: 6.5 },
+ { kind: "spoke", x: SHAFT.x, z: SHAFT.z, yawDeg: 180, r0: 6.3, r1: 13.4, halfWidth: 0.6 },
+ { kind: "spoke", x: SHAFT.x, z: SHAFT.z, yawDeg: 90, r0: 6.3, r1: 13.4, halfWidth: 0.6 },
+ { kind: "spoke", x: SHAFT.x, z: SHAFT.z, yawDeg: 0, r0: 6.3, r1: 13.4, halfWidth: 0.6 },
+ { kind: "spoke", x: SHAFT.x, z: SHAFT.z, yawDeg: 270, r0: 6.3, r1: 13.4, halfWidth: 0.6 },
+ ],
+ openings: [
+ // Gallery doorways in the south wall and the glass door to the control room.
+ { x0: 38.4, x1: 40.8, z0: 38.1, z1: 38.1, y1: 3 },
+ { x0: 52.8, x1: 55.2, z0: 38.1, z1: 38.1, y1: 3 },
+ { x0: 70.8, x1: 73.2, z0: 38.1, z1: 38.1, y1: 3 },
+ { x0: 33.0, x1: 33.0, z0: 20.8, z1: 23.2, y1: 3 },
+ ],
+ spawns: [
+ { x: 38.8, z: 22, yaw: Math.PI / 2 },
+ { x: 69.2, z: 22, yaw: -Math.PI / 2 },
+ ],
+ // The four consoles hung on the control ring (manifest sockets reactor_ring__ring_N, kind "stand").
+ terminals: [
+ { id: "reactor_ring__ring_1", x: 58.2356, z: 17.7644, yaw: (135 * Math.PI) / 180 },
+ { id: "reactor_ring__ring_2", x: 49.7644, z: 17.7644, yaw: (-135 * Math.PI) / 180 },
+ { id: "reactor_ring__ring_3", x: 49.7644, z: 26.2356, yaw: (-45 * Math.PI) / 180 },
+ { id: "reactor_ring__ring_4", x: 58.2356, z: 26.2356, yaw: (45 * Math.PI) / 180 },
+ ],
+ centre: SHAFT,
+};
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/aim.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/aim.ts
new file mode 100644
index 0000000000..91f22904ad
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/aim.ts
@@ -0,0 +1,88 @@
+/**
+ * The bot's hand on the mouse. It moves its aim toward where it wants to
+ * shoot like a person does: speed-limited, settling with some stiffness,
+ * with an error that wanders over time (Ornstein-Uhlenbeck) and a bigger
+ * error right after acquiring a new target that fades out.
+ */
+import { angleDiff, clamp, DEG, wrapAngle } from "../math";
+import { PITCH_LIMIT } from "../input";
+import type { Rng } from "../rng";
+import { TICK_DT } from "../tuning";
+import type { BotParams } from "./tiers";
+
+export class AimController {
+ yaw = 0;
+ pitch = 0;
+ /** Current wandering error, degrees. */
+ private noiseYaw = 0;
+ private noisePitch = 0;
+ private acqYaw = 0;
+ private acqPitch = 0;
+ private acqTick = -100000;
+
+ constructor(private readonly params: BotParams, private readonly rng: Rng) {}
+
+ reset(yaw: number, pitch: number): void {
+ this.yaw = yaw;
+ this.pitch = pitch;
+ this.noiseYaw = 0;
+ this.noisePitch = 0;
+ this.acqYaw = 0;
+ this.acqPitch = 0;
+ }
+
+ /** A new target: start with a larger error that fades. */
+ acquire(tick: number): void {
+ const a = this.rng.range(0, Math.PI * 2);
+ const m = Math.abs(this.rng.normal(1, 0.35)) * this.params.acquireErrorDeg;
+ this.acqYaw = Math.cos(a) * m;
+ this.acqPitch = Math.sin(a) * m * 0.5;
+ this.acqTick = tick;
+ }
+
+ /** Error currently added to the intended aim, degrees. */
+ errorDeg(tick: number): { yaw: number; pitch: number } {
+ const fade = Math.exp(-((tick - this.acqTick) * TICK_DT * 1000) / Math.max(1, this.params.acquireMs / 3));
+ return { yaw: this.noiseYaw + this.acqYaw * fade, pitch: this.noisePitch + this.acqPitch * fade };
+ }
+
+ /**
+ * One tick toward the intended aim. `noisy` false skips the error (looking
+ * around rather than aiming at someone).
+ */
+ update(tick: number, wantYaw: number, wantPitch: number, noisy: boolean): void {
+ const p = this.params;
+ const dt = TICK_DT;
+ // OU step: x += -k x dt + sd sqrt(2 k dt) N.
+ const k = p.aimNoiseRate;
+ const s = p.aimNoiseDeg * Math.sqrt(2 * k * dt);
+ this.noiseYaw += -k * this.noiseYaw * dt + s * this.rng.normal();
+ this.noisePitch += -k * this.noisePitch * dt + s * 0.6 * this.rng.normal();
+ let ty = wantYaw;
+ let tp = wantPitch;
+ if (noisy) {
+ const e = this.errorDeg(tick);
+ ty += e.yaw * DEG;
+ tp += e.pitch * DEG;
+ }
+ const maxStep = p.turnRateDeg * DEG * dt;
+ const blend = 1 - Math.exp(-p.aimStiffness * dt);
+ const dy = angleDiff(this.yaw, ty);
+ const dp = tp - this.pitch;
+ let sy = dy * blend;
+ let sp = dp * blend;
+ // A small floor so the aim actually arrives instead of creeping forever.
+ const floor = 0.02 * DEG;
+ if (Math.abs(dy) < floor) sy = dy; else if (Math.abs(sy) < floor) sy = Math.sign(dy) * floor;
+ if (Math.abs(dp) < floor) sp = dp; else if (Math.abs(sp) < floor) sp = Math.sign(dp) * floor;
+ const mag = Math.hypot(sy, sp);
+ if (mag > maxStep) { sy *= maxStep / mag; sp *= maxStep / mag; }
+ this.yaw = wrapAngle(this.yaw + sy);
+ this.pitch = clamp(this.pitch + sp, -PITCH_LIMIT, PITCH_LIMIT);
+ }
+
+ /** Angle between the current aim and a direction, radians. */
+ offFrom(yaw: number, pitch: number): number {
+ return Math.hypot(angleDiff(this.yaw, yaw) * Math.cos(pitch), this.pitch - pitch);
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/bot.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/bot.test.ts
new file mode 100644
index 0000000000..42dfea62e9
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/bot.test.ts
@@ -0,0 +1,128 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { idleControl, makeInput, type ControlState } from "../input";
+import { angleDiff, yawOf } from "../math";
+import { canSee, observe } from "../observe";
+import { createContext, createMatch, step, type SimContext } from "../sim";
+import { liveMatch, place } from "../testing";
+import { DEFAULT_TUNING, withTuning } from "../tuning";
+import type { CombatEvent, MatchState } from "../types";
+import { BotBrain } from "./brain";
+import { findRoute, routeLength } from "./nav";
+import { botParams, type BotTier } from "./tiers";
+
+/** Run a bot (slot 0) against a scripted opponent (slot 1) that sees the full state. */
+function duel(ctx: SimContext, state: MatchState, bot: BotBrain, other: (s: MatchState) => Partial<ControlState>, ticks: number, onTick?: (s: MatchState, ev: CombatEvent[], botCtl: ControlState) => void) {
+ let s = state;
+ let prev: CombatEvent[] = [];
+ const seq = [1000, 1000];
+ for (let i = 0; i < ticks && s.phase !== "ended"; i++) {
+ const obs = observe({ ...s, events: prev }, 0, ctx.arena, ctx.tuning);
+ const c = bot.think(obs);
+ const o = s.players[1];
+ const res = step(s, [makeInput(seq[0]++, c), makeInput(seq[1]++, { ...idleControl(o.yaw, o.pitch), ...other(s) })], ctx);
+ onTick?.(s, res.events, c);
+ s = res.state;
+ prev = res.events;
+ }
+ return s;
+}
+
+describe("bot fairness", () => {
+ it("never shoots at an opponent it has not seen lately (no wall hacks)", () => {
+ const ctx = createContext();
+ for (const seed of [1, 2, 3]) {
+ let s = createMatch(ctx, { seed, playerIds: ["bot", "x"] });
+ const bot = new BotBrain(0, botParams("elite"), ctx.arena, ctx.tuning, seed);
+ const seenAt: number[] = [];
+ let lastSeen = -1000;
+ // The opponent wanders round the shaft and never shoots.
+ s = duel(ctx, s, bot, (st) => ({ moveY: 1, yaw: st.players[1].yaw + 0.01 }), 60 * 40, (st, ev) => {
+ if (canSee(ctx.arena, ctx.tuning, st.players[0], st.players[1])) lastSeen = st.tick;
+ for (const e of ev) if (e.type === "shot" && e.player === 0) seenAt.push(st.tick - lastSeen);
+ });
+ for (const age of seenAt) expect(age).toBeLessThan(20);
+ }
+ });
+
+ it("answers a new sighting after a human reaction time, faster on higher tiers", () => {
+ const delays = (tier: BotTier) => {
+ const out: number[] = [];
+ for (let seed = 1; seed <= 12; seed++) {
+ const { ctx, state } = liveMatch({ seed });
+ const s = place(state, { x: 38.8, z: 12, yaw: 0 }, { x: 38.8, z: 26 });
+ const bot = new BotBrain(0, botParams(tier), ctx.arena, ctx.tuning, seed);
+ let first = -1;
+ const t0 = s.tick;
+ duel(ctx, s, bot, () => ({}), 120, (st, ev) => { for (const e of ev) if (e.type === "shot" && e.player === 0 && first < 0) first = st.tick - t0; });
+ out.push(first);
+ }
+ return out;
+ };
+ const normal = delays("normal");
+ const elite = delays("elite");
+ const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length;
+ for (const d of [...normal, ...elite]) expect(d).toBeGreaterThanOrEqual(7); // >= ~120 ms, never instant
+ expect(mean(elite)).toBeLessThan(mean(normal));
+ expect(mean(normal)).toBeGreaterThan(18); // ~300 ms and more
+ });
+
+ it("leads a target running across its sights", () => {
+ const { ctx, state } = liveMatch({ seed: 4 });
+ // Bot on the west floor, target 18 m away running north-south.
+ const s = place(state, { x: 36, z: 22, yaw: Math.PI / 2 }, { x: 54, z: 8 });
+ const bot = new BotBrain(0, botParams("elite", { coverUse: 0, flankUse: 0, aggression: 0 }), ctx.arena, ctx.tuning, 4);
+ const leads: number[] = [];
+ duel(ctx, s, bot, (st) => ({ moveX: st.tick % 200 < 100 ? 1 : -1, yaw: -Math.PI / 2 }), 600, (st, _ev, c) => {
+ const me = st.players[0];
+ const o = st.players[1];
+ if (!bot.aware || Math.hypot(o.vx, o.vz) < 3) return;
+ const toTarget = yawOf(o.x - me.x, o.z - me.z);
+ const motion = yawOf(o.vx, o.vz);
+ const side = Math.sign(angleDiff(toTarget, motion));
+ leads.push(angleDiff(toTarget, c.yaw) * side);
+ });
+ expect(leads.length).toBeGreaterThan(60);
+ const avg = leads.reduce((a, b) => a + b, 0) / leads.length;
+ expect(avg).toBeGreaterThan(0.005); // aims ahead, on average
+ });
+
+ it("parries some of the bolts it sees coming and blocks or dodges others", () => {
+ const exact = withTuning(DEFAULT_TUNING, { blaster: { hipSpreadDeg: 0, adsSpreadDeg: 0, moveSpreadHipDeg: 0, moveSpreadAdsDeg: 0 } });
+ const { ctx, state } = liveMatch({ tuning: exact, seed: 8 });
+ const s = place(state, { x: 38.8, z: 8 }, { x: 38.8, z: 34 });
+ // Defence only: it does not shoot back (so the marksman lives).
+ const bot = new BotBrain(0, botParams("elite", { aggression: 0, coverUse: 0, flankUse: 0 }), ctx.arena, ctx.tuning, 8, { fire: "never" });
+ let parries = 0;
+ let reached = 0;
+ // A marksman fires single bolts at the bot every second from 26 m.
+ duel(ctx, s, bot, (st) => {
+ const me = st.players[1];
+ const b = st.players[0];
+ return { yaw: yawOf(b.x - me.x, b.z - me.z), pitch: Math.atan2(1.15 - 1.38, Math.hypot(b.x - me.x, b.z - me.z)), fire: st.tick % 60 === 0 };
+ }, 60 * 20, (_st, ev) => {
+ for (const e of ev) {
+ if (e.type === "parry" && e.player === 0) { parries++; reached++; }
+ if ((e.type === "block" || e.type === "deflect") && e.player === 0) reached++;
+ if (e.type === "hit" && e.target === 0) reached++;
+ }
+ });
+ expect(reached).toBeGreaterThan(4);
+ expect(parries).toBeGreaterThan(0);
+ });
+});
+
+describe("bot navigation", () => {
+ it("finds routes round the shaft and over the catwalks", () => {
+ const ctx = createContext();
+ const west = { x: 38.8, z: 22 };
+ const east = { x: 69.2, z: 22 };
+ const r = findRoute(ctx.arena, west, east);
+ expect(r).not.toBeNull();
+ const len = routeLength(r!);
+ expect(len).toBeGreaterThan(30);
+ expect(len).toBeLessThan(46);
+ const ring = findRoute(ctx.arena, west, { x: 54, z: 16.25 });
+ expect(ring).not.toBeNull();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts
new file mode 100644
index 0000000000..3b25e7e83f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts
@@ -0,0 +1,938 @@
+/**
+ * The duel bot: one more client. Each tick it reads an Observation (exactly
+ * what a person at the screen could know) and answers with a ControlState,
+ * which becomes an InputCommand through the same path as a human's keys.
+ *
+ * Layers:
+ * - Perception memory: sightings of the opponent go into a short history and
+ * are used `trackLatency` late; a new sighting is acted on only after a
+ * sampled reaction time; shots heard and hits taken give a rough direction.
+ * - Tactics, chosen by utility a few times a second with hysteresis: fight in
+ * the open (strafe, hold a range), take cover and peek, retreat to
+ * regenerate, push a weakened or overheated opponent, flank, hunt.
+ * - Reflexes: incoming bolts it saw are answered (after a reaction delay) by
+ * a timed parry, a dodge roll or a block; vents are timed with an error;
+ * fresh shields are baited and their drop punished.
+ * - Aim: AimController (speed-limited, wandering error), partial lead and
+ * partial recoil compensation.
+ *
+ * Deterministic for a given seed and observation sequence.
+ */
+import { isWalkable, lineOfSight, nearestWalkable, type Arena, type CoverSpot } from "../arena";
+import { idleControl, type ControlState } from "../input";
+import { angleDiff, DEG, forwardX, forwardZ, rightX, rightZ, yawOf } from "../math";
+import type { BoltSighting, EnemySighting, Observation } from "../observe";
+import { Rng } from "../rng";
+import { CHEST_HEIGHT, muzzleOf } from "../sim";
+import { TICK_RATE, type CombatTuning } from "../tuning";
+import { AimController } from "./aim";
+import { findRoute, navGraph, type Pt } from "./nav";
+import type { BotParams } from "./tiers";
+
+export type BotAction = "fight" | "cover" | "retreat" | "push" | "flank" | "hunt" | "camp" | "circle" | "watch";
+
+/** Policy overrides used by the balance harness to script degenerate strategies. */
+export interface BotOverrides {
+ /**
+ * Forced tactic. Besides the bot's own: "camp" (sit in cover near the own
+ * spawn), "circle" (close in and orbit the opponent at point blank),
+ * "watch" (hold a spot that sees the other spawn, pre-aimed).
+ */
+ action?: BotAction;
+ fire?: "auto" | "spam" | "never";
+ shield?: "auto" | "never" | "always" | "flick" | "block";
+ dodge?: "auto" | "never" | "spam";
+ /** "edge": fire up to the heat cap, then vent at once (and time it). */
+ vent?: "auto" | "never" | "edge";
+ /** "jiggle": reverse the strafe every 140..300 ms (A-D spam). */
+ strafe?: "auto" | "jiggle";
+ /** Once ahead on health, break off and hide until found (play for the clock). */
+ hideWhenAhead?: boolean;
+ /** Preferred fighting distance, metres (default from aggression: 15 down to 8). */
+ range?: number;
+ /** How hard it walks in on a distant target without a reason to (0..0.8; default APPROACH_DRIFT). */
+ approach?: number;
+ /** Where a camper settles. */
+ campAt?: Pt;
+}
+
+interface Sighting extends EnemySighting { tick: number }
+
+const ms = (v: number) => Math.round((v * TICK_RATE) / 1000);
+
+/** Radial pull toward a distant target when there is no reason to close in (the strafe is 1). */
+const APPROACH_DRIFT = 0.2;
+
+export class BotBrain {
+ readonly slot: number;
+ private readonly rng: Rng;
+ readonly aim: AimController;
+ /** Last decision, for debugging and tests. */
+ action: BotAction = "fight";
+ aware = false;
+
+ private sightings: Sighting[] = [];
+ private lastSeen: Sighting | null = null;
+ private reactAt = Infinity;
+ private aimHead = false;
+ private leadErr = 0;
+ /** Last cue of where the opponent is (tick = when the bot may act on it, at = when it came). */
+ private heard: { x: number; z: number; tick: number; at: number } | null = null;
+
+ private nextDecision = 0;
+ private actionSince = 0;
+ private route: Pt[] | null = null;
+ private routeIdx = 0;
+ private routeGoal: Pt | null = null;
+ private routeAt = -100000;
+ private stuckCheck = { tick: 0, x: 0, z: 0 };
+ private strafeDir = 1;
+ private nextStrafe = 0;
+ private cover: { spot: CoverSpot; peek: Pt | null; state: "go" | "hide" | "peek"; until: number } | null = null;
+ private flankAt: Pt | null = null;
+
+ private bolts = new Map<number, { react: number; decided: boolean; seen: number }>();
+ private shieldPlan: { raiseAt: number; lowerAt: number } | null = null;
+ private dodgePlan: { at: number; dx: number; dz: number } | null = null;
+ private ventPressAt = -1;
+ private ventCycle = -1;
+ private lastVentPress = -100;
+ private enemyShieldSince = -100000;
+ private enemyShieldDropAt = -100000;
+ private baitThisRaise = false;
+ private lastPerceivedShield = false;
+ /** Ticks of enemy shots heard (for its firing rhythm), and when I was last hit. */
+ private enemyShots: number[] = [];
+ private rhythm = { shot: -1, react: 0, done: true };
+ private lastHurtTick = -100000;
+ private pressureNext = 0;
+ private blockStarted = -100000;
+ /** This round's approach: waypoints toward the other spawn. */
+ private lane: Pt[] = [];
+ private laneIdx = 0;
+ /** Tick of the last sighting whose place has been checked. */
+ private investigated = -1;
+
+ constructor(
+ slot: number,
+ readonly params: BotParams,
+ private readonly arena: Arena,
+ private readonly tuning: CombatTuning,
+ seed: number,
+ readonly overrides: BotOverrides = {},
+ ) {
+ this.slot = slot;
+ this.rng = new Rng(seed);
+ this.aim = new AimController(params, this.rng.fork(1));
+ }
+
+ // ------------------------------------------------------------ perception
+
+ private sampleReaction(scale = 1): number {
+ const [m, sd] = this.params.reactionMs;
+ return ms(Math.max(m * 0.6, this.rng.normal(m, sd)) * scale);
+ }
+
+ private perceive(obs: Observation): void {
+ const tick = obs.tick;
+ const e = obs.enemy;
+ if (e) {
+ const fresh = !this.lastSeen || tick - this.lastSeen.tick > 12;
+ if (fresh) {
+ this.reactAt = tick + this.sampleReaction();
+ this.aim.acquire(tick + ms(this.params.trackLatencyMs));
+ this.aimHead = this.rng.chance(this.params.headAim);
+ this.leadErr = this.rng.normal(0, this.params.leadNoise);
+ }
+ const s: Sighting = { ...e, tick };
+ this.sightings.push(s);
+ if (this.sightings.length > 90) this.sightings.shift();
+ this.lastSeen = s;
+ } else if (!obs.enemyAlive) {
+ this.lastSeen = null;
+ }
+ const err = this.params.hearingErrorM;
+ if (obs.heard.length > 0) {
+ this.enemyShots.push(tick);
+ if (this.enemyShots.length > 4) this.enemyShots.shift();
+ this.rhythm = { shot: tick, react: tick + this.sampleReaction(0.9), done: false };
+ }
+ if (obs.hurtFrom) this.lastHurtTick = tick;
+ if (e) return;
+ // Cues without sight: shots, footsteps, the surge ping, the direction of a hit.
+ const me = obs.me;
+ let cue: { x: number; z: number; err: number } | null = null;
+ if (obs.ping) cue = { ...obs.ping, err: 0.5 };
+ for (const h of obs.heard) cue = { ...h, err };
+ if (!cue && obs.footsteps) cue = { ...obs.footsteps, err: err * 1.5 };
+ if (!cue && obs.hurtFrom) {
+ const dx = obs.hurtFrom.x - me.x;
+ const dz = obs.hurtFrom.z - me.z;
+ const l = Math.hypot(dx, dz) || 1;
+ cue = { x: me.x + (dx / l) * 12, z: me.z + (dz / l) * 12, err };
+ }
+ if (cue) {
+ // A stream of cues keeps the first reaction time instead of postponing it.
+ const act = this.heard && tick - this.heard.at < 60 ? this.heard.tick : tick + this.sampleReaction();
+ this.heard = { x: cue.x + this.rng.normal(0, cue.err), z: cue.z + this.rng.normal(0, cue.err), tick: act, at: tick };
+ }
+ }
+
+ /** What the bot "sees" now: the sighting `trackLatency` old, extrapolated. Null when not (yet) aware. */
+ private perceived(tick: number): Sighting | null {
+ if (tick < this.reactAt || !this.lastSeen) return null;
+ const lat = ms(this.params.trackLatencyMs);
+ let s: Sighting | null = null;
+ for (let i = this.sightings.length - 1; i >= 0; i--) {
+ if (this.sightings[i].tick <= tick - lat) { s = this.sightings[i]; break; }
+ }
+ if (!s) s = this.sightings[0] ?? null;
+ if (!s || tick - s.tick > lat + 8) return null;
+ // The motion read: how it moved over the last moments, not this instant,
+ // so a target that keeps reversing (A-D strafing) is aimed at the middle
+ // of its wobble instead of chased. Rolls are read as they happen.
+ let vx = s.vx;
+ let vz = s.vz;
+ const win = ms(this.params.motionWindowMs);
+ if (win > 0 && !s.dodging && this.reversals(s.tick) >= 2) {
+ for (let i = this.sightings.length - 1; i >= 0; i--) {
+ const o = this.sightings[i];
+ if (o.tick > s.tick - win) continue;
+ if (o.tick >= s.tick - win - 4 && !o.dodging) {
+ const span = (s.tick - o.tick) / TICK_RATE;
+ vx = (s.x - o.x) / span;
+ vz = (s.z - o.z) / span;
+ }
+ break;
+ }
+ }
+ // Extrapolate over the latency with the bot's motion read.
+ const dt = ((tick - s.tick) / TICK_RATE) * this.params.leadSkill;
+ return { ...s, vx, vz, x: s.x + vx * dt, z: s.z + vz * dt };
+ }
+
+ /** How often the target turned its running round in the 0.7 s before `tick` (sampled every 0.1 s). */
+ private reversals(tick: number): number {
+ let n = 0;
+ let prev: Sighting | null = null;
+ let next = tick;
+ for (let i = this.sightings.length - 1; i >= 0; i--) {
+ const s = this.sightings[i];
+ if (s.tick > next) continue;
+ if (s.tick < tick - 42) break;
+ if (prev && Math.hypot(s.vx, s.vz) > 1.5 && Math.hypot(prev.vx, prev.vz) > 1.5 && s.vx * prev.vx + s.vz * prev.vz < 0) n++;
+ prev = s;
+ next = s.tick - 6;
+ }
+ return n;
+ }
+
+ // ------------------------------------------------------------ main
+
+ think(obs: Observation): ControlState {
+ const me = obs.me;
+ const tick = obs.tick;
+ const out = idleControl(this.aim.yaw, this.aim.pitch);
+ if (obs.phase !== "live" || !me.alive) {
+ this.resetRound(obs);
+ out.yaw = this.aim.yaw;
+ out.pitch = this.aim.pitch;
+ return out;
+ }
+ this.perceive(obs);
+ const target = this.perceived(tick);
+ this.aware = target !== null;
+ const visibleNow = obs.enemy !== null;
+ this.trackEnemyShield(target, tick);
+
+ if (tick >= this.nextDecision) {
+ this.decide(obs, target);
+ this.nextDecision = tick + ms(this.params.decisionMs * this.rng.range(0.8, 1.2));
+ }
+
+ // Movement.
+ const move = this.steer(obs, target);
+ // Reflexes.
+ this.defend(obs, target);
+ let shield = this.shieldWanted(obs);
+ let dodge = false;
+ if (this.dodgePlan && tick >= this.dodgePlan.at) {
+ dodge = tick >= me.dodgeReadyAt;
+ if (dodge) { move.x = this.dodgePlan.dx; move.z = this.dodgePlan.dz; shield = false; }
+ this.dodgePlan = null;
+ }
+ if (this.overrides.dodge === "spam" && tick >= me.dodgeReadyAt && target && !shield) {
+ dodge = true;
+ const side = this.rng.chance(0.5) ? 1 : -1;
+ move.x = rightX(this.aim.yaw) * side;
+ move.z = rightZ(this.aim.yaw) * side;
+ }
+
+ // Aim.
+ const aimInfo = this.aimAt(obs, target, move);
+ // Fire.
+ const fire = !shield && !dodge && this.wantFire(obs, target, visibleNow, aimInfo);
+ // Vent.
+ const vent = this.wantVent(obs, target, fire);
+
+ out.yaw = this.aim.yaw;
+ out.pitch = this.aim.pitch;
+ const ml = Math.hypot(move.x, move.z);
+ if (ml > 1e-6) {
+ const wx = move.x / Math.max(1, ml);
+ const wz = move.z / Math.max(1, ml);
+ out.moveX = wx * rightX(out.yaw) + wz * rightZ(out.yaw);
+ out.moveY = wx * forwardX(out.yaw) + wz * forwardZ(out.yaw);
+ }
+ out.sprint = move.sprint && !fire && !shield;
+ out.fire = fire;
+ out.ads = !shield && !dodge && ((aimInfo.dist > this.params.adsRange && target !== null && this.action !== "push" && this.action !== "circle")
+ || (this.action === "watch" && target === null && ml < 1e-6));
+ out.shield = shield;
+ out.dodge = dodge;
+ out.vent = vent;
+ return out;
+ }
+
+ private resetRound(obs: Observation): void {
+ this.sightings = [];
+ this.lastSeen = null;
+ this.reactAt = Infinity;
+ this.heard = null;
+ this.investigated = -1;
+ this.route = null;
+ this.cover = null;
+ this.flankAt = null;
+ this.shieldPlan = null;
+ this.dodgePlan = null;
+ this.bolts.clear();
+ this.ventPressAt = -1;
+ this.enemyShots = [];
+ this.nextDecision = obs.tick;
+ this.lane = this.pickLane(obs.me.side);
+ this.laneIdx = 0;
+ // Look toward the arena's centre (where the opponent will come from).
+ const me = obs.me;
+ const c = this.arena.def.centre;
+ this.aim.reset(yawOf(c.x - me.x, c.z - me.z), 0);
+ }
+
+ /**
+ * An approach for the round: through the middle (the walkways) or round
+ * either side of the drop, then on to the other spawn.
+ */
+ private pickLane(side: number): Pt[] {
+ const a = this.arena.def.spawns[side];
+ const b = this.arena.def.spawns[1 - side];
+ const mx = (a.x + b.x) / 2;
+ const mz = (a.z + b.z) / 2;
+ const l = Math.hypot(b.x - a.x, b.z - a.z) || 1;
+ const px = -(b.z - a.z) / l;
+ const pz = (b.x - a.x) / l;
+ const v = this.arena.def.voids[0];
+ const wide = v ? v.r + 2.6 : 6;
+ const roll = this.rng.next();
+ const sideSign = this.rng.chance(0.5) ? 1 : -1;
+ const off = roll < 0.4 ? sideSign * (v ? 5.75 : 0) : (roll < 0.7 ? 1 : -1) * wide;
+ const via = nearestWalkable(this.arena, mx + px * off, mz + pz * off, 4) ?? { x: mx, z: mz };
+ return [via, { x: b.x, z: b.z }];
+ }
+
+ // ------------------------------------------------------------ tactics
+
+ private decide(obs: Observation, target: Sighting | null): void {
+ const p = this.params;
+ const me = obs.me;
+ const tick = obs.tick;
+ const forced = this.overrides.action;
+ const seenAge = this.lastSeen ? (tick - this.lastSeen.tick) / TICK_RATE : 99;
+ const myH = me.health / this.tuning.health.max;
+ const enH = obs.enemyHealth / this.tuning.health.max;
+ const ref = target ?? this.lastSeen;
+ const enemyWeak = ref ? ref.venting || ref.shieldBroken : false;
+ let next: BotAction;
+ if (forced) next = forced;
+ else {
+ const score: Record<BotAction, number> = {
+ fight: 0.55 + 0.35 * (myH - enH) + (target ? 0.15 : -0.25) + 0.1 * p.aggression,
+ cover: p.coverUse * (0.15 + 0.55 * (1 - myH) + 0.4 * (me.heat / 100) + (me.shieldBrokenUntil > tick ? 0.25 : 0) + (enH > myH + 0.2 ? 0.2 : 0)),
+ retreat: myH < 0.38 && enH > myH + 0.12 ? p.coverUse * 1.05 : 0,
+ push: p.aggression * ((enemyWeak && seenAge < 1.5 ? 0.75 : 0) + (enH < 0.3 && myH > enH + 0.15 ? 0.6 : 0)),
+ flank: p.flankUse * ((seenAge > 1.5 && seenAge < 8 ? 0.55 : 0) + (ref && ref.shieldUp ? 0.35 : 0)),
+ hunt: seenAge > 2.5 ? 0.65 : 0,
+ camp: 0,
+ circle: 0,
+ watch: 0,
+ };
+ score[this.action] += 0.18;
+ for (const k of Object.keys(score) as BotAction[]) score[k] += this.rng.range(0, 0.08);
+ next = "fight";
+ for (const k of Object.keys(score) as BotAction[]) if (score[k] > score[next]) next = k;
+ if (this.overrides.hideWhenAhead && me.health > obs.enemyHealth + 8) {
+ const close = target && Math.hypot(target.x - me.x, target.z - me.z) < 10;
+ if (!close) next = "retreat";
+ }
+ }
+ if (next !== this.action) {
+ this.action = next;
+ this.actionSince = tick;
+ this.route = null;
+ this.cover = null;
+ this.flankAt = null;
+ }
+ if (next === "cover" || next === "retreat") this.pickCover(obs, next === "retreat");
+ if (next === "flank" && !this.flankAt) this.flankAt = this.pickFlank(obs);
+ }
+
+ private enemyRef(): Pt | null {
+ if (this.lastSeen) return this.lastSeen;
+ if (this.heard) return this.heard;
+ return null;
+ }
+
+ private hiddenFrom(enemy: Pt, x: number, z: number): boolean {
+ const ey = this.tuning.body.eyeHeight;
+ return !lineOfSight(this.arena, enemy.x, ey, enemy.z, x, 1.6, z) && !lineOfSight(this.arena, enemy.x, ey, enemy.z, x, 1.0, z);
+ }
+
+ private seesFrom(enemy: Pt, x: number, z: number): boolean {
+ return lineOfSight(this.arena, x, this.tuning.body.eyeHeight, z, enemy.x, CHEST_HEIGHT, enemy.z);
+ }
+
+ private pickCover(obs: Observation, far: boolean): void {
+ const me = obs.me;
+ const enemy = this.enemyRef();
+ if (!enemy) { this.cover = null; return; }
+ if (this.cover && this.hiddenFrom(enemy, this.cover.spot.x, this.cover.spot.z)) return;
+ let best: CoverSpot | null = null;
+ let bestScore = -Infinity;
+ for (const s of this.arena.cover) {
+ const dMe = Math.hypot(s.x - me.x, s.z - me.z);
+ if (dMe > 22) continue;
+ const dEn = Math.hypot(s.x - enemy.x, s.z - enemy.z);
+ if (dEn < 5) continue;
+ const score = far ? dEn - dMe * 0.6 : -dMe - Math.abs(dEn - 12) * 0.5;
+ if (score <= bestScore) continue;
+ if (!this.hiddenFrom(enemy, s.x, s.z)) continue;
+ best = s;
+ bestScore = score;
+ }
+ if (!best) { this.cover = null; return; }
+ this.cover = { spot: best, peek: far ? null : this.peekFor(best, enemy), state: "go", until: 0 };
+ }
+
+ private peekFor(s: CoverSpot, enemy: Pt): Pt | null {
+ const tx = s.nz;
+ const tz = -s.nx;
+ for (const [a, b] of [[1.2, 0], [-1.2, 0], [2.0, 0], [-2.0, 0], [0, 1.0], [2.8, 0], [-2.8, 0]]) {
+ const x = s.x + tx * a + s.nx * b;
+ const z = s.z + tz * a + s.nz * b;
+ if (isWalkable(this.arena, x, z) && this.seesFrom(enemy, x, z)) return { x, z };
+ }
+ return null;
+ }
+
+ private pickFlank(obs: Observation): Pt | null {
+ const enemy = this.lastSeen ?? this.heard;
+ if (!enemy) return null;
+ const me = obs.me;
+ const facing = this.lastSeen ? this.lastSeen.yaw : yawOf(me.x - enemy.x, me.z - enemy.z);
+ let best: Pt | null = null;
+ let bestD = Infinity;
+ for (const off of [100, -100, 130, -130, 70, -70]) {
+ for (const r of [9, 12, 15]) {
+ const a = facing + off * DEG;
+ const x = enemy.x + Math.sin(a) * r;
+ const z = enemy.z + Math.cos(a) * r;
+ if (!isWalkable(this.arena, x, z) || !this.seesFrom(enemy, x, z)) continue;
+ const d = Math.hypot(x - me.x, z - me.z);
+ if (d < bestD) { bestD = d; best = { x, z }; }
+ }
+ }
+ return best;
+ }
+
+ // ------------------------------------------------------------ movement
+
+ private follow(me: Pt, goal: Pt, tick: number): { x: number; z: number; left: number } {
+ const replan = !this.route || !this.routeGoal || Math.hypot(goal.x - this.routeGoal.x, goal.z - this.routeGoal.z) > 1.5 || tick - this.routeAt > 90;
+ if (replan) {
+ this.route = findRoute(this.arena, me, goal);
+ this.routeGoal = goal;
+ this.routeAt = tick;
+ this.routeIdx = 1;
+ }
+ const r = this.route;
+ if (!r || r.length < 2) return { x: 0, z: 0, left: 0 };
+ while (this.routeIdx < r.length - 1 && Math.hypot(r[this.routeIdx].x - me.x, r[this.routeIdx].z - me.z) < 0.6) this.routeIdx++;
+ const wp = r[Math.min(this.routeIdx, r.length - 1)];
+ const dx = wp.x - me.x;
+ const dz = wp.z - me.z;
+ const l = Math.hypot(dx, dz);
+ let left = l;
+ for (let i = this.routeIdx + 1; i < r.length; i++) left += Math.hypot(r[i].x - r[i - 1].x, r[i].z - r[i - 1].z);
+ if (l < 0.15) return { x: 0, z: 0, left };
+ return { x: dx / l, z: dz / l, left };
+ }
+
+ private strafe(me: Pt, toEnemyYaw: number, tick: number): { x: number; z: number } {
+ const p = this.params;
+ if (tick >= this.nextStrafe) {
+ const jiggle = this.overrides.strafe === "jiggle";
+ this.strafeDir = jiggle || this.rng.chance(0.7) ? -this.strafeDir : this.strafeDir;
+ this.nextStrafe = tick + ms(jiggle ? this.rng.range(140, 300) : this.rng.range(p.strafeMs[0], p.strafeMs[1]));
+ }
+ // Sideways to the line of fire; bend toward or away from the target where the floor ends.
+ for (const flip of [1, -1]) {
+ const dir = this.strafeDir * flip;
+ for (const bend of [0, 30, -30, 60, -60]) {
+ const a = toEnemyYaw - (Math.PI / 2) * dir + bend * DEG * dir;
+ const sx = Math.sin(a);
+ const sz = Math.cos(a);
+ if (isWalkable(this.arena, me.x + sx * 0.9, me.z + sz * 0.9)) {
+ if (flip < 0) { this.strafeDir = dir; this.nextStrafe = tick + ms(p.strafeMs[0]); }
+ return { x: sx, z: sz };
+ }
+ }
+ }
+ return { x: 0, z: 0 };
+ }
+
+ private steer(obs: Observation, target: Sighting | null): { x: number; z: number; sprint: boolean } {
+ const me = obs.me;
+ const tick = obs.tick;
+ const p = this.params;
+ const enemy = target ?? this.enemyRef();
+ const stuck = this.isStuck(me, tick);
+ if (stuck) { this.route = null; this.strafeDir = -this.strafeDir; }
+ const go = (goal: Pt, sprintFar = true) => {
+ const f = this.follow(me, goal, tick);
+ return { x: f.x, z: f.z, sprint: sprintFar && !target && f.left > 7 };
+ };
+ switch (this.action) {
+ case "camp":
+ case "watch": {
+ if (this.action === "watch" && target) break;
+ const spot = this.overrides.campAt ?? (this.action === "watch" ? this.watchSpot(me.side) : this.campSpot(me.side));
+ if (Math.hypot(spot.x - me.x, spot.z - me.z) > 0.8) return go(spot);
+ return { x: 0, z: 0, sprint: false };
+ }
+ case "circle": {
+ if (!enemy) break;
+ const d = Math.hypot(enemy.x - me.x, enemy.z - me.z);
+ if (d > 3.4 || !target) return go(enemy, !target);
+ // Orbit at about 2.2 m: tangent plus a pull to the radius.
+ const toYaw = yawOf(enemy.x - me.x, enemy.z - me.z);
+ if (tick >= this.nextStrafe) {
+ this.strafeDir = this.rng.chance(0.25) ? -this.strafeDir : this.strafeDir;
+ this.nextStrafe = tick + ms(this.rng.range(600, 1400));
+ }
+ for (const flip of [1, -1]) {
+ const dir = this.strafeDir * flip;
+ const a = toYaw - (Math.PI / 2) * dir;
+ const radial = Math.max(-0.7, Math.min(0.7, (d - 2.2) * 0.9));
+ const x = Math.sin(a) + Math.sin(toYaw) * radial;
+ const z = Math.cos(a) + Math.cos(toYaw) * radial;
+ if (isWalkable(this.arena, me.x + x * 0.8, me.z + z * 0.8)) {
+ if (flip < 0) this.strafeDir = dir;
+ return { x, z, sprint: false };
+ }
+ }
+ return { x: Math.sin(toYaw), z: Math.cos(toYaw), sprint: false };
+ }
+ case "cover":
+ case "retreat": {
+ const c = this.cover;
+ if (!c || !enemy) break;
+ const d = Math.hypot(c.spot.x - me.x, c.spot.z - me.z);
+ if (c.state === "go") {
+ if (d > 0.5) return go(c.spot, true);
+ c.state = "hide";
+ c.until = tick + ms(this.rng.range(500, 1100));
+ }
+ if (c.state === "hide") {
+ const ready = me.heat < 25 && me.ventStart < 0 && (me.shieldBrokenUntil <= tick) && (this.action === "cover" ? me.health > 45 || me.health >= obs.enemyHealth : me.health > 85);
+ if (tick >= c.until && ready && c.peek) { c.state = "peek"; c.until = tick + ms(this.rng.range(700, 1500)); }
+ if (this.action === "retreat" && target && Math.hypot(target.x - me.x, target.z - me.z) < 8) { this.nextDecision = tick; }
+ if (d > 0.4) return go(c.spot, false);
+ return { x: 0, z: 0, sprint: false };
+ }
+ // Peek: step out, shoot, step back in.
+ if (c.peek) {
+ if (tick >= c.until || me.heat > p.heatCap - 8 || me.health < 30) { c.state = "hide"; c.until = tick + ms(this.rng.range(400, 900)); return go(c.spot, false); }
+ if (Math.hypot(c.peek.x - me.x, c.peek.z - me.z) > 0.3) return go(c.peek, false);
+ }
+ return { x: 0, z: 0, sprint: false };
+ }
+ case "push": {
+ if (!enemy) break;
+ const d = Math.hypot(enemy.x - me.x, enemy.z - me.z);
+ if (d > 4.5 || !target) return go(enemy);
+ const s = this.strafe(me, yawOf(enemy.x - me.x, enemy.z - me.z), tick);
+ return { x: s.x, z: s.z, sprint: false };
+ }
+ case "flank": {
+ if (this.flankAt && Math.hypot(this.flankAt.x - me.x, this.flankAt.z - me.z) > 0.8) {
+ if (target && tick - this.actionSince > 30) break;
+ return go(this.flankAt);
+ }
+ this.nextDecision = Math.min(this.nextDecision, tick + 6);
+ break;
+ }
+ case "hunt":
+ return go(this.searchGoal(me, tick));
+ default:
+ break;
+ }
+ // Fight: hold a range and strafe; without sight, close in on the last known position.
+ if (!target) {
+ const goal = this.searchGoal(me, tick);
+ return go(goal, Math.hypot(goal.x - me.x, goal.z - me.z) > 14);
+ }
+ const yaw = yawOf(target.x - me.x, target.z - me.z);
+ const d = Math.hypot(target.x - me.x, target.z - me.z);
+ const pref = this.overrides.range ?? 15 - 7 * p.aggression;
+ let radial = 0;
+ if (d > pref + 3) {
+ // Walking straight at a shooter makes the easiest target there is, so
+ // close in only with a reason (it is busy or beaten, or out of range);
+ // otherwise trade from here and drift in slowly.
+ const busy = target.venting || target.shieldBroken;
+ const reason = busy || me.health > obs.enemyHealth + 25 || d > 34 || this.overrides.range !== undefined;
+ radial = reason ? 0.8 : this.overrides.approach ?? APPROACH_DRIFT;
+ } else if (d < pref - 4) radial = -0.6;
+ const s = this.strafe(me, yaw, tick);
+ let x = s.x + Math.sin(yaw) * radial;
+ let z = s.z + Math.cos(yaw) * radial;
+ // Without a clear line to the target, walk the route instead.
+ if (!this.seesFrom(target, me.x, me.z)) {
+ const f = this.follow(me, target, tick);
+ x = f.x; z = f.z;
+ }
+ return { x, z, sprint: false };
+ }
+
+ private campSpots: Pt[] = [];
+
+ /** The cover spot nearest this side's spawn that the other spawn cannot see. */
+ private campSpot(side: number): Pt {
+ if (!this.campSpots[side]) {
+ const own = this.arena.def.spawns[side];
+ const other = this.arena.def.spawns[1 - side];
+ let best: Pt = own;
+ let bestD = Infinity;
+ for (const s of this.arena.cover) {
+ const d = Math.hypot(s.x - own.x, s.z - own.z);
+ if (d < bestD && this.hiddenFrom(other, s.x, s.z)) { bestD = d; best = s; }
+ }
+ this.campSpots[side] = best;
+ }
+ return this.campSpots[side];
+ }
+
+ private watchSpots: Pt[] = [];
+
+ /** The cover spot nearest this side's spawn that sees the other spawn (a pre-aimed hold). */
+ private watchSpot(side: number): Pt {
+ if (!this.watchSpots[side]) {
+ const own = this.arena.def.spawns[side];
+ const other = this.arena.def.spawns[1 - side];
+ let best: Pt = own;
+ let bestD = Infinity;
+ for (const s of this.arena.cover) {
+ const d = Math.hypot(s.x - own.x, s.z - own.z);
+ if (d < bestD && this.seesFrom(other, s.x, s.z)) { bestD = d; best = s; }
+ }
+ this.watchSpots[side] = best;
+ }
+ return this.watchSpots[side];
+ }
+
+ private laneGoal(me: Pt): Pt {
+ while (this.laneIdx < this.lane.length - 1 && Math.hypot(this.lane[this.laneIdx].x - me.x, this.lane[this.laneIdx].z - me.z) < 2.5) this.laneIdx++;
+ const last = this.lane[this.lane.length - 1];
+ if (last && this.laneIdx === this.lane.length - 1 && Math.hypot(last.x - me.x, last.z - me.z) < 2.5) {
+ // Lane walked and nobody met: search on toward somewhere else in the room.
+ const g = navGraph(this.arena);
+ let pick: Pt = this.arena.def.centre;
+ for (let i = 0; i < 12; i++) {
+ const k = this.rng.int(g.xs.length);
+ pick = { x: g.xs[k], z: g.zs[k] };
+ if (Math.hypot(pick.x - me.x, pick.z - me.z) > 14) break;
+ }
+ this.lane.push(pick);
+ this.laneIdx = this.lane.length - 1;
+ }
+ return this.lane[this.laneIdx] ?? this.arena.def.centre;
+ }
+
+ /** Where to look for the opponent: a fresh cue, else its last sighting (until checked), else the lane. */
+ private searchGoal(me: Pt, tick: number): Pt {
+ const cue = this.heard && this.heard.tick <= tick ? this.heard : null;
+ if (cue) {
+ if (Math.hypot(cue.x - me.x, cue.z - me.z) > 2.5) return cue;
+ this.heard = null;
+ }
+ const seen = this.lastSeen && this.lastSeen.tick > this.investigated ? this.lastSeen : null;
+ if (seen) {
+ if (Math.hypot(seen.x - me.x, seen.z - me.z) > 2.5) return seen;
+ this.investigated = seen.tick;
+ }
+ return this.laneGoal(me);
+ }
+
+ private isStuck(me: Pt, tick: number): boolean {
+ const c = this.stuckCheck;
+ if (tick - c.tick < 45) return false;
+ const moved = Math.hypot(me.x - c.x, me.z - c.z);
+ const wasTrying = this.route !== null;
+ c.tick = tick; c.x = me.x; c.z = me.z;
+ return wasTrying && moved < 0.25 && this.action !== "camp" && !(this.cover && this.cover.state !== "go");
+ }
+
+ // ------------------------------------------------------------ reflexes
+
+ private trackEnemyShield(target: Sighting | null, tick: number): void {
+ const up = target ? target.shieldUp : false;
+ if (up && !this.lastPerceivedShield) {
+ this.enemyShieldSince = tick;
+ this.baitThisRaise = this.rng.chance(this.params.baitPunish);
+ }
+ if (!up && this.lastPerceivedShield) this.enemyShieldDropAt = tick;
+ this.lastPerceivedShield = up;
+ }
+
+ private defend(obs: Observation, target: Sighting | null): void {
+ const me = obs.me;
+ const tick = obs.tick;
+ for (const [id, rec] of this.bolts) if (tick - rec.seen > 120) this.bolts.delete(id);
+ if (this.overrides.shield === "always" || this.overrides.shield === "flick") return;
+ for (const b of obs.bolts) {
+ if (b.owner === this.slot) continue;
+ let rec = this.bolts.get(b.id);
+ if (!rec) {
+ rec = { react: tick + this.sampleReaction(target ? 0.85 : 1), decided: false, seen: tick };
+ this.bolts.set(b.id, rec);
+ }
+ if (rec.decided || tick < rec.react) continue;
+ rec.decided = true;
+ const thr = threat(b, me);
+ if (!thr || thr.miss > 0.75) continue;
+ this.answer(obs, tick + Math.max(1, Math.round(thr.t * TICK_RATE)), b);
+ }
+ if (this.overrides.shield === "never" || this.overrides.shield === "block" || !target) return;
+ const p = this.params;
+ const sh = this.tuning.shield;
+ const interval = this.tuning.blaster.fireIntervalTicks;
+ const facingMe = this.shieldCoversMe(target, me);
+ // Rhythm parry: a steady stream is read and the next bolt met on time.
+ const shots = this.enemyShots;
+ const r = this.rhythm;
+ if (!r.done && tick >= r.react && shots.length >= 2) {
+ r.done = true;
+ const gap = shots[shots.length - 1] - shots[shots.length - 2];
+ if (Math.abs(gap - interval) <= 1 && facingMe && !this.shieldPlan && this.rng.chance(p.parryChance * 0.75)) {
+ const dist = Math.hypot(target.x - me.x, target.z - me.z);
+ const arrival = r.shot + interval + Math.round((dist / this.tuning.blaster.boltSpeed) * TICK_RATE);
+ const raiseAt = arrival - Math.round(sh.parryWindowTicks / 2) + Math.round(this.rng.normal(0, ms(p.parryTimingSdMs)));
+ if (raiseAt >= tick && raiseAt >= me.parryReadyAt && this.canShieldAt(obs, raiseAt)) this.shieldPlan = { raiseAt, lowerAt: raiseAt + sh.parryWindowTicks + 3 };
+ }
+ }
+ // Under pressure and losing the trade: block for a moment, then answer.
+ if (!this.shieldPlan && tick >= this.pressureNext) {
+ this.pressureNext = tick + ms(250);
+ const recentShots = shots.filter((t) => tick - t < 30).length;
+ const underFire = tick - this.lastHurtTick < ms(450) || (recentShots >= 2 && facingMe);
+ const losing = me.health < obs.enemyHealth - 10 || me.ventStart >= 0 || me.heat >= p.heatCap - 5 || me.health < 35;
+ if (underFire && losing && this.rng.chance(p.blockChance * 0.55)) {
+ const raiseAt = tick + this.sampleReaction(0.5);
+ if (this.canShieldAt(obs, raiseAt)) {
+ this.shieldPlan = { raiseAt, lowerAt: raiseAt + ms(this.rng.range(400, 850)) };
+ this.blockStarted = raiseAt;
+ this.nextDecision = Math.min(this.nextDecision, tick + 3);
+ }
+ }
+ }
+ }
+
+ private canShieldAt(obs: Observation, at: number): boolean {
+ const me = obs.me;
+ const sh = this.tuning.shield;
+ return this.overrides.shield !== "never" && me.shieldBrokenUntil <= at && me.shieldEnergy >= sh.raiseMinEnergy + 4
+ && at - me.shieldLoweredAt >= sh.reRaiseTicks && at >= me.dodgeUntil;
+ }
+
+ private answer(obs: Observation, impact: number, b: BoltSighting): void {
+ const p = this.params;
+ const me = obs.me;
+ const tick = obs.tick;
+ const sh = this.tuning.shield;
+ const plan = this.shieldPlan;
+ if (plan && tick < plan.lowerAt) {
+ if (impact <= plan.lowerAt + 2) return;
+ if (me.shieldUp || tick >= plan.raiseAt) {
+ const long = tick - Math.max(plan.raiseAt, this.blockStarted) > ms(1400);
+ if (!long && me.shieldEnergy > 35 && this.rng.chance(p.blockChance)) plan.lowerAt = Math.max(plan.lowerAt, impact + 3);
+ }
+ return;
+ }
+ if (this.overrides.shield === "block") {
+ if (this.canShieldAt(obs, tick)) this.shieldPlan = { raiseAt: tick, lowerAt: impact + 4 };
+ return;
+ }
+ const exposed = me.ventStart >= 0 || me.heat >= p.heatCap - 5;
+ if (this.rng.chance(p.parryChance * (exposed ? 1.2 : 1))) {
+ const raiseAt = impact - Math.round(sh.parryWindowTicks / 2) + Math.round(this.rng.normal(0, ms(p.parryTimingSdMs)));
+ if (raiseAt >= tick && raiseAt >= me.parryReadyAt && this.canShieldAt(obs, raiseAt)) {
+ this.shieldPlan = { raiseAt, lowerAt: raiseAt + sh.parryWindowTicks + 3 };
+ return;
+ }
+ }
+ if (this.overrides.dodge !== "never" && tick >= me.dodgeReadyAt && impact - tick >= 5 && this.rng.chance(p.dodgeChance)) {
+ // Roll sideways out of the bolt's line, toward the open side.
+ const l = Math.hypot(b.vx, b.vz) || 1;
+ const px = -b.vz / l;
+ const pz = b.vx / l;
+ const side = isWalkable(this.arena, me.x + px * 3, me.z + pz * 3) ? 1 : -1;
+ this.dodgePlan = { at: tick, dx: px * side, dz: pz * side };
+ return;
+ }
+ if (this.rng.chance(p.blockChance * (exposed ? 1 : 0.3)) && this.canShieldAt(obs, tick) && impact - tick >= 2) {
+ this.shieldPlan = { raiseAt: tick, lowerAt: impact + 4 };
+ }
+ }
+
+ private shieldWanted(obs: Observation): boolean {
+ const me = obs.me;
+ const tick = obs.tick;
+ const mode = this.overrides.shield ?? "auto";
+ if (mode === "never") return false;
+ // Released for a tick whenever the simulation asks for a fresh press.
+ if (mode === "always") return !me.shieldNeedsRelease;
+ if (mode === "flick") {
+ if (me.shieldUp) return tick - me.shieldRaisedAt < this.tuning.shield.parryWindowTicks + 1;
+ return this.lastSeen !== null && !me.shieldNeedsRelease && tick - me.shieldLoweredAt >= this.tuning.shield.reRaiseTicks;
+ }
+ const plan = this.shieldPlan;
+ if (!plan) return false;
+ if (tick >= plan.lowerAt) { this.shieldPlan = null; return false; }
+ if (me.shieldBrokenUntil > tick) { this.shieldPlan = null; return false; }
+ return tick >= plan.raiseAt;
+ }
+
+ // ------------------------------------------------------------ aim and fire
+
+ private aimAt(obs: Observation, target: Sighting | null, move: { x: number; z: number }): { dist: number; off: number; tol: number; yaw: number; pitch: number } {
+ const me = obs.me;
+ const tick = obs.tick;
+ const t = this.tuning;
+ const p = this.params;
+ if (target) {
+ const m = muzzleOf(t, { x: me.x, z: me.z, yaw: this.aim.yaw });
+ const dist = Math.hypot(target.x - m.x, target.z - m.z);
+ const flight = dist / t.blaster.boltSpeed;
+ const lead = flight * p.leadSkill * (1 + this.leadErr);
+ let ax = target.x + target.vx * lead;
+ let az = target.z + target.vz * lead;
+ if (target.dodging) {
+ // A roll slows to a stop: aim where it will end (read with the bot's lead skill).
+ const v = Math.hypot(target.vx, target.vz);
+ const decel = (2 * t.dodge.distance) / (t.dodge.durationTicks / TICK_RATE) ** 2;
+ const rest = v > 0.1 ? ((v * v) / (2 * decel)) * p.leadSkill : 0;
+ ax = target.x + (target.vx / Math.max(v, 1e-6)) * rest;
+ az = target.z + (target.vz / Math.max(v, 1e-6)) * rest;
+ }
+ const ay = this.aimHead ? 1.62 : CHEST_HEIGHT;
+ const yaw = yawOf(ax - m.x, az - m.z);
+ const pitch = Math.atan2(ay - m.y, Math.hypot(ax - m.x, az - m.z));
+ // Pull against the recoil climb (partly).
+ const cy = yaw - me.recoilYaw * DEG * p.recoilComp;
+ const cp = pitch - me.recoilPitch * DEG * p.recoilComp;
+ this.aim.update(tick, cy, cp, true);
+ const effYaw = this.aim.yaw + me.recoilYaw * DEG;
+ const effPitch = this.aim.pitch + me.recoilPitch * DEG;
+ const off = Math.hypot(angleDiff(effYaw, yaw) * Math.cos(pitch), effPitch - pitch);
+ const tol = Math.atan2(t.body.hitRadius, Math.max(1, dist)) * p.fireTolerance;
+ return { dist, off, tol, yaw, pitch };
+ }
+ // No target: pre-aim where it was last seen (or heard), else look where walking.
+ let ref: Pt | null = this.lastSeen && tick - this.lastSeen.tick < 240 ? this.lastSeen : this.heard && this.heard.tick <= tick ? this.heard : null;
+ if (!ref && this.action === "watch") ref = this.arena.def.spawns[1 - me.side];
+ let yaw = this.aim.yaw;
+ const ml = Math.hypot(move.x, move.z);
+ if (ref && (ml < 0.1 || Math.hypot(ref.x - me.x, ref.z - me.z) < 18)) yaw = yawOf(ref.x - me.x, ref.z - me.z);
+ // Searching: sweep the camera across the way ahead, or turn slowly on the spot.
+ else if (ml > 0.1) yaw = yawOf(move.x, move.z) + Math.sin(tick / 40) * 50 * DEG;
+ else yaw = this.aim.yaw + 1.5 * DEG;
+ this.aim.update(tick, yaw, 0, false);
+ return { dist: 0, off: Math.PI, tol: 0, yaw, pitch: 0 };
+ }
+
+ private wantFire(obs: Observation, target: Sighting | null, visibleNow: boolean, aim: { dist: number; off: number; tol: number }): boolean {
+ const me = obs.me;
+ const tick = obs.tick;
+ const p = this.params;
+ const mode = this.overrides.fire ?? "auto";
+ if (mode === "never" || !target || me.ventStart >= 0) return false;
+ if (!visibleNow && tick - (this.lastSeen?.tick ?? -1000) > 6) return false;
+ if (aim.off > aim.tol) return false;
+ // Bolts into a roll mostly miss; skilled bots save the heat for where it ends.
+ if (mode !== "spam" && target.dodging && this.rng.chance(p.leadSkill)) return false;
+ if (mode === "spam") return true;
+ const finishing = obs.enemyHealth < 25;
+ const punishing = tick - this.enemyShieldDropAt < ms(450);
+ const cap = finishing || punishing ? 100 : p.heatCap;
+ if (me.heat + this.tuning.blaster.heatPerShot > cap) return false;
+ if (target.shieldUp && this.shieldCoversMe(target, me)) {
+ const fresh = tick - this.enemyShieldSince < ms(380);
+ if (fresh && this.baitThisRaise) return false;
+ // A long block: drain it while the heat allows, else wait it out.
+ if (!fresh && me.heat > 55 && this.rng.chance(p.baitPunish)) return false;
+ }
+ return true;
+ }
+
+ private shieldCoversMe(target: Sighting, me: Pt): boolean {
+ const toMe = yawOf(me.x - target.x, me.z - target.z);
+ return Math.abs(angleDiff(target.yaw, toMe)) <= this.tuning.shield.arcHalfDeg * DEG;
+ }
+
+ private wantVent(obs: Observation, target: Sighting | null, firing: boolean): boolean {
+ const me = obs.me;
+ const tick = obs.tick;
+ if (this.overrides.vent === "never") return false;
+ if (tick - this.lastVentPress < 2) return false;
+ const press = () => { this.lastVentPress = tick; return true; };
+ if (this.overrides.vent === "edge" && me.ventStart < 0 && !firing && me.heat + this.tuning.blaster.heatPerShot > this.params.heatCap) return press();
+ if (me.ventStart >= 0) {
+ if (me.ventAttempted) return false;
+ if (this.ventCycle !== me.ventStart) {
+ this.ventCycle = me.ventStart;
+ const centre = (me.ventWinStart + me.ventWinEnd) / 2;
+ const underFire = this.bolts.size > 0 && obs.bolts.some((b) => b.owner !== this.slot);
+ const sd = ms(this.params.ventTimingSdMs) * (underFire ? 1.5 : 1);
+ this.ventPressAt = Math.max(me.ventStart + 2, Math.round(centre + this.rng.normal(0, sd)));
+ }
+ return tick === this.ventPressAt ? press() : false;
+ }
+ if (firing || me.heat < 20) return false;
+ const safe = !target || (target.shieldUp && this.shieldCoversMe(target, me)) || target.venting;
+ const hiding = this.cover !== null && this.cover.state === "hide";
+ if ((safe && me.heat >= 45) || (hiding && me.heat >= 20)) return press();
+ return false;
+ }
+}
+
+/** When a bolt passes closest to me (seconds) and how close (metres); null when moving away. */
+export function threat(b: BoltSighting, me: Pt): { t: number; miss: number } | null {
+ const vv = b.vx * b.vx + b.vz * b.vz;
+ if (vv < 1e-6) return null;
+ const ex = me.x - b.x;
+ const ez = me.z - b.z;
+ const t = (ex * b.vx + ez * b.vz) / vv;
+ if (t <= 0) return null;
+ const qx = b.x + b.vx * t - me.x;
+ const qz = b.z + b.vz * t - me.z;
+ return { t, miss: Math.hypot(qx, qz) };
+}
+
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/nav.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/nav.ts
new file mode 100644
index 0000000000..25ecfbf976
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/nav.ts
@@ -0,0 +1,150 @@
+/**
+ * Route finding for bots: a waypoint graph over the arena's movement grid
+ * (a 2 m lattice, the walkways over drops, the cover spots), A* over it, then
+ * string-pulling so a route is a few straight legs. Built once per arena.
+ */
+import { isWalkable, nearestWalkable, walkableSegment, type Arena } from "../arena";
+
+export interface NavGraph {
+ xs: Float64Array;
+ zs: Float64Array;
+ /** Neighbours of node i: adj[i] = [j, cost, j, cost, ...]. */
+ adj: number[][];
+}
+
+const graphs = new WeakMap<Arena, NavGraph>();
+const LINK_RANGE = 6.5;
+
+export function navGraph(arena: Arena): NavGraph {
+ const hit = graphs.get(arena);
+ if (hit) return hit;
+ const pts: { x: number; z: number }[] = [];
+ const add = (x: number, z: number) => {
+ if (!isWalkable(arena, x, z)) return;
+ for (const p of pts) if (Math.abs(p.x - x) < 0.6 && Math.abs(p.z - z) < 0.6) return;
+ pts.push({ x, z });
+ };
+ const b = arena.def.bounds;
+ for (let z = b.z0 + 1; z < b.z1; z += 2) for (let x = b.x0 + 1; x < b.x1; x += 2) add(x, z);
+ for (const v of arena.def.voids) {
+ // Walkways: sample along every bridge, and round the rim.
+ for (const br of arena.def.bridges) {
+ if (br.kind === "annulus") {
+ const r = (br.r0 + br.r1) / 2;
+ for (let a = 0; a < 360; a += 15) add(br.x + Math.sin((a * Math.PI) / 180) * r, br.z + Math.cos((a * Math.PI) / 180) * r);
+ } else {
+ const a = (br.yawDeg * Math.PI) / 180;
+ for (let r = br.r0 + 0.4; r <= br.r1 + 1.2; r += 1.5) add(br.x + Math.sin(a) * r, br.z + Math.cos(a) * r);
+ }
+ }
+ for (let a = 0; a < 360; a += 10) {
+ const r = v.r + 0.9;
+ add(v.x + Math.sin((a * Math.PI) / 180) * r, v.z + Math.cos((a * Math.PI) / 180) * r);
+ }
+ }
+ for (const c of arena.cover) add(c.x, c.z);
+ const n = pts.length;
+ const xs = new Float64Array(n);
+ const zs = new Float64Array(n);
+ pts.forEach((p, i) => { xs[i] = p.x; zs[i] = p.z; });
+ const adj: number[][] = pts.map(() => []);
+ for (let i = 0; i < n; i++) {
+ for (let j = i + 1; j < n; j++) {
+ const d = Math.hypot(xs[i] - xs[j], zs[i] - zs[j]);
+ if (d > LINK_RANGE) continue;
+ if (!walkableSegment(arena, xs[i], zs[i], xs[j], zs[j])) continue;
+ adj[i].push(j, d);
+ adj[j].push(i, d);
+ }
+ }
+ const g = { xs, zs, adj };
+ graphs.set(arena, g);
+ return g;
+}
+
+function nearNodes(arena: Arena, g: NavGraph, x: number, z: number, k: number): number[] {
+ const cand: { i: number; d: number }[] = [];
+ for (let i = 0; i < g.xs.length; i++) {
+ const d = Math.hypot(g.xs[i] - x, g.zs[i] - z);
+ if (d <= LINK_RANGE) cand.push({ i, d });
+ }
+ cand.sort((a, b) => a.d - b.d);
+ const out: number[] = [];
+ for (const c of cand) {
+ if (walkableSegment(arena, x, z, g.xs[c.i], g.zs[c.i])) out.push(c.i);
+ if (out.length >= k) break;
+ }
+ return out;
+}
+
+export interface Pt { x: number; z: number }
+
+/** A walkable route from `from` to `to` (start, corners, goal), or null. */
+export function findRoute(arena: Arena, from: Pt, to: Pt): Pt[] | null {
+ const start = nearestWalkable(arena, from.x, from.z, 2);
+ const goal = nearestWalkable(arena, to.x, to.z, 4);
+ if (!start || !goal) return null;
+ if (walkableSegment(arena, start.x, start.z, goal.x, goal.z)) return [start, goal];
+ const g = navGraph(arena);
+ const n = g.xs.length;
+ const S = n;
+ const G = n + 1;
+ const startLinks = nearNodes(arena, g, start.x, start.z, 6);
+ const goalLinks = new Set(nearNodes(arena, g, goal.x, goal.z, 6));
+ if (startLinks.length === 0 || goalLinks.size === 0) return null;
+ const px = (i: number) => (i === S ? start.x : i === G ? goal.x : g.xs[i]);
+ const pz = (i: number) => (i === S ? start.z : i === G ? goal.z : g.zs[i]);
+ const h = (i: number) => Math.hypot(px(i) - goal.x, pz(i) - goal.z);
+ const gScore = new Float64Array(n + 2).fill(Infinity);
+ const from_ = new Int32Array(n + 2).fill(-1);
+ const closed = new Uint8Array(n + 2);
+ const open: number[] = [S];
+ gScore[S] = 0;
+ while (open.length) {
+ let bi = 0;
+ let bf = Infinity;
+ for (let k = 0; k < open.length; k++) {
+ const f = gScore[open[k]] + h(open[k]);
+ if (f < bf) { bf = f; bi = k; }
+ }
+ const cur = open[bi];
+ open[bi] = open[open.length - 1];
+ open.pop();
+ if (cur === G) break;
+ if (closed[cur]) continue;
+ closed[cur] = 1;
+ const relax = (j: number, cost: number) => {
+ const ng = gScore[cur] + cost;
+ if (ng < gScore[j]) { gScore[j] = ng; from_[j] = cur; open.push(j); }
+ };
+ if (cur === S) {
+ for (const j of startLinks) relax(j, Math.hypot(g.xs[j] - start.x, g.zs[j] - start.z));
+ } else {
+ const a = g.adj[cur];
+ for (let k = 0; k < a.length; k += 2) if (!closed[a[k]]) relax(a[k], a[k + 1]);
+ if (goalLinks.has(cur)) relax(G, Math.hypot(g.xs[cur] - goal.x, g.zs[cur] - goal.z));
+ }
+ }
+ if (from_[G] < 0) return null;
+ const chain: Pt[] = [];
+ for (let i = G; i !== -1; i = from_[i]) chain.push({ x: px(i), z: pz(i) });
+ chain.reverse();
+ // String-pull: skip every waypoint a straight walk can cut.
+ const out: Pt[] = [chain[0]];
+ let anchor = 0;
+ while (anchor < chain.length - 1) {
+ let next = anchor + 1;
+ for (let j = chain.length - 1; j > anchor + 1; j--) {
+ if (walkableSegment(arena, chain[anchor].x, chain[anchor].z, chain[j].x, chain[j].z)) { next = j; break; }
+ }
+ out.push(chain[next]);
+ anchor = next;
+ }
+ return out;
+}
+
+export function routeLength(route: readonly Pt[]): number {
+ let d = 0;
+ for (let i = 1; i < route.length; i++) d += Math.hypot(route[i].x - route[i - 1].x, route[i].z - route[i - 1].z);
+ return d;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/tiers.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/tiers.ts
new file mode 100644
index 0000000000..2592f57651
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/tiers.ts
@@ -0,0 +1,164 @@
+/**
+ * Bot difficulty as plain numbers. Every tier is human-like and imperfect:
+ * it reacts after a sampled delay, tracks with a wandering error, leads a
+ * moving target only partly, mistimes some vents and parries, and decides a
+ * few times a second rather than every frame.
+ */
+
+export type BotTier = "normal" | "hard" | "elite";
+
+export interface BotParams {
+ tier: BotTier;
+ /** Delay from first sight (of the opponent or of a bolt) to acting on it, ms: mean and sd. */
+ reactionMs: readonly [number, number];
+ /** Visual-motor delay while tracking a target already in sight, ms. */
+ trackLatencyMs: number;
+ /** Wandering aim error (Ornstein-Uhlenbeck): stationary sd in degrees and how fast it wanders (1/s). */
+ aimNoiseDeg: number;
+ aimNoiseRate: number;
+ /** Extra error on acquiring a target, degrees, decaying over `acquireMs`. */
+ acquireErrorDeg: number;
+ acquireMs: number;
+ /** Mouse speed limit (deg/s) and how quickly the aim settles (1/s). */
+ turnRateDeg: number;
+ aimStiffness: number;
+ /** Fraction of the correct lead on a moving target, and the relative noise on its velocity estimate. */
+ leadSkill: number;
+ leadNoise: number;
+ /**
+ * The target's motion is read over this many ms (its average velocity), so
+ * A-D strafing is aimed at the middle instead of chased; 0 = this instant.
+ */
+ motionWindowMs: number;
+ /** Fraction of the recoil climb pulled back down. */
+ recoilComp: number;
+ /** Fires when the aim is within this multiple of the target's angular half-width. */
+ fireTolerance: number;
+ /** Stops firing at this heat (unless finishing a weak opponent). */
+ heatCap: number;
+ /** Timing error of a vent press, ms (sd). */
+ ventTimingSdMs: number;
+ /** Chance to try a parry on an incoming bolt it saw, and the timing error, ms (sd). */
+ parryChance: number;
+ parryTimingSdMs: number;
+ /** Chance to hold a block against a stream of bolts it cannot answer. */
+ blockChance: number;
+ /** Chance to dodge-roll out of a bolt's path it saw coming. */
+ dodgeChance: number;
+ /** Strafe direction changes every this many ms (range). */
+ strafeMs: readonly [number, number];
+ /** Weights of the tactics. */
+ coverUse: number;
+ flankUse: number;
+ aggression: number;
+ /** Holds fire into a fresh shield and punishes the moment it drops. */
+ baitPunish: number;
+ /** Re-plans this often, ms. */
+ decisionMs: number;
+ /** Fraction of engagements aimed at the head. */
+ headAim: number;
+ /** Aims down sights beyond this distance, metres. */
+ adsRange: number;
+ /** Error on where a heard shot came from, metres. */
+ hearingErrorM: number;
+}
+
+export const BOT_TIERS: Readonly<Record<BotTier, BotParams>> = {
+ normal: {
+ tier: "normal",
+ reactionMs: [305, 60],
+ trackLatencyMs: 150,
+ aimNoiseDeg: 1.6,
+ aimNoiseRate: 1.6,
+ acquireErrorDeg: 7,
+ acquireMs: 650,
+ turnRateDeg: 380,
+ aimStiffness: 8,
+ leadSkill: 0.6,
+ leadNoise: 0.35,
+ motionWindowMs: 0,
+ recoilComp: 0.35,
+ fireTolerance: 2.0,
+ heatCap: 101,
+ ventTimingSdMs: 160,
+ parryChance: 0.25,
+ parryTimingSdMs: 110,
+ blockChance: 0.42,
+ dodgeChance: 0.12,
+ strafeMs: [700, 1500],
+ coverUse: 0.4,
+ flankUse: 0.2,
+ aggression: 0.5,
+ baitPunish: 0.0,
+ decisionMs: 320,
+ headAim: 0,
+ adsRange: 13,
+ hearingErrorM: 4,
+ },
+ hard: {
+ tier: "hard",
+ reactionMs: [255, 50],
+ trackLatencyMs: 120,
+ aimNoiseDeg: 1.15,
+ aimNoiseRate: 1.9,
+ acquireErrorDeg: 4.5,
+ acquireMs: 450,
+ turnRateDeg: 520,
+ aimStiffness: 12,
+ leadSkill: 0.8,
+ leadNoise: 0.22,
+ motionWindowMs: 200,
+ recoilComp: 0.7,
+ fireTolerance: 1.6,
+ heatCap: 86,
+ ventTimingSdMs: 85,
+ parryChance: 0.45,
+ parryTimingSdMs: 65,
+ blockChance: 0.6,
+ dodgeChance: 0.25,
+ strafeMs: [450, 1050],
+ coverUse: 0.65,
+ flankUse: 0.45,
+ aggression: 0.6,
+ baitPunish: 0.55,
+ decisionMs: 220,
+ headAim: 0.15,
+ adsRange: 10,
+ hearingErrorM: 2.5,
+ },
+ elite: {
+ tier: "elite",
+ reactionMs: [215, 40],
+ trackLatencyMs: 95,
+ aimNoiseDeg: 0.92,
+ aimNoiseRate: 2.2,
+ acquireErrorDeg: 3.6,
+ acquireMs: 340,
+ turnRateDeg: 720,
+ aimStiffness: 17,
+ leadSkill: 0.9,
+ leadNoise: 0.14,
+ motionWindowMs: 300,
+ recoilComp: 0.85,
+ fireTolerance: 1.3,
+ heatCap: 80,
+ ventTimingSdMs: 50,
+ parryChance: 0.65,
+ parryTimingSdMs: 42,
+ blockChance: 0.75,
+ dodgeChance: 0.35,
+ strafeMs: [300, 820],
+ coverUse: 0.85,
+ flankUse: 0.7,
+ aggression: 0.7,
+ baitPunish: 0.9,
+ decisionMs: 160,
+ headAim: 0.25,
+ adsRange: 9,
+ hearingErrorM: 1.5,
+ },
+};
+
+export function botParams(tier: BotTier, patch: Partial<BotParams> = {}): BotParams {
+ return { ...BOT_TIERS[tier], ...patch };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/camera.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/camera.ts
new file mode 100644
index 0000000000..e4b01b2d26
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/camera.ts
@@ -0,0 +1,99 @@
+/**
+ * Camera and aim hooks for the integrator: over-the-shoulder rig presets for
+ * hip fire, sights, sprint and shield, the camera pose that follows from
+ * them, and crosshair convergence (the blaster sits right of and below the
+ * camera, so aim is solved from the muzzle to whatever is under the
+ * crosshair; bolts then land where the crosshair is).
+ */
+import { raycastWorld } from "./arena";
+import { DEG, dirFromAngles, forwardX, forwardZ, lerp, rightX, rightZ, type Vec3 } from "./math";
+import { sweepCapsule, sweepOut } from "./raycast";
+import { muzzleOf, type SimContext } from "./sim";
+import type { PlayerView, ViewState } from "./view";
+
+export interface CameraRig {
+ /** Offset of the camera pivot from the feet: to the right, up; and its distance back along the view. */
+ right: number;
+ up: number;
+ back: number;
+ /** Vertical field of view, degrees. */
+ fovDeg: number;
+}
+
+export const CAMERA_RIGS: Readonly<Record<"hip" | "ads" | "sprint" | "shield", CameraRig>> = {
+ hip: { right: 0.55, up: 1.68, back: 2.5, fovDeg: 70 },
+ ads: { right: 0.42, up: 1.62, back: 1.3, fovDeg: 50 },
+ sprint: { right: 0.5, up: 1.6, back: 2.9, fovDeg: 76 },
+ shield: { right: 0.62, up: 1.72, back: 2.75, fovDeg: 68 },
+};
+
+function mix(a: CameraRig, b: CameraRig, t: number): CameraRig {
+ return { right: lerp(a.right, b.right, t), up: lerp(a.up, b.up, t), back: lerp(a.back, b.back, t), fovDeg: lerp(a.fovDeg, b.fovDeg, t) };
+}
+
+/** The rig for a player's state (sights blend in with `ads`). Ease the result over ~0.15 s in the view. */
+export function cameraRigFor(p: PlayerView): CameraRig {
+ if (p.sprinting) return CAMERA_RIGS.sprint;
+ if (p.shieldUp) return CAMERA_RIGS.shield;
+ return mix(CAMERA_RIGS.hip, CAMERA_RIGS.ads, p.ads);
+}
+
+/** Camera position and view direction for a rig: behind the right shoulder, orbiting the pivot with the pitch. */
+export function cameraPose(p: Pick<PlayerView, "x" | "z" | "yaw" | "pitch">, rig: CameraRig): { position: Vec3; dir: Vec3 } {
+ const dir = dirFromAngles(p.yaw, p.pitch);
+ const pivot = { x: p.x + rightX(p.yaw) * rig.right, y: rig.up, z: p.z + rightZ(p.yaw) * rig.right };
+ return { position: { x: pivot.x - dir.x * rig.back, y: pivot.y - dir.y * rig.back, z: pivot.z - dir.z * rig.back }, dir };
+}
+
+export interface AimSolution {
+ yaw: number;
+ pitch: number;
+ /** The world point under the crosshair. */
+ point: Vec3;
+ target: "player" | "world" | "none";
+}
+
+const sw = sweepOut();
+
+/**
+ * Aim for the local player so the bolt from its muzzle meets what the camera
+ * ray (crosshair) hits. Feed `yaw` and `pitch` into the ControlState.
+ */
+export function resolveAim(ctx: SimContext, view: ViewState, camPos: Vec3, camDir: Vec3, maxDist = 90): AimSolution {
+ const me = view.players[view.slot];
+ const l = Math.hypot(camDir.x, camDir.y, camDir.z) || 1;
+ const d = { x: camDir.x / l, y: camDir.y / l, z: camDir.z / l };
+ // Start the ray level with the player, so nothing between camera and shoulder counts.
+ const t0 = me ? Math.max(0, (me.x - camPos.x) * d.x + (1.4 - camPos.y) * d.y + (me.z - camPos.z) * d.z) : 0;
+ const a = { x: camPos.x + d.x * t0, y: camPos.y + d.y * t0, z: camPos.z + d.z * t0 };
+ const span = maxDist;
+ let best = 1;
+ let target: AimSolution["target"] = "none";
+ const hit = raycastWorld(ctx.arena, a.x, a.y, a.z, a.x + d.x * span, a.y + d.y * span, a.z + d.z * span);
+ if (hit && hit.surface !== "exit") { best = hit.t; target = "world"; }
+ const b = ctx.tuning.body;
+ for (const p of view.players) {
+ if (p.local || !p.alive) continue;
+ const t = sweepCapsule(a.x, a.y, a.z, d.x * span, d.y * span, d.z * span, p.x, p.z, b.hitBottom, b.hitTop, b.hitRadius, sw);
+ if (t >= 0 && t < best) { best = t; target = "player"; }
+ }
+ const point = { x: a.x + d.x * span * best, y: a.y + d.y * span * best, z: a.z + d.z * span * best };
+ if (!me) return { yaw: Math.atan2(d.x, d.z), pitch: Math.asin(d.y), point, target };
+ const m = muzzleOf(ctx.tuning, { x: me.x, z: me.z, yaw: Math.atan2(d.x, d.z) });
+ const dx = point.x - m.x;
+ const dy = point.y - m.y;
+ const dz = point.z - m.z;
+ // Too close to converge sensibly (a wall in the face): keep the camera's direction.
+ if (Math.hypot(dx, dz) < 1.5) return { yaw: Math.atan2(d.x, d.z), pitch: Math.asin(d.y), point, target };
+ return { yaw: Math.atan2(dx, dz), pitch: Math.atan2(dy, Math.hypot(dx, dz)), point, target };
+}
+
+/** Crosshair radius in pixels for a cone half-angle (HUD spread circle). */
+export function crosshairRadiusPx(spreadDeg: number, fovDeg: number, viewportHeightPx: number): number {
+ return (Math.tan(spreadDeg * DEG) / Math.tan((fovDeg * DEG) / 2)) * (viewportHeightPx / 2);
+}
+
+/** Forward on the floor for a yaw (for WASD in the camera frame). */
+export function floorForward(yaw: number): { x: number; z: number } {
+ return { x: forwardX(yaw), z: forwardZ(yaw) };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/client.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/client.ts
new file mode 100644
index 0000000000..76361b7730
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/client.ts
@@ -0,0 +1,328 @@
+/**
+ * A duel client: what a player's machine runs, human or bot.
+ *
+ * - Every 1/60 s it turns the current control state into an InputCommand,
+ * sends it (with the last few for loss), and steps its own copy of the
+ * match with it at once (prediction), so its own commander answers the
+ * keys without waiting for the server.
+ * - On a snapshot it takes the server's state, drops the inputs the server
+ * has applied (ackSeq) and replays the rest (reconciliation). The state is
+ * quantised on both sides, so a replay matches the server exactly unless
+ * the opponent did something the client could not know.
+ * - The opponent is shown from the snapshots, interpolated a little in the
+ * past (snapshot interpolation), never from guesses.
+ * - Events of its own actions (shots, dodges, shield, vents) are played from
+ * the prediction at once; everything else from the server. Each event is
+ * played once (eventKey).
+ */
+import { buildView, type ViewState } from "./view";
+import { idleControl, makeInput, type ControlState } from "./input";
+import { lerpAngle } from "./math";
+import { decodeState, encodeInput, PROTOCOL_VERSION, type EncodedState, type ServerMsg } from "./protocol";
+import { rulesHash, step, type SimContext } from "./sim";
+import { TICK_RATE } from "./tuning";
+import { eventKey, type CombatEvent, type EndReason, type InputCommand, type MatchConfig, type MatchState, type PlayerState } from "./types";
+import type { ClientChannel } from "./transport";
+import type { WorldView } from "./observe";
+
+export type ClientStatus = "connecting" | "playing" | "ended" | "rejected" | "closed";
+
+export interface MatchClientOptions {
+ ctx: SimContext;
+ channel: ClientChannel;
+ playerId: string;
+ name?: string;
+ /** How far behind the newest snapshot the opponent is shown, ticks (default: 2 snapshot periods + 2). */
+ interpDelayTicks?: number;
+ /** How many recent inputs each send repeats (default 3). */
+ redundancy?: number;
+ /**
+ * A controller called every tick with what this client can see, instead of
+ * `setControl` (bots).
+ */
+ controller?: (view: WorldView, slot: number) => ControlState;
+}
+
+interface Snap { tick: number; state: MatchState; recvMs: number }
+
+/** Own-action events the client plays from its prediction. */
+const PREDICTED = new Set<CombatEvent["type"]>(["shot", "dodge", "shield_up", "vent_start", "vent_perfect", "vent_miss", "overheat"]);
+
+export class MatchClient {
+ status: ClientStatus = "connecting";
+ slot = -1;
+ matchId = "";
+ config: MatchConfig | null = null;
+ rejectReason = "";
+ result: { winner: number; reason: EndReason; scores: number[] } | null = null;
+ /** Round-trip time estimate, ms. */
+ rttMs = 0;
+ /** Prediction check: snapshots compared with our guess for the same tick, how many differed, the worst position error (m). */
+ readonly prediction = { checked: 0, corrections: 0, maxErrorM: 0 };
+ private history = new Map<number, { x: number; z: number; health: number; heat: number; shieldUp: boolean }>();
+
+ private readonly ctx: SimContext;
+ private readonly channel: ClientChannel;
+ private readonly opts: MatchClientOptions;
+ private control: ControlState = idleControl();
+ private latch = { dodge: false, vent: false, forfeit: false };
+ private seq = 0;
+ private pending: InputCommand[] = [];
+ private sent: InputCommand[] = [];
+ private predicted: MatchState | null = null;
+ private prevPredicted: MatchState | null = null;
+ private snaps: Snap[] = [];
+ private acc = 0;
+ private lastNow: number | null = null;
+ private now = 0;
+ private out: CombatEvent[] = [];
+ private seen = new Map<string, number>();
+ /** Events (deduplicated, authoritative or own predicted) not yet handed to the controller. */
+ private viewEvents: CombatEvent[] = [];
+ private snapshotEvery = 1;
+ private unsub: (() => void)[] = [];
+ private pingAt = 0;
+
+ constructor(o: MatchClientOptions) {
+ this.ctx = o.ctx;
+ this.channel = o.channel;
+ this.opts = o;
+ this.unsub.push(o.channel.onMessage((m) => this.message(m)));
+ this.unsub.push(o.channel.onClose(() => { if (this.status === "playing" || this.status === "connecting") this.status = "closed"; }));
+ o.channel.send(["h", PROTOCOL_VERSION, o.playerId, o.name ?? o.playerId, rulesHash(o.ctx)]);
+ }
+
+ /** The player's current wish (keys and mouse). Presses are kept until a command carries them. */
+ setControl(c: ControlState): void {
+ this.control = c;
+ if (c.dodge) this.latch.dodge = true;
+ if (c.vent) this.latch.vent = true;
+ if (c.forfeit) this.latch.forfeit = true;
+ }
+
+ forfeit(): void {
+ if (this.status === "playing") this.channel.send(["l"]);
+ }
+
+ private message(m: ServerMsg): void {
+ if (!Array.isArray(m)) return;
+ switch (m[0]) {
+ case "w": {
+ this.slot = m[2];
+ this.matchId = m[3];
+ this.snapshotEvery = Math.max(1, m[7]);
+ this.config = m[8];
+ this.status = "playing";
+ break;
+ }
+ case "s":
+ this.snapshot(m[1], m[2], m[3], m[4]);
+ break;
+ case "e":
+ // The final snapshot rides along, so its events and state are never lost.
+ if (m.length >= 8) this.snapshot(m[4], m[5], m[6], m[7]);
+ this.result = { winner: m[1], reason: m[2], scores: m[3] };
+ this.status = "ended";
+ break;
+ case "o":
+ this.rttMs = Math.max(0, this.now - m[1]);
+ break;
+ case "r":
+ this.rejectReason = m[1];
+ this.status = "rejected";
+ break;
+ }
+ }
+
+ private snapshot(tick: number, ack: number, enc: EncodedState, events: readonly CombatEvent[]): void {
+ if (!this.config) return;
+ const newest = this.snaps[this.snaps.length - 1];
+ if (newest && tick <= newest.tick) {
+ // Late or duplicate: only its events are of use.
+ this.takeEvents(events);
+ return;
+ }
+ const state = decodeState(enc, this.config);
+ this.snaps.push({ tick, state, recvMs: this.now });
+ if (this.snaps.length > 40) this.snaps.shift();
+ this.takeEvents(events);
+ this.reconcile(state, ack);
+ }
+
+ /** Server events; own actions already played from the prediction are dropped by key. */
+ private takeEvents(events: readonly CombatEvent[]): void {
+ for (const e of events) this.emit(e);
+ }
+
+ private emit(e: CombatEvent): void {
+ const k = eventKey(e);
+ if (this.seen.has(k)) return;
+ this.seen.set(k, e.tick);
+ this.out.push(e);
+ if (this.opts.controller) this.viewEvents.push(e);
+ if (this.seen.size > 2000) {
+ const cutoff = e.tick - 600;
+ for (const [key, t] of this.seen) if (t < cutoff) this.seen.delete(key);
+ }
+ }
+
+ private inputsFor(cmd: InputCommand): (InputCommand | null)[] {
+ const arr: (InputCommand | null)[] = [null, null];
+ arr[this.slot] = cmd;
+ return arr;
+ }
+
+ private reconcile(server: MatchState, ack: number): void {
+ // How well did we predict ourselves? Compare our guess for this tick with the truth.
+ const guess = this.history.get(server.tick);
+ const truth = server.players[this.slot];
+ if (guess && truth) {
+ this.prediction.checked++;
+ const err = Math.hypot(guess.x - truth.x, guess.z - truth.z);
+ if (err > 1e-9 || guess.health !== truth.health || guess.heat !== truth.heat || guess.shieldUp !== truth.shieldUp) this.prediction.corrections++;
+ this.prediction.maxErrorM = Math.max(this.prediction.maxErrorM, err);
+ }
+ this.pending = this.pending.filter((c) => c.seq > ack);
+ let s = server;
+ let prev = server;
+ for (const c of this.pending) {
+ prev = s;
+ const res = step(s, this.inputsFor(c), this.ctx);
+ s = res.state;
+ this.predictedEvents(res.events);
+ }
+ this.prevPredicted = prev;
+ this.predicted = s;
+ this.remember(s);
+ }
+
+ /** Keep our predicted self per tick for the prediction check. */
+ private remember(s: MatchState): void {
+ const p = s.players[this.slot];
+ if (!p) return;
+ this.history.set(s.tick, { x: p.x, z: p.z, health: p.health, heat: p.heat, shieldUp: p.shieldUp });
+ if (this.history.size > 240) {
+ const cutoff = s.tick - 240;
+ for (const t of this.history.keys()) if (t < cutoff) this.history.delete(t);
+ }
+ }
+
+ private predictedEvents(events: readonly CombatEvent[]): void {
+ for (const e of events) if ("player" in e && e.player === this.slot && PREDICTED.has(e.type)) this.emit(e);
+ }
+
+ /** Advance the client clock: build, send and predict every tick due. */
+ update(nowMs: number): void {
+ if (this.lastNow === null) this.lastNow = nowMs;
+ const dt = Math.min(250, Math.max(0, nowMs - this.lastNow));
+ this.lastNow = nowMs;
+ this.now = nowMs;
+ if (this.status !== "playing" || !this.predicted) return;
+ if (nowMs - this.pingAt > 1000) { this.pingAt = nowMs; this.channel.send(["p", nowMs]); }
+ this.acc += dt;
+ const tickMs = 1000 / TICK_RATE;
+ while (this.acc >= tickMs) {
+ this.acc -= tickMs;
+ this.clientTick();
+ }
+ }
+
+ private clientTick(): void {
+ if (!this.predicted) return;
+ let c = this.control;
+ if (this.opts.controller) c = this.opts.controller(this.worldView(), this.slot);
+ else {
+ c = { ...c, dodge: c.dodge || this.latch.dodge, vent: c.vent || this.latch.vent, forfeit: c.forfeit || this.latch.forfeit };
+ this.latch = { dodge: false, vent: false, forfeit: false };
+ }
+ const viewTick = Math.floor(this.renderTick());
+ const cmd = makeInput(this.seq++, c, viewTick);
+ this.pending.push(cmd);
+ this.sent.push(cmd);
+ const red = this.opts.redundancy ?? 3;
+ if (this.sent.length > red) this.sent.splice(0, this.sent.length - red);
+ this.channel.send(["i", this.snaps.length ? this.snaps[this.snaps.length - 1].tick : -1, this.sent.map(encodeInput)]);
+ this.prevPredicted = this.predicted;
+ const res = step(this.predicted, this.inputsFor(cmd), this.ctx);
+ this.predicted = res.state;
+ this.predictedEvents(res.events);
+ this.remember(this.predicted);
+ }
+
+ /** The server tick the opponent is drawn at (fractional). */
+ renderTick(nowMs = this.now): number {
+ const newest = this.snaps[this.snaps.length - 1];
+ if (!newest) return 0;
+ const delay = this.opts.interpDelayTicks ?? this.snapshotEvery * 2 + 2;
+ const est = newest.tick + ((nowMs - newest.recvMs) * TICK_RATE) / 1000;
+ return Math.min(est, newest.tick + this.snapshotEvery * 3) - delay;
+ }
+
+ /** An opponent interpolated between the snapshots around `tick`. */
+ private remoteAt(slot: number, tick: number): PlayerState | null {
+ const snaps = this.snaps;
+ if (snaps.length === 0) return null;
+ let a = snaps[0];
+ let b = snaps[snaps.length - 1];
+ if (tick <= a.tick) return a.state.players[slot];
+ if (tick >= b.tick) return b.state.players[slot];
+ for (let i = snaps.length - 1; i > 0; i--) {
+ if (snaps[i - 1].tick <= tick) { a = snaps[i - 1]; b = snaps[i]; break; }
+ }
+ const t = (tick - a.tick) / Math.max(1, b.tick - a.tick);
+ const pa = a.state.players[slot];
+ const pb = b.state.players[slot];
+ if (!pa.alive || !pb.alive || Math.hypot(pb.x - pa.x, pb.z - pa.z) > 6) return t < 0.5 ? pa : pb;
+ return { ...pb, x: pa.x + (pb.x - pa.x) * t, z: pa.z + (pb.z - pa.z) * t, yaw: lerpAngle(pa.yaw, pb.yaw, t), pitch: pa.pitch + (pb.pitch - pa.pitch) * t, vx: pb.vx, vz: pb.vz };
+ }
+
+ /**
+ * What this client sees now as a WorldView: its own predicted self, the
+ * opponent interpolated, the predicted bolts, and the events that arrived
+ * since the last call (each once).
+ */
+ worldView(): WorldView {
+ const p = this.predicted as MatchState;
+ const players = p.players.map((pl) => (pl.slot === this.slot ? pl : this.remoteAt(pl.slot, this.renderTick()) ?? pl));
+ const events = this.viewEvents;
+ this.viewEvents = [];
+ return { tick: p.tick, phase: p.phase, round: p.round, scores: p.scores, players, bolts: p.bolts, events };
+ }
+
+ /** Presentation state for a frame at `nowMs` (own player smoothed between ticks). */
+ view(nowMs = this.now): ViewState | null {
+ if (!this.predicted) return null;
+ const alpha = Math.min(1, this.acc / (1000 / TICK_RATE));
+ const rt = this.renderTick(nowMs);
+ const remote = this.predicted.players.map((pl) => (pl.slot === this.slot ? null : this.remoteAt(pl.slot, rt)));
+ return buildView(this.ctx, this.predicted, this.prevPredicted ?? this.predicted, alpha, this.slot, remote, this.status);
+ }
+
+ /** Events to present since the last call (each once). */
+ drainEvents(): CombatEvent[] {
+ const out = this.out;
+ this.out = [];
+ return out;
+ }
+
+ /** The predicted match state (own present). */
+ get state(): MatchState | null {
+ return this.predicted;
+ }
+
+ /** The newest authoritative state received. */
+ get serverState(): MatchState | null {
+ return this.snaps.length ? this.snaps[this.snaps.length - 1].state : null;
+ }
+
+ /** Inputs sent but not yet confirmed by the server. */
+ get unconfirmed(): number {
+ return this.pending.length;
+ }
+
+ dispose(): void {
+ for (const u of this.unsub) u();
+ this.unsub = [];
+ }
+}
+
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/exploits.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/exploits.test.ts
new file mode 100644
index 0000000000..6d9a117a79
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/exploits.test.ts
@@ -0,0 +1,280 @@
+// @vitest-environment node
+/**
+ * Adversarial tests of the simulation: hit detection (tunnelling, cover,
+ * point blank, own bolts), fairness between the two slots, round flow edge
+ * cases and the heat edge. Each one is a way someone could try to break or
+ * cheese a duel.
+ */
+import { describe, expect, it } from "vitest";
+import { idleControl, makeInput } from "./input";
+import { yawOf } from "./math";
+import { createContext, createMatch, step } from "./sim";
+import { count, liveMatch, place, runner } from "./testing";
+import { DEFAULT_TUNING, withTuning } from "./tuning";
+import type { CombatEvent, MatchState } from "./types";
+
+/** No spread, bloom or recoil: every bolt goes exactly where it is aimed. */
+const EXACT = withTuning(DEFAULT_TUNING, {
+ blaster: {
+ hipSpreadDeg: 0, adsSpreadDeg: 0, moveSpreadHipDeg: 0, moveSpreadAdsDeg: 0,
+ bloomPerShotHipDeg: 0, bloomPerShotAdsDeg: 0, recoilPitchHipDeg: 0, recoilPitchAdsDeg: 0, recoilYawDeg: 0,
+ },
+});
+const ONE_SHOT = withTuning(EXACT, { blaster: { damageNear: 500, damageFar: 500 } });
+/** Bolts at 300 m/s: 5 m per tick, far more than any real bolt (max 96 m/s after parries). */
+const FAST = withTuning(EXACT, { blaster: { boltSpeed: 300 } });
+
+const MUZZLE_Y = DEFAULT_TUNING.body.muzzleHeight;
+
+/** Pitch from the muzzle to a height `y` at horizontal distance `d`. */
+const pitchTo = (y: number, d: number) => Math.atan2(y - MUZZLE_Y, d);
+
+function hits(ev: readonly CombatEvent[]) {
+ return ev.filter((e): e is Extract<CombatEvent, { type: "hit" }> => e.type === "hit");
+}
+function impacts(ev: readonly CombatEvent[]) {
+ return ev.filter((e): e is Extract<CombatEvent, { type: "impact" }> => e.type === "impact");
+}
+
+describe("hit detection", () => {
+ it("fast bolts do not tunnel through bodies: a 5 m step still hits a target 0.35 m off the line and misses one 0.45 m off", () => {
+ const { ctx, state } = liveMatch({ tuning: FAST });
+ for (const [off, expectHit] of [[0, true], [0.35, true], [0.45, false]] as const) {
+ // Shooter faces +Z; its muzzle sits 0.22 m to its right (-X).
+ const shooter = { x: 38.8, z: 8, yaw: 0 };
+ const mx = shooter.x - DEFAULT_TUNING.body.muzzleRight;
+ const r = runner(ctx, place(state, shooter, { x: mx + off, z: 30.4, yaw: Math.PI }));
+ const ev = r.run(20, { fire: true, yaw: 0, pitch: pitchTo(1.0, 22) }, { yaw: Math.PI });
+ expect(hits(ev).length > 0, `offset ${off}`).toBe(expectHit);
+ }
+ });
+
+ it("fast bolts do not tunnel through thin cover (wall pipes, a coolant run) and never pass the core", () => {
+ const { ctx, state } = liveMatch({ tuning: FAST });
+ // North at the far wall's pipe run (0.75 m deep, 0.9..2.3 m high).
+ let r = runner(ctx, place(state, { x: 38.8, z: 10, yaw: Math.PI }, { x: 70, z: 34 }));
+ let ev = r.run(20, { fire: true, yaw: Math.PI, pitch: 0 });
+ expect(impacts(ev)[0]?.collider).toBe("wall_pipes_w");
+ // East, low, at a waist-high coolant run (1.0 m) in front of a conduit.
+ r = runner(ctx, place(state, { x: 66, z: 12, yaw: Math.PI / 2 }, { x: 40, z: 34 }));
+ ev = r.run(20, { fire: true, yaw: Math.PI / 2, pitch: pitchTo(0.5, 6) });
+ expect(impacts(ev)[0]?.collider).toBe("coolant_0");
+ // Over the coolant run at chest height: on to the conduit behind it.
+ r = runner(ctx, place(state, { x: 66, z: 12, yaw: Math.PI / 2 }, { x: 40, z: 34 }));
+ ev = r.run(20, { fire: true, yaw: Math.PI / 2, pitch: 0 });
+ expect(impacts(ev)[0]?.collider).toBe("conduit_0");
+ // Across the shaft at a head behind the core: the core takes every bolt.
+ const s = place(state, { x: 38.8, z: 22 }, { x: 69.2, z: 22 });
+ r = runner(ctx, s);
+ ev = r.run(30, { fire: true, pitch: pitchTo(1.7, 30.4) });
+ expect(hits(ev)).toEqual([]);
+ expect(impacts(ev).every((e) => e.collider === "core")).toBe(true);
+ });
+
+ it("a waist-high coolant run stops low bolts but not a chest shot at someone behind it", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const shooter = { x: 64, z: 12, yaw: Math.PI / 2 };
+ const target = { x: 77.3, z: 12, yaw: -Math.PI / 2 };
+ const chest = runner(ctx, place(state, shooter, target));
+ expect(hits(chest.run(30, { fire: true, yaw: Math.PI / 2, pitch: pitchTo(1.15, 13) }, { yaw: -Math.PI / 2 })).length).toBeGreaterThan(0);
+ const low = runner(ctx, place(state, shooter, target));
+ const ev = low.run(30, { fire: true, yaw: Math.PI / 2, pitch: pitchTo(0.45, 13) }, { yaw: -Math.PI / 2 });
+ expect(hits(ev)).toEqual([]);
+ expect(impacts(ev)[0]?.collider).toMatch(/^coolant_/);
+ });
+
+ it("point blank: the shield still covers the front with the muzzle inside it, but not a flank", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const b = { x: 38.8, z: 20, yaw: Math.PI };
+ // In front, 1 m away: the muzzle is inside the 0.8 m shield radius.
+ const front = runner(ctx, place(state, { x: 38.8, z: 19, yaw: 0 }, b));
+ front.run(20, {}, { shield: true, yaw: Math.PI });
+ const ev = front.run(30, { fire: true, yaw: 0 }, { shield: true, yaw: Math.PI });
+ // (A glancing bolt may come back at the shooter; the shield bearer is never hit.)
+ expect(hits(ev).filter((h) => h.target === 1)).toEqual([]);
+ expect(count(ev, "block") + count(ev, "deflect") + count(ev, "parry")).toBeGreaterThan(0);
+ // From the side (90 deg off its aim): past the +-60 deg arc.
+ const side = runner(ctx, place(state, { x: 37.8, z: 20, yaw: Math.PI / 2 }, b));
+ side.run(20, {}, { shield: true, yaw: Math.PI });
+ expect(hits(side.run(30, { fire: true, yaw: Math.PI / 2 }, { shield: true, yaw: Math.PI })).length).toBeGreaterThan(0);
+ });
+
+ it("a bolt never hits its owner: parry rallies hand it over and stop after three reflections", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const A = { x: 38.8, z: 12 };
+ const B = { x: 38.8, z: 32 };
+ const r = runner(ctx, place(state, A, B));
+ // Each side raises its shield when a bolt it does not own is about to arrive.
+ const guard = (slot: number) => (s: MatchState) => {
+ const me = s.players[slot];
+ const o = s.players[1 - slot];
+ const incoming = s.bolts.some((b) => b.owner !== slot && Math.hypot(b.x - me.x, b.z - me.z) < 5 && (b.vx * (me.x - b.x) + b.vz * (me.z - b.z)) > 0);
+ return { yaw: yawOf(o.x - me.x, o.z - me.z), pitch: 0, shield: incoming };
+ };
+ const ev = r.run(1, { fire: true, yaw: 0 }, guard(1)).concat(r.run(200, guard(0), guard(1)));
+ // Three reflections, never a fourth: the bolt then ends on a shield or a body.
+ expect(count(ev, "parry")).toBe(DEFAULT_TUNING.shield.maxReflections);
+ for (const h of hits(ev)) expect(h.owner).not.toBe(h.target);
+ expect(r.state.bolts).toEqual([]);
+ });
+
+ it("a deflected bolt never comes back at the one who deflected it", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT, seed: 4 });
+ const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 20 }));
+ r.run(30, {}, { shield: true });
+ // Six bolts: the shield holds (it would break on the seventh).
+ const ev = r.run(70, { fire: true }, { shield: true });
+ expect(count(ev, "deflect", 1)).toBeGreaterThan(0);
+ for (const h of hits(ev)) expect(h.target).toBe(0);
+ });
+});
+
+describe("fairness between the slots", () => {
+ it("a lag-compensated shot never stops the other player's shot of the same tick: point-blank one-shots trade", () => {
+ const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
+ let s = place(state, { x: 38.8, z: 14 }, { x: 38.8, z: 20 });
+ for (let i = 0; i < 12; i++) s = step(s, [makeInput(i, idleControl(0, 0)), makeInput(i, idleControl(Math.PI, 0))], ctx).state;
+ const vt = s.tick - 10;
+ const res = step(s, [makeInput(20, { ...idleControl(0, 0), fire: true }, vt), makeInput(20, { ...idleControl(Math.PI, 0), fire: true }, vt)], ctx);
+ expect(count(res.events, "shot")).toBe(2);
+ expect(res.events.filter((e) => e.type === "death").map((e) => (e as { player: number }).player).sort()).toEqual([0, 1]);
+ // Swapping who is slot 0 gives the mirror result.
+ expect(res.state.players.every((p) => !p.alive)).toBe(true);
+ });
+
+ it("mirror-image duels play out as mirror images (no hidden slot order)", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const run = (swap: boolean) => {
+ const a = { x: 38.8, z: 12 };
+ const b = { x: 38.8, z: 28 };
+ const r = runner(ctx, swap ? place(state, b, a) : place(state, a, b));
+ const shooter = swap ? 1 : 0;
+ // The shooter stands at `a` facing +Z in both runs; only its slot differs.
+ const ctl = (s: MatchState) => ({ fire: s.tick % 30 < 12, yaw: 0 });
+ r.run(240, swap ? undefined : ctl, swap ? ctl : undefined);
+ return { damage: r.state.players[1 - shooter].stats.damageTaken, shots: r.state.players[shooter].stats.shots };
+ };
+ // Spread is seeded per slot, so only exact (spread-free) shots must match.
+ const a = run(false);
+ expect(a.damage).toBeGreaterThan(40);
+ expect(run(true)).toEqual(a);
+ });
+});
+
+describe("round flow edge cases", () => {
+ const live = (r: ReturnType<typeof runner>) => {
+ for (let i = 0; i < 2000 && r.state.phase !== "live"; i++) r.run(1);
+ };
+
+ it("a double knock-out scores nobody, and five of them end the match as a draw", () => {
+ const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
+ const r = runner(ctx, state);
+ const ends: Extract<CombatEvent, { type: "round_end" }>[] = [];
+ for (let round = 1; round <= 5; round++) {
+ live(r);
+ r.state = place(r.state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 });
+ const ev = r.run(30, { fire: true }, { fire: true });
+ ends.push(...ev.filter((e): e is Extract<CombatEvent, { type: "round_end" }> => e.type === "round_end"));
+ }
+ expect(ends.map((e) => e.reason)).toEqual(["trade", "trade", "trade", "trade", "trade"]);
+ expect(r.state.scores).toEqual([0, 0]);
+ expect(r.state.phase).toBe("ended");
+ expect(r.state.winner).toBe(-1);
+ expect(r.state.endReason).toBe("draw");
+ });
+
+ it("time running out with equal health is a drawn round, not a win for slot 0", () => {
+ const { ctx, state } = liveMatch({ config: { roundTimeLimitTicks: 120 } });
+ const r = runner(ctx, state);
+ const ev = r.run(130);
+ const end = ev.find((e) => e.type === "round_end") as Extract<CombatEvent, { type: "round_end" }>;
+ expect(end.reason).toBe("time");
+ expect(end.winner).toBe(-1);
+ expect(r.state.scores).toEqual([0, 0]);
+ });
+
+ it("the dead cannot shoot, roll, raise a shield or move until the next round", () => {
+ const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
+ const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
+ r.run(30, { fire: true });
+ expect(r.state.players[1].alive).toBe(false);
+ const at = { x: r.state.players[1].x, z: r.state.players[1].z };
+ const ev = r.run(60, {}, (s) => ({ fire: true, moveY: 1, shield: s.tick % 2 === 0, dodge: s.tick % 2 === 0, vent: true }));
+ expect(ev.filter((e) => "player" in e && e.player === 1 && e.type !== "ping")).toEqual([]);
+ expect({ x: r.state.players[1].x, z: r.state.players[1].z }).toEqual(at);
+ });
+
+ it("a shield held through the round change needs a fresh press, and presses in the countdown do nothing", () => {
+ const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
+ const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
+ r.run(30, { fire: true });
+ expect(r.state.phase).toBe("round_end");
+ // Slot 0 holds the shield and mashes fire, roll and vent through the pause and the countdown.
+ const ev: CombatEvent[] = [];
+ const mash = (s: MatchState) => ({ shield: true, dodge: s.tick % 3 === 0, vent: s.tick % 3 === 1, fire: true });
+ for (let i = 0; i < 1000 && r.state.phase !== "live"; i++) ev.push(...r.run(1, mash));
+ expect(count(ev, "dodge") + count(ev, "vent_start") + count(ev, "shot") + count(ev, "shield_up")).toBe(0);
+ expect(r.state.phase).toBe("live");
+ r.run(5, { shield: true });
+ expect(r.state.players[0].shieldUp).toBe(false);
+ r.run(1);
+ r.run(2, { shield: true });
+ expect(r.state.players[0].shieldUp).toBe(true);
+ });
+
+ it("a forfeit works in the countdown and in the pause between rounds", () => {
+ const ctx = createContext();
+ const counting = runner(ctx, createMatch(ctx, { seed: 2, playerIds: ["a", "b"] }));
+ expect(counting.state.phase).toBe("countdown");
+ const e1 = counting.run(1, {}, { forfeit: true }).find((e) => e.type === "match_end") as Extract<CombatEvent, { type: "match_end" }>;
+ expect(e1.winner).toBe(0);
+ const { ctx: oneCtx, state } = liveMatch({ tuning: ONE_SHOT });
+ const one = runner(oneCtx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
+ one.run(30, { fire: true });
+ expect(one.state.phase).toBe("round_end");
+ const e2 = one.run(1, { forfeit: true }).find((e) => e.type === "match_end") as Extract<CombatEvent, { type: "match_end" }>;
+ expect(e2.winner).toBe(1);
+ expect(e2.reason).toBe("forfeit");
+ });
+});
+
+describe("the heat edge", () => {
+ it("eleven bolts and a timed vent, again and again, never overheat; the twelfth always does", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 70, z: 30 }));
+ let overheats = 0;
+ let shots = 0;
+ for (let cycle = 0; cycle < 4; cycle++) {
+ // Eleven bolts at the far wall.
+ for (let i = 0; i < 11 * 12 && r.state.players[0].shotCount < shots + 11; i++) {
+ const ev = r.run(1, { fire: true, yaw: Math.PI });
+ overheats += count(ev, "overheat");
+ }
+ shots += 11;
+ r.run(1);
+ expect(r.state.players[0].heat).toBeGreaterThan(90);
+ r.run(1, { vent: true });
+ const p = r.state.players[0];
+ expect(p.ventStart).toBeGreaterThanOrEqual(0);
+ r.run(Math.max(0, p.ventWinStart + 1 - r.state.tick));
+ expect(count(r.run(1, { vent: true }), "vent_perfect")).toBe(1);
+ expect(r.state.players[0].heat).toBe(0);
+ }
+ expect(overheats).toBe(0);
+ const ev = r.run(12 * 12, { fire: true, yaw: Math.PI });
+ expect(count(ev, "overheat")).toBe(1);
+ });
+
+ it("holding the vent key does not start vent after vent, and spamming it spends the one timing try", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 70, z: 30 }));
+ r.run(6 * 12, { fire: true, yaw: Math.PI });
+ const ev = r.run(200, { vent: true });
+ expect(count(ev, "vent_start")).toBe(1);
+ const spam = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 70, z: 30 }));
+ spam.run(6 * 12, { fire: true, yaw: Math.PI });
+ const ev2 = spam.run(200, (s) => ({ vent: s.tick % 2 === 0 }));
+ expect(count(ev2, "vent_perfect")).toBe(0);
+ expect(count(ev2, "vent_miss")).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/balance.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/balance.test.ts
new file mode 100644
index 0000000000..b9a68580f4
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/balance.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment node
+/**
+ * Balance smoke test: a handful of headless duels per key pairing, enough to
+ * catch a balance regression. The full matrix (hundreds of duels per
+ * pairing) runs from harness/cli.ts, or here with COMBAT_BALANCE=full.
+ */
+import { describe, expect, it } from "vitest";
+import { createContext } from "../sim";
+import { CROSS, EXPLOITS, formatReport, HUMANS, runBalance, runPairing, TIER_LADDER, VS_ELITE } from "./balance";
+import { runDuel } from "./duel";
+import { strategy } from "./strategies";
+
+const full = typeof process !== "undefined" && process.env.COMBAT_BALANCE === "full";
+
+describe("balance (smoke)", () => {
+ const ctx = createContext();
+
+ it("higher tiers win more", () => {
+ const { report } = runPairing(ctx, "elite", "normal", 6, 11);
+ expect(report.winRateA).toBeGreaterThanOrEqual(4 / 6);
+ expect(report.timeoutRounds).toBe(0);
+ expect(report.accuracy[0]).toBeGreaterThan(report.accuracy[1]);
+ });
+
+ it("one-trick strategies do not beat the hard bot", () => {
+ for (const trick of ["spam", "turtle", "camper"] as const) {
+ const { report } = runPairing(ctx, "hard", trick, 6, 17);
+ expect(report.winRateA, trick).toBeGreaterThanOrEqual(0.5);
+ }
+ });
+
+ it("a headless duel is reproducible from its seed", () => {
+ const a = runDuel({ ctx, seed: 99, players: [strategy("hard"), strategy("elite")] });
+ const b = runDuel({ ctx, seed: 99, players: [strategy("hard"), strategy("elite")] });
+ expect(a).toEqual(b);
+ expect(a.rounds.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it.runIf(full)("full matrix", () => {
+ const pairings = [...TIER_LADDER, ...HUMANS, ...EXPLOITS, ...VS_ELITE, ...CROSS];
+ const reports = runBalance({ pairings, duels: 200, seed: 1, onPairing: (r) => console.log(formatReport(r)) });
+ expect(reports.length).toBe(pairings.length);
+ }, 3_600_000);
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/balance.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/balance.ts
new file mode 100644
index 0000000000..96e8ec5338
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/balance.ts
@@ -0,0 +1,151 @@
+/**
+ * Balance runs: many headless duels per pairing, both slots alternated, and
+ * the numbers that tell whether the duel is fair and skill-based: win rate,
+ * round length, time to kill, accuracy, parries, blocks, overheats, perfect
+ * vents, and the win rate of each spawn side.
+ */
+import { createContext, type SimContext } from "../sim";
+import { DEFAULT_TUNING, TICK_RATE, type CombatTuning } from "../tuning";
+import { runDuel, type DuelResult } from "./duel";
+import { strategy, TRICK_IDS, type StrategyId } from "./strategies";
+
+export interface PairingReport {
+ a: StrategyId;
+ b: StrategyId;
+ duels: number;
+ /** Share of duels a won (draws count half). */
+ winRateA: number;
+ /** Share of decided rounds a won. */
+ roundWinRateA: number;
+ draws: number;
+ roundsPerDuel: number;
+ roundSeconds: number;
+ timeoutRounds: number;
+ ttkSeconds: number;
+ /** Per side of the pairing: a then b. */
+ accuracy: [number, number];
+ headshotShare: [number, number];
+ parriesPerRound: [number, number];
+ blocksPerRound: [number, number];
+ /** Share of the bolts reaching a player that the shield parried. */
+ parryRate: [number, number];
+ overheatsPerRound: [number, number];
+ perfectVentRate: [number, number];
+ dodgesPerRound: [number, number];
+ /** Round win rate of spawn side 0 (both players together). */
+ side0RoundWinRate: number;
+}
+
+export interface BalanceOptions {
+ pairings: readonly (readonly [StrategyId, StrategyId])[];
+ duels: number;
+ seed?: number;
+ tuning?: CombatTuning;
+ onPairing?: (r: PairingReport) => void;
+}
+
+const sum = (xs: readonly number[]) => xs.reduce((a, b) => a + b, 0);
+const ratio = (a: number, b: number) => (b > 0 ? a / b : 0);
+
+export function runPairing(ctx: SimContext, a: StrategyId, b: StrategyId, duels: number, seed0: number): { report: PairingReport; results: DuelResult[] } {
+ const results: DuelResult[] = [];
+ let winsA = 0;
+ let draws = 0;
+ const S = [[0, 0], [0, 0]].map(() => ({ shots: 0, hits: 0, heads: 0, parries: 0, blocks: 0, overheats: 0, perfect: 0, ventTries: 0, dodges: 0, incoming: 0 }));
+ let rounds = 0;
+ let roundTicks = 0;
+ let timeouts = 0;
+ let side0Wins = 0;
+ let decided = 0;
+ let roundsA = 0;
+ const ttk: number[] = [];
+ for (let i = 0; i < duels; i++) {
+ const swap = i % 2 === 1;
+ const seed = (seed0 + i * 7919) >>> 0;
+ const r = runDuel({ ctx, seed, players: swap ? [strategy(b), strategy(a)] : [strategy(a), strategy(b)] });
+ results.push(r);
+ const slotA = swap ? 1 : 0;
+ if (r.winner === slotA) winsA++;
+ else if (r.winner < 0) draws++;
+ for (const [k, slot] of [[0, slotA], [1, 1 - slotA]] as const) {
+ const st = r.stats[slot];
+ const acc = S[k];
+ acc.shots += st.shots; acc.hits += st.hits; acc.heads += st.headshots; acc.parries += st.parries; acc.blocks += st.blocks;
+ acc.overheats += st.overheats; acc.perfect += st.perfectVents; acc.ventTries += st.perfectVents + st.ventMisses; acc.dodges += st.dodges;
+ acc.incoming += r.incoming[slot];
+ }
+ rounds += r.rounds.length;
+ for (const rd of r.rounds) {
+ roundTicks += rd.ticks;
+ if (rd.reason === "time") timeouts++;
+ if (rd.winner >= 0) { decided++; if (rd.sides[rd.winner] === 0) side0Wins++; if (rd.winner === slotA) roundsA++; }
+ }
+ ttk.push(...r.ttk);
+ }
+ const per = (k: 0 | 1, f: (x: (typeof S)[number]) => number) => f(S[k]);
+ const pair = (f: (x: (typeof S)[number]) => number): [number, number] => [per(0, f), per(1, f)];
+ const report: PairingReport = {
+ a, b, duels,
+ winRateA: (winsA + draws / 2) / duels,
+ roundWinRateA: ratio(roundsA, decided),
+ draws,
+ roundsPerDuel: rounds / duels,
+ roundSeconds: ratio(roundTicks, rounds) / TICK_RATE,
+ timeoutRounds: timeouts,
+ ttkSeconds: ratio(sum(ttk), ttk.length) / TICK_RATE,
+ accuracy: pair((x) => ratio(x.hits, x.shots)),
+ headshotShare: pair((x) => ratio(x.heads, x.hits)),
+ parriesPerRound: pair((x) => ratio(x.parries, rounds)),
+ blocksPerRound: pair((x) => ratio(x.blocks, rounds)),
+ parryRate: pair((x) => ratio(x.parries, x.incoming)),
+ overheatsPerRound: pair((x) => ratio(x.overheats, rounds)),
+ perfectVentRate: pair((x) => ratio(x.perfect, x.ventTries)),
+ dodgesPerRound: pair((x) => ratio(x.dodges, rounds)),
+ side0RoundWinRate: ratio(side0Wins, decided),
+ };
+ return { report, results };
+}
+
+export function runBalance(o: BalanceOptions): PairingReport[] {
+ const ctx = createContext(undefined, o.tuning ?? DEFAULT_TUNING);
+ const out: PairingReport[] = [];
+ o.pairings.forEach(([a, b], i) => {
+ const { report } = runPairing(ctx, a, b, o.duels, (o.seed ?? 1) + i * 104729);
+ out.push(report);
+ o.onPairing?.(report);
+ });
+ return out;
+}
+
+type Pairing = readonly [StrategyId, StrategyId];
+
+export const TIER_LADDER: readonly Pairing[] = [
+ ["hard", "normal"], ["elite", "hard"], ["elite", "normal"], ["normal", "normal"], ["hard", "hard"], ["elite", "elite"],
+];
+
+/** The person models against the tiers: where a skilled and an average player stand. */
+export const HUMANS: readonly Pairing[] = [
+ ["skilled", "normal"], ["skilled", "hard"], ["skilled", "elite"], ["average", "normal"], ["average", "hard"], ["average", "elite"],
+];
+
+/** One-trick strategies against the hard bot (same aim, one behaviour forced). */
+export const EXPLOITS: readonly Pairing[] = TRICK_IDS.map((t): Pairing => ["hard", t]);
+
+/** A skilled person playing one trick against the elite bot: must not beat plain skilled play. */
+export const VS_ELITE: readonly Pairing[] = TRICK_IDS.filter((t) => t !== "turtle").map((t): Pairing => ["elite", `skilled+${t}`]);
+
+/** Tricks against each other: no one trick should beat them all. */
+export const CROSS: readonly Pairing[] = [
+ ["spam", "blocker"], ["spam", "flicker"], ["dodger", "spam"], ["rusher", "camper"], ["flicker", "rusher"],
+ ["dodger", "blocker"], ["dodger", "flicker"], ["blocker", "flicker"], ["blocker", "rusher"], ["kiter", "brawler"],
+ ["kiter", "dodger"], ["edge", "blocker"], ["jiggle", "kiter"], ["normal", "spam"], ["normal", "turtle"],
+];
+
+export function formatReport(r: PairingReport): string {
+ const f = (v: number, d = 2) => v.toFixed(d);
+ const p = (v: number) => `${(v * 100).toFixed(0)}%`;
+ return `${r.a.padEnd(7)} vs ${r.b.padEnd(7)} n=${r.duels} winA=${p(r.winRateA)} roundsA=${p(r.roundWinRateA)} draws=${r.draws} rounds=${f(r.roundsPerDuel)} round=${f(r.roundSeconds, 1)}s timeouts=${r.timeoutRounds} ttk=${f(r.ttkSeconds)}s`
+ + ` acc=${p(r.accuracy[0])}/${p(r.accuracy[1])} head=${p(r.headshotShare[0])}/${p(r.headshotShare[1])} parry=${p(r.parryRate[0])}/${p(r.parryRate[1])}`
+ + ` blocks/rd=${f(r.blocksPerRound[0])}/${f(r.blocksPerRound[1])} oh/rd=${f(r.overheatsPerRound[0])}/${f(r.overheatsPerRound[1])}`
+ + ` vent=${p(r.perfectVentRate[0])}/${p(r.perfectVentRate[1])} dodge/rd=${f(r.dodgesPerRound[0])}/${f(r.dodgesPerRound[1])} side0=${p(r.side0RoundWinRate)}`;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/cli.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/cli.ts
new file mode 100644
index 0000000000..38b1846c59
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/cli.ts
@@ -0,0 +1,71 @@
+/**
+ * Heavy balance run from a shell (not part of the test suite):
+ *
+ * npx esbuild src/components/society/verse/combat/harness/cli.ts --bundle \
+ * --platform=node --format=esm --outfile=<tmp>/balance.mjs
+ * node <tmp>/balance.mjs [duelsPerPairing] [ladder|humans|exploits|elite|cross|all|a:b,c:d] [seed] [tuningPatchJson|-] [jobs]
+ *
+ * e.g. `node balance.mjs 300 hard:dodger 1 '{"dodge":{"iframeTicks":9}}'` to
+ * try a change, or `node balance.mjs 300 elite:skilled+kiter` for one trick.
+ * Strategy ids: normal, hard, elite, skilled, average, a trick (on the hard
+ * bot), or base+trick; harness/strategies.ts lists them. With `jobs` > 1 every
+ * pairing runs in its own process (same seeds, same results as one process).
+ * Prints one line per pairing and a JSON summary at the end.
+ */
+import { spawn } from "node:child_process";
+import { DEFAULT_TUNING, withTuning, type CombatTuning, type DeepPartial } from "../tuning";
+import { CROSS, EXPLOITS, formatReport, HUMANS, runBalance, TIER_LADDER, VS_ELITE, type PairingReport } from "./balance";
+import type { StrategyId } from "./strategies";
+
+const duels = Number(process.argv[2] ?? 200);
+const which = process.argv[3] ?? "all";
+const seed = Number(process.argv[4] ?? 1);
+const patchArg = process.argv[5] && process.argv[5] !== "-" ? process.argv[5] : "";
+const jobs = Number(process.argv[6] ?? 1);
+const patch = patchArg ? (JSON.parse(patchArg) as DeepPartial<CombatTuning>) : null;
+const sets: Record<string, readonly (readonly [StrategyId, StrategyId])[]> = {
+ ladder: TIER_LADDER, humans: HUMANS, exploits: EXPLOITS, elite: VS_ELITE, cross: CROSS,
+ all: [...TIER_LADDER, ...HUMANS, ...EXPLOITS, ...VS_ELITE, ...CROSS],
+};
+const pairings = sets[which] ?? which.split(",").map((p) => p.split(":") as [StrategyId, StrategyId]);
+const tuning = patch ? withTuning(DEFAULT_TUNING, patch) : DEFAULT_TUNING;
+const started = Date.now();
+
+/** Run pairing i in a child process (seeded exactly as the sequential run seeds it). */
+function child(i: number): Promise<PairingReport> {
+ const [a, b] = pairings[i];
+ const args = [process.argv[1], String(duels), `${a}:${b}`, String(seed + i * 104729), patchArg || "-", "1"];
+ return new Promise((resolve, reject) => {
+ const p = spawn(process.execPath, args, { stdio: ["ignore", "pipe", "inherit"] });
+ let out = "";
+ p.stdout.on("data", (d: Buffer) => { out += d.toString(); });
+ p.on("close", (code) => {
+ const last = out.trim().split("\n").pop() ?? "";
+ try { resolve((JSON.parse(last) as PairingReport[])[0]); } catch { reject(new Error(`pairing ${a}:${b} failed (${code})`)); }
+ });
+ });
+}
+
+async function main(): Promise<void> {
+ let reports: PairingReport[];
+ if (jobs > 1 && pairings.length > 1) {
+ reports = new Array(pairings.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < pairings.length) {
+ const i = next++;
+ reports[i] = await child(i);
+ console.log(formatReport(reports[i]));
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(jobs, pairings.length) }, worker));
+ console.log("in order:");
+ for (const r of reports) console.log(formatReport(r));
+ } else {
+ reports = runBalance({ pairings, duels, seed, tuning, onPairing: (r) => console.log(formatReport(r)) });
+ }
+ console.log(`done: ${reports.length} pairings x ${duels} duels in ${((Date.now() - started) / 1000).toFixed(1)} s`);
+ console.log(JSON.stringify(reports));
+}
+
+void main();
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/duel.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/duel.ts
new file mode 100644
index 0000000000..8f6a1c00b6
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/duel.ts
@@ -0,0 +1,98 @@
+/**
+ * Headless duels for tests and balance: two controllers (bots or scripted
+ * strategies) observe the authoritative state through `observe` (the same
+ * perception a player has) and answer with controls, turned into
+ * InputCommands exactly as for a human. No network; see netcode tests for
+ * the same duel over a transport.
+ */
+import { makeInput, type ControlState } from "../input";
+import { observe, type Observation } from "../observe";
+import { createMatch, step, type SimContext } from "../sim";
+import type { CombatEvent, EndReason, MatchConfig, PlayerStats } from "../types";
+
+export interface Controller {
+ readonly label: string;
+ think(obs: Observation): ControlState;
+}
+
+export type ControllerFactory = (slot: number, seed: number, ctx: SimContext) => Controller;
+
+export interface RoundRecord {
+ round: number;
+ winner: number;
+ reason: "kill" | "time" | "trade";
+ ticks: number;
+ /** Side (spawn) each slot had. */
+ sides: number[];
+}
+
+export interface DuelResult {
+ seed: number;
+ labels: string[];
+ winner: number;
+ reason: EndReason;
+ scores: number[];
+ ticks: number;
+ rounds: RoundRecord[];
+ stats: PlayerStats[];
+ /** Ticks from the first hit on a full-health player to their death. */
+ ttk: number[];
+ /** Bolts that reached each player (blocks, parries, deflects, hits). */
+ incoming: number[];
+ events?: CombatEvent[];
+}
+
+export interface DuelOptions {
+ ctx: SimContext;
+ seed: number;
+ players: readonly [ControllerFactory, ControllerFactory];
+ config?: Partial<MatchConfig>;
+ /** Safety cap (ticks). */
+ maxTicks?: number;
+ keepEvents?: boolean;
+}
+
+export function runDuel(o: DuelOptions): DuelResult {
+ const { ctx, seed } = o;
+ const ctrls = o.players.map((f, slot) => f(slot, seed * 2 + slot + 1, ctx));
+ let state = createMatch(ctx, { seed, playerIds: ctrls.map((c, i) => `${c.label}#${i}`), config: o.config });
+ const seq = [0, 0];
+ let prev: readonly CombatEvent[] = [];
+ const rounds: RoundRecord[] = [];
+ const ttk: number[] = [];
+ const engaged = [-1, -1];
+ const incoming = [0, 0];
+ const all: CombatEvent[] = [];
+ let roundStart = 0;
+ const max = o.maxTicks ?? 60 * 60 * 12;
+ while (state.phase !== "ended" && state.tick < max) {
+ const view = { ...state, events: prev };
+ const cmds = [0, 1].map((slot) => makeInput(seq[slot]++, ctrls[slot].think(observe(view, slot, ctx.arena, ctx.tuning))));
+ const res = step(state, cmds, ctx);
+ for (const e of res.events) {
+ if (e.type === "round_start") { roundStart = e.tick; engaged[0] = engaged[1] = -1; }
+ else if (e.type === "hit" && engaged[e.target] < 0) engaged[e.target] = e.tick;
+ else if (e.type === "death" && engaged[e.player] >= 0) ttk.push(e.tick - engaged[e.player]);
+ else if (e.type === "round_end") rounds.push({ round: e.round, winner: e.winner, reason: e.reason, ticks: e.tick - roundStart, sides: state.players.map((p) => p.side) });
+ if (e.type === "hit") incoming[e.target]++;
+ else if (e.type === "block" || e.type === "parry" || e.type === "deflect") incoming[e.player]++;
+ }
+ state = res.state;
+ for (const p of state.players) if (p.health >= ctx.tuning.health.max) engaged[p.slot] = -1;
+ if (o.keepEvents) all.push(...res.events);
+ prev = res.events;
+ }
+ return {
+ seed,
+ labels: ctrls.map((c) => c.label),
+ winner: state.winner ?? -1,
+ reason: state.endReason ?? "cancelled",
+ scores: state.scores.slice(),
+ ticks: state.tick,
+ rounds,
+ stats: state.players.map((p) => ({ ...p.stats })),
+ ttk,
+ incoming,
+ events: o.keepEvents ? all : undefined,
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/exploits.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/exploits.test.ts
new file mode 100644
index 0000000000..57e6d4eddc
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/exploits.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+/**
+ * Exploit smoke test: the cheap strategies found in the adversarial pass, in
+ * a small, fast configuration (a few seeded duels each, lenient bounds). The
+ * real numbers come from the full matrix (balance.test.ts with
+ * COMBAT_BALANCE=full, or cli.ts) and are in docs/verse/combat.md.
+ */
+import { describe, expect, it } from "vitest";
+import { createContext } from "../sim";
+import { runPairing } from "./balance";
+import type { StrategyId } from "./strategies";
+
+describe("exploits (smoke)", () => {
+ const ctx = createContext();
+
+ it("keeping your distance across the shaft does not beat the bot", () => {
+ // Before the bots stopped walking straight at a far shooter, holding 28 m won 62%.
+ const { report } = runPairing(ctx, "hard", "kiter", 10, 23);
+ expect(report.winRateA).toBeGreaterThanOrEqual(0.4);
+ expect(report.timeoutRounds).toBe(0);
+ });
+
+ it("point-blank orbiting and rushing lose clearly to the hard bot", () => {
+ // 300 duels: the hard bot wins 70..73% of the rounds against either.
+ for (const trick of ["circle", "rusher"] as const satisfies readonly StrategyId[]) {
+ const { report } = runPairing(ctx, "hard", trick, 8, 29);
+ expect(report.roundWinRateA, trick).toBeGreaterThanOrEqual(0.55);
+ }
+ });
+
+ it("playing for the clock and watching the other spawn are no walkover", () => {
+ // 300 duels: the hard bot wins 59% (hider) and 54% (watcher) of the rounds.
+ for (const trick of ["hider", "watcher"] as const satisfies readonly StrategyId[]) {
+ const { report } = runPairing(ctx, "hard", trick, 16, 43);
+ expect(report.roundWinRateA, trick).toBeGreaterThanOrEqual(0.35);
+ }
+ });
+
+ it("a skilled person (200..250 ms reactions) beats the lower tiers and finds the elite bot hard but beatable", () => {
+ const vsNormal = runPairing(ctx, "skilled", "normal", 8, 31).report;
+ expect(vsNormal.winRateA).toBeGreaterThanOrEqual(0.75);
+ // Rounds over 24 duels (about 60 rounds; 300 duels give 44%): neither a walkover nor hopeless.
+ const vsElite = runPairing(ctx, "skilled", "elite", 24, 41).report;
+ expect(vsElite.roundWinRateA).toBeGreaterThan(0.2);
+ expect(vsElite.roundWinRateA).toBeLessThan(0.65);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/strategies.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/strategies.ts
new file mode 100644
index 0000000000..e934990234
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/harness/strategies.ts
@@ -0,0 +1,163 @@
+/**
+ * The players the balance harness pits against each other:
+ *
+ * - the bot tiers (normal, hard, elite);
+ * - "skilled", a stand-in for a skilled person: human reaction times
+ * (200..250 ms), good but imperfect mouse aim, decent timing; it plays
+ * every mechanic, so its results estimate how a practised player fares;
+ * - one-trick strategies: a base player (the hard bot unless named) with one
+ * behaviour forced, so a result shows what the trick itself is worth.
+ * "elite+dodger" is the elite bot rolling all the time, "skilled+circle" a
+ * skilled person orbiting at point blank, plain "dodger" = "hard+dodger".
+ */
+import { BotBrain, type BotOverrides } from "../bot/brain";
+import { botParams, type BotParams, type BotTier } from "../bot/tiers";
+import type { ControllerFactory } from "./duel";
+
+export type BaseId = BotTier | "skilled" | "average";
+
+export type TrickId =
+ | "spam" // holds the trigger whenever it sees the opponent, never vents, never shields
+ | "turtle" // shield up all the time, never fires
+ | "blocker" // blocks every bolt it sees (no planned parries), fires otherwise
+ | "camper" // sits in cover near its spawn and waits
+ | "dodger" // rolls whenever the roll is ready
+ | "flicker" // flicks the shield for parries as fast as the lockout allows
+ | "rusher" // runs straight at the opponent
+ | "circle" // closes in and orbits the opponent at point blank, firing
+ | "jiggle" // reverses its strafe every 140..300 ms (A-D spam)
+ | "hider" // once ahead on health, breaks off and hides (plays for the clock)
+ | "edge" // fires to the edge of an overheat, then vents at once, timed
+ | "parrier" // tries to parry every bolt it sees, nothing else
+ | "watcher" // holds a spot that sees the other spawn, pre-aimed
+ | "kiter" // keeps 28 m away and fights from range, in sights
+ | "brawler"; // fights at 6 m (close, but not hugging)
+
+export type StrategyId = BaseId | TrickId | `${BaseId}+${TrickId}`;
+
+/**
+ * A skilled person as bot numbers: reaction 225 +- 18 ms (nearly all within
+ * 200..250 ms), a visual-motor tracking delay of 110 ms, aim error a little
+ * above the elite bot's but much faster flicks, heads more often, vents and
+ * parries timed by eye (55..60 ms sd), and aims at the middle of an A-D
+ * wobble once it sees one. Between the hard and elite tiers on paper; what
+ * decides its games is the same rules and perception as the bots'.
+ */
+export const SKILLED_HUMAN: BotParams = {
+ tier: "elite",
+ reactionMs: [225, 18],
+ trackLatencyMs: 110,
+ aimNoiseDeg: 1.0,
+ aimNoiseRate: 2.0,
+ acquireErrorDeg: 4.0,
+ acquireMs: 380,
+ turnRateDeg: 900,
+ aimStiffness: 14,
+ leadSkill: 0.85,
+ leadNoise: 0.18,
+ motionWindowMs: 250,
+ recoilComp: 0.8,
+ fireTolerance: 1.5,
+ heatCap: 90,
+ ventTimingSdMs: 60,
+ parryChance: 0.5,
+ parryTimingSdMs: 55,
+ blockChance: 0.65,
+ dodgeChance: 0.3,
+ strafeMs: [300, 800],
+ coverUse: 0.7,
+ flankUse: 0.55,
+ aggression: 0.65,
+ baitPunish: 0.6,
+ decisionMs: 200,
+ headAim: 0.3,
+ adsRange: 11,
+ hearingErrorM: 3,
+};
+
+/**
+ * An average player: slower (270 +- 40 ms) and looser aim, overheats now and
+ * then, parries rarely. Where the normal tier should be a fair fight.
+ */
+export const AVERAGE_HUMAN: BotParams = {
+ tier: "normal",
+ reactionMs: [270, 40],
+ trackLatencyMs: 140,
+ aimNoiseDeg: 1.45,
+ aimNoiseRate: 1.7,
+ acquireErrorDeg: 6,
+ acquireMs: 550,
+ turnRateDeg: 600,
+ aimStiffness: 10,
+ leadSkill: 0.7,
+ leadNoise: 0.3,
+ motionWindowMs: 0,
+ recoilComp: 0.5,
+ fireTolerance: 1.8,
+ heatCap: 101,
+ ventTimingSdMs: 110,
+ parryChance: 0.25,
+ parryTimingSdMs: 90,
+ blockChance: 0.5,
+ dodgeChance: 0.2,
+ strafeMs: [400, 1100],
+ coverUse: 0.5,
+ flankUse: 0.3,
+ aggression: 0.6,
+ baitPunish: 0.2,
+ decisionMs: 280,
+ headAim: 0.15,
+ adsRange: 12,
+ hearingErrorM: 4,
+};
+
+const TRICKS: Record<TrickId, { overrides: BotOverrides; params?: Partial<BotParams> }> = {
+ spam: { overrides: { fire: "spam", vent: "never", shield: "never", dodge: "never", action: "fight" } },
+ turtle: { overrides: { fire: "never", shield: "always", dodge: "never", action: "push" } },
+ blocker: { overrides: { shield: "block", dodge: "never" } },
+ camper: { overrides: { action: "camp" } },
+ dodger: { overrides: { dodge: "spam" } },
+ flicker: { overrides: { shield: "flick", dodge: "never" } },
+ rusher: { overrides: { action: "push", dodge: "never" } },
+ circle: { overrides: { action: "circle", dodge: "never" } },
+ jiggle: { overrides: { strafe: "jiggle" } },
+ hider: { overrides: { hideWhenAhead: true } },
+ edge: { overrides: { vent: "edge" }, params: { heatCap: 100, ventTimingSdMs: 35 } },
+ parrier: { overrides: {}, params: { parryChance: 1, blockChance: 0.15, dodgeChance: 0 } },
+ watcher: { overrides: { action: "watch" } },
+ kiter: { overrides: { range: 28 }, params: { adsRange: 0, aggression: 0.2 } },
+ brawler: { overrides: { range: 6 }, params: { adsRange: 30, aggression: 0.9 } },
+};
+
+export const TRICK_IDS = Object.keys(TRICKS) as TrickId[];
+
+export const STRATEGIES: readonly StrategyId[] = ["normal", "hard", "elite", "skilled", "average", ...TRICK_IDS];
+
+function baseParams(base: BaseId): BotParams {
+ return base === "skilled" ? { ...SKILLED_HUMAN } : base === "average" ? { ...AVERAGE_HUMAN } : botParams(base);
+}
+
+/** Split "skilled+dodger" into its base and trick; a bare trick runs on the hard bot. */
+export function parseStrategy(id: StrategyId): { base: BaseId; trick: TrickId | null } {
+ const [a, b] = id.split("+") as [string, string | undefined];
+ if (b) return { base: a as BaseId, trick: b as TrickId };
+ if (a === "normal" || a === "hard" || a === "elite" || a === "skilled" || a === "average") return { base: a, trick: null };
+ return { base: "hard", trick: a as TrickId };
+}
+
+export function strategy(id: StrategyId): ControllerFactory {
+ const { base, trick } = parseStrategy(id);
+ // Harness experiments: "rangeN" fights at N metres, "approachN" walks in at N/10 without a reason,
+ // "mwN" reads the target's motion over N ms.
+ const ranged: { overrides: BotOverrides; params?: Partial<BotParams> } | null =
+ trick && /^range\d+$/.test(trick) ? { overrides: { range: Number(trick.slice(5)) } }
+ : trick && /^approach\d+$/.test(trick) ? { overrides: { approach: Number(trick.slice(8)) / 10 } }
+ : trick && /^mw\d+$/.test(trick) ? { overrides: {}, params: { motionWindowMs: Number(trick.slice(2)) } } : null;
+ if (trick && !TRICKS[trick] && !ranged) throw new Error(`unknown strategy ${id}`);
+ return (slot, seed, ctx) => {
+ const t = ranged ?? (trick ? TRICKS[trick] : null);
+ const params = { ...baseParams(base), ...((t && "params" in t ? t.params : undefined) ?? {}) };
+ const b = new BotBrain(slot, params, ctx.arena, ctx.tuning, seed, t?.overrides ?? {});
+ return { label: id, think: (o) => b.think(o) };
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/index.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/index.ts
new file mode 100644
index 0000000000..dc1be55ed9
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/index.ts
@@ -0,0 +1,27 @@
+/**
+ * Dodaios Verse combat: an optional 1v1 blaster duel in the Reactor Shaft.
+ * Renderer-independent and React-free; see docs/verse/combat.md.
+ *
+ * Integrator entry points:
+ * - createLocalDuel() a duel against the bot, one call per frame
+ * - REACTOR_ARENA where it happens (deck coordinates)
+ * - resolveAim, cameraRigFor, cameraPose, CAMERA_RIGS camera and crosshair
+ * - ControlState / idleControl what the keys and mouse map to
+ * - ViewState / CombatEvent what to draw and which effects to play
+ */
+export { createLocalDuel, type DuelResult, type FrameResult, type LocalDuel, type LocalDuelOptions } from "./session";
+export { REACTOR_ARENA } from "./arenaReactor";
+export { buildArena, isWalkable, lineOfSight, raycastWorld, type Arena, type ArenaDef, type ArenaPoint } from "./arena";
+export { CAMERA_RIGS, cameraPose, cameraRigFor, crosshairRadiusPx, resolveAim, type AimSolution, type CameraRig } from "./camera";
+export { idleControl, makeInput, sanitizeInput, type ControlState } from "./input";
+export { buildView, type BoltView, type HudState, type MatchView, type PlayerView, type ViewState } from "./view";
+export { eventKey, BTN, type CombatEvent, type CombatEventType, type InputCommand, type MatchState } from "./types";
+export { DEFAULT_TUNING, TICK_RATE, TICK_DT, type CombatTuning } from "./tuning";
+export { createContext, createMatch, step, muzzleOf, rulesHash, type SimContext } from "./sim";
+export { MatchServer, type MatchServerOptions } from "./server";
+export { MatchClient, type MatchClientOptions } from "./client";
+export { LocalNetwork, socketChannel, type Channel, type LinkOptions, type SocketLike } from "./transport";
+export { PROTOCOL_VERSION, type ClientMsg, type ServerMsg } from "./protocol";
+export { observe, type Observation, type WorldView } from "./observe";
+export { BotBrain } from "./bot/brain";
+export { BOT_TIERS, botParams, type BotParams, type BotTier } from "./bot/tiers";
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/input.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/input.ts
new file mode 100644
index 0000000000..3400b4f6c7
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/input.ts
@@ -0,0 +1,95 @@
+/**
+ * From a control state (what the keys, mouse or a bot want right now) to the
+ * quantised InputCommand the simulation and the wire both use.
+ */
+import { clamp, q, wrapAngle } from "./math";
+import { BTN, type InputCommand } from "./types";
+
+/** Aim is sent to 1/10000 rad, movement to 1/127. */
+export const AIM_SCALE = 10000;
+export const MOVE_SCALE = 127;
+export const PITCH_LIMIT = 1.2;
+
+/** What a player wants this tick, in plain terms. */
+export interface ControlState {
+ /** Strafe right and forward, -1..1, in the aim frame (WASD). */
+ moveX: number;
+ moveY: number;
+ /** Absolute aim, radians (0 faces +Z, positive pitch looks up). */
+ yaw: number;
+ pitch: number;
+ fire: boolean;
+ ads: boolean;
+ shield: boolean;
+ sprint: boolean;
+ /** Presses: true for one command (the client latches them between ticks). */
+ dodge: boolean;
+ vent: boolean;
+ forfeit: boolean;
+}
+
+export function idleControl(yaw = 0, pitch = 0): ControlState {
+ return { moveX: 0, moveY: 0, yaw, pitch, fire: false, ads: false, shield: false, sprint: false, dodge: false, vent: false, forfeit: false };
+}
+
+export function buttonsOf(c: ControlState): number {
+ return (c.fire ? BTN.FIRE : 0) | (c.ads ? BTN.ADS : 0) | (c.shield ? BTN.SHIELD : 0) | (c.dodge ? BTN.DODGE : 0)
+ | (c.vent ? BTN.VENT : 0) | (c.sprint ? BTN.SPRINT : 0) | (c.forfeit ? BTN.FORFEIT : 0);
+}
+
+/** Every button bit an input may carry. */
+const ALL_BUTTONS = BTN.FIRE | BTN.ADS | BTN.SHIELD | BTN.DODGE | BTN.VENT | BTN.SPRINT | BTN.FORFEIT;
+
+const finite = (v: unknown, fallback: number): number => (typeof v === "number" && Number.isFinite(v) ? v : fallback);
+
+/**
+ * The move stick on the wire grid, never longer than 1 (a diagonal is not
+ * faster): components are rounded, and if that pushed the length past 1 they
+ * are rounded toward zero instead.
+ */
+function quantMove(mx: number, my: number): [number, number] {
+ mx = clamp(mx, -1, 1);
+ my = clamp(my, -1, 1);
+ const len = Math.hypot(mx, my);
+ if (len > 1) { mx /= len; my /= len; }
+ let qx = Math.round(mx * MOVE_SCALE);
+ let qy = Math.round(my * MOVE_SCALE);
+ if (qx * qx + qy * qy > MOVE_SCALE * MOVE_SCALE) { qx = Math.trunc(mx * MOVE_SCALE); qy = Math.trunc(my * MOVE_SCALE); }
+ return [qx / MOVE_SCALE + 0, qy / MOVE_SCALE + 0];
+}
+
+export function makeInput(seq: number, c: ControlState, viewTick = -1): InputCommand {
+ const [mx, my] = quantMove(c.moveX, c.moveY);
+ return {
+ seq,
+ mx,
+ my,
+ yaw: q(wrapAngle(c.yaw), AIM_SCALE),
+ pitch: q(clamp(c.pitch, -PITCH_LIMIT, PITCH_LIMIT), AIM_SCALE),
+ buttons: buttonsOf(c),
+ viewTick,
+ };
+}
+
+/**
+ * An input as the server may trust it: whatever arrived over the wire (a
+ * modified client, a broken encoder) becomes a legal command on the same grid
+ * `makeInput` produces. Legal commands come out unchanged, so client
+ * prediction and the server still agree. Non-numbers become 0 (aim: the
+ * previous aim), the move stick is clamped to length 1, unknown button bits
+ * are dropped.
+ */
+export function sanitizeInput(c: InputCommand, prevYaw = 0, prevPitch = 0): InputCommand {
+ const [mx, my] = quantMove(finite(c.mx, 0), finite(c.my, 0));
+ const yaw = finite(c.yaw, prevYaw);
+ return {
+ seq: Math.trunc(finite(c.seq, -1)),
+ mx,
+ my,
+ // +-3.1416 (the grid's ends, just past +-PI) are legal as they are.
+ yaw: q(Math.abs(yaw) <= Math.PI + 1e-3 ? yaw : wrapAngle(yaw), AIM_SCALE),
+ pitch: q(clamp(finite(c.pitch, prevPitch), -PITCH_LIMIT, PITCH_LIMIT), AIM_SCALE),
+ buttons: Math.trunc(finite(c.buttons, 0)) & ALL_BUTTONS,
+ viewTick: Math.max(-1, Math.trunc(finite(c.viewTick, -1))),
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/math.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/math.ts
new file mode 100644
index 0000000000..30636d6ad6
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/math.ts
@@ -0,0 +1,70 @@
+/**
+ * Small math for the combat core, in the deck's frame: x to the right, z
+ * toward the camera, y up, metres. Yaw is radians about +Y with 0 facing +Z
+ * (the socket convention), pitch is radians with positive looking up.
+ */
+
+export const DEG = Math.PI / 180;
+export const TAU = Math.PI * 2;
+
+export interface Vec2 { x: number; z: number }
+export interface Vec3 { x: number; y: number; z: number }
+
+export function clamp(v: number, lo: number, hi: number): number {
+ return v < lo ? lo : v > hi ? hi : v;
+}
+
+export function lerp(a: number, b: number, t: number): number {
+ return a + (b - a) * t;
+}
+
+/** Angle in (-PI, PI]. */
+export function wrapAngle(a: number): number {
+ a = a % TAU;
+ if (a <= -Math.PI) a += TAU;
+ else if (a > Math.PI) a -= TAU;
+ return a;
+}
+
+/** Signed shortest difference b - a. */
+export function angleDiff(a: number, b: number): number {
+ return wrapAngle(b - a);
+}
+
+export function lerpAngle(a: number, b: number, t: number): number {
+ return a + angleDiff(a, b) * t;
+}
+
+/** Yaw that faces along (dx, dz). */
+export function yawOf(dx: number, dz: number): number {
+ return Math.atan2(dx, dz);
+}
+
+/** Forward on the floor for a yaw. */
+export function forwardX(yaw: number): number { return Math.sin(yaw); }
+export function forwardZ(yaw: number): number { return Math.cos(yaw); }
+/** Right-hand side on the floor for a yaw (forward x up). */
+export function rightX(yaw: number): number { return -Math.cos(yaw); }
+export function rightZ(yaw: number): number { return Math.sin(yaw); }
+
+/** Unit direction for yaw and pitch. */
+export function dirFromAngles(yaw: number, pitch: number): Vec3 {
+ const c = Math.cos(pitch);
+ return { x: Math.sin(yaw) * c, y: Math.sin(pitch), z: Math.cos(yaw) * c };
+}
+
+/** Yaw and pitch of a direction. */
+export function anglesOf(dx: number, dy: number, dz: number): { yaw: number; pitch: number } {
+ return { yaw: Math.atan2(dx, dz), pitch: Math.atan2(dy, Math.hypot(dx, dz)) };
+}
+
+/** Move `v` toward `target` by at most `step`. */
+export function approach(v: number, target: number, step: number): number {
+ return v < target ? Math.min(target, v + step) : Math.max(target, v - step);
+}
+
+/** Round to a fixed grid of 1/scale (snapshot quantisation). */
+export function q(v: number, scale: number): number {
+ // + 0 turns -0 into 0, so JSON round trips are exact.
+ return Math.round(v * scale) / scale + 0;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/netcode.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/netcode.test.ts
new file mode 100644
index 0000000000..1831eee588
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/netcode.test.ts
@@ -0,0 +1,224 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { MatchClient } from "./client";
+import { idleControl, makeInput, type ControlState } from "./input";
+import { decodeInput, decodeState, encodeInput, encodeState, PROTOCOL_VERSION, wireSize, type ServerMsg } from "./protocol";
+import { MatchServer } from "./server";
+import { createContext, historyAt, step } from "./sim";
+import { liveMatch, place, runner } from "./testing";
+import { LocalNetwork, socketChannel, type LinkOptions, type SocketLike } from "./transport";
+import { DEFAULT_TUNING, withTuning } from "./tuning";
+import type { MatchState } from "./types";
+
+describe("protocol", () => {
+ it("round-trips a mid-duel state exactly (all but the server's pose history)", () => {
+ const { ctx, state } = liveMatch();
+ const r = runner(ctx, place(state, { x: 38.8, z: 12 }, { x: 38.8, z: 28 }));
+ r.run(200, (s) => ({ fire: s.tick % 50 < 30, moveX: Math.sin(s.tick / 9), ads: true, vent: s.tick % 97 === 0 }),
+ (s) => ({ shield: s.tick % 40 < 15, moveY: -0.5, fire: s.tick % 40 > 20, dodge: s.tick % 77 === 0 }));
+ expect(r.state.bolts.length).toBeGreaterThan(0);
+ const back = decodeState(JSON.parse(JSON.stringify(encodeState(r.state))), r.state.config);
+ expect(back).toEqual({ ...r.state, history: { ticks: [], poses: [] } });
+ });
+
+ it("round-trips inputs and keeps a snapshot small", () => {
+ const cmd = makeInput(77, { ...idleControl(-2.5, 0.31), moveX: -0.4, moveY: 0.9, fire: true, shield: true }, 1234);
+ expect(decodeInput(encodeInput(cmd))).toEqual(cmd);
+ const { state } = liveMatch();
+ const msg: ServerMsg = ["s", state.tick, 5, encodeState(state), []];
+ expect(wireSize(msg)).toBeLessThan(900);
+ });
+});
+
+describe("local transport", () => {
+ it("delays, jitters, drops only unreliable messages, and keeps reliable ones in order", () => {
+ const net = new LocalNetwork(3);
+ const { client, server, stats } = net.link({ latencyMs: 50, jitterMs: 30, loss: 0.3 });
+ const got: string[] = [];
+ server.onMessage((m) => got.push(m[0] === "p" ? `p${m[1]}` : m[0]));
+ client.send(["h", PROTOCOL_VERSION, "a", "a", 0]);
+ for (let i = 0; i < 200; i++) client.send(["p", i]);
+ client.send(["l"]);
+ net.advance(49);
+ expect(got).toEqual([]);
+ net.advance(200);
+ // Reliable messages all arrive, in their own order (unreliable ones may overtake them).
+ expect(got.filter((g) => g === "h" || g === "l")).toEqual(["h", "l"]);
+ const pings = got.filter((g) => g.startsWith("p")).length;
+ expect(pings).toBeGreaterThan(100);
+ expect(pings).toBeLessThan(180);
+ expect(stats.up.dropped).toBe(200 - pings);
+ });
+
+ it("adapts a WebSocket-like object", () => {
+ const handlers: Record<string, ((ev: { data: unknown }) => void)[]> = { message: [], close: [] };
+ const sent: string[] = [];
+ const ws = {
+ readyState: 1,
+ send: (d: string) => sent.push(d),
+ close: () => undefined,
+ addEventListener: (type: string, cb: (ev: { data: unknown }) => void) => handlers[type].push(cb),
+ } as unknown as SocketLike;
+ const ch = socketChannel<["p", number], ["o", number, number]>(ws);
+ const got: unknown[] = [];
+ ch.onMessage((m) => got.push(m));
+ ch.send(["p", 1]);
+ handlers.message[0]({ data: JSON.stringify(["o", 1, 2]) });
+ handlers.message[0]({ data: "not json" });
+ expect(sent).toEqual(['["p",1]']);
+ expect(got).toEqual([["o", 1, 2]]);
+ });
+});
+
+interface Rig {
+ net: LocalNetwork;
+ server: MatchServer;
+ a: MatchClient;
+ b: MatchClient;
+ now: number;
+ run(ms: number, ca?: (s: MatchState) => Partial<ControlState>, cb?: (s: MatchState) => Partial<ControlState>): void;
+}
+
+function rig(link: LinkOptions = {}, opts: { snapshotEvery?: number; lagCompensation?: boolean; skipCountdown?: boolean } = {}): Rig {
+ const ctx = createContext();
+ const net = new LocalNetwork(5);
+ const server = new MatchServer({ ctx, seed: 21, snapshotEvery: opts.snapshotEvery ?? 1, lagCompensation: opts.lagCompensation });
+ const la = net.link(link);
+ const lb = net.link(link);
+ server.accept(la.server);
+ server.accept(lb.server);
+ const a = new MatchClient({ ctx, channel: la.client, playerId: "a" });
+ const b = new MatchClient({ ctx, channel: lb.client, playerId: "b" });
+ const r: Rig = {
+ net, server, a, b, now: 0,
+ run(ms, ca, cb) {
+ for (let t = 0; t < ms; t += 4) {
+ r.now += 4;
+ net.advance(r.now);
+ server.update(r.now);
+ net.advance(r.now);
+ for (const [c, f] of [[a, ca], [b, cb]] as const) {
+ const s = c.state;
+ if (s && f) { const me = s.players[c.slot]; c.setControl({ ...idleControl(me.yaw, me.pitch), ...f(s) }); }
+ c.update(r.now);
+ }
+ net.advance(r.now);
+ }
+ },
+ };
+ r.run(50);
+ return r;
+}
+
+describe("server and clients", () => {
+ it("start a duel once both said hello, with the same match on both sides", () => {
+ const r = rig();
+ expect(r.a.status).toBe("playing");
+ expect(r.b.status).toBe("playing");
+ expect([r.a.slot, r.b.slot].sort()).toEqual([0, 1]);
+ expect(r.a.matchId).toBe(r.server.matchId);
+ });
+
+ it("predict their own player exactly when nothing else interferes", () => {
+ const r = rig();
+ r.run(9000, (s) => ({ moveY: 1, moveX: Math.sin(s.tick / 30), fire: s.tick % 120 < 60, ads: s.tick % 200 < 80, sprint: s.tick % 300 < 40, dodge: s.tick % 170 === 0 }));
+ expect(r.a.prediction.checked).toBeGreaterThan(300);
+ expect(r.a.prediction.corrections).toBe(0);
+ expect(r.a.prediction.maxErrorM).toBe(0);
+ });
+
+ it("stay close under latency, jitter and loss, and the server applies nearly every input", () => {
+ const r = rig({ latencyMs: 70, jitterMs: 25, loss: 0.08 }, { snapshotEvery: 2 });
+ r.run(12000, (s) => ({ moveY: 1, moveX: Math.sin(s.tick / 25), fire: s.tick % 90 < 45 }), (s) => ({ moveX: Math.cos(s.tick / 40), fire: s.tick % 70 < 30 }));
+ const p = r.a.prediction;
+ expect(p.checked).toBeGreaterThan(200);
+ // Mispredictions come from lost or late inputs and the opponent's hits; they stay small.
+ expect(p.maxErrorM).toBeLessThan(0.75);
+ expect(p.corrections / p.checked).toBeLessThan(0.35);
+ const server = r.server.state as MatchState;
+ const applied = server.players[r.a.slot].lastSeq;
+ // About 12 s of inputs, all but the ones still in flight were applied.
+ expect(applied).toBeGreaterThan(600);
+ });
+
+ it("show the opponent smoothly from snapshots", () => {
+ const r = rig({ latencyMs: 40, jitterMs: 15 }, { snapshotEvery: 2 });
+ r.run(3500); // through the countdown
+ let last: { x: number; z: number } | null = null;
+ let worst = 0;
+ for (let i = 0; i < 300; i++) {
+ r.run(8, undefined, (s) => ({ moveY: 1, moveX: Math.sin(s.tick / 20) }));
+ const v = r.a.view();
+ const other = v?.players.find((p) => !p.local);
+ if (other && last) worst = Math.max(worst, Math.hypot(other.x - last.x, other.z - last.z));
+ if (other) last = { x: other.x, z: other.z };
+ }
+ // 8 ms frames at <= 7 m/s: no teleports.
+ expect(worst).toBeLessThan(0.25);
+ });
+
+ it("end the match for the other player when one leaves or drops", () => {
+ const r = rig();
+ r.a.forfeit();
+ r.run(50);
+ expect(r.b.status).toBe("ended");
+ expect(r.b.result?.winner).toBe(r.b.slot);
+ expect(r.b.result?.reason).toBe("forfeit");
+
+ const d = rig();
+ const ended: string[] = [];
+ d.server.onStep((ev) => { for (const e of ev) if (e.type === "match_end") ended.push(e.reason); });
+ // Pull the plug on a.
+ (d.a as unknown as { channel: { close(): void } }).channel.close();
+ d.run(50);
+ expect(ended).toEqual(["disconnect"]);
+ expect(d.b.result?.winner).toBe(d.b.slot);
+ });
+
+ it("reject a client with other balance numbers or a third player", () => {
+ const ctx = createContext();
+ const net = new LocalNetwork();
+ const server = new MatchServer({ ctx, seed: 1 });
+ const l1 = net.link();
+ server.accept(l1.server);
+ const odd = new MatchClient({ ctx: createContext(undefined, withTuning(DEFAULT_TUNING, { blaster: { damageNear: 99 } })), channel: l1.client, playerId: "x" });
+ net.advance(10);
+ expect(odd.status).toBe("rejected");
+ expect(odd.rejectReason).toContain("tuning");
+ const r = rig();
+ const l3 = r.net.link();
+ r.server.accept(l3.server);
+ const third = new MatchClient({ ctx: createContext(), channel: l3.client, playerId: "c" });
+ r.run(20);
+ expect(third.status).toBe("rejected");
+ });
+});
+
+describe("lag compensation", () => {
+ it("flies a late shot through the poses the shooter saw", () => {
+ const tuning = withTuning(DEFAULT_TUNING, {
+ blaster: { hipSpreadDeg: 0, moveSpreadHipDeg: 0, bloomPerShotHipDeg: 0, recoilPitchHipDeg: 0, recoilYawDeg: 0 },
+ });
+ const { ctx, state } = liveMatch({ tuning });
+ // b stood 6 m ahead of a, then stepped aside; a saw it there 8 ticks ago and fires at it.
+ let s = place(state, { x: 38.8, z: 14 }, { x: 38.8, z: 20 });
+ const idle = (seq: number) => makeInput(seq, idleControl(0, 0));
+ for (let i = 0; i < 10; i++) s = step(s, [idle(i), idle(i)], ctx).state;
+ const seen = s.tick - 8;
+ expect(historyAt(s, seen)).not.toBeNull();
+ s = JSON.parse(JSON.stringify(s));
+ s.players[1].x = 41.5; // moved out of the line of fire since
+ const shot = (viewTick: number) => {
+ let t = s;
+ const hits: number[] = [];
+ for (let i = 0; i < 30; i++) {
+ const res = step(t, [i === 0 ? makeInput(10, { ...idleControl(0, 0), fire: true }, viewTick) : idle(11 + i), idle(11 + i)], ctx);
+ t = res.state;
+ for (const e of res.events) if (e.type === "hit") hits.push(e.target);
+ }
+ return hits;
+ };
+ expect(shot(-1)).toEqual([]);
+ expect(shot(seen)).toEqual([1]);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/netcodeAdversarial.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/netcodeAdversarial.test.ts
new file mode 100644
index 0000000000..f7c856c52f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/netcodeAdversarial.test.ts
@@ -0,0 +1,201 @@
+// @vitest-environment node
+/**
+ * Adversarial netcode tests: a modified client (garbage, oversized or
+ * malformed inputs), inputs arriving in bursts, a client built for another
+ * arena, and whole bot duels over a jittery, lossy link (every event reaches
+ * both clients exactly once, the end carries the final state, the same seeds
+ * replay the same duel).
+ */
+import { describe, expect, it } from "vitest";
+import { BotBrain } from "./bot/brain";
+import { botParams, type BotTier } from "./bot/tiers";
+import { MatchClient } from "./client";
+import { idleControl, makeInput, sanitizeInput } from "./input";
+import { observe } from "./observe";
+import { PROTOCOL_VERSION, type ClientMsg } from "./protocol";
+import { MatchServer } from "./server";
+import { createContext, rulesHash, type SimContext } from "./sim";
+import { LocalNetwork, type ClientChannel, type LinkOptions } from "./transport";
+import { REACTOR_ARENA } from "./arenaReactor";
+import { eventKey, type CombatEvent, type MatchState } from "./types";
+
+const TICK_MS = 1000 / 60;
+
+/** A server, one raw channel we drive by hand (the "cheater"), and an honest client. */
+function rawRig(ctx: SimContext = createContext()) {
+ const net = new LocalNetwork(1);
+ const server = new MatchServer({ ctx, seed: 3, snapshotEvery: 1 });
+ const la = net.link();
+ const lb = net.link();
+ server.accept(la.server);
+ server.accept(lb.server);
+ la.client.send(["h", PROTOCOL_VERSION, "raw", "raw", rulesHash(ctx)]);
+ const honest = new MatchClient({ ctx, channel: lb.client, playerId: "honest" });
+ let now = 0;
+ let seq = 0;
+ const steps: CombatEvent[] = [];
+ server.onStep((ev) => steps.push(...ev));
+ const tick = (send?: unknown) => {
+ now += TICK_MS;
+ if (send !== undefined) la.client.send(send as ClientMsg);
+ net.advance(now);
+ server.update(now);
+ honest.update(now);
+ net.advance(now);
+ };
+ const input = (mx: unknown, my: unknown, yaw: unknown, pitch: unknown, buttons: unknown) => ["i", -1, [[seq++, mx, my, yaw, pitch, buttons, -1]]];
+ return { server, honest, tick, input, steps, get state() { return server.state as MatchState; }, nextSeq: () => seq++, raw: la.client };
+}
+
+describe("a modified client", () => {
+ it("cannot move faster than the run speed, aim at NaN, or set unknown buttons", () => {
+ const r = rawRig();
+ for (let i = 0; i < 200; i++) r.tick(r.input(0, 0, 0, 0, 0));
+ expect(r.state.phase).toBe("live");
+ const p0 = { ...r.state.players[0] };
+ // A full second of a 10x move stick, both axes.
+ for (let i = 0; i < 60; i++) r.tick(r.input(1270, 1270, 0, 0, 0));
+ const p1 = r.state.players[0];
+ expect(Math.hypot(p1.x - p0.x, p1.z - p0.z)).toBeLessThanOrEqual(4.8 + 1e-6);
+ // Strings, nulls and huge numbers where numbers belong.
+ r.tick(r.input("x", null, "abc", 1e30, 0xffff));
+ r.tick(r.input(Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER, 31415926, -9e9, -1));
+ const p = r.state.players[0];
+ for (const k of ["x", "z", "vx", "vz", "yaw", "pitch", "heat", "health", "shieldEnergy"] as const) expect(Number.isFinite(p[k]), k).toBe(true);
+ expect(Math.abs(p.pitch)).toBeLessThanOrEqual(1.2);
+ expect(p.buttons & ~0x7f).toBe(0);
+ });
+
+ it("malformed messages are ignored, not thrown", () => {
+ const r = rawRig();
+ for (let i = 0; i < 10; i++) r.tick(r.input(0, 0, 0, 0, 0));
+ const junk: unknown[] = [null, 42, "i", ["i"], ["i", -1, "nope"], ["i", -1, [null, "x", [], ["a"]]], ["p"], ["p", "x"], ["zz", 1]];
+ for (const j of junk) expect(() => r.tick(j)).not.toThrow();
+ // Still playing, and the honest player is unaffected.
+ expect(r.server.finished).toBe(false);
+ expect(r.honest.status).toBe("playing");
+ });
+
+ it("legal inputs pass the server's sanitising unchanged (so prediction still matches)", () => {
+ for (let i = 0; i < 500; i++) {
+ const a = (i * 0.731) % (2 * Math.PI) - Math.PI;
+ const c = makeInput(i, { ...idleControl(a * 3, Math.sin(i) * 1.5), moveX: Math.cos(i * 1.3) * 1.4, moveY: Math.sin(i * 0.7) * 1.4, fire: i % 2 === 0, dodge: i % 7 === 0 }, i % 3 === 0 ? -1 : i);
+ expect(sanitizeInput(c)).toEqual(c);
+ expect(Math.hypot(c.mx, c.my)).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it("a press inside a burst of late inputs is not lost when the server catches up", () => {
+ const r = rawRig();
+ for (let i = 0; i < 220; i++) r.tick(r.input(0, 0, 0, 0, 0));
+ expect(r.state.phase).toBe("live");
+ // 200 ms of nothing, then twelve inputs at once; the roll press is in the second.
+ const burst = [];
+ for (let i = 0; i < 12; i++) burst.push([r.nextSeq(), 0, 127, 0, 0, i === 1 ? 8 : 0, -1]);
+ const before = r.steps.length;
+ r.tick(["i", -1, burst]);
+ for (let i = 0; i < 20; i++) r.tick();
+ expect(r.steps.slice(before).filter((e) => e.type === "dodge" && e.player === 0).length).toBe(1);
+ });
+});
+
+describe("handshake", () => {
+ it("rejects a client built for another arena (its predictions would hit other walls)", () => {
+ const net = new LocalNetwork(2);
+ const server = new MatchServer({ ctx: createContext(), seed: 1 });
+ const l = net.link();
+ server.accept(l.server);
+ const moved = { ...REACTOR_ARENA, spawns: [{ ...REACTOR_ARENA.spawns[0], x: 39.4 }, REACTOR_ARENA.spawns[1]] as const };
+ const c = new MatchClient({ ctx: createContext(moved), channel: l.client, playerId: "x" });
+ net.advance(10);
+ expect(c.status).toBe("rejected");
+ expect(c.rejectReason).toContain("arena");
+ });
+});
+
+interface NetDuel {
+ server: MatchServer;
+ clients: MatchClient[];
+ published: CombatEvent[];
+ presented: CombatEvent[][];
+ finalServer: MatchState;
+}
+
+/** A whole bot duel through server, transport and two clients. */
+function netDuel(seed: number, link: LinkOptions, tiers: [BotTier, BotTier] = ["hard", "elite"]): NetDuel {
+ const ctx = createContext();
+ const net = new LocalNetwork(seed);
+ const server = new MatchServer({ ctx, seed, snapshotEvery: 2, lagCompensation: true });
+ const links = [net.link(link), net.link(link)];
+ for (const l of links) server.accept(l.server);
+ const published: CombatEvent[] = [];
+ server.onStep((ev) => published.push(...ev));
+ const mk = (ch: ClientChannel, i: number) => {
+ const box: { b: BotBrain | null } = { b: null };
+ return new MatchClient({
+ ctx, channel: ch, playerId: `p${i}`,
+ controller: (v, slot) => {
+ if (!box.b) box.b = new BotBrain(slot, botParams(tiers[i]), ctx.arena, ctx.tuning, seed * 31 + i);
+ return box.b.think(observe(v, slot, ctx.arena, ctx.tuning));
+ },
+ });
+ };
+ const clients = links.map((l, i) => mk(l.client, i));
+ const presented: CombatEvent[][] = [[], []];
+ // Uneven frame times, like a real browser.
+ let now = 0;
+ for (let f = 0; f < 60 * 300 && !clients.every((c) => c.status === "ended"); f++) {
+ now += 5 + ((f * 7919) % 13);
+ net.advance(now);
+ server.update(now);
+ net.advance(now);
+ for (const [i, c] of clients.entries()) { c.update(now); presented[i].push(...c.drainEvents()); }
+ net.advance(now);
+ }
+ return { server, clients, published, presented, finalServer: server.state as MatchState };
+}
+
+describe("a whole duel over a bad link", () => {
+ const bad = { latencyMs: 70, jitterMs: 40, loss: 0.15 };
+
+ it("every event reaches both clients exactly once, and the end carries the final state", () => {
+ const d = netDuel(7, bad);
+ expect(d.finalServer.phase).toBe("ended");
+ for (const [i, c] of d.clients.entries()) {
+ expect(c.status).toBe("ended");
+ // The last thing the client knows is the server's final state.
+ expect(c.serverState?.tick).toBe(d.finalServer.tick);
+ expect(c.serverState?.scores).toEqual(d.finalServer.scores);
+ expect(c.result?.winner).toBe(d.finalServer.winner);
+ const keys = d.presented[i].map(eventKey);
+ expect(new Set(keys).size).toBe(keys.length); // never twice
+ const got = new Set(keys);
+ // Everything the server published was presented (own predicted actions count too).
+ const missing = d.published.filter((e) => !got.has(eventKey(e)));
+ expect(missing.map((e) => e.type)).toEqual([]);
+ }
+ const kinds = new Set(d.published.map((e) => e.type));
+ for (const k of ["shot", "hit", "death", "round_end", "match_end"] as const) expect(kinds.has(k)).toBe(true);
+ });
+
+ it("own movement is predicted exactly on a clean link; on a bad one corrections stay small", () => {
+ const clean = netDuel(9, { latencyMs: 40 });
+ const dirty = netDuel(9, bad);
+ for (const c of clean.clients) {
+ expect(c.prediction.checked).toBeGreaterThan(300);
+ // Only what the client cannot know (the opponent's new hits, deaths) corrects it.
+ expect(c.prediction.corrections / c.prediction.checked).toBeLessThan(0.15);
+ }
+ for (const c of dirty.clients) {
+ expect(c.prediction.corrections / c.prediction.checked).toBeLessThan(0.3);
+ expect(c.prediction.maxErrorM).toBeLessThan(1.5);
+ }
+ });
+
+ it("the same seeds replay the same networked duel, event for event", () => {
+ const a = netDuel(11, bad);
+ const b = netDuel(11, bad);
+ expect(JSON.stringify(a.published)).toBe(JSON.stringify(b.published));
+ expect(a.finalServer.scores).toEqual(b.finalServer.scores);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/observe.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/observe.ts
new file mode 100644
index 0000000000..e48e0d2309
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/observe.ts
@@ -0,0 +1,182 @@
+/**
+ * What one player can know: the same information a person at the screen gets.
+ *
+ * - Their own state in full (it is on their HUD).
+ * - The opponent only when in sight: a line of sight from the eye to the
+ * head, chest or hips that no collider blocks, inside the view cone of the
+ * over-the-shoulder camera (or very close by). Health is known always,
+ * because the duel HUD shows both bars.
+ * - Bolts only when in sight (they glow, but not through walls).
+ * - Shots heard (where they came from) and the direction of a hit taken.
+ *
+ * A bot reads nothing else, so it cannot see through walls. Works on the
+ * authoritative state (headless duels) and on a client's view alike.
+ */
+import { lineOfSight, raycastWorld, type Arena } from "./arena";
+import { angleDiff, DEG, forwardX, forwardZ, q, rightX, rightZ, yawOf } from "./math";
+import type { CombatTuning } from "./tuning";
+import type { BoltKind, BoltState, CombatEvent, MatchPhase, PlayerState } from "./types";
+
+/**
+ * Half the horizontal view of the hip camera (70 deg vertical at 16:9 shows
+ * +-51 deg), with a little peripheral margin. Measured from the camera, which
+ * sits behind the right shoulder, so close by it shows far more to the sides
+ * than this angle from the body would.
+ */
+export const VIEW_HALF_DEG = 55;
+/** The hip camera's place (camera.ts CAMERA_RIGS.hip): right of, above and behind the feet. */
+const CAM_RIGHT = 0.55;
+const CAM_UP = 1.68;
+const CAM_BACK = 2.5;
+/** Closer than this, the opponent is noticed whatever the view (heard, felt). */
+export const AWARE_RADIUS = 3;
+const BOLT_AWARE_RADIUS = 6;
+/** Running footsteps carry this far (sprinting further); walking in sights is silent. */
+export const FOOTSTEP_RUN_M = 9;
+export const FOOTSTEP_SPRINT_M = 16;
+
+export interface WorldView {
+ tick: number;
+ phase: MatchPhase;
+ round: number;
+ scores: readonly number[];
+ players: readonly PlayerState[];
+ bolts: readonly BoltState[];
+ /** Events since the previous observation (for shots heard and hits taken). */
+ events?: readonly CombatEvent[];
+}
+
+export interface EnemySighting {
+ x: number;
+ z: number;
+ vx: number;
+ vz: number;
+ yaw: number;
+ pitch: number;
+ shieldUp: boolean;
+ shieldBroken: boolean;
+ /** Steam from the vents. */
+ venting: boolean;
+ overheated: boolean;
+ ads: boolean;
+ dodging: boolean;
+ sprinting: boolean;
+}
+
+export interface BoltSighting {
+ id: number;
+ x: number;
+ y: number;
+ z: number;
+ vx: number;
+ vy: number;
+ vz: number;
+ owner: number;
+ kind: BoltKind;
+}
+
+export interface Observation {
+ tick: number;
+ phase: MatchPhase;
+ round: number;
+ scores: readonly number[];
+ slot: number;
+ me: PlayerState;
+ enemySlot: number;
+ enemyAlive: boolean;
+ enemyHealth: number;
+ /** Null when the opponent is out of sight. */
+ enemy: EnemySighting | null;
+ bolts: BoltSighting[];
+ /** Where enemy shots were heard from this tick. */
+ heard: { x: number; z: number }[];
+ /** Where the bolt that hurt me came from (this tick), if any. */
+ hurtFrom: { x: number; z: number } | null;
+ /** Footsteps: a running opponent nearby is heard, roughly where it is. */
+ footsteps: { x: number; z: number } | null;
+ /** HUD ping of the opponent during the reactor surge. */
+ ping: { x: number; z: number } | null;
+}
+
+/**
+ * Where a player's camera is (behind the right shoulder, level), pulled in
+ * where a wall is in the way, as the view's camera collision does.
+ */
+export function cameraPoint(arena: Arena, me: { x: number; z: number; yaw: number }): { x: number; y: number; z: number } {
+ const px = me.x + rightX(me.yaw) * CAM_RIGHT;
+ const pz = me.z + rightZ(me.yaw) * CAM_RIGHT;
+ const bx = px - forwardX(me.yaw) * CAM_BACK;
+ const bz = pz - forwardZ(me.yaw) * CAM_BACK;
+ if (raycastWorld(arena, me.x, CAM_UP, me.z, px, CAM_UP, pz)) {
+ // No room beside the shoulder: the camera stays just behind the head.
+ return { x: me.x - forwardX(me.yaw) * 0.3, y: CAM_UP, z: me.z - forwardZ(me.yaw) * 0.3 };
+ }
+ const hit = raycastWorld(arena, px, CAM_UP, pz, bx, CAM_UP, bz);
+ const k = hit ? Math.max(0, hit.t - 0.08) : 1;
+ return { x: px + (bx - px) * k, y: CAM_UP, z: pz + (bz - pz) * k };
+}
+
+function inView(me: PlayerState, cam: { x: number; z: number }, x: number, z: number, aware: number): boolean {
+ const dx = x - me.x;
+ const dz = z - me.z;
+ if (dx * dx + dz * dz <= aware * aware) return true;
+ return Math.abs(angleDiff(me.yaw, yawOf(x - cam.x, z - cam.z))) <= VIEW_HALF_DEG * DEG;
+}
+
+/**
+ * True when `me` can see `other`: inside what the camera shows, with an
+ * unblocked line to its head, chest or hips from the eyes or from the camera
+ * (the over-the-shoulder view looks round a right-hand corner before the
+ * body leaves cover, for people and bots alike).
+ */
+export function canSee(arena: Arena, t: CombatTuning, me: PlayerState, other: { x: number; z: number }, cam = cameraPoint(arena, me)): boolean {
+ if (!inView(me, cam, other.x, other.z, AWARE_RADIUS)) return false;
+ const ey = t.body.eyeHeight;
+ for (const y of [1.65, 1.15, 0.6]) {
+ if (lineOfSight(arena, me.x, ey, me.z, other.x, y, other.z)) return true;
+ if (lineOfSight(arena, cam.x, cam.y, cam.z, other.x, y, other.z)) return true;
+ }
+ return false;
+}
+
+export function observe(view: WorldView, slot: number, arena: Arena, t: CombatTuning): Observation {
+ const me = view.players[slot];
+ const enemySlot = 1 - slot;
+ const e = view.players[enemySlot];
+ let enemy: EnemySighting | null = null;
+ const cam = cameraPoint(arena, me);
+ if (e && e.alive && me.alive && canSee(arena, t, me, e, cam)) {
+ enemy = {
+ x: e.x, z: e.z, vx: e.vx, vz: e.vz, yaw: e.yaw, pitch: e.pitch,
+ shieldUp: e.shieldUp, shieldBroken: e.shieldBrokenUntil > view.tick,
+ venting: e.ventStart >= 0, overheated: e.ventStart >= 0 && e.ventForced,
+ ads: e.ads > 0.5, dodging: view.tick < e.dodgeUntil, sprinting: e.sprinting,
+ };
+ }
+ const bolts: BoltSighting[] = [];
+ const ey = t.body.eyeHeight;
+ for (const b of view.bolts) {
+ if (!inView(me, cam, b.x, b.z, BOLT_AWARE_RADIUS)) continue;
+ if (!lineOfSight(arena, me.x, ey, me.z, b.x, b.y, b.z) && !lineOfSight(arena, cam.x, cam.y, cam.z, b.x, b.y, b.z)) continue;
+ bolts.push({ id: b.id, x: b.x, y: b.y, z: b.z, vx: b.vx, vy: b.vy, vz: b.vz, owner: b.owner, kind: b.kind });
+ }
+ const heard: { x: number; z: number }[] = [];
+ let hurtFrom: { x: number; z: number } | null = null;
+ let ping: { x: number; z: number } | null = null;
+ for (const ev of view.events ?? []) {
+ if (ev.type === "shot" && ev.player === enemySlot) heard.push({ x: ev.x, z: ev.z });
+ else if (ev.type === "hit" && ev.target === slot) hurtFrom = { x: ev.fromX, z: ev.fromZ };
+ else if (ev.type === "ping" && ev.player === enemySlot) ping = { x: ev.x, z: ev.z };
+ }
+ let footsteps: { x: number; z: number } | null = null;
+ if (e && e.alive && me.alive && !enemy) {
+ const speed = Math.hypot(e.vx, e.vz);
+ const range = e.sprinting ? FOOTSTEP_SPRINT_M : FOOTSTEP_RUN_M;
+ if (speed > 3 && Math.hypot(e.x - me.x, e.z - me.z) <= range) footsteps = { x: q(e.x, 2), z: q(e.z, 2) };
+ }
+ return {
+ tick: view.tick, phase: view.phase, round: view.round, scores: view.scores, slot, me,
+ enemySlot, enemyAlive: !!e && e.alive, enemyHealth: e ? e.health : 0,
+ enemy, bolts, heard, hurtFrom, footsteps, ping,
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/protocol.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/protocol.ts
new file mode 100644
index 0000000000..bbecc88c39
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/protocol.ts
@@ -0,0 +1,154 @@
+/**
+ * The duel wire protocol, version 2.
+ *
+ * Messages are JSON arrays with a one-letter tag (compact, schema-free on the
+ * wire, typed here). Numbers in states and inputs are integers on a fixed
+ * grid; the simulation quantises its state to the same grid after every
+ * step, so encode/decode is lossless and a client replays from exactly the
+ * server's state.
+ *
+ * client -> server
+ * ["h", v, playerId, name, rulesHash] hello (reliable); rulesHash covers tuning and arena
+ * ["i", lastSnapTick, [input, ...]] the newest inputs, oldest first;
+ * each send repeats the last few (loss)
+ * ["l"] leave = forfeit (reliable)
+ * ["p", clientMs] ping
+ * server -> client
+ * ["w", v, slot, matchId, seed, tuningHash, arenaId, snapshotEvery, config, playerIds] welcome (reliable)
+ * ["s", tick, ackSeq, state, events] snapshot (unreliable, full state); the events
+ * since the snapshot the client last confirmed
+ * ["e", winner, reason, scores, tick, ackSeq, state, events]
+ * match over, with the final snapshot (reliable)
+ * ["o", clientMs, serverTick] pong
+ * ["r", reason] rejected (reliable)
+ *
+ * input = [seq, mx*127, my*127, yaw*1e4, pitch*1e4, buttons, viewTick]
+ */
+import { AIM_SCALE, MOVE_SCALE } from "./input";
+import type {
+ BoltKind, BoltState, CombatEvent, EndReason, InputCommand, MatchConfig, MatchPhase, MatchState, PlayerState, PlayerStats,
+} from "./types";
+
+/** 2: the end message carries the final snapshot; snapshots carry the events since the last confirmed one. */
+export const PROTOCOL_VERSION = 2;
+
+export type EncodedInput = [number, number, number, number, number, number, number];
+export type EncodedState = (number | (string | number)[] | (string | number)[][])[];
+
+export type ClientMsg =
+ | ["h", number, string, string, number]
+ | ["i", number, EncodedInput[]]
+ | ["l"]
+ | ["p", number];
+
+export type ServerMsg =
+ | ["w", number, number, string, number, number, string, number, MatchConfig, string[]]
+ | ["s", number, number, EncodedState, CombatEvent[]]
+ /** Match over; carries the final snapshot (tick, ackSeq, state, events) so it cannot be overtaken by it. */
+ | ["e", number, EndReason, number[], number, number, EncodedState, CombatEvent[]]
+ | ["o", number, number]
+ | ["r", string];
+
+export function isReliable(msg: ClientMsg | ServerMsg): boolean {
+ if (!Array.isArray(msg)) return false;
+ const t = msg[0];
+ return t === "h" || t === "l" || t === "w" || t === "e" || t === "r";
+}
+
+// ---------------------------------------------------------------- inputs
+
+export function encodeInput(c: InputCommand): EncodedInput {
+ return [c.seq, Math.round(c.mx * MOVE_SCALE), Math.round(c.my * MOVE_SCALE), Math.round(c.yaw * AIM_SCALE), Math.round(c.pitch * AIM_SCALE), c.buttons, c.viewTick];
+}
+
+export function decodeInput(e: EncodedInput): InputCommand {
+ return { seq: e[0], mx: e[1] / MOVE_SCALE, my: e[2] / MOVE_SCALE, yaw: e[3] / AIM_SCALE, pitch: e[4] / AIM_SCALE, buttons: e[5], viewTick: e[6] };
+}
+
+// ---------------------------------------------------------------- state
+
+type NumKey = { [K in keyof PlayerState]: PlayerState[K] extends number | boolean ? K : never }[keyof PlayerState];
+
+/** Player fields in wire order with their grid (0 = boolean). */
+export const PLAYER_FIELDS: readonly (readonly [NumKey, number])[] = [
+ ["slot", 1], ["side", 1], ["x", 1000], ["z", 1000], ["vx", 1000], ["vz", 1000], ["yaw", AIM_SCALE], ["pitch", AIM_SCALE],
+ ["recoilPitch", 1000], ["recoilYaw", 1000], ["alive", 0], ["health", 1000], ["lastDamageTick", 1],
+ ["mx", MOVE_SCALE], ["my", MOVE_SCALE], ["buttons", 1], ["lastSeq", 1],
+ ["heat", 1000], ["lastShotTick", 1], ["nextShotTick", 1], ["bloom", 1000], ["shotCount", 1],
+ ["ventStart", 1], ["ventEnd", 1], ["ventWinStart", 1], ["ventWinEnd", 1], ["ventFromHeat", 1000], ["ventForced", 0], ["ventAttempted", 0],
+ ["ads", 1000], ["sprinting", 0], ["sprintEndTick", 1],
+ ["shieldUp", 0], ["shieldEnergy", 1000], ["shieldRaisedAt", 1], ["shieldLoweredAt", 1], ["shieldBrokenUntil", 1],
+ ["shieldNeedsRelease", 0], ["shieldParryUsed", 0], ["parryReadyAt", 1],
+ ["dodgeStart", 1], ["dodgeUntil", 1], ["dodgeReadyAt", 1], ["dodgeDx", 10000], ["dodgeDz", 10000],
+];
+
+export const STAT_FIELDS: readonly (readonly [keyof PlayerStats, number])[] = [
+ ["shots", 1], ["hits", 1], ["headshots", 1], ["damageDealt", 100], ["damageTaken", 100], ["blocks", 1], ["parries", 1],
+ ["deflects", 1], ["dodges", 1], ["overheats", 1], ["perfectVents", 1], ["ventMisses", 1], ["kills", 1],
+];
+
+const PHASES: readonly MatchPhase[] = ["countdown", "live", "round_end", "ended"];
+const REASONS: readonly EndReason[] = ["rounds", "forfeit", "disconnect", "draw", "cancelled"];
+const KINDS: readonly BoltKind[] = ["shot", "deflect", "parry"];
+
+function encodePlayer(p: PlayerState): (string | number)[] {
+ const out: (string | number)[] = [p.id];
+ for (const [k, scale] of PLAYER_FIELDS) {
+ const v = p[k];
+ out.push(scale === 0 ? (v ? 1 : 0) : Math.round((v as number) * scale));
+ }
+ for (const [k, scale] of STAT_FIELDS) out.push(Math.round(p.stats[k] * scale));
+ return out;
+}
+
+function decodePlayer(a: (string | number)[]): PlayerState {
+ const p = { id: String(a[0]) } as Record<string, unknown>;
+ let i = 1;
+ for (const [k, scale] of PLAYER_FIELDS) {
+ const v = a[i++] as number;
+ p[k] = scale === 0 ? v === 1 : v / scale + 0;
+ }
+ const stats = {} as Record<string, number>;
+ for (const [k, scale] of STAT_FIELDS) stats[k] = (a[i++] as number) / scale + 0;
+ p.stats = stats;
+ return p as unknown as PlayerState;
+}
+
+function encodeBolt(b: BoltState): number[] {
+ return [b.id, b.owner, b.shooter, KINDS.indexOf(b.kind), Math.round(b.x * 1000), Math.round(b.y * 1000), Math.round(b.z * 1000),
+ Math.round(b.vx * 1000), Math.round(b.vy * 1000), Math.round(b.vz * 1000), Math.round(b.damageMul * 10000), Math.round(b.traveled * 1000), b.bornTick, b.reflections];
+}
+
+function decodeBolt(a: number[]): BoltState {
+ return {
+ id: a[0], owner: a[1], shooter: a[2], kind: KINDS[a[3]] ?? "shot",
+ x: a[4] / 1000 + 0, y: a[5] / 1000 + 0, z: a[6] / 1000 + 0, vx: a[7] / 1000 + 0, vy: a[8] / 1000 + 0, vz: a[9] / 1000 + 0,
+ damageMul: a[10] / 10000 + 0, traveled: a[11] / 1000 + 0, bornTick: a[12], reflections: a[13],
+ };
+}
+
+/** Everything but the lag-compensation history (the server keeps that to itself). */
+export function encodeState(s: MatchState): EncodedState {
+ return [
+ s.tick, PHASES.indexOf(s.phase), s.phaseStart, s.phaseEndsAt, s.round, s.roundStartTick, s.scores[0], s.scores[1],
+ s.winner === null ? -9 : s.winner, s.endReason === null ? -1 : REASONS.indexOf(s.endReason), s.nextBoltId, s.seed,
+ s.players.map(encodePlayer), s.bolts.map(encodeBolt),
+ ];
+}
+
+export function decodeState(e: EncodedState, config: MatchConfig): MatchState {
+ const n = (i: number) => e[i] as number;
+ return {
+ v: 1, tick: n(0), phase: PHASES[n(1)] ?? "live", phaseStart: n(2), phaseEndsAt: n(3), round: n(4), roundStartTick: n(5),
+ scores: [n(6), n(7)], winner: n(8) === -9 ? null : n(8), endReason: n(9) < 0 ? null : REASONS[n(9)] ?? "cancelled",
+ nextBoltId: n(10), seed: n(11), config,
+ players: (e[12] as (string | number)[][]).map(decodePlayer),
+ bolts: (e[13] as unknown as number[][]).map(decodeBolt),
+ history: { ticks: [], poses: [] },
+ };
+}
+
+/** Bytes a message takes as JSON text (for budgets and tests). */
+export function wireSize(msg: ClientMsg | ServerMsg): number {
+ return JSON.stringify(msg).length;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/raycast.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/raycast.test.ts
new file mode 100644
index 0000000000..e572e55e91
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/raycast.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { closestApproachXZ, sweepBox, sweepCapsule, sweepCylinder, sweepOut, sweepSphere } from "./raycast";
+import { hash32, rand01, Rng } from "./rng";
+
+describe("segment sweeps", () => {
+ const o = sweepOut();
+
+ it("enters a box at the near face with its normal", () => {
+ const t = sweepBox(0, 1, 0, 10, 0, 0, 4, 0, -1, 6, 2, 1, o);
+ expect(t).toBeCloseTo(0.4, 9);
+ expect([o.nx, o.ny, o.nz]).toEqual([-1, 0, 0]);
+ expect(sweepBox(0, 3, 0, 10, 0, 0, 4, 0, -1, 6, 2, 1, o)).toBe(-1);
+ expect(sweepBox(0, 1, 0, 3, 0, 0, 4, 0, -1, 6, 2, 1, o)).toBe(-1);
+ });
+
+ it("hits a vertical cylinder's side and its top cap", () => {
+ expect(sweepCylinder(-5, 1, 0, 10, 0, 0, 0, 0, 1, 0, 2, o)).toBeCloseTo(0.4, 9);
+ expect(o.nx).toBeCloseTo(-1, 9);
+ const t = sweepCylinder(0.2, 5, 0, 0, -10, 0, 0, 0, 1, 0, 2, o);
+ expect(t).toBeCloseTo(0.3, 9);
+ expect(o.ny).toBe(1);
+ expect(sweepCylinder(-5, 3, 0, 10, 0, 0, 0, 0, 1, 0, 2, o)).toBe(-1);
+ });
+
+ it("hits a capsule on its side and its rounded ends", () => {
+ expect(sweepCapsule(-5, 1, 0, 10, 0, 0, 0, 0, 0.5, 1.5, 0.4, o)).toBeCloseTo(0.46, 9);
+ // Just over the top segment end: the cap still catches it.
+ expect(sweepCapsule(-5, 1.7, 0, 10, 0, 0, 0, 0, 0.5, 1.5, 0.4, o)).toBeGreaterThan(0);
+ expect(sweepCapsule(-5, 2.0, 0, 10, 0, 0, 0, 0, 0.5, 1.5, 0.4, o)).toBe(-1);
+ expect(sweepSphere(-5, 0, 0, 10, 0, 0, 0, 0, 0, 1, o)).toBeCloseTo(0.4, 9);
+ });
+
+ it("reports the closest approach of a moving point", () => {
+ const c = closestApproachXZ(-10, 1, 10, 0, 0, 0);
+ expect(c.t).toBeCloseTo(1, 9);
+ expect(c.dist).toBeCloseTo(1, 9);
+ });
+});
+
+describe("seeded randomness", () => {
+ it("hashes are stable and spread", () => {
+ expect(hash32(1)).toBe(hash32(1));
+ expect(hash32(1)).not.toBe(hash32(2));
+ let sum = 0;
+ for (let i = 0; i < 2000; i++) sum += rand01(7, i, 3, 1);
+ expect(sum / 2000).toBeGreaterThan(0.45);
+ expect(sum / 2000).toBeLessThan(0.55);
+ });
+
+ it("a generator replays from its state", () => {
+ const a = new Rng(42);
+ a.next();
+ const copy = new Rng(0);
+ copy.state = a.state;
+ expect([a.next(), a.next()]).toEqual([copy.next(), copy.next()]);
+ const n = new Rng(3);
+ let s = 0;
+ let s2 = 0;
+ for (let i = 0; i < 4000; i++) { const v = n.normal(); s += v; s2 += v * v; }
+ expect(Math.abs(s / 4000)).toBeLessThan(0.06);
+ expect(Math.sqrt(s2 / 4000)).toBeGreaterThan(0.93);
+ expect(Math.sqrt(s2 / 4000)).toBeLessThan(1.07);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/raycast.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/raycast.ts
new file mode 100644
index 0000000000..a27477aaad
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/raycast.ts
@@ -0,0 +1,206 @@
+/**
+ * Segment sweeps: P(t) = A + t·D for t in [0, 1]. Each test returns the
+ * entry parameter t (0 when A starts inside) or -1 for a miss, and writes the
+ * surface normal into `out`. Allocation-free; the bolts call these every tick.
+ */
+
+export interface SweepOut {
+ t: number;
+ nx: number;
+ ny: number;
+ nz: number;
+}
+
+export function sweepOut(): SweepOut {
+ return { t: -1, nx: 0, ny: 0, nz: 0 };
+}
+
+/** Axis-aligned box. */
+export function sweepBox(
+ ax: number, ay: number, az: number, dx: number, dy: number, dz: number,
+ x0: number, y0: number, z0: number, x1: number, y1: number, z1: number,
+ out: SweepOut,
+): number {
+ let tmin = 0;
+ let tmax = 1;
+ let axis = -1;
+ let sign = 0;
+ // x slab
+ if (Math.abs(dx) < 1e-12) {
+ if (ax < x0 || ax > x1) return -1;
+ } else {
+ const inv = 1 / dx;
+ let t0 = (x0 - ax) * inv;
+ let t1 = (x1 - ax) * inv;
+ let s = -1;
+ if (t0 > t1) { const tmp = t0; t0 = t1; t1 = tmp; s = 1; }
+ if (t0 > tmin) { tmin = t0; axis = 0; sign = s; }
+ if (t1 < tmax) tmax = t1;
+ if (tmin > tmax) return -1;
+ }
+ // y slab
+ if (Math.abs(dy) < 1e-12) {
+ if (ay < y0 || ay > y1) return -1;
+ } else {
+ const inv = 1 / dy;
+ let t0 = (y0 - ay) * inv;
+ let t1 = (y1 - ay) * inv;
+ let s = -1;
+ if (t0 > t1) { const tmp = t0; t0 = t1; t1 = tmp; s = 1; }
+ if (t0 > tmin) { tmin = t0; axis = 1; sign = s; }
+ if (t1 < tmax) tmax = t1;
+ if (tmin > tmax) return -1;
+ }
+ // z slab
+ if (Math.abs(dz) < 1e-12) {
+ if (az < z0 || az > z1) return -1;
+ } else {
+ const inv = 1 / dz;
+ let t0 = (z0 - az) * inv;
+ let t1 = (z1 - az) * inv;
+ let s = -1;
+ if (t0 > t1) { const tmp = t0; t0 = t1; t1 = tmp; s = 1; }
+ if (t0 > tmin) { tmin = t0; axis = 2; sign = s; }
+ if (t1 < tmax) tmax = t1;
+ if (tmin > tmax) return -1;
+ }
+ out.t = tmin;
+ out.nx = axis === 0 ? sign : 0;
+ out.ny = axis === 1 ? sign : 0;
+ out.nz = axis === 2 ? sign : 0;
+ if (axis === -1) {
+ // Started inside: push back against the travel direction.
+ const l = Math.hypot(dx, dy, dz) || 1;
+ out.nx = -dx / l; out.ny = -dy / l; out.nz = -dz / l;
+ }
+ return tmin;
+}
+
+/** Vertical cylinder (axis along y) with caps. */
+export function sweepCylinder(
+ ax: number, ay: number, az: number, dx: number, dy: number, dz: number,
+ cx: number, cz: number, r: number, y0: number, y1: number,
+ out: SweepOut,
+): number {
+ const ex = ax - cx;
+ const ez = az - cz;
+ const c = ex * ex + ez * ez - r * r;
+ if (c <= 0 && ay >= y0 && ay <= y1) {
+ out.t = 0;
+ const l = Math.hypot(ex, ez) || 1;
+ out.nx = ex / l; out.ny = 0; out.nz = ez / l;
+ return 0;
+ }
+ let best = -1;
+ const a = dx * dx + dz * dz;
+ if (a > 1e-12 && c > 0) {
+ const b = 2 * (ex * dx + ez * dz);
+ const disc = b * b - 4 * a * c;
+ if (disc >= 0) {
+ const t = (-b - Math.sqrt(disc)) / (2 * a);
+ if (t >= 0 && t <= 1) {
+ const y = ay + t * dy;
+ if (y >= y0 && y <= y1) {
+ best = t;
+ out.nx = (ex + t * dx) / r; out.ny = 0; out.nz = (ez + t * dz) / r;
+ }
+ }
+ }
+ }
+ if (Math.abs(dy) > 1e-12) {
+ // Top cap from above, bottom cap from below.
+ const capY = dy < 0 ? y1 : y0;
+ const t = (capY - ay) / dy;
+ if (t >= 0 && t <= 1 && (best < 0 || t < best)) {
+ const px = ex + t * dx;
+ const pz = ez + t * dz;
+ if (px * px + pz * pz <= r * r) {
+ best = t;
+ out.nx = 0; out.ny = dy < 0 ? 1 : -1; out.nz = 0;
+ }
+ }
+ }
+ out.t = best;
+ return best;
+}
+
+export function sweepSphere(
+ ax: number, ay: number, az: number, dx: number, dy: number, dz: number,
+ cx: number, cy: number, cz: number, r: number,
+ out: SweepOut,
+): number {
+ const ex = ax - cx;
+ const ey = ay - cy;
+ const ez = az - cz;
+ const c = ex * ex + ey * ey + ez * ez - r * r;
+ if (c <= 0) {
+ const l = Math.hypot(ex, ey, ez) || 1;
+ out.t = 0; out.nx = ex / l; out.ny = ey / l; out.nz = ez / l;
+ return 0;
+ }
+ const a = dx * dx + dy * dy + dz * dz;
+ if (a < 1e-12) return -1;
+ const b = 2 * (ex * dx + ey * dy + ez * dz);
+ const disc = b * b - 4 * a * c;
+ if (disc < 0) return -1;
+ const t = (-b - Math.sqrt(disc)) / (2 * a);
+ if (t < 0 || t > 1) return -1;
+ out.t = t;
+ out.nx = (ex + t * dx) / r; out.ny = (ey + t * dy) / r; out.nz = (ez + t * dz) / r;
+ return t;
+}
+
+const tmp = sweepOut();
+
+/** Vertical capsule: the segment (cx, yb, cz)–(cx, yt, cz) inflated by r. */
+export function sweepCapsule(
+ ax: number, ay: number, az: number, dx: number, dy: number, dz: number,
+ cx: number, cz: number, yb: number, yt: number, r: number,
+ out: SweepOut,
+): number {
+ let best = -1;
+ // The open cylinder between the two sphere centres.
+ const ex = ax - cx;
+ const ez = az - cz;
+ const c = ex * ex + ez * ez - r * r;
+ const a = dx * dx + dz * dz;
+ if (c <= 0 && ay >= yb && ay <= yt) {
+ const l = Math.hypot(ex, ez) || 1;
+ out.t = 0; out.nx = ex / l; out.ny = 0; out.nz = ez / l;
+ return 0;
+ }
+ if (a > 1e-12 && c > 0) {
+ const b = 2 * (ex * dx + ez * dz);
+ const disc = b * b - 4 * a * c;
+ if (disc >= 0) {
+ const t = (-b - Math.sqrt(disc)) / (2 * a);
+ if (t >= 0 && t <= 1) {
+ const y = ay + t * dy;
+ if (y >= yb && y <= yt) {
+ best = t;
+ out.nx = (ex + t * dx) / r; out.ny = 0; out.nz = (ez + t * dz) / r;
+ }
+ }
+ }
+ }
+ for (let k = 0; k < 2; k++) {
+ const t = sweepSphere(ax, ay, az, dx, dy, dz, cx, k === 0 ? yb : yt, cz, r, tmp);
+ if (t >= 0 && (best < 0 || t < best)) {
+ best = t;
+ out.nx = tmp.nx; out.ny = tmp.ny; out.nz = tmp.nz;
+ }
+ }
+ out.t = best;
+ return best;
+}
+
+/** Closest approach of a moving point to a vertical axis, for "will this bolt pass near me". */
+export function closestApproachXZ(px: number, pz: number, vx: number, vz: number, cx: number, cz: number): { t: number; dist: number } {
+ const ex = cx - px;
+ const ez = cz - pz;
+ const vv = vx * vx + vz * vz;
+ const t = vv > 1e-12 ? (ex * vx + ez * vz) / vv : 0;
+ const qx = px + vx * t - cx;
+ const qz = pz + vz * t - cz;
+ return { t, dist: Math.hypot(qx, qz) };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/rng.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/rng.ts
new file mode 100644
index 0000000000..111443c01a
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/rng.ts
@@ -0,0 +1,93 @@
+/**
+ * Seeded randomness for the combat simulation. Nothing in combat/ calls
+ * Math.random or reads a clock.
+ *
+ * Two kinds:
+ * - `hashN` / `rand01`: counter-based. A draw is a pure function of
+ * (match seed, who, which shot, salt), so a client predicting its own shot
+ * gets the same spread as the server without sharing an RNG stream.
+ * - `Rng`: a small sequential generator (mulberry32) with a one-number state,
+ * for the bots and the harness, which own their stream.
+ */
+
+/** 32-bit avalanche hash (lowbias32). */
+export function hash32(x: number): number {
+ x >>>= 0;
+ x ^= x >>> 16;
+ x = Math.imul(x, 0x7feb352d);
+ x ^= x >>> 15;
+ x = Math.imul(x, 0x846ca68b);
+ x ^= x >>> 16;
+ return x >>> 0;
+}
+
+export function hash2(a: number, b: number): number {
+ return hash32(hash32(a) ^ Math.imul(b | 0, 0x9e3779b1));
+}
+
+export function hash3(a: number, b: number, c: number): number {
+ return hash32(hash2(a, b) ^ Math.imul(c | 0, 0x85ebca77));
+}
+
+export function hash4(a: number, b: number, c: number, d: number): number {
+ return hash32(hash3(a, b, c) ^ Math.imul(d | 0, 0xc2b2ae3d));
+}
+
+/** Uniform in [0, 1) from four integers. */
+export function rand01(a: number, b: number, c: number, d: number): number {
+ return hash4(a, b, c, d) / 4294967296;
+}
+
+/** Salts so different draws for the same event never correlate. */
+export const SALT = {
+ spreadA: 1,
+ spreadB: 2,
+ spreadC: 3,
+ recoilYaw: 4,
+ deflectRoll: 5,
+ deflectYaw: 6,
+ deflectPitch: 7,
+ parryYaw: 8,
+ parryPitch: 9,
+} as const;
+
+/** Sequential seeded generator (mulberry32). `state` is the whole state. */
+export class Rng {
+ state: number;
+
+ constructor(seed: number) {
+ this.state = hash32(seed ^ 0x6d2b79f5) >>> 0;
+ }
+
+ /** Uniform in [0, 1). */
+ next(): number {
+ let t = (this.state = (this.state + 0x6d2b79f5) >>> 0);
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ }
+
+ range(lo: number, hi: number): number {
+ return lo + (hi - lo) * this.next();
+ }
+
+ int(n: number): number {
+ return Math.floor(this.next() * n);
+ }
+
+ chance(p: number): boolean {
+ return this.next() < p;
+ }
+
+ /** Normal deviate (Box-Muller). */
+ normal(mean = 0, sd = 1): number {
+ const u = Math.max(this.next(), 1e-12);
+ const v = this.next();
+ return mean + sd * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
+ }
+
+ /** A fresh generator split off this one (for a sub-system that needs its own stream). */
+ fork(salt: number): Rng {
+ return new Rng(hash2(this.state, salt));
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/server.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/server.ts
new file mode 100644
index 0000000000..27e6be5ca2
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/server.ts
@@ -0,0 +1,243 @@
+/**
+ * The authoritative duel server. It owns the MatchState; players (human or
+ * bot, local or remote) only send InputCommands.
+ *
+ * - Accepts channels; a duel starts once two players said hello with the
+ * same protocol version and tuning.
+ * - Runs the fixed 60 Hz step on its own clock (`update(nowMs)`).
+ * - Each player's inputs go into a queue; one is applied per tick. A late
+ * player's last input is repeated (held buttons stay held, presses are not
+ * repeated); a queue that grows past `maxQueue` is trimmed so a player who
+ * fell behind catches up instead of lagging forever.
+ * - Every `snapshotEvery` ticks each player gets the full state, the last
+ * input it applied for them (`ackSeq`, for reconciliation) and the events
+ * of the last two snapshot periods (repeated so a lost snapshot loses no
+ * effects; clients drop duplicates by eventKey).
+ * - Leave or a closed channel ends the match for the other player.
+ *
+ * Runs in the browser today (in-process, LocalNetwork) and unchanged in Node
+ * behind a WebSocket later.
+ */
+import { decodeInput, encodeState, PROTOCOL_VERSION, type ClientMsg, type EncodedInput, type ServerMsg } from "./protocol";
+import { createMatch, endMatch, rulesHash, step, type SimContext } from "./sim";
+import { TICK_RATE } from "./tuning";
+import { EDGE_BUTTONS, type CombatEvent, type InputCommand, type MatchConfig, type MatchState } from "./types";
+import type { ServerChannel } from "./transport";
+
+/** Events kept for clients that stop confirming snapshots (ticks). Older ones are dropped. */
+const EVENT_WINDOW_TICKS = 90;
+
+const isInt = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v);
+
+export interface MatchServerOptions {
+ ctx: SimContext;
+ seed: number;
+ matchId?: string;
+ config?: Partial<MatchConfig>;
+ /** Send a snapshot every N ticks (1 = 60 Hz in-process, 2 = 30 Hz over a network). */
+ snapshotEvery?: number;
+ /** Inputs buffered per player before the oldest are dropped. */
+ maxQueue?: number;
+ /** Rewind shots to what the shooter saw (PvP over a network). */
+ lagCompensation?: boolean;
+}
+
+interface Conn {
+ channel: ServerChannel;
+ playerId: string;
+ name: string;
+ slot: number;
+ queue: InputCommand[];
+ lastQueued: number;
+ /** Newest snapshot tick the client says it has (from its input messages). */
+ snapAck: number;
+ unsub: (() => void)[];
+}
+
+export class MatchServer {
+ state: MatchState | null = null;
+ readonly matchId: string;
+ private readonly ctx: SimContext;
+ private readonly opts: Required<Omit<MatchServerOptions, "ctx" | "config" | "matchId">> & { config?: Partial<MatchConfig> };
+ private readonly hash: number;
+ private conns: Conn[] = [];
+ private lobby: { channel: ServerChannel; unsub: (() => void)[] }[] = [];
+ private acc = 0;
+ private lastNow: number | null = null;
+ private recent: CombatEvent[] = [];
+ private listeners = new Set<(events: readonly CombatEvent[], state: MatchState) => void>();
+ private ended = false;
+
+ constructor(o: MatchServerOptions) {
+ this.ctx = o.ctx;
+ this.matchId = o.matchId ?? `duel-${(o.seed >>> 0).toString(36)}`;
+ this.opts = { seed: o.seed, snapshotEvery: o.snapshotEvery ?? 2, maxQueue: o.maxQueue ?? 6, lagCompensation: o.lagCompensation ?? false, config: o.config };
+ this.hash = rulesHash(o.ctx);
+ }
+
+ /** Every step's events and the new state (for logging or a spectator). */
+ onStep(cb: (events: readonly CombatEvent[], state: MatchState) => void): () => void {
+ this.listeners.add(cb);
+ return () => this.listeners.delete(cb);
+ }
+
+ accept(channel: ServerChannel): void {
+ const entry = { channel, unsub: [] as (() => void)[] };
+ entry.unsub.push(channel.onMessage((msg) => this.lobbyMessage(entry, msg)));
+ this.lobby.push(entry);
+ }
+
+ private lobbyMessage(entry: { channel: ServerChannel; unsub: (() => void)[] }, msg: ClientMsg): void {
+ if (!Array.isArray(msg) || msg[0] !== "h") return;
+ const [, v, playerId, name, hash] = msg;
+ const reject = (why: string) => { entry.channel.send(["r", why]); entry.channel.close(); };
+ if (v !== PROTOCOL_VERSION) return reject(`protocol ${v} != ${PROTOCOL_VERSION}`);
+ if (hash !== this.hash) return reject("tuning or arena differs");
+ if (typeof playerId !== "string" || playerId.length === 0 || playerId.length > 64) return reject("bad player id");
+ if (this.state || this.conns.length >= 2) return reject("match full");
+ if (this.conns.some((c) => c.playerId === playerId)) return reject("duplicate player");
+ for (const u of entry.unsub) u();
+ this.lobby = this.lobby.filter((l) => l !== entry);
+ const conn: Conn = { channel: entry.channel, playerId, name: String(name ?? playerId).slice(0, 64), slot: this.conns.length, queue: [], lastQueued: -1, snapAck: -1, unsub: [] };
+ conn.unsub.push(conn.channel.onMessage((m) => this.message(conn, m)));
+ conn.unsub.push(conn.channel.onClose(() => this.drop(conn, "disconnect")));
+ this.conns.push(conn);
+ if (this.conns.length === 2) this.start();
+ }
+
+ private start(): void {
+ const ctx = this.ctx;
+ this.state = createMatch(ctx, { seed: this.opts.seed, playerIds: this.conns.map((c) => c.playerId), config: this.opts.config });
+ const ids = this.conns.map((c) => c.playerId);
+ for (const c of this.conns) {
+ c.channel.send(["w", PROTOCOL_VERSION, c.slot, this.matchId, this.state.seed, this.hash, ctx.arena.def.id, this.opts.snapshotEvery, this.state.config, ids]);
+ }
+ this.sendSnapshots();
+ }
+
+ /**
+ * A client message. Nothing from the wire is trusted: malformed messages are
+ * ignored, and inputs are made legal by the simulation (sanitizeInput).
+ */
+ private message(c: Conn, msg: ClientMsg): void {
+ if (!Array.isArray(msg)) return;
+ if (msg[0] === "i") {
+ const list = msg[2];
+ if (!Array.isArray(list)) return;
+ if (isInt(msg[1]) && msg[1] > c.snapAck && (!this.state || msg[1] <= this.state.tick)) c.snapAck = msg[1];
+ for (const e of list.slice(-32) as EncodedInput[]) {
+ if (!Array.isArray(e) || !isInt(e[0])) continue;
+ const cmd = decodeInput(e);
+ if (cmd.seq <= c.lastQueued) continue;
+ c.queue.push(cmd);
+ c.lastQueued = cmd.seq;
+ }
+ } else if (msg[0] === "l") {
+ this.drop(c, "forfeit");
+ } else if (msg[0] === "p") {
+ if (typeof msg[1] === "number") c.channel.send(["o", msg[1], this.state ? this.state.tick : 0]);
+ }
+ }
+
+ private drop(c: Conn, reason: "forfeit" | "disconnect"): void {
+ if (this.state && this.state.phase !== "ended") {
+ const res = endMatch(this.state, 1 - c.slot, reason);
+ this.state = res.state;
+ this.publish(res.events);
+ this.finish();
+ }
+ }
+
+ /** Run every tick due by `nowMs`. */
+ update(nowMs: number): void {
+ if (this.lastNow === null) this.lastNow = nowMs;
+ const dt = Math.min(250, Math.max(0, nowMs - this.lastNow));
+ this.lastNow = nowMs;
+ if (!this.state || this.ended) return;
+ this.acc += dt;
+ const tickMs = 1000 / TICK_RATE;
+ while (this.acc >= tickMs && this.state && !this.ended) {
+ this.acc -= tickMs;
+ this.tick();
+ }
+ }
+
+ /** One authoritative tick (also usable directly by a headless host). */
+ tick(): void {
+ const s = this.state;
+ if (!s || this.ended) return;
+ const cmds: (InputCommand | null)[] = [];
+ for (const c of this.conns) {
+ // A player who fell behind catches up: the oldest inputs are dropped,
+ // but their presses (roll, vent, forfeit) carry over into the next one.
+ let carry = 0;
+ while (c.queue.length > this.opts.maxQueue) carry |= (c.queue.shift() as InputCommand).buttons & EDGE_BUTTONS;
+ let cmd = c.queue.shift() ?? null;
+ if (cmd && carry) cmd = { ...cmd, buttons: cmd.buttons | carry };
+ cmds[c.slot] = cmd && !this.opts.lagCompensation ? { ...cmd, viewTick: -1 } : cmd;
+ }
+ const res = step(s, cmds, this.ctx);
+ this.state = res.state;
+ this.publish(res.events);
+ if (this.state.tick % this.opts.snapshotEvery === 0 || this.state.phase === "ended") this.sendSnapshots();
+ if (this.state.phase === "ended") this.finish();
+ }
+
+ private publish(events: readonly CombatEvent[]): void {
+ if (!this.state) return;
+ const tick = this.state.tick;
+ let cut = 0;
+ while (cut < this.recent.length && tick - this.recent[cut].tick > EVENT_WINDOW_TICKS) cut++;
+ this.recent = (cut > 0 ? this.recent.slice(cut) : this.recent).concat(events);
+ for (const l of [...this.listeners]) l(events, this.state);
+ }
+
+ /**
+ * Events a client still needs: everything since the newest snapshot it
+ * confirmed (it got the events up to that tick with it), at least the last
+ * two snapshot periods, at most EVENT_WINDOW_TICKS. A lost snapshot thus
+ * loses no effect; the client drops repeats by eventKey.
+ */
+ private eventsFor(c: Conn, tick: number): CombatEvent[] {
+ const from = Math.max(tick - EVENT_WINDOW_TICKS, Math.min(c.snapAck - 1, tick - this.opts.snapshotEvery * 2));
+ let i = 0;
+ while (i < this.recent.length && this.recent[i].tick < from) i++;
+ return i === 0 ? this.recent : this.recent.slice(i);
+ }
+
+ private sendSnapshots(): void {
+ const s = this.state;
+ if (!s) return;
+ const enc = encodeState(s);
+ for (const c of this.conns) {
+ const ack = s.players[c.slot].lastSeq;
+ c.channel.send(["s", s.tick, ack, enc, this.eventsFor(c, s.tick)] as ServerMsg);
+ }
+ }
+
+ private finish(): void {
+ if (this.ended || !this.state) return;
+ this.ended = true;
+ const s = this.state;
+ const enc = encodeState(s);
+ for (const c of this.conns) {
+ // Reliable, and with the final snapshot inside: the end can never arrive
+ // without the last state and its events (death, round and match end).
+ c.channel.send(["e", s.winner ?? -1, s.endReason ?? "cancelled", s.scores.slice(), s.tick, s.players[c.slot].lastSeq, enc, this.eventsFor(c, s.tick)]);
+ for (const u of c.unsub) u();
+ }
+ }
+
+ /** Stop the match now (host closed the duel). */
+ cancel(): void {
+ if (!this.state || this.ended) return;
+ const res = endMatch(this.state, -1, "cancelled");
+ this.state = res.state;
+ this.publish(res.events);
+ this.finish();
+ }
+
+ get finished(): boolean {
+ return this.ended;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/session.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/session.test.ts
new file mode 100644
index 0000000000..cc1376bc9c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/session.test.ts
@@ -0,0 +1,89 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { cameraPose, cameraRigFor, crosshairRadiusPx, resolveAim } from "./camera";
+import { idleControl } from "./input";
+import { createLocalDuel } from "./session";
+import { step } from "./sim";
+import { liveMatch, place } from "./testing";
+import { DEFAULT_TUNING, withTuning } from "./tuning";
+import { buildView } from "./view";
+import { makeInput } from "./input";
+import type { CombatEvent } from "./types";
+
+describe("local duel session", () => {
+ it("plays a whole match against the bot and reports it", () => {
+ const duel = createLocalDuel({ difficulty: "normal", seed: 3 });
+ const events: CombatEvent[] = [];
+ let frames = 0;
+ let sawHud = false;
+ while (!duel.finished && frames < 60 * 60 * 6) {
+ const { view, events: ev } = duel.frame(16.7, idleControl());
+ events.push(...ev);
+ frames++;
+ if (view?.hud) {
+ sawHud = true;
+ expect(view.hud.heat).toBeGreaterThanOrEqual(0);
+ expect(view.hud.heat).toBeLessThanOrEqual(1);
+ expect(view.hud.shieldEnergy).toBeLessThanOrEqual(1);
+ expect(view.players).toHaveLength(2);
+ }
+ }
+ expect(sawHud).toBe(true);
+ expect(duel.finished).toBe(true);
+ // Standing still does not win duels.
+ expect(duel.result?.outcome).toBe("lost");
+ expect(duel.result?.rounds).toEqual([0, 2]);
+ const types = new Set(events.map((e) => e.type));
+ for (const t of ["countdown", "round_start", "shot", "hit", "death", "round_end", "match_end"] as const) expect(types.has(t), t).toBe(true);
+ duel.dispose();
+ });
+
+ it("can be left at any time", () => {
+ const duel = createLocalDuel({ difficulty: "elite", seed: 4 });
+ for (let i = 0; i < 60; i++) duel.frame(16.7, idleControl());
+ duel.forfeit();
+ for (let i = 0; i < 10 && !duel.finished; i++) duel.frame(16.7, idleControl());
+ expect(duel.finished).toBe(true);
+ expect(duel.result?.outcome).toBe("lost");
+ expect(duel.result?.reason).toBe("forfeit");
+ });
+
+ it("runs over a laggy link too", () => {
+ const duel = createLocalDuel({ difficulty: "hard", seed: 5, latencyMs: 60, jitterMs: 20, loss: 0.05 });
+ let frames = 0;
+ while (!duel.finished && frames < 60 * 60 * 6) { duel.frame(16.7, idleControl()); frames++; }
+ expect(duel.finished).toBe(true);
+ expect(duel.result?.reason).toBe("rounds");
+ });
+});
+
+describe("camera hooks", () => {
+ it("converges the blaster on what the crosshair covers", () => {
+ const exact = withTuning(DEFAULT_TUNING, { blaster: { hipSpreadDeg: 0, moveSpreadHipDeg: 0 } });
+ const { ctx, state } = liveMatch({ tuning: exact });
+ const s = place(state, { x: 38.8, z: 10 }, { x: 40.5, z: 27 });
+ const view = buildView(ctx, s, s, 1, 0, [], "playing");
+ const me = view.players[0];
+ const target = view.players[1];
+ const rig = cameraRigFor(me);
+ // Look from the shoulder camera at the target's chest.
+ const pose = cameraPose({ ...me, yaw: Math.atan2(target.x - me.x, target.z - me.z), pitch: 0 }, rig);
+ const dir = { x: target.x - pose.position.x, y: 1.2 - pose.position.y, z: target.z - pose.position.z };
+ const aim = resolveAim(ctx, view, pose.position, dir);
+ expect(aim.target).toBe("player");
+ // Fire along the solution: it hits.
+ let st = s;
+ let hit = false;
+ for (let i = 0; i < 40 && !hit; i++) {
+ const res = step(st, [makeInput(i, { ...idleControl(aim.yaw, aim.pitch), fire: i === 0 }), null], ctx);
+ st = res.state;
+ hit = res.events.some((e) => e.type === "hit" && e.target === 1);
+ }
+ expect(hit).toBe(true);
+ });
+
+ it("sizes the crosshair from the spread and the field of view", () => {
+ expect(crosshairRadiusPx(1.6, 70, 1000)).toBeGreaterThan(crosshairRadiusPx(0.3, 70, 1000));
+ expect(crosshairRadiusPx(1, 50, 1000)).toBeGreaterThan(crosshairRadiusPx(1, 70, 1000));
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts
new file mode 100644
index 0000000000..9aadb76c6d
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts
@@ -0,0 +1,150 @@
+/**
+ * A duel against the bot, in-process: the one object the 3D view needs.
+ *
+ * const duel = createLocalDuel({ difficulty: "hard" });
+ * // every animation frame:
+ * const { view, events } = duel.frame(dtMs, controlsFromKeysAndMouse);
+ * // view: players, bolts, HUD, match clock; events: shots, hits, parries...
+ * duel.forfeit(); // leave at any time
+ *
+ * Inside it is exactly the multiplayer shape: an authoritative MatchServer,
+ * a LocalNetwork, a MatchClient for the person (prediction and
+ * reconciliation) and a MatchClient for the bot whose controller is a
+ * BotBrain reading only its own observations. PvP later swaps the bot client
+ * for a remote player and the LocalNetwork for a WebSocket; nothing else
+ * changes.
+ */
+import { buildArena, type Arena, type ArenaDef } from "./arena";
+import { REACTOR_ARENA } from "./arenaReactor";
+import { BotBrain } from "./bot/brain";
+import { botParams, type BotParams, type BotTier } from "./bot/tiers";
+import { MatchClient } from "./client";
+import { idleControl, type ControlState } from "./input";
+import { observe } from "./observe";
+import { hash2 } from "./rng";
+import { MatchServer } from "./server";
+import type { SimContext } from "./sim";
+import { LocalNetwork } from "./transport";
+import { DEFAULT_TUNING, type CombatTuning } from "./tuning";
+import type { CombatEvent, EndReason, MatchConfig, PlayerStats } from "./types";
+import type { ViewState } from "./view";
+
+export interface LocalDuelOptions {
+ difficulty?: BotTier;
+ /** Finer control over the bot than a tier. */
+ bot?: Partial<BotParams>;
+ seed?: number;
+ arena?: ArenaDef;
+ tuning?: CombatTuning;
+ config?: Partial<MatchConfig>;
+ playerId?: string;
+ playerName?: string;
+ /** Simulated one-way latency between the person and the in-process server, ms (0 = none). */
+ latencyMs?: number;
+ jitterMs?: number;
+ loss?: number;
+}
+
+export interface DuelResult {
+ outcome: "won" | "lost" | "draw" | "cancelled";
+ reason: EndReason;
+ /** Rounds won: [person, bot]. */
+ rounds: [number, number];
+ stats: { player: PlayerStats; bot: PlayerStats } | null;
+}
+
+export interface FrameResult {
+ view: ViewState | null;
+ events: CombatEvent[];
+}
+
+export interface LocalDuel {
+ readonly arena: Arena;
+ readonly ctx: SimContext;
+ readonly difficulty: BotTier;
+ /** Advance by `dtMs` with the person's controls; returns this frame's view and new events. Keep calling until `finished`. */
+ frame(dtMs: number, control: ControlState): FrameResult;
+ forfeit(): void;
+ readonly result: DuelResult | null;
+ readonly finished: boolean;
+ dispose(): void;
+}
+
+export function createLocalDuel(o: LocalDuelOptions = {}): LocalDuel {
+ const tuning = o.tuning ?? DEFAULT_TUNING;
+ const arena = buildArena(o.arena ?? REACTOR_ARENA, tuning.body.radius);
+ const ctx: SimContext = { arena, tuning };
+ const seed = (o.seed ?? 1) >>> 0;
+ const difficulty = o.difficulty ?? "hard";
+ const net = new LocalNetwork(hash2(seed, 0x0e7));
+ const laggy = (o.latencyMs ?? 0) > 0 || (o.jitterMs ?? 0) > 0;
+ // Lag compensation on: shots are judged against what the shooter saw (the
+ // opponent is drawn a little in the past), for the person and the bot alike.
+ const server = new MatchServer({ ctx, seed, config: o.config, snapshotEvery: laggy ? 2 : 1, lagCompensation: true });
+ const human = net.link({ latencyMs: o.latencyMs ?? 0, jitterMs: o.jitterMs ?? 0, loss: o.loss ?? 0 });
+ const bot = net.link();
+ server.accept(human.server);
+ server.accept(bot.server);
+ const playerId = o.playerId ?? "commander";
+ // In-process every tick brings a snapshot, so the opponent is drawn just one tick back.
+ const interpDelayTicks = laggy ? undefined : 1;
+ const person = new MatchClient({ ctx, channel: human.client, playerId, name: o.playerName ?? "Commander", interpDelayTicks });
+ const brain = { current: null as BotBrain | null };
+ const botClient = new MatchClient({
+ ctx, channel: bot.client, playerId: `bot-${difficulty}`, name: `Bot (${difficulty})`, interpDelayTicks: 1,
+ controller: (view, slot) => {
+ if (!brain.current) brain.current = new BotBrain(slot, botParams(difficulty, o.bot), arena, tuning, hash2(seed, 0xb07));
+ return brain.current.think(observe(view, slot, arena, tuning));
+ },
+ });
+ let now = 0;
+ let disposed = false;
+ const pump = () => net.advance(now);
+ pump();
+
+ const resultOf = (): DuelResult | null => {
+ const s = server.state;
+ if (!s || s.phase !== "ended") return null;
+ const me = person.slot;
+ const them = 1 - me;
+ const outcome = s.endReason === "cancelled" ? "cancelled" : s.winner === me ? "won" : s.winner === them ? "lost" : "draw";
+ return {
+ outcome, reason: s.endReason ?? "cancelled", rounds: [s.scores[me] ?? 0, s.scores[them] ?? 0],
+ stats: me >= 0 ? { player: { ...s.players[me].stats }, bot: { ...s.players[them].stats } } : null,
+ };
+ };
+
+ return {
+ arena, ctx, difficulty,
+ frame(dtMs: number, control: ControlState): FrameResult {
+ if (disposed) return { view: null, events: [] };
+ now += Math.min(250, Math.max(0, dtMs));
+ person.setControl(control);
+ pump();
+ server.update(now);
+ pump();
+ botClient.update(now);
+ person.update(now);
+ pump();
+ botClient.drainEvents();
+ return { view: person.view(now), events: person.drainEvents() };
+ },
+ forfeit() {
+ person.setControl({ ...idleControl(), forfeit: true });
+ person.forfeit();
+ pump();
+ server.update(now);
+ pump();
+ },
+ get result() { return resultOf(); },
+ // Over once the person's client has the end (so the last events reached the view).
+ get finished() { return person.status === "ended" || person.status === "closed" || person.status === "rejected"; },
+ dispose() {
+ disposed = true;
+ if (!server.finished) server.cancel();
+ pump();
+ person.dispose();
+ botClient.dispose();
+ },
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/sim.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/sim.test.ts
new file mode 100644
index 0000000000..8444177dbe
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/sim.test.ts
@@ -0,0 +1,351 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { makeInput, idleControl } from "./input";
+import { createContext, createMatch, spreadDeg, step } from "./sim";
+import { count, liveMatch, place, runner } from "./testing";
+import { DEFAULT_TUNING, withTuning } from "./tuning";
+import type { CombatEvent } from "./types";
+
+/** No spread, bloom or recoil: every bolt goes where it is aimed. */
+const EXACT = withTuning(DEFAULT_TUNING, {
+ blaster: {
+ hipSpreadDeg: 0, adsSpreadDeg: 0, moveSpreadHipDeg: 0, moveSpreadAdsDeg: 0,
+ bloomPerShotHipDeg: 0, bloomPerShotAdsDeg: 0, recoilPitchHipDeg: 0, recoilPitchAdsDeg: 0, recoilYawDeg: 0,
+ },
+});
+const ONE_SHOT = withTuning(EXACT, { blaster: { damageNear: 500, damageFar: 500 } });
+
+// A clear 16 m lane on the west floor of the reactor hall.
+const A = { x: 38.8, z: 12 };
+const B = { x: 38.8, z: 28 };
+
+function first<T extends CombatEvent["type"]>(ev: CombatEvent[], type: T): Extract<CombatEvent, { type: T }> {
+ const e = ev.find((x) => x.type === type);
+ if (!e) throw new Error(`no ${type} event`);
+ return e as Extract<CombatEvent, { type: T }>;
+}
+
+describe("match flow", () => {
+ it("counts down, then starts round 1 with the players at opposite spawns", () => {
+ const ctx = createContext();
+ let s = createMatch(ctx, { seed: 3, playerIds: ["me", "bot"] });
+ expect(s.phase).toBe("countdown");
+ const [p, o] = s.players;
+ expect(Math.hypot(p.x - o.x, p.z - o.z)).toBeGreaterThan(25);
+ const events: CombatEvent[] = [];
+ for (let i = 0; i < DEFAULT_TUNING.match.countdownTicks; i++) {
+ // Movement and fire are ignored during the countdown.
+ const res = step(s, [makeInput(i, { ...idleControl(), moveY: 1, fire: true }), null], ctx);
+ s = res.state;
+ events.push(...res.events);
+ }
+ expect(s.phase).toBe("live");
+ expect(events[0].type).toBe("countdown");
+ expect(count(events, "round_start")).toBe(1);
+ expect(count(events, "shot")).toBe(0);
+ expect(s.players[0].x).toBe(p.x);
+ });
+});
+
+describe("blaster", () => {
+ it("fires five bolts a second that fly at 60 m/s", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ const ev = r.run(60, { fire: true });
+ expect(count(ev, "shot", 0)).toBe(5);
+ const shot = first(ev, "shot");
+ const hit = first(ev, "hit");
+ // 16 m minus the muzzle reach and the hit capsule's radius, at 1 m per tick.
+ expect(hit.tick - shot.tick).toBeGreaterThanOrEqual(14);
+ expect(hit.tick - shot.tick).toBeLessThanOrEqual(16);
+ expect(hit.target).toBe(1);
+ });
+
+ it("loses damage with distance and gains it on the head", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const near = runner(ctx, place(state, A, { x: 38.8, z: 20 }));
+ const e1 = first(near.run(20, { fire: true }), "hit");
+ expect(e1.damage).toBeCloseTo(DEFAULT_TUNING.blaster.damageNear, 1);
+ const far = runner(ctx, place(state, { x: 38.8, z: 6 }, { x: 38.8, z: 34 }));
+ const e2 = first(far.run(40, { fire: true }), "hit");
+ expect(e2.damage).toBeLessThan(e1.damage);
+ // Aim up at the head: muzzle 1.38 m, head 1.65 m, 8 m away.
+ const head = runner(ctx, place(state, A, { x: 38.8, z: 20 }));
+ const pitch = Math.atan2(1.68 - 1.38, 7.55);
+ const e3 = first(head.run(20, { fire: true, pitch }), "hit");
+ expect(e3.headshot).toBe(true);
+ expect(e3.damage).toBeCloseTo(e1.damage * DEFAULT_TUNING.health.headshotMul, 1);
+ });
+
+ it("overheats on the 12th shot in a row and locks the blaster", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ // Firing at the far wall, away from the other player.
+ const ev = r.run(12 * 12, { fire: true, yaw: Math.PI });
+ const oh = first(ev, "overheat");
+ expect(oh.shot).toBe(11);
+ expect(r.state.players[0].ventStart).toBeGreaterThanOrEqual(0);
+ const more = r.run(60, { fire: true, yaw: Math.PI });
+ expect(count(more, "shot", 0)).toBe(0);
+ const rest = r.run(DEFAULT_TUNING.blaster.overheatTicks, { fire: true, yaw: Math.PI });
+ expect(count(rest, "vent_end", 0)).toBe(1);
+ expect(count(rest, "shot", 0)).toBeGreaterThan(0);
+ });
+
+ it("a vent press inside the window ends the overheat early; a miss waits it out", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const s0 = place(state, A, B);
+ const good = runner(ctx, s0);
+ good.run(12 * 12 - 11, { fire: true, yaw: Math.PI });
+ const p = good.state.players[0];
+ expect(p.ventForced).toBe(true);
+ const wait = p.ventWinStart + 3 - good.state.tick;
+ good.run(wait);
+ const ev = good.run(1, { vent: true });
+ expect(count(ev, "vent_perfect", 0)).toBe(1);
+ expect(good.state.players[0].heat).toBe(0);
+ expect(good.state.players[0].ventStart).toBe(-1);
+
+ const bad = runner(ctx, s0);
+ bad.run(12 * 12 - 11, { fire: true, yaw: Math.PI });
+ bad.run(10);
+ const miss = bad.run(1, { vent: true });
+ expect(count(miss, "vent_miss", 0)).toBe(1);
+ // A second press in the window no longer counts.
+ const q = bad.state.players[0];
+ bad.run(q.ventWinStart + 2 - bad.state.tick);
+ expect(count(bad.run(1, { vent: true }), "vent_perfect")).toBe(0);
+ expect(bad.state.players[0].ventStart).toBeGreaterThanOrEqual(0);
+ });
+
+ it("a manual vent clears heat faster than waiting, a timed one faster still", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const s0 = place(state, A, B);
+ const ticksToCool = (mode: "wait" | "vent" | "perfect") => {
+ const r = runner(ctx, s0);
+ r.run(8 * 12 - 11, { fire: true, yaw: Math.PI });
+ const start = r.state.tick;
+ if (mode !== "wait") r.run(1, { vent: true });
+ for (let i = 0; i < 600 && r.state.players[0].heat > 0; i++) {
+ const p = r.state.players[0];
+ r.run(1, { vent: mode === "perfect" && p.ventStart >= 0 && r.state.tick === p.ventWinStart + 1 });
+ }
+ return r.state.tick - start;
+ };
+ const wait = ticksToCool("wait");
+ const vent = ticksToCool("vent");
+ const perfect = ticksToCool("perfect");
+ expect(vent).toBeLessThan(wait);
+ expect(perfect).toBeLessThan(vent);
+ });
+
+ it("aiming down sights tightens the cone and moving widens it", () => {
+ const { ctx, state } = liveMatch();
+ const r = runner(ctx, place(state, A, B));
+ const hip = spreadDeg(DEFAULT_TUNING, r.state.players[0]);
+ r.run(30, { ads: true });
+ const ads = spreadDeg(DEFAULT_TUNING, r.state.players[0]);
+ expect(ads).toBeLessThan(hip / 3);
+ r.run(30, { moveX: 1 });
+ expect(spreadDeg(DEFAULT_TUNING, r.state.players[0])).toBeGreaterThan(hip);
+ });
+});
+
+describe("energy shield", () => {
+ it("absorbs bolts from the front and pays for them with energy", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ r.run(30, {}, { shield: true });
+ const ev = r.run(40, { fire: true }, { shield: true });
+ expect(count(ev, "hit")).toBe(0);
+ expect(count(ev, "block") + count(ev, "deflect")).toBeGreaterThan(2);
+ expect(r.state.players[1].health).toBe(100);
+ expect(r.state.players[1].shieldEnergy).toBeLessThan(70);
+ });
+
+ it("does not cover the back", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, { ...B, yaw: 0 }));
+ r.run(30, {}, { shield: true, yaw: 0 });
+ const ev = r.run(40, { fire: true }, { shield: true, yaw: 0 });
+ expect(count(ev, "hit")).toBeGreaterThan(0);
+ });
+
+ it("parries a bolt met right after raising and sends it back at the shooter", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ r.run(1, { fire: true });
+ r.run(9);
+ const ev = r.run(40, {}, { shield: true });
+ const parry = first(ev, "parry");
+ expect(parry.player).toBe(1);
+ expect(parry.target).toBe(0);
+ const back = first(ev, "hit");
+ expect(back.target).toBe(0);
+ expect(back.owner).toBe(1);
+ expect(r.state.players[1].health).toBe(100);
+ expect(r.state.players[1].stats.parries).toBe(1);
+ });
+
+ it("breaks when empty, drops for the cooldown, and lets bolts through", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ r.run(30, {}, { shield: true });
+ const ev = r.run(12 * 12, { fire: true }, { shield: true });
+ const brk = first(ev, "shield_break");
+ expect(brk.player).toBe(1);
+ const after = ev.filter((e) => e.tick > brk.tick);
+ expect(count(after, "hit")).toBeGreaterThan(0);
+ expect(r.state.players[1].shieldUp).toBe(false);
+ // Holding the key does not bring it back: it needs a fresh press after the cooldown.
+ r.run(DEFAULT_TUNING.shield.brokenTicks + 60, {}, { shield: true });
+ expect(r.state.players[1].shieldUp).toBe(false);
+ r.run(1);
+ r.run(2, {}, { shield: true });
+ expect(r.state.players[1].shieldUp).toBe(true);
+ });
+
+ it("blocks firing while raised and cannot be flicked faster than the lockout", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ const ev = r.run(30, { fire: true, shield: true });
+ expect(count(ev, "shot", 0)).toBe(0);
+ r.run(1); // lower
+ r.run(5, { shield: true }); // too soon
+ expect(r.state.players[0].shieldUp).toBe(false);
+ r.run(1);
+ r.run(DEFAULT_TUNING.shield.reRaiseTicks, { shield: true });
+ expect(r.state.players[0].shieldUp).toBe(true);
+ });
+});
+
+describe("movement", () => {
+ const dist = (shape: Parameters<ReturnType<typeof runner>["run"]>[1]) => {
+ const { ctx, state } = liveMatch();
+ const r = runner(ctx, place(state, A, { x: 70, z: 22 }, ));
+ r.state.players[0].yaw = 0;
+ r.run(60, typeof shape === "function" ? shape : { yaw: 0, ...shape });
+ return Math.hypot(r.state.players[0].x - A.x, r.state.players[0].z - A.z);
+ };
+
+ it("runs, sprints, and slows in sights or behind the shield", () => {
+ const run = dist({ moveY: 1 });
+ const sprint = dist({ moveY: 1, sprint: true });
+ const ads = dist({ moveY: 1, ads: true });
+ const shield = dist({ moveY: 1, shield: true });
+ expect(run).toBeGreaterThan(4.3);
+ expect(run).toBeLessThan(4.8);
+ expect(sprint).toBeGreaterThan(6.2);
+ expect(ads).toBeLessThan(run * 0.75);
+ expect(shield).toBeLessThan(run * 0.6);
+ });
+
+ it("stops at the shaft's edge but crosses on the catwalk", () => {
+ const { ctx, state } = liveMatch();
+ const edge = runner(ctx, place(state, { x: 38.8, z: 18 }, { x: 70, z: 30 }));
+ edge.run(180, { moveY: 1, yaw: Math.PI / 2 });
+ const e = edge.state.players[0];
+ expect(Math.hypot(e.x - 54, e.z - 22)).toBeGreaterThan(13.2);
+ expect(e.x).toBeGreaterThan(40.5);
+ const walk = runner(ctx, place(state, { x: 38.8, z: 22 }, { x: 70, z: 30 }));
+ walk.run(180, { moveY: 1, yaw: Math.PI / 2 });
+ expect(walk.state.players[0].x).toBeGreaterThan(47.5);
+ });
+
+ it("dodge rolls about 4 m and has a cooldown", () => {
+ const { ctx, state } = liveMatch();
+ const r = runner(ctx, place(state, A, B));
+ r.run(1, { dodge: true, moveX: -1 });
+ r.run(30);
+ const p = r.state.players[0];
+ expect(Math.hypot(p.x - A.x, p.z - A.z)).toBeGreaterThan(3.6);
+ expect(Math.hypot(p.x - A.x, p.z - A.z)).toBeLessThan(4.4);
+ expect(count(r.run(1, { dodge: true }), "dodge")).toBe(0);
+ r.run(DEFAULT_TUNING.dodge.cooldownTicks);
+ expect(count(r.run(1, { dodge: true }), "dodge")).toBe(1);
+ });
+});
+
+describe("rounds", () => {
+ it("a kill ends the round, sides swap, and two wins end the match", () => {
+ const { ctx, state } = liveMatch({ tuning: ONE_SHOT });
+ const r = runner(ctx, place(state, A, B));
+ const side0 = r.state.players[0].side;
+ const ev = r.run(30, { fire: true });
+ expect(first(ev, "death").player).toBe(1);
+ const end = first(ev, "round_end");
+ expect(end.winner).toBe(0);
+ expect(r.state.phase).toBe("round_end");
+ r.run(DEFAULT_TUNING.match.roundEndTicks + DEFAULT_TUNING.match.countdownTicks + 1);
+ expect(r.state.phase).toBe("live");
+ expect(r.state.round).toBe(2);
+ expect(r.state.players[0].side).toBe(1 - side0);
+ expect(r.state.players[1].health).toBe(100);
+ r.state = place(r.state, A, B);
+ const ev2 = r.run(30, { fire: true });
+ const me = first(ev2, "match_end");
+ expect(me.winner).toBe(0);
+ expect(me.reason).toBe("rounds");
+ expect(r.state.phase).toBe("ended");
+ });
+
+ it("forfeit ends the match at once in the other player's favour", () => {
+ const { ctx, state } = liveMatch();
+ const r = runner(ctx, state);
+ const ev = r.run(1, { forfeit: true });
+ const me = first(ev, "match_end");
+ expect(me.winner).toBe(1);
+ expect(me.reason).toBe("forfeit");
+ });
+
+ it("health comes back after five quiet seconds", () => {
+ const { ctx, state } = liveMatch({ tuning: EXACT });
+ const r = runner(ctx, place(state, A, B));
+ r.run(13, { fire: true });
+ r.run(30);
+ const hurt = r.state.players[1].health;
+ expect(hurt).toBeLessThan(100);
+ r.run(DEFAULT_TUNING.health.regenDelayTicks - 20);
+ expect(r.state.players[1].health).toBe(hurt);
+ r.run(120);
+ expect(r.state.players[1].health).toBeGreaterThan(hurt + 10);
+ });
+});
+
+describe("determinism", () => {
+ const script = (seed: number) => {
+ const { ctx, state } = liveMatch({ seed });
+ const r = runner(ctx, place(state, A, B));
+ r.run(400, (s) => ({ fire: s.tick % 90 < 50, moveX: Math.sin(s.tick / 20), ads: s.tick % 200 < 100 }),
+ (s) => ({ shield: s.tick % 70 < 20, moveX: -1, fire: s.tick % 70 > 25, dodge: s.tick % 130 === 0 }));
+ return r;
+ };
+
+ it("the same seed and inputs give the same states and events", () => {
+ const a = script(11);
+ const b = script(11);
+ expect(JSON.stringify(a.state)).toBe(JSON.stringify(b.state));
+ expect(JSON.stringify(a.events)).toBe(JSON.stringify(b.events));
+ expect(a.events.length).toBeGreaterThan(20);
+ });
+
+ it("a different seed changes the spread", () => {
+ expect(JSON.stringify(script(11).events)).not.toBe(JSON.stringify(script(12).events));
+ });
+
+ it("the state survives JSON and steps the same after it", () => {
+ const a = script(5);
+ const copy = JSON.parse(JSON.stringify(a.state));
+ expect(copy).toEqual(a.state);
+ const ctx = createContext();
+ const cmd = makeInput(9999, { ...idleControl(0.3, 0), fire: true, moveY: 1 });
+ expect(JSON.stringify(step(copy, [cmd, null], ctx))).toBe(JSON.stringify(step(a.state, [cmd, null], ctx)));
+ });
+
+ it("never mutates the state it is given", () => {
+ const { ctx, state } = liveMatch();
+ const before = JSON.stringify(state);
+ step(state, [makeInput(0, { ...idleControl(), fire: true, moveY: 1, dodge: true }), null], ctx);
+ expect(JSON.stringify(state)).toBe(before);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/sim.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/sim.ts
new file mode 100644
index 0000000000..c86b63de54
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/sim.ts
@@ -0,0 +1,755 @@
+/**
+ * The duel simulation: a pure, deterministic fixed-tick step.
+ *
+ * step(state, inputs, ctx) -> { state, events }
+ *
+ * - `state` is plain JSON (MatchState); the input state is never mutated.
+ * - `inputs[slot]` is that player's InputCommand for this tick, or null to
+ * repeat their last one (held buttons stay held, presses are not repeated).
+ * - No clock, no Math.random: randomness is hashed from the match seed and
+ * the shot or bolt it belongs to, so a client predicting its own shot gets
+ * the server's spread.
+ * - Continuous values are quantised at the end of every step, so a snapshot
+ * on the wire carries the exact state and a client's replay matches the
+ * server's bit for bit.
+ *
+ * Order inside a tick: aim and presses for every player, then shields,
+ * dodges, vents and sights, then movement, then firing, then bolts, then
+ * regeneration and timers, then the round rules.
+ */
+import { buildArena, isWalkable, moveBody, nearestWalkable, raycastWorld, type Arena, type ArenaDef } from "./arena";
+import { REACTOR_ARENA } from "./arenaReactor";
+import { PITCH_LIMIT, sanitizeInput } from "./input";
+import { approach, clamp, DEG, dirFromAngles, forwardX, forwardZ, lerp, q, rightX, rightZ, wrapAngle } from "./math";
+import { sweepCapsule, sweepCylinder, sweepOut } from "./raycast";
+import { hash2, rand01, SALT } from "./rng";
+import { DEFAULT_TUNING, TICK_DT, tuningHash, type CombatTuning } from "./tuning";
+import {
+ BTN, EDGE_BUTTONS,
+ type BoltState, type CombatEvent, type EndReason, type InputCommand, type MatchConfig, type MatchState, type PlayerState, type PlayerStats,
+} from "./types";
+
+export interface SimContext {
+ arena: Arena;
+ tuning: CombatTuning;
+}
+
+export function createContext(def: ArenaDef = REACTOR_ARENA, tuning: CombatTuning = DEFAULT_TUNING): SimContext {
+ return { arena: buildArena(def, tuning.body.radius), tuning };
+}
+
+/**
+ * Everything both ends of a duel must agree on for prediction to match the
+ * server: the tuning and the arena (a re-laid-out room predicts walls in the
+ * wrong places). Compared in the handshake.
+ */
+export function rulesHash(ctx: SimContext): number {
+ const text = JSON.stringify(ctx.arena.def);
+ let h = tuningHash(ctx.tuning);
+ for (let i = 0; i < text.length; i++) h = hash2(h, text.charCodeAt(i));
+ return h >>> 0;
+}
+
+export interface MatchSetup {
+ seed: number;
+ playerIds: readonly string[];
+ config?: Partial<MatchConfig>;
+}
+
+export interface StepResult {
+ state: MatchState;
+ events: CombatEvent[];
+}
+
+/** Chest height used to aim parries and by the bots. */
+export const CHEST_HEIGHT = 1.15;
+
+// ---------------------------------------------------------------- creation
+
+function emptyStats(): PlayerStats {
+ return { shots: 0, hits: 0, headshots: 0, damageDealt: 0, damageTaken: 0, blocks: 0, parries: 0, deflects: 0, dodges: 0, overheats: 0, perfectVents: 0, ventMisses: 0, kills: 0 };
+}
+
+function newPlayer(slot: number, id: string): PlayerState {
+ return {
+ slot, id, side: slot, x: 0, z: 0, vx: 0, vz: 0, yaw: 0, pitch: 0, recoilPitch: 0, recoilYaw: 0,
+ alive: true, health: 0, lastDamageTick: -100000, mx: 0, my: 0, buttons: 0, lastSeq: -1,
+ heat: 0, lastShotTick: -100000, nextShotTick: 0, bloom: 0, shotCount: 0,
+ ventStart: -1, ventEnd: -1, ventWinStart: -1, ventWinEnd: -1, ventFromHeat: 0, ventForced: false, ventAttempted: false,
+ ads: 0, sprinting: false, sprintEndTick: -100000,
+ shieldUp: false, shieldEnergy: 0, shieldRaisedAt: -100000, shieldLoweredAt: -100000, shieldBrokenUntil: 0, shieldNeedsRelease: false, shieldParryUsed: false, parryReadyAt: 0,
+ dodgeStart: -100000, dodgeUntil: -100000, dodgeReadyAt: 0, dodgeDx: 0, dodgeDz: 0,
+ stats: emptyStats(),
+ };
+}
+
+/** Which side (spawn) a slot takes in a round: alternating, the first round by the seed. */
+export function sideFor(seed: number, slot: number, round: number): number {
+ return (slot + round - 1 + (hash2(seed, 0x51de) & 1)) % 2;
+}
+
+function placeForRound(s: MatchState, ctx: SimContext): void {
+ const t = ctx.tuning;
+ for (const p of s.players) {
+ p.side = sideFor(s.seed, p.slot, s.round);
+ const sp = ctx.arena.def.spawns[p.side];
+ p.x = sp.x; p.z = sp.z; p.vx = 0; p.vz = 0; p.yaw = sp.yaw; p.pitch = 0;
+ p.recoilPitch = 0; p.recoilYaw = 0;
+ p.alive = true; p.health = t.health.max; p.lastDamageTick = -100000;
+ p.heat = 0; p.lastShotTick = -100000; p.nextShotTick = 0; p.bloom = 0;
+ p.ventStart = -1; p.ventEnd = -1; p.ventWinStart = -1; p.ventWinEnd = -1; p.ventFromHeat = 0; p.ventForced = false; p.ventAttempted = false;
+ p.ads = 0; p.sprinting = false; p.sprintEndTick = -100000;
+ p.shieldUp = false; p.shieldEnergy = t.shield.energyMax; p.shieldRaisedAt = -100000; p.shieldLoweredAt = -100000;
+ p.shieldBrokenUntil = 0; p.shieldNeedsRelease = (p.buttons & BTN.SHIELD) !== 0;
+ p.shieldParryUsed = false; p.parryReadyAt = 0;
+ p.dodgeStart = -100000; p.dodgeUntil = -100000; p.dodgeReadyAt = 0; p.dodgeDx = 0; p.dodgeDz = 0;
+ }
+ s.bolts = [];
+}
+
+export function createMatch(ctx: SimContext, setup: MatchSetup): MatchState {
+ if (setup.playerIds.length !== 2) throw new Error("A duel takes exactly two players");
+ const m = ctx.tuning.match;
+ const config: MatchConfig = {
+ roundsToWin: m.roundsToWin, maxRounds: m.maxRounds, countdownTicks: m.countdownTicks,
+ roundEndTicks: m.roundEndTicks, roundTimeLimitTicks: m.roundTimeLimitTicks,
+ surgeAfterTicks: m.surgeAfterTicks, pingEveryTicks: m.pingEveryTicks, ...setup.config,
+ };
+ const s: MatchState = {
+ v: 1, seed: setup.seed >>> 0, tick: 0, phase: "countdown", phaseStart: 0, phaseEndsAt: config.countdownTicks,
+ round: 1, roundStartTick: 0, scores: [0, 0], winner: null, endReason: null, config,
+ players: setup.playerIds.map((id, slot) => newPlayer(slot, id)),
+ bolts: [], nextBoltId: 1, history: { ticks: [], poses: [] },
+ };
+ placeForRound(s, ctx);
+ quantise(s);
+ return s;
+}
+
+// ---------------------------------------------------------------- helpers
+
+export function copyState(s: MatchState): MatchState {
+ return {
+ ...s,
+ scores: s.scores.slice(),
+ players: s.players.map((p) => ({ ...p, stats: { ...p.stats } })),
+ bolts: s.bolts.map((b) => ({ ...b })),
+ history: { ticks: s.history.ticks.slice(), poses: s.history.poses.slice() },
+ };
+}
+
+/** Damage of a bolt after flying `dist` metres (before the headshot factor). */
+export function boltDamage(t: CombatTuning, dist: number, mul: number): number {
+ const b = t.blaster;
+ const k = clamp((dist - b.falloffStart) / (b.falloffEnd - b.falloffStart), 0, 1);
+ return lerp(b.damageNear, b.damageFar, k) * mul;
+}
+
+/** Current cone half-angle of a player's blaster, degrees (the crosshair size). */
+export function spreadDeg(t: CombatTuning, p: PlayerState): number {
+ const b = t.blaster;
+ const speed = Math.min(1, Math.hypot(p.vx, p.vz) / t.move.run);
+ return lerp(b.hipSpreadDeg, b.adsSpreadDeg, p.ads) + p.bloom + lerp(b.moveSpreadHipDeg, b.moveSpreadAdsDeg, p.ads) * speed;
+}
+
+/** Muzzle position of a player (world). */
+export function muzzleOf(t: CombatTuning, p: { x: number; z: number; yaw: number }): { x: number; y: number; z: number } {
+ const bd = t.body;
+ return {
+ x: p.x + forwardX(p.yaw) * bd.muzzleForward + rightX(p.yaw) * bd.muzzleRight,
+ y: bd.muzzleHeight,
+ z: p.z + forwardZ(p.yaw) * bd.muzzleForward + rightZ(p.yaw) * bd.muzzleRight,
+ };
+}
+
+/** Why a player cannot fire right now, or null. */
+export function fireBlock(t: CombatTuning, p: PlayerState, tick: number): "shield" | "dodge" | "vent" | "sprint" | "cycle" | null {
+ if (p.shieldUp) return "shield";
+ if (tick < p.dodgeUntil + t.dodge.recoverTicks) return "dodge";
+ if (p.ventStart >= 0) return "vent";
+ if (p.sprinting || tick < p.sprintEndTick + t.move.sprintToFireTicks) return "sprint";
+ if (tick < p.nextShotTick) return "cycle";
+ return null;
+}
+
+export function canRaiseShield(t: CombatTuning, p: PlayerState, tick: number): boolean {
+ return p.alive && tick >= p.shieldBrokenUntil && p.shieldEnergy >= t.shield.raiseMinEnergy
+ && tick - p.shieldLoweredAt >= t.shield.reRaiseTicks && tick >= p.dodgeUntil;
+}
+
+/** Parry window open for this raise: right after raising, and not locked by a whiff. */
+export function parryOpen(t: CombatTuning, p: PlayerState, tick: number): boolean {
+ return p.shieldUp && p.shieldRaisedAt >= p.parryReadyAt && tick - p.shieldRaisedAt <= t.shield.parryWindowTicks;
+}
+
+function lowerShield(t: CombatTuning, p: PlayerState, tick: number, ev: CombatEvent[]): void {
+ if (!p.shieldUp) return;
+ p.shieldUp = false;
+ p.shieldLoweredAt = tick;
+ // A raise whose window met nothing was a whiff: no parry window for a while.
+ if (!p.shieldParryUsed && p.shieldRaisedAt >= p.parryReadyAt) p.parryReadyAt = tick + t.shield.parryWhiffLockTicks;
+ ev.push({ type: "shield_down", tick, player: p.slot });
+}
+
+function breakShield(t: CombatTuning, p: PlayerState, tick: number, ev: CombatEvent[]): void {
+ p.shieldEnergy = 0;
+ p.shieldUp = false;
+ p.shieldLoweredAt = tick;
+ p.shieldBrokenUntil = tick + t.shield.brokenTicks;
+ p.shieldNeedsRelease = true;
+ ev.push({ type: "shield_break", tick, player: p.slot });
+}
+
+function endMatchIn(s: MatchState, winner: number, reason: EndReason, ev: CombatEvent[]): void {
+ if (s.phase === "ended") return;
+ s.phase = "ended";
+ s.phaseStart = s.tick + 1;
+ s.phaseEndsAt = s.tick + 1;
+ s.winner = winner;
+ s.endReason = reason;
+ s.bolts = [];
+ ev.push({ type: "match_end", tick: s.tick, winner, reason, scores: s.scores.slice() });
+}
+
+/**
+ * End a match from outside the step (a player left, the server cancelled).
+ * Pure: returns a new state.
+ */
+export function endMatch(state: MatchState, winner: number, reason: EndReason): StepResult {
+ const s = copyState(state);
+ const events: CombatEvent[] = [];
+ endMatchIn(s, winner, reason, events);
+ return { state: s, events };
+}
+
+// ---------------------------------------------------------------- step
+
+export function step(state: MatchState, inputs: ReadonlyArray<InputCommand | null | undefined>, ctx: SimContext): StepResult {
+ const s = copyState(state);
+ const ev: CombatEvent[] = [];
+ const T = s.tick;
+ if (s.phase === "ended") {
+ s.tick = T + 1;
+ return { state: s, events: ev };
+ }
+ if (s.phase === "countdown" && T === s.phaseStart) ev.push({ type: "countdown", tick: T, round: s.round, endsAt: s.phaseEndsAt });
+
+ // 1. Aim and buttons.
+ const pressedOf: number[] = [];
+ const cmdOf: (InputCommand | null)[] = [];
+ for (const p of s.players) {
+ const raw = inputs[p.slot] ?? null;
+ // Legal commands pass unchanged; anything else (a modified client) is made legal.
+ const inp = raw ? sanitizeInput(raw, p.yaw, p.pitch) : null;
+ cmdOf.push(inp);
+ const buttons = inp ? inp.buttons : p.buttons & ~EDGE_BUTTONS;
+ pressedOf.push(buttons & ~p.buttons);
+ p.buttons = buttons;
+ if (inp) {
+ p.mx = inp.mx;
+ p.my = inp.my;
+ p.yaw = wrapAngle(inp.yaw);
+ p.pitch = clamp(inp.pitch, -PITCH_LIMIT, PITCH_LIMIT);
+ p.lastSeq = inp.seq;
+ }
+ if ((p.buttons & BTN.SHIELD) === 0) p.shieldNeedsRelease = false;
+ }
+ for (const p of s.players) {
+ if (pressedOf[p.slot] & BTN.FORFEIT) {
+ endMatchIn(s, 1 - p.slot, "forfeit", ev);
+ return finish(s, ev, ctx);
+ }
+ }
+
+ if (s.phase === "live") {
+ const t = ctx.tuning;
+ // 2. Shield, dodge, vent, sights, sprint.
+ for (const p of s.players) {
+ if (!p.alive) continue;
+ const seq = p.lastSeq;
+ const pressed = pressedOf[p.slot];
+ const held = p.buttons;
+ // Dodge first: it drops the shield.
+ if ((pressed & BTN.DODGE) && T >= p.dodgeReadyAt && T >= p.dodgeUntil) {
+ let wx = rightX(p.yaw) * p.mx + forwardX(p.yaw) * p.my;
+ let wz = rightZ(p.yaw) * p.mx + forwardZ(p.yaw) * p.my;
+ let l = Math.hypot(wx, wz);
+ if (l < 0.1) { wx = -forwardX(p.yaw); wz = -forwardZ(p.yaw); l = 1; }
+ p.dodgeDx = wx / l;
+ p.dodgeDz = wz / l;
+ p.dodgeStart = T;
+ p.dodgeUntil = T + t.dodge.durationTicks;
+ p.dodgeReadyAt = T + t.dodge.cooldownTicks;
+ if (p.sprinting) { p.sprinting = false; p.sprintEndTick = T; }
+ if (p.shieldUp) { lowerShield(t, p, T, ev); p.shieldNeedsRelease = true; }
+ p.stats.dodges++;
+ ev.push({ type: "dodge", tick: T, player: p.slot, seq, dx: q(p.dodgeDx, 1000), dz: q(p.dodgeDz, 1000) });
+ }
+ const dodging = T < p.dodgeUntil;
+ // Shield: up while held (after a fresh press once it broke or a dodge dropped it).
+ const wantUp = (held & BTN.SHIELD) !== 0 && !p.shieldNeedsRelease;
+ if (p.shieldUp && !wantUp) lowerShield(t, p, T, ev);
+ else if (!p.shieldUp && wantUp && canRaiseShield(t, p, T)) {
+ p.shieldUp = true;
+ p.shieldRaisedAt = T;
+ p.shieldParryUsed = false;
+ p.shieldEnergy = Math.max(0, p.shieldEnergy - t.shield.raiseCost);
+ if (p.sprinting) { p.sprinting = false; p.sprintEndTick = T; }
+ ev.push({ type: "shield_up", tick: T, player: p.slot, seq });
+ }
+ // Vent: start one, or time the press inside a running one.
+ if (pressed & BTN.VENT) {
+ if (p.ventStart >= 0) {
+ if (!p.ventAttempted && T >= p.ventWinStart && T <= p.ventWinEnd) {
+ p.ventStart = -1;
+ p.heat = 0;
+ p.nextShotTick = Math.min(p.nextShotTick, T + 1);
+ p.stats.perfectVents++;
+ ev.push({ type: "vent_perfect", tick: T, player: p.slot, seq });
+ ev.push({ type: "vent_end", tick: T, player: p.slot });
+ } else if (!p.ventAttempted && T > p.ventStart) {
+ p.ventAttempted = true;
+ p.stats.ventMisses++;
+ ev.push({ type: "vent_miss", tick: T, player: p.slot, seq });
+ }
+ } else if (p.heat >= 5) {
+ startVent(t, p, T, false, seq, ev);
+ }
+ }
+ // Sights and sprint.
+ const adsWanted = (held & BTN.ADS) !== 0 && !p.shieldUp && !dodging && !p.sprinting;
+ p.ads = approach(p.ads, adsWanted ? 1 : 0, adsWanted ? 1 / t.blaster.adsInTicks : 1 / t.blaster.adsOutTicks);
+ const mlen = Math.hypot(p.mx, p.my);
+ const sprintOk = (held & BTN.SPRINT) !== 0 && mlen > 0.3 && p.my / mlen >= Math.cos(t.move.sprintConeDeg * DEG)
+ && !p.shieldUp && !dodging && (held & (BTN.FIRE | BTN.ADS)) === 0;
+ if (p.sprinting && !sprintOk) p.sprintEndTick = T;
+ p.sprinting = sprintOk;
+ }
+ // 3. Movement.
+ for (const p of s.players) if (p.alive) movePlayer(s, p, ctx, T);
+ // 4. Firing: every player's trigger first, then the lag-compensated
+ // fast-forward of the new bolts, so a rewound bolt can never stop the
+ // other player's shot of the same tick (no advantage for slot 0).
+ const fired: { bolt: BoltState; cmd: InputCommand | null }[] = [];
+ for (const p of s.players) {
+ if (!p.alive || (p.buttons & BTN.FIRE) === 0 || fireBlock(t, p, T) !== null) continue;
+ fired.push({ bolt: fire(s, p, ctx, T, ev), cmd: cmdOf[p.slot] });
+ }
+ for (const f of fired) rewindBolt(s, f.bolt, ctx, T, f.cmd, ev);
+ // 5. Bolts.
+ updateBolts(s, ctx, T, ev);
+ // 6. Heat, bloom, recoil, shield and health regeneration (no health back once the reactor surges).
+ const surge = surgeActive(s, T);
+ for (const p of s.players) if (p.alive) regenerate(t, p, T, ev, !surge);
+ if (surge) {
+ const since = T - s.roundStartTick - s.config.surgeAfterTicks;
+ if (since === 0) ev.push({ type: "surge", tick: T, round: s.round });
+ if (since % s.config.pingEveryTicks === 0) {
+ for (const p of s.players) if (p.alive) ev.push({ type: "ping", tick: T, player: p.slot, x: q(p.x, 100), z: q(p.z, 100) });
+ }
+ }
+ }
+
+ // 7. Round rules.
+ rules(s, ctx, T, ev);
+ return finish(s, ev, ctx);
+}
+
+function finish(s: MatchState, ev: CombatEvent[], ctx: SimContext): StepResult {
+ quantise(s);
+ // Pose history for lag compensation.
+ const h = s.history;
+ h.ticks.push(s.tick);
+ const pose: number[] = [];
+ for (const p of s.players) pose.push(p.x, p.z);
+ h.poses.push(pose);
+ const keep = ctx.tuning.lagComp.historyTicks;
+ if (h.ticks.length > keep) { h.ticks.splice(0, h.ticks.length - keep); h.poses.splice(0, h.poses.length - keep); }
+ s.tick += 1;
+ return { state: s, events: ev };
+}
+
+function startVent(t: CombatTuning, p: PlayerState, T: number, forced: boolean, seq: number, ev: CombatEvent[]): void {
+ const b = t.blaster;
+ const dur = forced ? b.overheatTicks : Math.round(b.ventBaseTicks + b.ventTicksPerHeat * p.heat);
+ p.ventStart = T;
+ p.ventEnd = T + dur;
+ if (forced) {
+ p.ventWinStart = T + b.overheatWindow[0];
+ p.ventWinEnd = T + b.overheatWindow[1];
+ } else {
+ p.ventWinStart = T + Math.round(dur * b.ventWindowFrac[0]);
+ p.ventWinEnd = T + Math.round(dur * b.ventWindowFrac[1]);
+ }
+ p.ventFromHeat = p.heat;
+ p.ventForced = forced;
+ p.ventAttempted = false;
+ ev.push({ type: "vent_start", tick: T, player: p.slot, seq, forced, end: p.ventEnd, winStart: p.ventWinStart, winEnd: p.ventWinEnd });
+}
+
+function movePlayer(s: MatchState, p: PlayerState, ctx: SimContext, T: number): void {
+ const t = ctx.tuning;
+ const dt = TICK_DT;
+ if (T < p.dodgeUntil) {
+ const n = t.dodge.durationTicks;
+ const k = (T - p.dodgeStart + 0.5) / n;
+ const v0 = (2 * t.dodge.distance) / (n * dt);
+ const v = v0 * Math.max(0, 1 - k);
+ p.vx = p.dodgeDx * v;
+ p.vz = p.dodgeDz * v;
+ } else {
+ const wx = rightX(p.yaw) * p.mx + forwardX(p.yaw) * p.my;
+ const wz = rightZ(p.yaw) * p.mx + forwardZ(p.yaw) * p.my;
+ let max: number;
+ if (p.sprinting) max = t.move.sprint;
+ else {
+ max = t.move.run * lerp(1, t.move.backMul, Math.max(0, -p.my)) * lerp(1, t.move.adsMul, p.ads);
+ if (p.shieldUp) max *= t.move.shieldMul;
+ }
+ const tx = wx * max;
+ const tz = wz * max;
+ const dvx = tx - p.vx;
+ const dvz = tz - p.vz;
+ const dv = Math.hypot(dvx, dvz);
+ const speeding = tx * tx + tz * tz > p.vx * p.vx + p.vz * p.vz;
+ const lim = (speeding ? t.move.accel : t.move.decel) * dt;
+ if (dv <= lim) { p.vx = tx; p.vz = tz; } else { p.vx += (dvx / dv) * lim; p.vz += (dvz / dv) * lim; }
+ }
+ const minD = 2 * t.body.radius;
+ const others = s.players.filter((o) => o !== p && o.alive);
+ const free = others.length === 0 ? undefined : (x: number, z: number) => {
+ for (const o of others) {
+ const dn = (x - o.x) ** 2 + (z - o.z) ** 2;
+ if (dn < minD * minD && dn < (p.x - o.x) ** 2 + (p.z - o.z) ** 2) return false;
+ }
+ return true;
+ };
+ const r = moveBody(ctx.arena, p.x, p.z, p.vx * dt, p.vz * dt, free);
+ if (r.blockedX) p.vx = 0;
+ if (r.blockedZ) p.vz = 0;
+ p.x = r.x;
+ p.z = r.z;
+ if (!isWalkable(ctx.arena, p.x, p.z)) {
+ const n = nearestWalkable(ctx.arena, p.x, p.z, 3);
+ if (n) { p.x = n.x; p.z = n.z; }
+ }
+}
+
+function fire(s: MatchState, p: PlayerState, ctx: SimContext, T: number, ev: CombatEvent[]): BoltState {
+ const t = ctx.tuning;
+ const b = t.blaster;
+ const shot = p.shotCount++;
+ const aimYaw = p.yaw + p.recoilYaw * DEG;
+ const aimPitch = p.pitch + p.recoilPitch * DEG;
+ const cone = spreadDeg(t, p) * DEG;
+ const u1 = rand01(s.seed, p.slot, shot, SALT.spreadA);
+ const u2 = rand01(s.seed, p.slot, shot, SALT.spreadB);
+ const u3 = rand01(s.seed, p.slot, shot, SALT.spreadC);
+ const rad = cone * Math.abs(u1 + u2 - 1);
+ const ang = 2 * Math.PI * u3;
+ const yaw = aimYaw + (rad * Math.cos(ang)) / Math.max(0.2, Math.cos(aimPitch));
+ const pitch = aimPitch + rad * Math.sin(ang);
+ const d = dirFromAngles(yaw, pitch);
+ const m = muzzleOf(t, p);
+ // A muzzle poking through a wall fires from the body instead.
+ let ox = m.x, oy = m.y, oz = m.z;
+ if (raycastWorld(ctx.arena, p.x, m.y, p.z, m.x, m.y, m.z)) { ox = p.x; oz = p.z; }
+ const bolt: BoltState = {
+ id: s.nextBoltId++, owner: p.slot, shooter: p.slot, kind: "shot",
+ x: ox, y: oy, z: oz, vx: d.x * b.boltSpeed, vy: d.y * b.boltSpeed, vz: d.z * b.boltSpeed,
+ damageMul: 1, traveled: 0, bornTick: T, reflections: 0,
+ };
+ s.bolts.push(bolt);
+ p.lastShotTick = T;
+ p.nextShotTick = T + b.fireIntervalTicks;
+ p.bloom = Math.min(lerp(b.bloomMaxHipDeg, b.bloomMaxAdsDeg, p.ads), p.bloom + lerp(b.bloomPerShotHipDeg, b.bloomPerShotAdsDeg, p.ads));
+ p.recoilPitch += lerp(b.recoilPitchHipDeg, b.recoilPitchAdsDeg, p.ads);
+ p.recoilYaw += (rand01(s.seed, p.slot, shot, SALT.recoilYaw) * 2 - 1) * b.recoilYawDeg;
+ p.heat += b.heatPerShot;
+ p.stats.shots++;
+ ev.push({ type: "shot", tick: T, player: p.slot, bolt: bolt.id, shot, x: q(m.x, 1000), y: q(m.y, 1000), z: q(m.z, 1000), dx: q(d.x, 10000), dy: q(d.y, 10000), dz: q(d.z, 10000), heat: q(Math.min(p.heat, 100), 100), ads: p.ads > 0.5 });
+ if (p.heat >= 100) {
+ p.heat = 100;
+ p.stats.overheats++;
+ ev.push({ type: "overheat", tick: T, player: p.slot, shot });
+ startVent(t, p, T, true, p.lastSeq, ev);
+ }
+ return bolt;
+}
+
+/**
+ * Lag compensation: the shooter saw the world `rewind` ticks ago, so the new
+ * bolt is flown through those ticks against the poses of that time.
+ */
+function rewindBolt(s: MatchState, bolt: BoltState, ctx: SimContext, T: number, cmd: InputCommand | null, ev: CombatEvent[]): void {
+ const rewind = cmd && cmd.viewTick >= 0 ? clamp(T - cmd.viewTick, 0, ctx.tuning.lagComp.maxRewindTicks) : 0;
+ for (let k = rewind; k >= 1; k--) {
+ const poses = historyAt(s, T - k);
+ if (!advanceBolt(s, bolt, ctx, T, ev, poses)) {
+ s.bolts.splice(s.bolts.indexOf(bolt), 1);
+ break;
+ }
+ }
+}
+
+/** Player positions at a past tick, or null when it is not in the history. */
+export function historyAt(s: MatchState, tick: number): number[] | null {
+ const i = s.history.ticks.indexOf(tick);
+ return i < 0 ? null : s.history.poses[i];
+}
+
+const swShield = sweepOut();
+const swBody = sweepOut();
+
+/** Fly a bolt one tick. False when it is gone. `poses` overrides where the players stand (lag compensation). */
+function advanceBolt(s: MatchState, b: BoltState, ctx: SimContext, T: number, ev: CombatEvent[], poses: number[] | null): boolean {
+ const t = ctx.tuning;
+ const dt = TICK_DT;
+ const ax = b.x, ay = b.y, az = b.z;
+ const dx = b.vx * dt, dy = b.vy * dt, dz = b.vz * dt;
+ const segLen = Math.hypot(dx, dy, dz);
+ let bestT = 2;
+ let what: "world" | "shield" | "body" = "world";
+ let victim: PlayerState | null = null;
+ let nx = 0, ny = 0, nz = 0;
+ const world = raycastWorld(ctx.arena, ax, ay, az, ax + dx, ay + dy, az + dz);
+ if (world) { bestT = world.t; nx = world.nx; ny = world.ny; nz = world.nz; }
+ const hitR = t.body.hitRadius + t.blaster.boltRadius;
+ for (const o of s.players) {
+ if (!o.alive || o.slot === b.owner) continue;
+ if (T - o.dodgeStart < t.dodge.iframeTicks && T < o.dodgeUntil) continue;
+ const ox = poses ? poses[o.slot * 2] : o.x;
+ const oz = poses ? poses[o.slot * 2 + 1] : o.z;
+ if (o.shieldUp) {
+ const ts = sweepCylinder(ax, ay, az, dx, dy, dz, ox, oz, t.shield.radius, 0, t.shield.height, swShield);
+ if (ts >= 0 && ts < bestT) {
+ const px = ax + dx * ts - ox;
+ const pz = az + dz * ts - oz;
+ const off = Math.abs(wrapAngle(Math.atan2(px, pz) - o.yaw));
+ if (off <= t.shield.arcHalfDeg * DEG) {
+ bestT = ts; what = "shield"; victim = o;
+ const l = Math.hypot(px, pz) || 1;
+ nx = px / l; ny = 0; nz = pz / l;
+ continue;
+ }
+ }
+ }
+ const tb = sweepCapsule(ax, ay, az, dx, dy, dz, ox, oz, t.body.hitBottom, t.body.hitTop, hitR, swBody);
+ if (tb >= 0 && tb < bestT) { bestT = tb; what = "body"; victim = o; }
+ }
+ if (bestT > 1) {
+ b.x = ax + dx; b.y = ay + dy; b.z = az + dz;
+ b.traveled += segLen;
+ if (b.traveled > t.blaster.boltMaxRange || b.y < -4) {
+ ev.push({ type: "bolt_expire", tick: T, bolt: b.id });
+ return false;
+ }
+ return true;
+ }
+ const hx = ax + dx * bestT, hy = ay + dy * bestT, hz = az + dz * bestT;
+ const dist = b.traveled + segLen * bestT;
+ if (what === "world" && world) {
+ if (world.surface === "exit") ev.push({ type: "bolt_expire", tick: T, bolt: b.id });
+ else ev.push({ type: "impact", tick: T, bolt: b.id, surface: world.surface, collider: world.collider, x: q(hx, 1000), y: q(hy, 1000), z: q(hz, 1000), nx, ny, nz });
+ return false;
+ }
+ const o = victim as PlayerState;
+ const shooter = s.players[b.owner];
+ if (what === "body") {
+ const head = hy >= t.body.headFrom;
+ const dmg = boltDamage(t, dist, b.damageMul) * (head ? t.health.headshotMul : 1);
+ o.health -= dmg;
+ o.lastDamageTick = T;
+ o.stats.damageTaken += dmg;
+ if (shooter) {
+ shooter.stats.hits++;
+ shooter.stats.damageDealt += dmg;
+ if (head) shooter.stats.headshots++;
+ }
+ ev.push({ type: "hit", tick: T, bolt: b.id, owner: b.owner, target: o.slot, damage: q(dmg, 100), headshot: head, health: q(Math.max(0, o.health), 100), x: q(hx, 1000), y: q(hy, 1000), z: q(hz, 1000), fromX: q(ax, 1000), fromZ: q(az, 1000) });
+ if (o.health <= 0) {
+ o.health = 0;
+ o.alive = false;
+ o.shieldUp = false;
+ o.vx = 0; o.vz = 0;
+ if (shooter) shooter.stats.kills++;
+ ev.push({ type: "death", tick: T, player: o.slot, killer: b.owner });
+ }
+ return false;
+ }
+ // Shield.
+ const speed = Math.hypot(b.vx, b.vy, b.vz);
+ if (parryOpen(t, o, T)) o.shieldParryUsed = true;
+ if (parryOpen(t, o, T) && b.reflections < t.shield.maxReflections) {
+ // Perfect parry: straight back at whoever sent it.
+ const target = s.players[b.owner];
+ let ux: number, uy: number, uz: number;
+ if (target && target.alive) {
+ const tx = target.x - hx, ty = CHEST_HEIGHT - hy, tz = target.z - hz;
+ const l = Math.hypot(tx, ty, tz) || 1;
+ const yaw = Math.atan2(tx, tz) + (rand01(s.seed, b.id, T, SALT.parryYaw) * 2 - 1) * t.shield.parryAimErrorDeg * DEG;
+ const pitch = Math.asin(clamp(ty / l, -1, 1)) + (rand01(s.seed, b.id, T, SALT.parryPitch) * 2 - 1) * t.shield.parryAimErrorDeg * DEG;
+ const d = dirFromAngles(yaw, pitch);
+ ux = d.x; uy = d.y; uz = d.z;
+ } else {
+ const dot = (b.vx * nx + b.vz * nz) / (speed || 1);
+ ux = b.vx / speed - 2 * dot * nx; uy = b.vy / speed; uz = b.vz / speed - 2 * dot * nz;
+ }
+ const v = Math.min(speed * t.shield.parrySpeedMul, t.blaster.boltSpeed * 1.6);
+ const from = b.owner;
+ b.owner = o.slot;
+ b.kind = "parry";
+ b.reflections++;
+ b.damageMul *= t.shield.parryDamageMul;
+ b.traveled = 0;
+ b.vx = ux * v; b.vy = uy * v; b.vz = uz * v;
+ b.x = hx + ux * 0.05; b.y = hy + uy * 0.05; b.z = hz + uz * 0.05;
+ o.stats.parries++;
+ ev.push({ type: "parry", tick: T, player: o.slot, bolt: b.id, target: from, x: q(hx, 1000), y: q(hy, 1000), z: q(hz, 1000) });
+ return true;
+ }
+ const cost = boltDamage(t, dist, b.damageMul) * t.shield.blockCostPerDamage;
+ o.shieldEnergy -= cost;
+ o.stats.blocks++;
+ const broke = o.shieldEnergy <= 0;
+ if (broke) breakShield(t, o, T, ev);
+ if (!broke && rand01(s.seed, b.id, T, SALT.deflectRoll) < t.shield.deflectChance) {
+ // Glance off at a seeded angle around the mirror direction.
+ const dot = (b.vx * nx + b.vz * nz) / speed;
+ const rx = b.vx / speed - 2 * dot * nx;
+ const rz = b.vz / speed - 2 * dot * nz;
+ const yaw = Math.atan2(rx, rz) + (rand01(s.seed, b.id, T, SALT.deflectYaw) * 2 - 1) * t.shield.deflectSpreadDeg * DEG;
+ const pitch = Math.asin(clamp(b.vy / speed, -1, 1)) * 0.5 + (rand01(s.seed, b.id, T, SALT.deflectPitch) * 2 - 1) * 8 * DEG;
+ const d = dirFromAngles(yaw, pitch);
+ b.owner = o.slot;
+ b.kind = "deflect";
+ b.reflections++;
+ b.damageMul *= t.shield.deflectDamageMul;
+ b.traveled = 0;
+ b.vx = d.x * speed; b.vy = d.y * speed; b.vz = d.z * speed;
+ b.x = hx + d.x * 0.05; b.y = hy + d.y * 0.05; b.z = hz + d.z * 0.05;
+ o.stats.deflects++;
+ ev.push({ type: "deflect", tick: T, player: o.slot, bolt: b.id, x: q(hx, 1000), y: q(hy, 1000), z: q(hz, 1000) });
+ return true;
+ }
+ ev.push({ type: "block", tick: T, player: o.slot, bolt: b.id, energy: q(Math.max(0, o.shieldEnergy), 100), x: q(hx, 1000), y: q(hy, 1000), z: q(hz, 1000) });
+ return false;
+}
+
+function updateBolts(s: MatchState, ctx: SimContext, T: number, ev: CombatEvent[]): void {
+ const keep: BoltState[] = [];
+ for (const b of s.bolts) {
+ if (advanceBolt(s, b, ctx, T, ev, null)) keep.push(b);
+ }
+ s.bolts = keep;
+}
+
+/** True once the round has run long enough for the reactor surge. */
+export function surgeActive(s: MatchState, tick: number): boolean {
+ return s.phase === "live" && tick - s.roundStartTick >= s.config.surgeAfterTicks;
+}
+
+function regenerate(t: CombatTuning, p: PlayerState, T: number, ev: CombatEvent[], healthRegen: boolean): void {
+ const dt = TICK_DT;
+ const b = t.blaster;
+ if (p.ventStart >= 0) {
+ if (T >= p.ventEnd) {
+ p.ventStart = -1;
+ p.heat = 0;
+ ev.push({ type: "vent_end", tick: T, player: p.slot });
+ } else {
+ p.heat = p.ventFromHeat * (1 - (T - p.ventStart) / (p.ventEnd - p.ventStart));
+ }
+ } else if (T - p.lastShotTick > b.heatCoolDelayTicks) {
+ p.heat = Math.max(0, p.heat - b.heatCoolPerSec * dt);
+ }
+ if (T - p.lastShotTick > b.bloomRecoverDelayTicks) p.bloom = Math.max(0, p.bloom - b.bloomRecoverDegPerSec * dt);
+ if (T - p.lastShotTick > 3) {
+ p.recoilPitch = approach(p.recoilPitch, 0, b.recoilRecoverDegPerSec * dt);
+ p.recoilYaw = approach(p.recoilYaw, 0, b.recoilRecoverDegPerSec * dt);
+ }
+ const sh = t.shield;
+ if (p.shieldUp) {
+ p.shieldEnergy -= sh.drainPerSec * dt;
+ if (p.shieldEnergy <= 0) breakShield(t, p, T, ev);
+ } else {
+ if (p.shieldBrokenUntil > 0 && T >= p.shieldBrokenUntil) {
+ p.shieldBrokenUntil = 0;
+ p.shieldLoweredAt = T - sh.regenDelayTicks;
+ ev.push({ type: "shield_ready", tick: T, player: p.slot });
+ }
+ if (p.shieldBrokenUntil === 0 && T - p.shieldLoweredAt >= sh.regenDelayTicks) {
+ p.shieldEnergy = Math.min(sh.energyMax, p.shieldEnergy + sh.regenPerSec * dt);
+ }
+ }
+ if (healthRegen && T - p.lastDamageTick >= t.health.regenDelayTicks) p.health = Math.min(t.health.max, p.health + t.health.regenPerSec * dt);
+}
+
+function rules(s: MatchState, ctx: SimContext, T: number, ev: CombatEvent[]): void {
+ const next = T + 1;
+ if (s.phase === "countdown") {
+ if (next >= s.phaseEndsAt) {
+ s.phase = "live";
+ s.phaseStart = next;
+ s.roundStartTick = next;
+ s.phaseEndsAt = next + s.config.roundTimeLimitTicks;
+ ev.push({ type: "round_start", tick: T, round: s.round });
+ }
+ return;
+ }
+ if (s.phase === "live") {
+ const alive = s.players.filter((p) => p.alive);
+ let winner: number | null = null;
+ let reason: "kill" | "time" | "trade" = "kill";
+ if (alive.length === 0) { winner = -1; reason = "trade"; }
+ else if (alive.length === 1) winner = alive[0].slot;
+ else if (next - s.roundStartTick >= s.config.roundTimeLimitTicks) {
+ const [a, b] = s.players;
+ winner = a.health > b.health ? a.slot : b.health > a.health ? b.slot : -1;
+ reason = "time";
+ }
+ if (winner === null) return;
+ if (winner >= 0) s.scores[winner]++;
+ s.bolts = [];
+ ev.push({ type: "round_end", tick: T, round: s.round, winner, reason, scores: s.scores.slice() });
+ const c = s.config;
+ const best = Math.max(...s.scores);
+ if (best >= c.roundsToWin) {
+ endMatchIn(s, s.scores.indexOf(best), "rounds", ev);
+ } else if (s.round >= c.maxRounds) {
+ const w = s.scores[0] > s.scores[1] ? 0 : s.scores[1] > s.scores[0] ? 1 : -1;
+ endMatchIn(s, w, w < 0 ? "draw" : "rounds", ev);
+ } else {
+ s.phase = "round_end";
+ s.phaseStart = next;
+ s.phaseEndsAt = next + c.roundEndTicks;
+ }
+ return;
+ }
+ if (s.phase === "round_end" && next >= s.phaseEndsAt) {
+ s.round += 1;
+ s.phase = "countdown";
+ s.phaseStart = next;
+ s.phaseEndsAt = next + s.config.countdownTicks;
+ placeForRound(s, ctx);
+ }
+}
+
+/** Snap continuous values to the wire grid (done after every step). */
+export function quantise(s: MatchState): void {
+ for (const p of s.players) {
+ p.x = q(p.x, 1000); p.z = q(p.z, 1000);
+ p.yaw = q(p.yaw, 10000); p.pitch = q(p.pitch, 10000);
+ p.vx = q(p.vx, 1000); p.vz = q(p.vz, 1000);
+ p.recoilPitch = q(p.recoilPitch, 1000); p.recoilYaw = q(p.recoilYaw, 1000);
+ p.health = q(p.health, 1000); p.heat = q(p.heat, 1000); p.bloom = q(p.bloom, 1000);
+ p.ads = q(p.ads, 1000); p.shieldEnergy = q(p.shieldEnergy, 1000); p.ventFromHeat = q(p.ventFromHeat, 1000);
+ p.dodgeDx = q(p.dodgeDx, 10000); p.dodgeDz = q(p.dodgeDz, 10000);
+ p.stats.damageDealt = q(p.stats.damageDealt, 100); p.stats.damageTaken = q(p.stats.damageTaken, 100);
+ }
+ for (const b of s.bolts) {
+ b.x = q(b.x, 1000); b.y = q(b.y, 1000); b.z = q(b.z, 1000);
+ b.vx = q(b.vx, 1000); b.vy = q(b.vy, 1000); b.vz = q(b.vz, 1000);
+ b.traveled = q(b.traveled, 1000); b.damageMul = q(b.damageMul, 10000);
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/testing.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/testing.ts
new file mode 100644
index 0000000000..cfe5624077
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/testing.ts
@@ -0,0 +1,62 @@
+/**
+ * Helpers shared by the combat tests and the balance harness: a match that is
+ * already live, players placed by hand, and a quick way to run ticks.
+ */
+import { idleControl, makeInput, type ControlState } from "./input";
+import { yawOf } from "./math";
+import { createContext, createMatch, step, type SimContext } from "./sim";
+import { DEFAULT_TUNING, type CombatTuning } from "./tuning";
+import type { CombatEvent, InputCommand, MatchConfig, MatchState } from "./types";
+
+export function liveMatch(opts: { tuning?: CombatTuning; seed?: number; config?: Partial<MatchConfig> } = {}): { ctx: SimContext; state: MatchState } {
+ const ctx = createContext(undefined, opts.tuning ?? DEFAULT_TUNING);
+ let state = createMatch(ctx, { seed: opts.seed ?? 7, playerIds: ["a", "b"], config: opts.config });
+ while (state.phase === "countdown") state = step(state, [null, null], ctx).state;
+ return { ctx, state };
+}
+
+/** Put both players somewhere, facing each other unless told otherwise. */
+export function place(state: MatchState, a: { x: number; z: number; yaw?: number }, b: { x: number; z: number; yaw?: number }): MatchState {
+ const s: MatchState = JSON.parse(JSON.stringify(state));
+ const [p, o] = s.players;
+ p.x = a.x; p.z = a.z; p.vx = 0; p.vz = 0; p.yaw = a.yaw ?? yawOf(b.x - a.x, b.z - a.z);
+ o.x = b.x; o.z = b.z; o.vx = 0; o.vz = 0; o.yaw = b.yaw ?? yawOf(a.x - b.x, a.z - b.z);
+ s.history = { ticks: [], poses: [] };
+ return s;
+}
+
+export interface Runner {
+ state: MatchState;
+ events: CombatEvent[];
+ seq: number[];
+ /** Run `n` ticks with these controls (functions are called every tick). */
+ run(n: number, a?: Partial<ControlState> | ((s: MatchState) => Partial<ControlState>), b?: Partial<ControlState> | ((s: MatchState) => Partial<ControlState>)): CombatEvent[];
+}
+
+export function runner(ctx: SimContext, state: MatchState): Runner {
+ const r: Runner = {
+ state,
+ events: [],
+ seq: [0, 0],
+ run(n, a, b) {
+ const out: CombatEvent[] = [];
+ for (let i = 0; i < n; i++) {
+ const cmds: InputCommand[] = [a, b].map((c, slot) => {
+ const p = r.state.players[slot];
+ const partial = typeof c === "function" ? c(r.state) : c ?? {};
+ return makeInput(r.seq[slot]++, { ...idleControl(p.yaw, p.pitch), ...partial });
+ });
+ const res = step(r.state, cmds, ctx);
+ r.state = res.state;
+ out.push(...res.events);
+ }
+ r.events.push(...out);
+ return out;
+ },
+ };
+ return r;
+}
+
+export function count(events: readonly CombatEvent[], type: CombatEvent["type"], player?: number): number {
+ return events.filter((e) => e.type === type && (player === undefined || ("player" in e && e.player === player))).length;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/transport.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/transport.ts
new file mode 100644
index 0000000000..3eb3ec9025
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/transport.ts
@@ -0,0 +1,166 @@
+/**
+ * How duel messages travel. Server and clients only see a Channel; what is
+ * behind it is a detail:
+ *
+ * - LocalNetwork: in-process links on a virtual clock, with optional
+ * latency, jitter and loss (seeded) for tests and for practising against
+ * lag. Messages go through JSON on the way, like on a real wire.
+ * - socketChannel: a thin adapter for a WebSocket (browser or Node) for the
+ * later PvP server. A WebSocket is reliable and ordered; the protocol also
+ * tolerates an unreliable channel (inputs are repeated, snapshots are full).
+ */
+import { isReliable, type ClientMsg, type ServerMsg } from "./protocol";
+import { Rng } from "./rng";
+
+export interface Channel<Out, In> {
+ send(msg: Out): void;
+ /** Subscribe; returns the unsubscribe. */
+ onMessage(cb: (msg: In) => void): () => void;
+ onClose(cb: () => void): () => void;
+ close(): void;
+ readonly open: boolean;
+}
+
+export type ClientChannel = Channel<ClientMsg, ServerMsg>;
+export type ServerChannel = Channel<ServerMsg, ClientMsg>;
+
+export interface LinkOptions {
+ /** One-way delay, ms. */
+ latencyMs?: number;
+ /** Extra random delay 0..jitter, ms (unreliable messages may arrive out of order). */
+ jitterMs?: number;
+ /** Chance an unreliable message is dropped. */
+ loss?: number;
+}
+
+interface Packet { at: number; order: number; text: string; deliver: (text: string) => void }
+
+class Endpoint<Out, In> implements Channel<Out, In> {
+ open = true;
+ peer: Endpoint<In, Out> | null = null;
+ private listeners = new Set<(msg: In) => void>();
+ private closers = new Set<() => void>();
+ private lastReliableAt = 0;
+
+ constructor(private readonly net: LocalNetwork, private readonly opts: Required<LinkOptions>, private readonly rng: Rng, readonly stats: { sent: number; bytes: number; dropped: number }) {}
+
+ send(msg: Out): void {
+ if (!this.open || !this.peer) return;
+ const text = JSON.stringify(msg);
+ this.stats.sent++;
+ this.stats.bytes += text.length;
+ const reliable = isReliable(msg as unknown as ClientMsg | ServerMsg);
+ if (!reliable && this.opts.loss > 0 && this.rng.next() < this.opts.loss) { this.stats.dropped++; return; }
+ let at = this.net.now + this.opts.latencyMs + (this.opts.jitterMs > 0 ? this.rng.next() * this.opts.jitterMs : 0);
+ if (reliable) { at = Math.max(at, this.lastReliableAt); this.lastReliableAt = at; }
+ const peer = this.peer;
+ this.net.enqueue(at, (t) => peer.receive(t), text);
+ }
+
+ receive(text: string): void {
+ if (!this.open) return;
+ const msg = JSON.parse(text) as In;
+ for (const l of [...this.listeners]) l(msg);
+ }
+
+ onMessage(cb: (msg: In) => void): () => void {
+ this.listeners.add(cb);
+ return () => this.listeners.delete(cb);
+ }
+
+ onClose(cb: () => void): () => void {
+ this.closers.add(cb);
+ return () => this.closers.delete(cb);
+ }
+
+ close(): void {
+ if (!this.open) return;
+ this.open = false;
+ for (const c of [...this.closers]) c();
+ const peer = this.peer;
+ if (peer && peer.open) this.net.enqueue(this.net.now + this.opts.latencyMs, () => peer.close(), "");
+ }
+}
+
+/** In-process network on a virtual clock (milliseconds). */
+export class LocalNetwork {
+ now = 0;
+ private queue: Packet[] = [];
+ private order = 0;
+ private readonly rng: Rng;
+
+ constructor(seed = 1) {
+ this.rng = new Rng(seed);
+ }
+
+ /** A client/server pair of channels. */
+ link(opts: LinkOptions = {}): { client: ClientChannel; server: ServerChannel; stats: { up: { sent: number; bytes: number; dropped: number }; down: { sent: number; bytes: number; dropped: number } } } {
+ const o: Required<LinkOptions> = { latencyMs: opts.latencyMs ?? 0, jitterMs: opts.jitterMs ?? 0, loss: opts.loss ?? 0 };
+ const up = { sent: 0, bytes: 0, dropped: 0 };
+ const down = { sent: 0, bytes: 0, dropped: 0 };
+ const client = new Endpoint<ClientMsg, ServerMsg>(this, o, this.rng.fork(this.order + 1), up);
+ const server = new Endpoint<ServerMsg, ClientMsg>(this, o, this.rng.fork(this.order + 2), down);
+ client.peer = server;
+ server.peer = client;
+ this.order += 2;
+ return { client, server, stats: { up, down } };
+ }
+
+ enqueue(at: number, deliver: (text: string) => void, text: string): void {
+ this.queue.push({ at, order: this.order++, text, deliver });
+ }
+
+ /** Move the clock and deliver everything due, in time order. */
+ advance(nowMs: number): void {
+ this.now = Math.max(this.now, nowMs);
+ for (;;) {
+ let best = -1;
+ for (let i = 0; i < this.queue.length; i++) {
+ const p = this.queue[i];
+ if (p.at > this.now) continue;
+ if (best < 0 || p.at < this.queue[best].at || (p.at === this.queue[best].at && p.order < this.queue[best].order)) best = i;
+ }
+ if (best < 0) return;
+ const [p] = this.queue.splice(best, 1);
+ p.deliver(p.text);
+ }
+ }
+
+ get pending(): number {
+ return this.queue.length;
+ }
+}
+
+/** The part of a WebSocket the adapter needs (browser WebSocket and Node `ws` both fit). */
+export interface SocketLike {
+ readonly readyState: number;
+ send(data: string): void;
+ close(): void;
+ addEventListener(type: "message", cb: (ev: { data: unknown }) => void): void;
+ addEventListener(type: "close", cb: () => void): void;
+}
+
+/** A Channel over a WebSocket (JSON text frames). */
+export function socketChannel<Out, In>(ws: SocketLike): Channel<Out, In> {
+ const listeners = new Set<(msg: In) => void>();
+ const closers = new Set<() => void>();
+ let open = true;
+ ws.addEventListener("message", (ev) => {
+ if (typeof ev.data !== "string") return;
+ let msg: In;
+ try { msg = JSON.parse(ev.data) as In; } catch { return; }
+ for (const l of [...listeners]) l(msg);
+ });
+ ws.addEventListener("close", () => {
+ if (!open) return;
+ open = false;
+ for (const c of [...closers]) c();
+ });
+ return {
+ get open() { return open && ws.readyState === 1; },
+ send(msg: Out) { if (open && ws.readyState === 1) ws.send(JSON.stringify(msg)); },
+ onMessage(cb) { listeners.add(cb); return () => listeners.delete(cb); },
+ onClose(cb) { closers.add(cb); return () => closers.delete(cb); },
+ close() { if (open) { open = false; ws.close(); for (const c of [...closers]) c(); } },
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/tuning.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/tuning.ts
new file mode 100644
index 0000000000..1e18229b13
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/tuning.ts
@@ -0,0 +1,302 @@
+/**
+ * Every balance number of the duel in one place. Durations are in ticks of
+ * the fixed simulation step (60 Hz), speeds in metres per second, angles in
+ * degrees, energy/heat/health in points. The defaults are the values the
+ * balance harness settled on (docs/verse/combat.md, "Tuned numbers").
+ *
+ * Server and clients must run the same tuning: the handshake compares
+ * `tuningHash`.
+ */
+import { hash2 } from "./rng";
+
+export const TICK_RATE = 60;
+export const TICK_DT = 1 / TICK_RATE;
+
+/** Seconds to whole ticks. */
+export function ticks(seconds: number): number {
+ return Math.round(seconds * TICK_RATE);
+}
+
+export interface BodyTuning {
+ /** Movement radius (the arena grid is eroded by it). */
+ radius: number;
+ /** Bolt hit capsule: radius and the y range of its core segment. */
+ hitRadius: number;
+ hitBottom: number;
+ hitTop: number;
+ /** A hit at or above this height is a headshot. */
+ headFrom: number;
+ eyeHeight: number;
+ /** Muzzle offset from the feet: up, forward along the aim, to the right. */
+ muzzleHeight: number;
+ muzzleForward: number;
+ muzzleRight: number;
+}
+
+export interface MoveTuning {
+ run: number;
+ /** Speed factor when moving straight back (lerped by how backward the input is). */
+ backMul: number;
+ adsMul: number;
+ shieldMul: number;
+ sprint: number;
+ /** Sprint needs the move input within this many degrees of straight ahead. */
+ sprintConeDeg: number;
+ accel: number;
+ decel: number;
+ /** After sprinting stops, the blaster comes up after this many ticks. */
+ sprintToFireTicks: number;
+}
+
+export interface DodgeTuning {
+ durationTicks: number;
+ distance: number;
+ cooldownTicks: number;
+ /** Ticks at the start of the roll in which bolts pass through. */
+ iframeTicks: number;
+ /** Ticks after the roll before the blaster fires again. */
+ recoverTicks: number;
+}
+
+export interface HealthTuning {
+ max: number;
+ regenDelayTicks: number;
+ regenPerSec: number;
+ headshotMul: number;
+}
+
+export interface BlasterTuning {
+ fireIntervalTicks: number;
+ boltSpeed: number;
+ boltRadius: number;
+ boltMaxRange: number;
+ damageNear: number;
+ damageFar: number;
+ falloffStart: number;
+ falloffEnd: number;
+ heatPerShot: number;
+ heatCoolDelayTicks: number;
+ heatCoolPerSec: number;
+ /** Forced vent after an overheat, and its perfect-timing window (ticks from the start). */
+ overheatTicks: number;
+ overheatWindow: readonly [number, number];
+ /** Manual vent: base ticks plus ticks per point of heat; the window is a fraction of that. */
+ ventBaseTicks: number;
+ ventTicksPerHeat: number;
+ ventWindowFrac: readonly [number, number];
+ /** Cone half-angles (degrees). */
+ hipSpreadDeg: number;
+ adsSpreadDeg: number;
+ /** Extra spread at full run speed. */
+ moveSpreadHipDeg: number;
+ moveSpreadAdsDeg: number;
+ bloomPerShotHipDeg: number;
+ bloomPerShotAdsDeg: number;
+ bloomMaxHipDeg: number;
+ bloomMaxAdsDeg: number;
+ bloomRecoverDegPerSec: number;
+ bloomRecoverDelayTicks: number;
+ /** Recoil kicks the aim up (and a little sideways); it recovers on its own. */
+ recoilPitchHipDeg: number;
+ recoilPitchAdsDeg: number;
+ recoilYawDeg: number;
+ recoilRecoverDegPerSec: number;
+ adsInTicks: number;
+ adsOutTicks: number;
+}
+
+export interface ShieldTuning {
+ energyMax: number;
+ raiseMinEnergy: number;
+ raiseCost: number;
+ drainPerSec: number;
+ /** Energy lost per point of damage a normal block absorbs. */
+ blockCostPerDamage: number;
+ regenDelayTicks: number;
+ regenPerSec: number;
+ brokenTicks: number;
+ /** The shield covers this half-angle either side of the aim yaw. */
+ arcHalfDeg: number;
+ radius: number;
+ height: number;
+ /** A bolt meeting the shield within this many ticks of raising it is parried. */
+ parryWindowTicks: number;
+ /**
+ * Whiff penalty: a raise whose parry window met no bolt leaves the parry
+ * window off for raises within this many ticks after it is lowered.
+ * Timed parries stay strong; flicking the shield earns nothing.
+ */
+ parryWhiffLockTicks: number;
+ /** Ticks after lowering before it can be raised again. */
+ reRaiseTicks: number;
+ /** A normal block deflects (instead of absorbing) with this chance. */
+ deflectChance: number;
+ deflectSpreadDeg: number;
+ deflectDamageMul: number;
+ parryDamageMul: number;
+ parrySpeedMul: number;
+ parryAimErrorDeg: number;
+ /** A bolt is absorbed instead of reflected once it has been reflected this often. */
+ maxReflections: number;
+}
+
+export interface MatchTuning {
+ roundsToWin: number;
+ maxRounds: number;
+ countdownTicks: number;
+ roundEndTicks: number;
+ roundTimeLimitTicks: number;
+ /**
+ * Anti-stalemate "reactor surge": this long into a round, health stops
+ * regenerating and both players' positions are pinged on the HUD every
+ * `pingEveryTicks`.
+ */
+ surgeAfterTicks: number;
+ pingEveryTicks: number;
+}
+
+export interface LagCompTuning {
+ /** Pose history kept for rewinding (ticks). */
+ historyTicks: number;
+ /** A shot is fast-forwarded through at most this many past ticks. */
+ maxRewindTicks: number;
+}
+
+export interface CombatTuning {
+ body: BodyTuning;
+ move: MoveTuning;
+ dodge: DodgeTuning;
+ health: HealthTuning;
+ blaster: BlasterTuning;
+ shield: ShieldTuning;
+ match: MatchTuning;
+ lagComp: LagCompTuning;
+}
+
+export const DEFAULT_TUNING: CombatTuning = {
+ body: {
+ radius: 0.3,
+ hitRadius: 0.34,
+ hitBottom: 0.34,
+ hitTop: 1.46,
+ headFrom: 1.5,
+ eyeHeight: 1.62,
+ muzzleHeight: 1.38,
+ muzzleForward: 0.45,
+ muzzleRight: 0.22,
+ },
+ move: {
+ run: 4.8,
+ backMul: 0.78,
+ adsMul: 0.6,
+ shieldMul: 0.5,
+ sprint: 7.0,
+ sprintConeDeg: 50,
+ accel: 34,
+ decel: 42,
+ sprintToFireTicks: ticks(0.15),
+ },
+ dodge: {
+ durationTicks: ticks(0.4),
+ distance: 4.0,
+ cooldownTicks: ticks(2.0),
+ iframeTicks: 0,
+ recoverTicks: ticks(0.2),
+ },
+ health: {
+ max: 100,
+ regenDelayTicks: ticks(5),
+ regenPerSec: 10,
+ headshotMul: 1.5,
+ },
+ blaster: {
+ fireIntervalTicks: 12,
+ boltSpeed: 60,
+ boltRadius: 0.06,
+ boltMaxRange: 90,
+ damageNear: 15,
+ damageFar: 9,
+ falloffStart: 12,
+ falloffEnd: 32,
+ heatPerShot: 9,
+ heatCoolDelayTicks: ticks(0.3),
+ heatCoolPerSec: 35,
+ overheatTicks: ticks(2.5),
+ overheatWindow: [ticks(0.9), ticks(1.25)],
+ ventBaseTicks: ticks(0.5),
+ ventTicksPerHeat: 0.6,
+ ventWindowFrac: [0.3, 0.52],
+ hipSpreadDeg: 1.6,
+ adsSpreadDeg: 0.3,
+ moveSpreadHipDeg: 1.0,
+ moveSpreadAdsDeg: 0.3,
+ bloomPerShotHipDeg: 0.45,
+ bloomPerShotAdsDeg: 0.2,
+ bloomMaxHipDeg: 3.5,
+ bloomMaxAdsDeg: 1.5,
+ bloomRecoverDegPerSec: 5,
+ bloomRecoverDelayTicks: ticks(0.1),
+ recoilPitchHipDeg: 0.55,
+ recoilPitchAdsDeg: 0.35,
+ recoilYawDeg: 0.2,
+ recoilRecoverDegPerSec: 9,
+ adsInTicks: ticks(0.18),
+ adsOutTicks: ticks(0.12),
+ },
+ shield: {
+ energyMax: 100,
+ raiseMinEnergy: 20,
+ raiseCost: 6,
+ drainPerSec: 8,
+ blockCostPerDamage: 0.9,
+ regenDelayTicks: ticks(0.9),
+ regenPerSec: 20,
+ brokenTicks: ticks(3),
+ arcHalfDeg: 60,
+ radius: 0.8,
+ height: 2.0,
+ parryWindowTicks: ticks(0.15),
+ parryWhiffLockTicks: ticks(1.0),
+ reRaiseTicks: ticks(0.4),
+ deflectChance: 0.4,
+ deflectSpreadDeg: 40,
+ deflectDamageMul: 0.5,
+ parryDamageMul: 1.0,
+ parrySpeedMul: 1.2,
+ parryAimErrorDeg: 1.2,
+ maxReflections: 3,
+ },
+ match: {
+ roundsToWin: 2,
+ maxRounds: 5,
+ countdownTicks: ticks(3),
+ roundEndTicks: ticks(2.5),
+ roundTimeLimitTicks: ticks(90),
+ surgeAfterTicks: ticks(40),
+ pingEveryTicks: ticks(1.5),
+ },
+ lagComp: {
+ historyTicks: 32,
+ maxRewindTicks: 15,
+ },
+};
+
+/** Deep-merge partial overrides onto a tuning (for tests and the harness). */
+export function withTuning(base: CombatTuning, patch: DeepPartial<CombatTuning>): CombatTuning {
+ const out = JSON.parse(JSON.stringify(base)) as CombatTuning;
+ for (const [group, values] of Object.entries(patch)) {
+ if (!values) continue;
+ Object.assign((out as unknown as Record<string, object>)[group], values);
+ }
+ return out;
+}
+
+export type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? Partial<T[K]> : T[K] };
+
+/** Stable hash of a tuning, compared in the handshake. */
+export function tuningHash(t: CombatTuning): number {
+ const text = JSON.stringify(t);
+ let h = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) h = hash2(h, text.charCodeAt(i));
+ return h >>> 0;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/types.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/types.ts
new file mode 100644
index 0000000000..6929cc46fc
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/types.ts
@@ -0,0 +1,229 @@
+/**
+ * The data of a duel: what a player sends each tick (InputCommand), the
+ * authoritative match state (plain, JSON-serialisable, no classes), and the
+ * events a step emits for presentation.
+ */
+
+/** Button bits of an InputCommand. */
+export const BTN = {
+ FIRE: 1,
+ ADS: 2,
+ SHIELD: 4,
+ DODGE: 8,
+ VENT: 16,
+ SPRINT: 32,
+ FORFEIT: 64,
+} as const;
+
+/** Buttons that act on the press, not while held. */
+export const EDGE_BUTTONS = BTN.DODGE | BTN.VENT | BTN.FORFEIT;
+
+/**
+ * One tick of one player's control. The only thing a client ever sends.
+ * Values are quantised on creation (`makeInput`) so client prediction and the
+ * server see the same numbers.
+ */
+export interface InputCommand {
+ /** Per-player sequence number, +1 per tick. */
+ seq: number;
+ /** Strafe right (-1..1) and forward (-1..1), in the aim frame. */
+ mx: number;
+ my: number;
+ /** Absolute aim (radians). Recoil is added on top by the simulation. */
+ yaw: number;
+ pitch: number;
+ buttons: number;
+ /**
+ * The server tick the client was displaying when it made this command
+ * (its interpolation time). Lag compensation rewinds a shot to it; -1 = none.
+ */
+ viewTick: number;
+}
+
+export type MatchPhase = "countdown" | "live" | "round_end" | "ended";
+export type EndReason = "rounds" | "forfeit" | "disconnect" | "draw" | "cancelled";
+
+export interface MatchConfig {
+ roundsToWin: number;
+ maxRounds: number;
+ countdownTicks: number;
+ roundEndTicks: number;
+ roundTimeLimitTicks: number;
+ surgeAfterTicks: number;
+ pingEveryTicks: number;
+}
+
+export interface PlayerStats {
+ shots: number;
+ hits: number;
+ headshots: number;
+ damageDealt: number;
+ damageTaken: number;
+ blocks: number;
+ parries: number;
+ deflects: number;
+ dodges: number;
+ overheats: number;
+ perfectVents: number;
+ ventMisses: number;
+ kills: number;
+}
+
+export interface PlayerState {
+ slot: number;
+ id: string;
+ /** Spawn side this round (0 or 1); sides swap every round. */
+ side: number;
+ x: number;
+ z: number;
+ vx: number;
+ vz: number;
+ yaw: number;
+ pitch: number;
+ recoilPitch: number;
+ recoilYaw: number;
+ alive: boolean;
+ health: number;
+ lastDamageTick: number;
+ /** Last input applied (repeated by the server when a client's input is late). */
+ mx: number;
+ my: number;
+ buttons: number;
+ lastSeq: number;
+ /** Blaster. */
+ heat: number;
+ lastShotTick: number;
+ nextShotTick: number;
+ bloom: number;
+ shotCount: number;
+ /** Vent cycle in progress (manual or forced by an overheat); -1 = none. */
+ ventStart: number;
+ ventEnd: number;
+ ventWinStart: number;
+ ventWinEnd: number;
+ ventFromHeat: number;
+ ventForced: boolean;
+ ventAttempted: boolean;
+ /** Aim-down-sights blend 0..1. */
+ ads: number;
+ sprinting: boolean;
+ sprintEndTick: number;
+ /** Shield. */
+ shieldUp: boolean;
+ shieldEnergy: number;
+ shieldRaisedAt: number;
+ shieldLoweredAt: number;
+ shieldBrokenUntil: number;
+ /** After a break or a dodge the shield key must be released before it raises again. */
+ shieldNeedsRelease: boolean;
+ /** A bolt met the shield inside this raise's parry window. */
+ shieldParryUsed: boolean;
+ /** Raises before this tick get no parry window (whiff penalty). */
+ parryReadyAt: number;
+ /** Dodge roll. */
+ dodgeStart: number;
+ dodgeUntil: number;
+ dodgeReadyAt: number;
+ dodgeDx: number;
+ dodgeDz: number;
+ stats: PlayerStats;
+}
+
+export type BoltKind = "shot" | "deflect" | "parry";
+
+export interface BoltState {
+ id: number;
+ /** Who it belongs to now (a parry or deflection hands it to the blocker). */
+ owner: number;
+ /** Who fired it first. */
+ shooter: number;
+ kind: BoltKind;
+ x: number;
+ y: number;
+ z: number;
+ vx: number;
+ vy: number;
+ vz: number;
+ /** Damage multiplier on the falloff curve (1 for a shot, less for a deflection). */
+ damageMul: number;
+ /** Metres flown since it was fired or last turned by a shield (falloff runs on this). */
+ traveled: number;
+ bornTick: number;
+ reflections: number;
+}
+
+/** Recent poses for lag compensation: ring of [tick, x0, z0, x1, z1]. */
+export interface PoseHistory {
+ ticks: number[];
+ poses: number[][];
+}
+
+export interface MatchState {
+ v: 1;
+ seed: number;
+ tick: number;
+ phase: MatchPhase;
+ /** Tick the current phase began and the tick it is due to end (countdown, round time limit, pause). */
+ phaseStart: number;
+ phaseEndsAt: number;
+ round: number;
+ roundStartTick: number;
+ scores: number[];
+ /** Winning slot, -1 for a draw, null while the match runs. */
+ winner: number | null;
+ endReason: EndReason | null;
+ config: MatchConfig;
+ players: PlayerState[];
+ bolts: BoltState[];
+ nextBoltId: number;
+ history: PoseHistory;
+}
+
+export type Surface = "wall" | "floor" | "prop" | "ceiling";
+
+export type CombatEvent =
+ | { type: "shot"; tick: number; player: number; bolt: number; shot: number; x: number; y: number; z: number; dx: number; dy: number; dz: number; heat: number; ads: boolean }
+ | { type: "hit"; tick: number; bolt: number; owner: number; target: number; damage: number; headshot: boolean; health: number; x: number; y: number; z: number; fromX: number; fromZ: number }
+ | { type: "impact"; tick: number; bolt: number; surface: Surface; collider: string | null; x: number; y: number; z: number; nx: number; ny: number; nz: number }
+ | { type: "block"; tick: number; player: number; bolt: number; energy: number; x: number; y: number; z: number }
+ | { type: "deflect"; tick: number; player: number; bolt: number; x: number; y: number; z: number }
+ | { type: "parry"; tick: number; player: number; bolt: number; target: number; x: number; y: number; z: number }
+ | { type: "bolt_expire"; tick: number; bolt: number }
+ | { type: "shield_up"; tick: number; player: number; seq: number }
+ | { type: "shield_down"; tick: number; player: number }
+ | { type: "shield_break"; tick: number; player: number }
+ | { type: "shield_ready"; tick: number; player: number }
+ | { type: "overheat"; tick: number; player: number; shot: number }
+ | { type: "vent_start"; tick: number; player: number; seq: number; forced: boolean; end: number; winStart: number; winEnd: number }
+ | { type: "vent_perfect"; tick: number; player: number; seq: number }
+ | { type: "vent_miss"; tick: number; player: number; seq: number }
+ | { type: "vent_end"; tick: number; player: number }
+ | { type: "dodge"; tick: number; player: number; seq: number; dx: number; dz: number }
+ | { type: "death"; tick: number; player: number; killer: number }
+ | { type: "countdown"; tick: number; round: number; endsAt: number }
+ | { type: "round_start"; tick: number; round: number }
+ | { type: "surge"; tick: number; round: number }
+ | { type: "ping"; tick: number; player: number; x: number; z: number }
+ | { type: "round_end"; tick: number; round: number; winner: number; reason: "kill" | "time" | "trade"; scores: number[] }
+ | { type: "match_end"; tick: number; winner: number; reason: EndReason; scores: number[] };
+
+export type CombatEventType = CombatEvent["type"];
+
+/**
+ * A stable identity for an event, the same whether a client predicted it or
+ * the server sent it, so presentation plays it once.
+ */
+export function eventKey(e: CombatEvent): string {
+ switch (e.type) {
+ case "shot": return `shot:${e.player}:${e.shot}`;
+ case "overheat": return `overheat:${e.player}:${e.shot}`;
+ case "shield_up":
+ case "vent_start":
+ case "vent_perfect":
+ case "vent_miss":
+ case "dodge":
+ return `${e.type}:${e.player}:${e.seq}`;
+ default:
+ return `${e.type}:${e.tick}:${"player" in e ? e.player : ""}:${"bolt" in e ? e.bolt : ""}`;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/view.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/view.ts
new file mode 100644
index 0000000000..f6d9ceddfb
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/view.ts
@@ -0,0 +1,205 @@
+/**
+ * The presentation state of a duel for one frame: plain data for the 3D view
+ * and the HUD, already smoothed between simulation ticks. React-free.
+ */
+import { lerp, lerpAngle } from "./math";
+import { canRaiseShield, fireBlock, parryOpen, spreadDeg, surgeActive, type SimContext } from "./sim";
+import { TICK_DT, TICK_RATE } from "./tuning";
+import type { BoltKind, EndReason, MatchPhase, MatchState, PlayerState } from "./types";
+
+export interface PlayerView {
+ slot: number;
+ id: string;
+ /** The player this view belongs to (the camera follows them). */
+ local: boolean;
+ side: number;
+ x: number;
+ z: number;
+ /** Body facing (= aim yaw). */
+ yaw: number;
+ pitch: number;
+ /** Where the blaster actually points (aim plus recoil), radians. */
+ aimYaw: number;
+ aimPitch: number;
+ vx: number;
+ vz: number;
+ speed: number;
+ alive: boolean;
+ health: number;
+ healthMax: number;
+ shieldUp: boolean;
+ /** 0..1 */
+ shieldEnergy: number;
+ shieldBroken: boolean;
+ /** The parry window is open right now (for a flash on the shield). */
+ parrying: boolean;
+ ads: number;
+ sprinting: boolean;
+ dodging: boolean;
+ /** 0..1 through the roll (0 when not rolling). */
+ dodgeProgress: number;
+ venting: boolean;
+ overheated: boolean;
+ /** 0..1 heat (vents glow with it). */
+ heat: number;
+}
+
+export interface BoltView {
+ id: number;
+ owner: number;
+ shooter: number;
+ kind: BoltKind;
+ x: number;
+ y: number;
+ z: number;
+ /** Unit direction of travel. */
+ dx: number;
+ dy: number;
+ dz: number;
+ speed: number;
+ ageTicks: number;
+}
+
+export interface HudState {
+ health: number;
+ healthMax: number;
+ /** 0..1 */
+ heat: number;
+ overheated: boolean;
+ venting: boolean;
+ /** 0..1 through the vent cycle, and its perfect window as fractions (null when not venting). */
+ ventProgress: number;
+ ventWindow: readonly [number, number] | null;
+ /** A timing press was already spent on this vent. */
+ ventAttempted: boolean;
+ /** 0..1 */
+ shieldEnergy: number;
+ shieldUp: boolean;
+ shieldBroken: boolean;
+ /** Seconds until a broken shield comes back. */
+ shieldBrokenLeft: number;
+ shieldCanRaise: boolean;
+ /** The next raise gets a parry window (no whiff lock). */
+ parryReady: boolean;
+ dodgeReady: boolean;
+ /** 0..1 of the dodge cooldown still to run. */
+ dodgeCooldown: number;
+ /** Crosshair cone half-angle, degrees. */
+ spreadDeg: number;
+ ads: number;
+ sprinting: boolean;
+ canFire: boolean;
+ recoilPitchDeg: number;
+ recoilYawDeg: number;
+ enemyHealth: number;
+ enemyHealthMax: number;
+}
+
+export interface MatchView {
+ tick: number;
+ phase: MatchPhase;
+ round: number;
+ scores: readonly number[];
+ roundsToWin: number;
+ winner: number | null;
+ endReason: EndReason | null;
+ /** Seconds left in the countdown (0 outside it). */
+ countdown: number;
+ /** Seconds left before the round times out (live only). */
+ roundTimeLeft: number;
+ /** Reactor surge: no health regeneration, positions pinged. */
+ surge: boolean;
+}
+
+export interface ViewState {
+ status: string;
+ slot: number;
+ match: MatchView;
+ players: PlayerView[];
+ bolts: BoltView[];
+ /** The local player's HUD; null for a spectator. */
+ hud: HudState | null;
+}
+
+function playerView(ctx: SimContext, p: PlayerState, tick: number, local: boolean): PlayerView {
+ const t = ctx.tuning;
+ const dodging = tick < p.dodgeUntil;
+ return {
+ slot: p.slot, id: p.id, local, side: p.side, x: p.x, z: p.z, yaw: p.yaw, pitch: p.pitch,
+ aimYaw: p.yaw + (p.recoilYaw * Math.PI) / 180, aimPitch: p.pitch + (p.recoilPitch * Math.PI) / 180,
+ vx: p.vx, vz: p.vz, speed: Math.hypot(p.vx, p.vz), alive: p.alive, health: p.health, healthMax: t.health.max,
+ shieldUp: p.shieldUp, shieldEnergy: p.shieldEnergy / t.shield.energyMax, shieldBroken: p.shieldBrokenUntil > tick,
+ parrying: parryOpen(t, p, tick), ads: p.ads, sprinting: p.sprinting, dodging,
+ dodgeProgress: dodging ? (tick - p.dodgeStart) / t.dodge.durationTicks : 0,
+ venting: p.ventStart >= 0, overheated: p.ventStart >= 0 && p.ventForced, heat: p.heat / 100,
+ };
+}
+
+function hud(ctx: SimContext, p: PlayerState, enemy: PlayerState | undefined, tick: number): HudState {
+ const t = ctx.tuning;
+ const venting = p.ventStart >= 0;
+ const len = Math.max(1, p.ventEnd - p.ventStart);
+ const block = fireBlock(t, p, tick);
+ return {
+ health: p.health, healthMax: t.health.max, heat: p.heat / 100, overheated: venting && p.ventForced, venting,
+ ventProgress: venting ? (tick - p.ventStart) / len : 0,
+ ventWindow: venting ? [(p.ventWinStart - p.ventStart) / len, (p.ventWinEnd - p.ventStart) / len] : null,
+ ventAttempted: venting && p.ventAttempted,
+ shieldEnergy: p.shieldEnergy / t.shield.energyMax, shieldUp: p.shieldUp, shieldBroken: p.shieldBrokenUntil > tick,
+ shieldBrokenLeft: Math.max(0, p.shieldBrokenUntil - tick) * TICK_DT,
+ shieldCanRaise: !p.shieldUp && canRaiseShield(t, p, tick),
+ parryReady: tick >= p.parryReadyAt,
+ dodgeReady: tick >= p.dodgeReadyAt && tick >= p.dodgeUntil,
+ dodgeCooldown: Math.max(0, p.dodgeReadyAt - tick) / t.dodge.cooldownTicks,
+ spreadDeg: spreadDeg(t, p), ads: p.ads, sprinting: p.sprinting, canFire: block === null || block === "cycle",
+ recoilPitchDeg: p.recoilPitch, recoilYawDeg: p.recoilYaw,
+ enemyHealth: enemy ? enemy.health : 0, enemyHealthMax: t.health.max,
+ };
+}
+
+/**
+ * Build the frame. `state` is the newest tick, `prev` the one before; the
+ * local player and the bolts are blended between them by `alpha` (0..1 into
+ * the next tick). `remote[slot]` replaces a remote player (interpolated
+ * snapshots); missing entries come from `state`.
+ */
+export function buildView(
+ ctx: SimContext, state: MatchState, prev: MatchState, alpha: number, slot: number,
+ remote: readonly (PlayerState | null)[], status: string,
+): ViewState {
+ const tick = state.tick;
+ const players = state.players.map((p) => {
+ if (p.slot !== slot) return playerView(ctx, remote[p.slot] ?? p, tick, false);
+ const q = prev.players[p.slot];
+ const v = playerView(ctx, p, tick, true);
+ if (q && q.alive && p.alive && Math.hypot(p.x - q.x, p.z - q.z) < 3) {
+ v.x = lerp(q.x, p.x, alpha);
+ v.z = lerp(q.z, p.z, alpha);
+ v.yaw = lerpAngle(q.yaw, p.yaw, alpha);
+ v.pitch = lerp(q.pitch, p.pitch, alpha);
+ }
+ return v;
+ });
+ const back = (1 - alpha) * TICK_DT;
+ const bolts: BoltView[] = state.bolts.map((b) => {
+ const speed = Math.hypot(b.vx, b.vy, b.vz) || 1;
+ return {
+ id: b.id, owner: b.owner, shooter: b.shooter, kind: b.kind,
+ x: b.x - b.vx * back, y: b.y - b.vy * back, z: b.z - b.vz * back,
+ dx: b.vx / speed, dy: b.vy / speed, dz: b.vz / speed, speed, ageTicks: tick - b.bornTick,
+ };
+ });
+ const c = state.config;
+ const match: MatchView = {
+ tick, phase: state.phase, round: state.round, scores: state.scores, roundsToWin: c.roundsToWin,
+ winner: state.winner, endReason: state.endReason,
+ countdown: state.phase === "countdown" ? Math.max(0, state.phaseEndsAt - tick) / TICK_RATE : 0,
+ roundTimeLeft: state.phase === "live" ? Math.max(0, state.roundStartTick + c.roundTimeLimitTicks - tick) / TICK_RATE : 0,
+ surge: surgeActive(state, tick),
+ };
+ const me = slot >= 0 ? state.players[slot] : undefined;
+ return {
+ status, slot, match, players, bolts,
+ hud: me ? hud(ctx, me, state.players.find((p) => p.slot !== slot), tick) : null,
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/content/deck.ts b/dodaios/ui/web/frontend/src/components/society/verse/content/deck.ts
index 0a3b72e9e2..692feab6c1 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/content/deck.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/content/deck.ts
@@ -118,6 +118,42 @@ export interface PlateImages {
levels: readonly PlateLevel[];
}
+/** The specular layer of one realtime material (see ManifestRealtimeMaterial). */
+export interface RealtimeMaterial {
+ roughness: number;
+ metalness: number;
+ color: readonly [number, number, number];
+ clearcoat: number;
+ clearcoatRoughness: number;
+ specular: number;
+ detail: string;
+ transparent: boolean;
+ opacity: number;
+ collide: boolean;
+}
+
+export interface RealtimeProbe {
+ room: string;
+ url: string;
+ width: number;
+ height: number;
+ range: number;
+ position: readonly [number, number, number];
+ boxMin: readonly [number, number, number];
+ boxMax: readonly [number, number, number];
+}
+
+/** The deck as an eye-level 3D scene (docs/verse/realtime.md), URLs resolved. */
+export interface RealtimeContent {
+ sceneUrl: string;
+ /** rgbm2 span of the lightmap pages. */
+ range: number;
+ pages: readonly { url: string; size: number }[];
+ probes: readonly RealtimeProbe[];
+ materials: Readonly<Record<string, RealtimeMaterial>>;
+ triangles: number;
+}
+
export interface Deck {
id: DeckId;
/** The content folder it was cooked into (the deck id, or "testbed" in development). */
@@ -136,6 +172,8 @@ export interface Deck {
stations: readonly Station[];
rooms: readonly Room[];
probes: readonly LightProbe[];
+ /** The eye-level scene, or null when the deck has none (or one this runtime cannot read). */
+ realtime: RealtimeContent | null;
}
export function socketById(deck: Deck, kind: SocketKind, id: string): Socket | undefined {
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/content/loadDeck.ts b/dodaios/ui/web/frontend/src/components/society/verse/content/loadDeck.ts
index 75c3630e84..7cc098424b 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/content/loadDeck.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/content/loadDeck.ts
@@ -7,11 +7,13 @@
* half-built scene.
*/
import type { DeckId } from "../decks";
-import { STATION_KINDS, type Deck, type NavGrid, type PlateImages, type PlateLevel, type Socket, type Station, type StationKind } from "./deck";
+import {
+ STATION_KINDS, type Deck, type NavGrid, type PlateImages, type PlateLevel, type RealtimeContent, type Socket, type Station, type StationKind,
+} from "./deck";
import { fetchImageBitmap } from "../engine/imageFetch";
import {
- fillTileUrl, manifestUrl as resolveUrl, parseDeckManifest,
- type DeckManifest, type ManifestCamera, type ManifestNav, type ManifestPlate, type ManifestSocket,
+ fillTileUrl, manifestUrl as resolveUrl, parseDeckManifest, REALTIME_VERSION,
+ type DeckManifest, type ManifestCamera, type ManifestNav, type ManifestPlate, type ManifestRealtime, type ManifestSocket,
} from "./manifest";
export class DeckLoadError extends Error {
@@ -83,6 +85,32 @@ export function plateImages(camera: ManifestCamera, plate: ManifestPlate, url: (
};
}
+/** The realtime block as the runtime uses it; null for a version this runtime does not read. Pure apart from URL resolution. */
+export function realtimeContent(r: ManifestRealtime | undefined, url: (relative: string) => string): RealtimeContent | null {
+ if (!r || r.version !== REALTIME_VERSION) return null;
+ const materials: Record<string, RealtimeContent["materials"][string]> = {};
+ for (const [name, m] of Object.entries(r.materials)) {
+ materials[name] = {
+ roughness: m.roughness, metalness: m.metalness, color: [m.color[0], m.color[1], m.color[2]],
+ clearcoat: m.clearcoat, clearcoatRoughness: m.clearcoat_roughness, specular: m.specular,
+ detail: m.detail, transparent: m.transparent, opacity: m.opacity, collide: m.collide,
+ };
+ }
+ return {
+ sceneUrl: url(r.scene.url),
+ range: r.lightmaps.range,
+ pages: r.lightmaps.pages.map((p) => ({ url: url(p.url), size: p.size })),
+ probes: r.probes.map((p) => ({
+ room: p.room, url: url(p.url), width: p.w, height: p.h, range: p.range,
+ position: [p.position[0], p.position[1], p.position[2]],
+ boxMin: [p.box_min[0], p.box_min[1], p.box_min[2]],
+ boxMax: [p.box_max[0], p.box_max[1], p.box_max[2]],
+ })),
+ materials,
+ triangles: r.scene.triangles,
+ };
+}
+
/** Validate a manifest and turn it into a deck (nav still to decode). Pure apart from URL resolution. */
export function deckFromManifest(json: unknown, at: string, deckId: DeckId, contentId: string): Omit<Deck, "nav"> & { navUrl: string; navMeta: ManifestNav } {
let m: DeckManifest;
@@ -118,6 +146,7 @@ export function deckFromManifest(json: unknown, at: string, deckId: DeckId, cont
stations,
rooms: m.rooms.map((r) => ({ id: r.id, name: r.name, floorY: r.floor_y, polygon: r.polygon, main: r.main })),
probes: m.probes.map((p) => ({ room: p.room, x: p.position[0], y: p.position[1], z: p.position[2], sh: p.sh })),
+ realtime: realtimeContent(m.realtime, url),
navUrl: url(m.nav.url),
navMeta: m.nav,
};
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/content/manifest.ts b/dodaios/ui/web/frontend/src/components/society/verse/content/manifest.ts
index 294d23ad25..64adad04a8 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/content/manifest.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/content/manifest.ts
@@ -144,6 +144,62 @@ export interface ManifestStation {
sockets: Readonly<Partial<Record<ManifestSocketKind, readonly string[]>>>;
}
+/** One lightmap atlas page (RGBA WebP, "rgbm2"). */
+export interface ManifestRealtimePage {
+ url: string;
+ /** Edge in texels (pages are square). */
+ size: number;
+ /** Texels per metre at density weight 1. */
+ density: number;
+}
+
+/** A room's reflection panorama (equirect, three.js layout, "rgbm2") and its projection box. */
+export interface ManifestRealtimeProbe {
+ room: string;
+ url: string;
+ w: number;
+ h: number;
+ /** The rgbm2 span of this image. */
+ range: number;
+ position: ManifestVec3;
+ box_min: ManifestVec3;
+ box_max: ManifestVec3;
+}
+
+/** The specular layer the runtime adds to the baked radiance of one material. */
+export interface ManifestRealtimeMaterial {
+ roughness: number;
+ metalness: number;
+ /** Specular tint of metals, linear RGB. */
+ color: ManifestVec3;
+ clearcoat: number;
+ clearcoat_roughness: number;
+ /** Blender's Specular IOR Level: 0.5 = F0 4 %. */
+ specular: number;
+ /** Close-up detail layer: "deck_plates", "painted", "metal" or "none". */
+ detail: string;
+ transparent: boolean;
+ opacity: number;
+ /** The camera stops at it. */
+ collide: boolean;
+}
+
+/**
+ * The deck as an eye-level 3D scene (optional; docs/verse/realtime.md):
+ * geometry with a lightmap UV set, baked radiance pages, reflection probes.
+ */
+export interface ManifestRealtime {
+ version: number;
+ quality: "preview" | "final";
+ /** Meshopt-compressed glTF; one node per (material, room, page) chunk, `extras` name them. */
+ scene: { url: string; vertices: number; triangles: number; chunks: number };
+ lightmaps: { encoding: "rgbm2"; range: number; pages: readonly ManifestRealtimePage[] };
+ probes: readonly ManifestRealtimeProbe[];
+ materials: Readonly<Record<string, ManifestRealtimeMaterial>>;
+ bytes: number;
+ stats: Readonly<Record<string, unknown>>;
+}
+
export interface DeckManifest {
schema: typeof DECK_MANIFEST_SCHEMA;
id: string;
@@ -161,6 +217,8 @@ export interface DeckManifest {
sockets: readonly ManifestSocket[];
stations: readonly ManifestStation[];
stats: Readonly<Record<string, number | string>>;
+ /** The eye-level scene, when the deck has been exported for it. */
+ realtime?: ManifestRealtime;
}
// ------------------------------------------------------------------ maths
@@ -331,6 +389,55 @@ function checkSocket(value: Json, path: string): void {
if (s.props !== undefined) obj(s.props, `${path}.props`);
}
+/** The realtime block's version this runtime reads. */
+export const REALTIME_VERSION = 1;
+
+function bool(value: Json, path: string): boolean {
+ if (typeof value !== "boolean") fail(path, "expected a boolean");
+ return value;
+}
+
+function checkRealtime(value: Json): void {
+ const r = obj(value, "realtime");
+ int(r.version, "realtime.version", 1);
+ if (r.quality !== "preview" && r.quality !== "final") fail("realtime.quality", 'expected "preview" or "final"');
+ const scene = obj(r.scene, "realtime.scene");
+ str(scene.url, "realtime.scene.url");
+ for (const key of ["vertices", "triangles", "chunks"]) int(scene[key], `realtime.scene.${key}`, 1);
+ const maps = obj(r.lightmaps, "realtime.lightmaps");
+ if (maps.encoding !== "rgbm2") fail("realtime.lightmaps.encoding", 'expected "rgbm2"');
+ if (num(maps.range, "realtime.lightmaps.range") <= 0) fail("realtime.lightmaps.range", "expected > 0");
+ const pages = list(maps.pages, "realtime.lightmaps.pages");
+ if (pages.length === 0) fail("realtime.lightmaps.pages", "expected at least one page");
+ pages.forEach((page, i) => {
+ const p = obj(page, `realtime.lightmaps.pages[${i}]`);
+ str(p.url, `realtime.lightmaps.pages[${i}].url`);
+ int(p.size, `realtime.lightmaps.pages[${i}].size`, 1);
+ num(p.density, `realtime.lightmaps.pages[${i}].density`);
+ });
+ list(r.probes, "realtime.probes").forEach((probe, i) => {
+ const p = obj(probe, `realtime.probes[${i}]`);
+ str(p.room, `realtime.probes[${i}].room`);
+ str(p.url, `realtime.probes[${i}].url`);
+ int(p.w, `realtime.probes[${i}].w`, 1);
+ int(p.h, `realtime.probes[${i}].h`, 1);
+ num(p.range, `realtime.probes[${i}].range`);
+ for (const key of ["position", "box_min", "box_max"]) vec(p[key], `realtime.probes[${i}].${key}`, 3);
+ });
+ for (const [name, material] of Object.entries(obj(r.materials, "realtime.materials"))) {
+ const m = obj(material, `realtime.materials.${name}`);
+ for (const key of ["roughness", "metalness", "clearcoat", "clearcoat_roughness", "specular", "opacity"]) {
+ num(m[key], `realtime.materials.${name}.${key}`);
+ }
+ vec(m.color, `realtime.materials.${name}.color`, 3);
+ str(m.detail, `realtime.materials.${name}.detail`);
+ bool(m.transparent, `realtime.materials.${name}.transparent`);
+ bool(m.collide, `realtime.materials.${name}.collide`);
+ }
+ int(r.bytes, "realtime.bytes");
+ obj(r.stats, "realtime.stats");
+}
+
/** Validate parsed JSON as a deck manifest; throws ManifestError naming the first bad field. */
export function parseDeckManifest(value: Json): DeckManifest {
const m = obj(value, "manifest");
@@ -388,5 +495,6 @@ export function parseDeckManifest(value: Json): DeckManifest {
}
});
obj(m.stats, "stats");
+ if (m.realtime !== undefined) checkRealtime(m.realtime);
return value as DeckManifest;
}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/DuelLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/duel/DuelLayer.tsx
new file mode 100644
index 0000000000..9a8f615437
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/DuelLayer.tsx
@@ -0,0 +1,224 @@
+/**
+ * The duel in the eye-level scene: runs the match once per rendered frame
+ * (before the eye view renders), hands the shoulder camera to the renderer
+ * (`runtime.cameraOverride`), and draws both duellists, their blasters and
+ * shields, the bolts and every effect the frame's events call for (muzzle
+ * flashes, impact sparks and scorches, hit sparks, block ripples, parry
+ * bursts, overheat steam).
+ *
+ * Mounted inside the stage's Canvas while a duel is on; everything it adds
+ * to the scene goes again when it unmounts.
+ */
+import { useEffect, useMemo, useRef } from "react";
+import { useFrame, useThree } from "@react-three/fiber";
+import { Color, Group, Vector3 } from "three";
+import type { Deck } from "../content/deck";
+import type { StageRuntime } from "../runtime";
+import { disposeInstance, type CharacterLibrary } from "../actors/characters";
+import { applyLook, type Look } from "../actors/look";
+import { hash32 } from "../life/crew";
+import type { CombatEvent } from "../combat/types";
+import { BOLT_COLOURS } from "./blaster";
+import type { DuelController } from "./duelController";
+import { BoltPool, Flashes, radialTexture, Scorches, Sparks, Steam } from "./effects";
+import { DuelFigure, type FigureLook } from "./figure";
+import { ShieldMesh } from "./shield";
+
+interface Props {
+ runtime: StageRuntime;
+ controller: DuelController;
+ deck: Deck;
+ library: CharacterLibrary | null;
+ commanderId: string;
+ commanderLook: Look;
+}
+
+/** The bot: the trooper body in gunmetal armour with red accents and a red visor. */
+export const OPPONENT_LOOK: FigureLook = {
+ tint: { M_Armor: "#3a3f46", M_Accent: "#a3221a", M_Undersuit: "#141619" },
+ glow: { M_Visor: "#ff2a1a" },
+ accent: new Color(1, 0.16, 0.08),
+};
+
+const OWN_ACCENT = new Color(1, 0.6, 0.15);
+const WHITE = new Color(1, 1, 1);
+const SPARK_HOT = new Color(1, 0.62, 0.25);
+const SHIELD_SPARK = new Color(0.45, 0.8, 1);
+const HIT_SPARK = new Color(1, 0.35, 0.15);
+
+export function DuelLayer({ runtime, controller, deck, library, commanderId, commanderLook }: Props) {
+ const scene = useThree((s) => s.scene);
+ const fx = useMemo(() => {
+ const group = new Group();
+ group.name = "Duel";
+ const bolts = new BoltPool();
+ const sparks = new Sparks();
+ const flashes = new Flashes();
+ const scorches = new Scorches();
+ const steam = new Steam();
+ const shields = [new ShieldMesh(OWN_ACCENT), new ShieldMesh(OPPONENT_LOOK.accent)];
+ group.add(bolts.group, sparks.points, flashes.group, scorches.group, steam.points, ...shields.map((s) => s.mesh));
+ return { group, bolts, sparks, flashes, scorches, steam, shields };
+ }, []);
+ const shadow = useMemo(() => radialTexture([[0, "rgba(255,255,255,0.9)"], [0.35, "rgba(255,255,255,0.55)"], [1, "rgba(255,255,255,0)"]]), []);
+
+ useEffect(() => {
+ scene.add(fx.group);
+ return () => {
+ scene.remove(fx.group);
+ fx.bolts.dispose();
+ fx.sparks.dispose();
+ fx.flashes.dispose();
+ fx.scorches.dispose();
+ fx.steam.dispose();
+ for (const s of fx.shields) s.dispose();
+ shadow.dispose();
+ };
+ }, [scene, fx, shadow]);
+
+ // Both bodies: the commander's own (their look) and the trooper.
+ const figures = useRef<{ own: DuelFigure | null; foe: DuelFigure | null }>({ own: null, foe: null });
+ useEffect(() => {
+ if (!library) return;
+ let alive = true;
+ const own = library.model("officer", undefined, hash32(commanderId));
+ const foe = library.model("trooper") ?? library.model("technician");
+ const load = async () => {
+ const [a, b] = await Promise.all([own ? library.instantiate(own) : null, foe ? library.instantiate(foe) : null]);
+ if (!alive) { for (const i of [a, b]) if (i) disposeInstance(i); return; }
+ if (a) {
+ applyLook(a, library.contract, commanderLook);
+ const f = new DuelFigure(a, { accent: OWN_ACCENT }, shadow);
+ figures.current.own = f;
+ fx.group.add(f.group);
+ }
+ if (b) {
+ const f = new DuelFigure(b, OPPONENT_LOOK, shadow);
+ figures.current.foe = f;
+ fx.group.add(f.group);
+ }
+ };
+ load().catch((error: unknown) => console.warn("Duel bodies failed to load", error));
+ return () => {
+ alive = false;
+ for (const key of ["own", "foe"] as const) {
+ const f = figures.current[key];
+ if (f) { fx.group.remove(f.group); f.dispose(); }
+ figures.current[key] = null;
+ }
+ };
+ }, [library, commanderId, commanderLook, fx, shadow]);
+
+ // Leaving the duel gives the camera back; the next match starts with a clean room.
+ useEffect(() => controller.subscribe(() => {
+ if (controller.phase === "off") runtime.cameraOverride = null;
+ if (controller.phase === "running" && !controller.view) {
+ fx.bolts.clear(); fx.sparks.clear(); fx.flashes.clear(); fx.scorches.clear(); fx.steam.clear();
+ }
+ }), [controller, runtime, fx]);
+ useEffect(() => () => { runtime.cameraOverride = null; }, [runtime]);
+
+ const scratch = useMemo(() => ({ v: new Vector3(), time: 0, steamAcc: [0, 0] }), []);
+ const override = useMemo(() => ({ position: { x: 0, y: 0, z: 0 }, target: { x: 0, y: 0, z: 0 }, fovDeg: 70 }), []);
+
+ useFrame((_, dt) => {
+ if (!controller.active) {
+ fx.group.visible = false;
+ return;
+ }
+ fx.group.visible = true;
+ const floorY = controller.floorY;
+ controller.frame(Math.min(dt, 0.25) * 1000, runtime.eye?.test ?? null);
+ const view = controller.view;
+ if (!view) return;
+ const pose = controller.pose;
+ override.position.x = pose.position.x; override.position.y = pose.position.y; override.position.z = pose.position.z;
+ override.target.x = pose.target.x; override.target.y = pose.target.y; override.target.z = pose.target.z;
+ override.fovDeg = pose.fovDeg;
+ runtime.cameraOverride = override;
+
+ const step = controller.phase === "paused" ? 0 : Math.min(dt, 0.1);
+ scratch.time += step;
+ const mySlot = view.slot;
+ const bySlot = (slot: number) => (slot === mySlot ? figures.current.own : figures.current.foe);
+ for (const p of view.players) {
+ const f = bySlot(p.slot);
+ f?.update(step, p, floorY, deck, scratch.time);
+ fx.shields[p.slot === mySlot ? 0 : 1].update(step, p, floorY);
+ // A venting blaster steams.
+ const k = p.slot === mySlot ? 0 : 1;
+ if (f && p.alive && (p.venting || p.heat > 0.85)) {
+ scratch.steamAcc[k] += step * (p.overheated ? 40 : p.venting ? 26 : 8);
+ const n = Math.floor(scratch.steamAcc[k]);
+ if (n > 0) { scratch.steamAcc[k] -= n; f.muzzle(scratch.v); fx.steam.emit(scratch.v.x, scratch.v.y - 0.02, scratch.v.z, n); }
+ }
+ }
+ fx.bolts.update(view.bolts, mySlot, floorY);
+
+ const events = controller.visualEvents;
+ for (const e of events) play(e);
+ events.length = 0;
+
+ fx.sparks.update(step, floorY);
+ fx.flashes.update(step);
+ fx.scorches.update(step);
+ fx.steam.update(step);
+
+ function play(e: CombatEvent): void {
+ const y = (v: number) => v + floorY;
+ switch (e.type) {
+ case "shot": {
+ const own = e.player === mySlot;
+ const colour = own ? BOLT_COLOURS.own : BOLT_COLOURS.foe;
+ const f = bySlot(e.player);
+ const at = f ? f.muzzle(scratch.v) : scratch.v.set(e.x, y(e.y), e.z);
+ fx.flashes.spawn(at.x, at.y, at.z, colour, 9, 0.12, 0.42, 0.07, true);
+ fx.flashes.spawn(at.x, at.y, at.z, WHITE, 6, 0.05, 0.14, 0.05);
+ break;
+ }
+ case "impact": {
+ const ix = e.x, iy = y(e.y), iz = e.z;
+ fx.sparks.burst(ix, iy, iz, e.nx, e.ny, e.nz, 14, SPARK_HOT, 4.5, 0.8, 7);
+ fx.flashes.spawn(ix + e.nx * 0.05, iy + e.ny * 0.05, iz + e.nz * 0.05, SPARK_HOT, 7, 0.2, 0.6, 0.12);
+ fx.scorches.add(ix, iy, iz, e.nx, e.ny, e.nz);
+ break;
+ }
+ case "hit": {
+ const hx = e.x, hy = y(e.y), hz = e.z;
+ const dx = hx - e.fromX, dz = hz - e.fromZ;
+ const l = Math.hypot(dx, dz) || 1;
+ fx.sparks.burst(hx, hy, hz, -dx / l, 0.2, -dz / l, e.headshot ? 26 : 18, HIT_SPARK, 3.5, 1.0, 8);
+ fx.flashes.spawn(hx, hy, hz, e.headshot ? WHITE : HIT_SPARK, e.headshot ? 9 : 6, 0.2, 0.55, 0.12);
+ break;
+ }
+ case "block": case "deflect": {
+ const s = fx.shields[e.player === mySlot ? 0 : 1];
+ s.block(e.x, y(e.y), e.z);
+ fx.sparks.burst(e.x, y(e.y), e.z, 0, 0.3, 0, e.type === "deflect" ? 18 : 10, SHIELD_SPARK, 3.2, 1.2, 6);
+ fx.flashes.spawn(e.x, y(e.y), e.z, SHIELD_SPARK, 6, 0.18, 0.5, 0.1);
+ break;
+ }
+ case "parry": {
+ const s = fx.shields[e.player === mySlot ? 0 : 1];
+ s.parry(e.x, y(e.y), e.z);
+ fx.flashes.spawn(e.x, y(e.y), e.z, BOLT_COLOURS.parry, 14, 0.3, 1.4, 0.22, true);
+ fx.flashes.spawn(e.x, y(e.y), e.z, WHITE, 8, 0.1, 0.4, 0.08);
+ fx.sparks.burst(e.x, y(e.y), e.z, 0, 0.4, 0, 30, BOLT_COLOURS.parry, 5, 1.3, 9);
+ break;
+ }
+ case "shield_break":
+ fx.shields[e.player === mySlot ? 0 : 1].shatter();
+ break;
+ case "overheat": {
+ const f = bySlot(e.player);
+ if (f) { f.muzzle(scratch.v); fx.steam.emit(scratch.v.x, scratch.v.y, scratch.v.z, 30); fx.flashes.spawn(scratch.v.x, scratch.v.y, scratch.v.z, HIT_SPARK, 5, 0.1, 0.35, 0.2); }
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ }, 0);
+
+ return null;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/blaster.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/blaster.ts
new file mode 100644
index 0000000000..6507898305
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/blaster.ts
@@ -0,0 +1,116 @@
+/**
+ * The duel blaster, built procedurally: a compact, sleek energy carbine in
+ * graphite and brushed gold with glowing energy cells along the receiver,
+ * heat vents on the shroud and an emitter ring at the muzzle.
+ *
+ * Local frame: +Z is the barrel's direction, +Y up, the origin is the
+ * right hand's grip. `muzzle` and `fore` (where the left hand holds the
+ * shroud) are fixed points in that frame. `setHeat` drives the cells and
+ * vents from cool blue-white through amber to an overheated red, and pulses
+ * them while venting.
+ */
+import {
+ BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshStandardMaterial, TorusGeometry, Vector3, type BufferGeometry, type Material,
+} from "three";
+
+export interface Blaster {
+ group: Group;
+ /** Muzzle point and the left hand's hold point, local. */
+ muzzle: Vector3;
+ fore: Vector3;
+ materials: Material[];
+ /** Heat 0..1; `venting` pulses the vents; `overheated` turns them red. */
+ setHeat(heat: number, venting: boolean, overheated: boolean, timeS: number): void;
+ dispose(): void;
+}
+
+/** Bolt colours (linear, before the HDR gain): the person's and the opponent's. */
+export const BOLT_COLOURS = {
+ own: new Color(1.0, 0.62, 0.16),
+ foe: new Color(1.0, 0.13, 0.08),
+ parry: new Color(1.0, 0.92, 0.7),
+} as const;
+
+const COOL = new Color(0.35, 0.75, 1.0);
+const BLASTER_SCALE = 1.3;
+const WARM = new Color(1.0, 0.55, 0.12);
+const HOT = new Color(1.0, 0.12, 0.04);
+
+export function buildBlaster(accent: Color): Blaster {
+ const group = new Group();
+ group.name = "DuelBlaster";
+ // Built at true size, drawn a little larger so it reads at shoulder-camera distance.
+ const parts = new Group();
+ parts.scale.setScalar(BLASTER_SCALE);
+ group.add(parts);
+ const graphite = new MeshStandardMaterial({ name: "M_Blaster_Body", color: 0x16191d, metalness: 0.8, roughness: 0.3 });
+ const steel = new MeshStandardMaterial({ name: "M_Blaster_Steel", color: 0x4a5058, metalness: 0.9, roughness: 0.26 });
+ const gold = new MeshStandardMaterial({ name: "M_Blaster_Trim", color: 0xc9a24a, metalness: 1, roughness: 0.28 });
+ const grip = new MeshStandardMaterial({ name: "M_Blaster_Grip", color: 0x0d0e10, metalness: 0.1, roughness: 0.75 });
+ const cells = new MeshStandardMaterial({ name: "M_Blaster_Cells", color: 0x050505, emissive: accent.clone(), emissiveIntensity: 3, roughness: 0.4 });
+ const vents = new MeshStandardMaterial({ name: "M_Blaster_Vents", color: 0x050505, emissive: COOL.clone(), emissiveIntensity: 0.6, roughness: 0.5 });
+ const emitter = new MeshStandardMaterial({ name: "M_Blaster_Emitter", color: 0x050505, emissive: accent.clone(), emissiveIntensity: 5, roughness: 0.3 });
+ const materials: Material[] = [graphite, steel, gold, grip, cells, vents, emitter];
+ const geometries: BufferGeometry[] = [];
+
+ const add = (geo: BufferGeometry, mat: MeshStandardMaterial, x: number, y: number, z: number, rx = 0, ry = 0, rz = 0): Mesh => {
+ geometries.push(geo);
+ const m = new Mesh(geo, mat);
+ m.position.set(x, y, z);
+ m.rotation.set(rx, ry, rz);
+ m.castShadow = false;
+ parts.add(m);
+ return m;
+ };
+ const alongZ = (geo: BufferGeometry) => geo.rotateX(Math.PI / 2);
+
+ // Receiver: a long, slightly tapered block, a gold spine on top.
+ add(new BoxGeometry(0.056, 0.078, 0.32), graphite, 0, 0.012, 0.06);
+ add(new BoxGeometry(0.06, 0.03, 0.2), steel, 0, -0.03, 0.03);
+ add(new BoxGeometry(0.012, 0.008, 0.26), gold, 0, 0.055, 0.07);
+ // Energy cells along both sides.
+ add(new BoxGeometry(0.004, 0.016, 0.17), cells, 0.0295, 0.016, 0.07);
+ add(new BoxGeometry(0.004, 0.016, 0.17), cells, -0.0295, 0.016, 0.07);
+ // Shroud and barrel: an octagonal sleeve with vents, a slim barrel inside.
+ add(alongZ(new CylinderGeometry(0.026, 0.03, 0.22, 8)), graphite, 0, 0.012, 0.31);
+ add(alongZ(new CylinderGeometry(0.012, 0.012, 0.3, 10)), steel, 0, 0.012, 0.34);
+ for (let i = 0; i < 3; i++) add(new BoxGeometry(0.03, 0.006, 0.022), vents, 0, 0.04, 0.25 + i * 0.045);
+ add(new BoxGeometry(0.006, 0.022, 0.16), gold, 0, -0.018, 0.31);
+ // Emitter ring and muzzle.
+ add(new TorusGeometry(0.022, 0.005, 6, 16), emitter, 0, 0.012, 0.43);
+ add(alongZ(new CylinderGeometry(0.02, 0.016, 0.04, 10)), steel, 0, 0.012, 0.47);
+ // Optic: a low rail and a small holographic sight.
+ add(new BoxGeometry(0.028, 0.012, 0.08), steel, 0, 0.058, 0.0);
+ add(new BoxGeometry(0.03, 0.03, 0.006), gold, 0, 0.078, 0.035);
+ add(new BoxGeometry(0.022, 0.018, 0.002), emitter, 0, 0.08, 0.034);
+ // Grip, trigger guard, a short angular stock.
+ add(new BoxGeometry(0.034, 0.105, 0.042), grip, 0, -0.06, -0.01, -0.28);
+ add(new BoxGeometry(0.008, 0.008, 0.07), steel, 0, -0.06, 0.04);
+ add(new BoxGeometry(0.04, 0.06, 0.13), graphite, 0, -0.005, -0.15, 0.12);
+ add(new BoxGeometry(0.044, 0.07, 0.014), gold, 0, -0.01, -0.22, 0.12);
+
+ const base = { cells: accent.clone() };
+ const tmp = new Color();
+ return {
+ group,
+ muzzle: new Vector3(0, 0.012, 0.49).multiplyScalar(BLASTER_SCALE),
+ fore: new Vector3(0, -0.02, 0.29).multiplyScalar(BLASTER_SCALE),
+ materials,
+ setHeat(heat, venting, overheated, timeS) {
+ const h = Math.max(0, Math.min(1, heat));
+ if (overheated) tmp.copy(HOT);
+ else if (h < 0.5) tmp.copy(COOL).lerp(WARM, h / 0.5);
+ else tmp.copy(WARM).lerp(HOT, (h - 0.5) / 0.5);
+ vents.emissive.copy(tmp);
+ const pulse = venting ? 0.6 + 0.4 * Math.sin(timeS * 22) : 1;
+ vents.emissiveIntensity = (0.4 + h * h * 9 + (overheated ? 6 : 0)) * pulse;
+ cells.emissive.copy(base.cells).lerp(HOT, overheated ? 0.8 : h * 0.4);
+ cells.emissiveIntensity = venting ? 2 : 6 + h * 4;
+ emitter.emissiveIntensity = venting ? 1.2 : 4 + h * 4;
+ },
+ dispose() {
+ for (const g of geometries) g.dispose();
+ for (const m of materials) m.dispose();
+ },
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/duel.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/duel.test.ts
new file mode 100644
index 0000000000..6bcd5b099c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duel.test.ts
@@ -0,0 +1,383 @@
+// @vitest-environment node
+/**
+ * The duel as the stage runs it: the input mapping (keys and buttons to the
+ * combat core's ControlState), the shoulder camera, the HUD model from the
+ * view and the events, and the start / pause / leave / result / rematch flow
+ * of the controller against the real local duel.
+ */
+import { describe, expect, it } from "vitest";
+import { createLocalDuel, type LocalDuelOptions } from "../combat/session";
+import type { CombatEvent } from "../combat/types";
+import type { PlayerView, ViewState } from "../combat/view";
+import { DuelCamera, DUEL_CAMERA } from "./duelCamera";
+import { DuelController, type DuelExit } from "./duelController";
+import { buildHudModel, DuelHudFeed, HUD_TIMES } from "./duelHud";
+import { DuelInput, isDuelKey } from "./duelInput";
+
+describe("duel input mapping", () => {
+ it("maps WASD to strafe and forward in the aim frame", () => {
+ const input = new DuelInput();
+ input.keyDown("KeyW");
+ let c = input.control(0.5, 0.1);
+ expect([c.moveX, c.moveY]).toEqual([0, 1]);
+ expect(c.yaw).toBe(0.5);
+ expect(c.pitch).toBe(0.1);
+ input.keyDown("KeyD");
+ c = input.control(0, 0);
+ expect([c.moveX, c.moveY]).toEqual([1, 1]);
+ input.keyUp("KeyW");
+ input.keyDown("KeyS");
+ input.keyDown("KeyA");
+ c = input.control(0, 0);
+ expect([c.moveX, c.moveY]).toEqual([0, -1]);
+ input.keyUp("KeyD");
+ c = input.control(0, 0);
+ expect([c.moveX, c.moveY]).toEqual([-1, -1]);
+ });
+
+ it("moves with the arrow keys too", () => {
+ const input = new DuelInput();
+ input.keyDown("ArrowUp");
+ input.keyDown("ArrowLeft");
+ const c = input.control(0, 0);
+ expect([c.moveX, c.moveY]).toEqual([-1, 1]);
+ });
+
+ it("holds fire, sights and shield; sprints only going forward", () => {
+ const input = new DuelInput();
+ input.mouseDown(0);
+ input.mouseDown(2);
+ input.keyDown("KeyQ");
+ input.keyDown("ShiftLeft");
+ let c = input.control(0, 0);
+ expect(c.fire && c.ads && c.shield).toBe(true);
+ expect(c.sprint).toBe(false);
+ input.keyDown("KeyW");
+ c = input.control(0, 0);
+ expect(c.sprint).toBe(true);
+ input.mouseUp(0);
+ input.mouseUp(2);
+ input.keyUp("KeyQ");
+ c = input.control(0, 0);
+ expect(c.fire || c.ads || c.shield).toBe(false);
+ expect(c.forfeit).toBe(false);
+ });
+
+ it("latches a dodge or vent press for exactly one read, and ignores auto-repeat", () => {
+ const input = new DuelInput();
+ input.keyDown("Space");
+ input.keyUp("Space");
+ input.keyDown("KeyR");
+ let c = input.control(0, 0);
+ expect(c.dodge).toBe(true);
+ expect(c.vent).toBe(true);
+ c = input.control(0, 0);
+ expect(c.dodge).toBe(false);
+ expect(c.vent).toBe(false);
+ input.keyDown("Space", true);
+ expect(input.control(0, 0).dodge).toBe(false);
+ });
+
+ it("lets everything go on clear (focus lost, pause)", () => {
+ const input = new DuelInput();
+ input.keyDown("KeyW");
+ input.mouseDown(0);
+ input.keyDown("KeyR");
+ input.clear();
+ const c = input.control(0, 0);
+ expect([c.moveX, c.moveY, c.fire, c.vent]).toEqual([0, 0, false, false]);
+ });
+
+ it("claims only the keys it uses", () => {
+ expect(isDuelKey("KeyW")).toBe(true);
+ expect(isDuelKey("KeyQ")).toBe(true);
+ expect(isDuelKey("Space")).toBe(true);
+ expect(isDuelKey("KeyV")).toBe(false);
+ expect(isDuelKey("KeyE")).toBe(false);
+ expect(new DuelInput().keyDown("KeyL")).toBe(false);
+ });
+});
+
+function player(over: Partial<PlayerView> = {}): PlayerView {
+ return {
+ slot: 0, id: "a", local: true, side: 0, x: 40, z: 20, yaw: 0, pitch: 0, aimYaw: 0, aimPitch: 0, vx: 0, vz: 0, speed: 0,
+ alive: true, health: 100, healthMax: 100, shieldUp: false, shieldEnergy: 1, shieldBroken: false, parrying: false, ads: 0,
+ sprinting: false, dodging: false, dodgeProgress: 0, venting: false, overheated: false, heat: 0, ...over,
+ };
+}
+
+describe("duel camera", () => {
+ it("turns with the mouse: right turns right, up looks up, pitch is clamped", () => {
+ const cam = new DuelCamera();
+ cam.look(100, 0);
+ // Yaw 0 faces +Z; the right of that is -X, which a smaller yaw turns toward.
+ expect(cam.yaw).toBeLessThan(0);
+ cam.look(0, -100);
+ expect(cam.pitch).toBeGreaterThan(0);
+ cam.invertY = true;
+ const before = cam.pitch;
+ cam.look(0, -50);
+ expect(cam.pitch).toBeLessThan(before);
+ cam.look(0, -1e6);
+ expect(cam.pitch).toBeGreaterThanOrEqual(DUEL_CAMERA.minPitch);
+ cam.look(0, 1e6);
+ expect(cam.pitch).toBeLessThanOrEqual(DUEL_CAMERA.maxPitch);
+ });
+
+ it("sits behind the right shoulder and closes in for the sights", () => {
+ const cam = new DuelCamera();
+ cam.face(0);
+ const hip = cam.update(1 / 60, player(), 0);
+ // Facing +Z: behind is -Z, the right shoulder is -X.
+ expect(hip.position.z).toBeLessThan(20 - 2);
+ expect(hip.position.x).toBeLessThan(40);
+ expect(hip.position.y).toBeGreaterThan(1.4);
+ const hipBack = 20 - hip.position.z;
+ const hipFov = hip.fovDeg;
+ let ads = hip;
+ for (let i = 0; i < 60; i++) ads = cam.update(1 / 60, player({ ads: 1 }), 0);
+ expect(20 - ads.position.z).toBeLessThan(hipBack);
+ expect(ads.fovDeg).toBeLessThan(hipFov);
+ });
+
+ it("is pulled in front of a wall behind the player", () => {
+ const cam = new DuelCamera();
+ cam.face(0);
+ // A wall 1 m behind the player (z = 19): every segment crossing it is cut there.
+ const test = (from: { z: number }, to: { z: number }) => {
+ if ((from.z - 19) * (to.z - 19) >= 0) return null;
+ return (from.z - 19) / (from.z - to.z);
+ };
+ const pose = cam.update(1 / 60, player(), 0, test);
+ expect(pose.position.z).toBeGreaterThan(19);
+ });
+
+ it("follows the recoil in the view but not in the aim", () => {
+ const cam = new DuelCamera();
+ cam.face(0);
+ const pose = cam.update(1 / 60, player({ aimPitch: 0.02 }), 0);
+ expect(pose.dir.y).toBeGreaterThan(0.015);
+ expect(pose.aimDir.y).toBeCloseTo(0, 6);
+ });
+});
+
+function viewOf(over: { phase?: ViewState["match"]["phase"]; countdown?: number; round?: number; me?: Partial<PlayerView> } = {}): ViewState {
+ const me = player(over.me);
+ const foe = player({ slot: 1, id: "b", local: false, x: 60, z: 20 });
+ return {
+ status: "playing", slot: 0,
+ match: {
+ tick: 100, phase: over.phase ?? "live", round: over.round ?? 1, scores: [1, 0], roundsToWin: 2, winner: null, endReason: null,
+ countdown: over.countdown ?? 0, roundTimeLeft: 61.2, surge: false,
+ },
+ players: [me, foe],
+ bolts: [],
+ hud: {
+ health: me.health, healthMax: 100, heat: 0.4, overheated: false, venting: false, ventProgress: 0, ventWindow: null, ventAttempted: false,
+ shieldEnergy: 0.8, shieldUp: false, shieldBroken: false, shieldBrokenLeft: 0, shieldCanRaise: true, parryReady: true, dodgeReady: true,
+ dodgeCooldown: 0, spreadDeg: 1.6, ads: 0, sprinting: false, canFire: true, recoilPitchDeg: 0, recoilYawDeg: 0, enemyHealth: 55, enemyHealthMax: 100,
+ },
+ };
+}
+
+const hit = (over: Partial<Extract<CombatEvent, { type: "hit" }>>): CombatEvent => ({
+ type: "hit", tick: 1, bolt: 1, owner: 0, target: 1, damage: 15, headshot: false, health: 70, x: 0, y: 1, z: 0, fromX: 0, fromZ: 0, ...over,
+});
+
+describe("duel HUD model", () => {
+ it("reads health, shield, heat, score and clock off the view", () => {
+ const m = buildHudModel(viewOf({ me: { health: 25 } }), new DuelHudFeed(), 0, 0);
+ expect(m.health).toBe(25);
+ expect(m.healthFrac).toBeCloseTo(0.25);
+ expect(m.lowHealth).toBe(true);
+ expect(m.myScore).toBe(1);
+ expect(m.theirScore).toBe(0);
+ expect(m.timeLeft).toBe(62);
+ expect(m.enemyHealthFrac).toBeCloseTo(0.55);
+ expect(m.shieldFrac).toBeCloseTo(0.8);
+ expect(m.heat).toBeCloseTo(0.4);
+ expect(buildHudModel(viewOf(), new DuelHudFeed(), 0, 0).lowHealth).toBe(false);
+ });
+
+ it("marks hits, headshots and the knockout, and lets them fade", () => {
+ const feed = new DuelHudFeed();
+ feed.ingest([hit({})], 0, 1000);
+ expect(buildHudModel(viewOf(), feed, 1000, 0).hitMarker?.kind).toBe("hit");
+ feed.ingest([hit({ headshot: true })], 0, 1100);
+ expect(buildHudModel(viewOf(), feed, 1100, 0).hitMarker?.kind).toBe("head");
+ feed.ingest([hit({ health: 0 })], 0, 1200);
+ feed.ingest([hit({})], 0, 1210);
+ expect(buildHudModel(viewOf(), feed, 1210, 0).hitMarker?.kind).toBe("kill");
+ expect(buildHudModel(viewOf(), feed, 1200 + HUD_TIMES.killMarker + 1, 0).hitMarker).toBeNull();
+ // The opponent's hits on the opponent are not the person's markers.
+ const other = new DuelHudFeed();
+ other.ingest([hit({ owner: 1, target: 1 })], 0, 0);
+ expect(buildHudModel(viewOf(), other, 0, 0).hitMarker).toBeNull();
+ });
+
+ it("points the damage arc where the hit came from, relative to the camera", () => {
+ const feed = new DuelHudFeed();
+ // The person at (40, 20) looks along +Z (camera yaw 0); the shooter straight ahead, then on the right (-X).
+ feed.ingest([hit({ owner: 1, target: 0, fromX: 40, fromZ: 40 })], 0, 0);
+ let m = buildHudModel(viewOf(), feed, 10, 0);
+ expect(m.damageArcs).toHaveLength(1);
+ expect(m.damageArcs[0].angleDeg).toBeCloseTo(0, 5);
+ expect(m.hurt).toBeGreaterThan(0.9);
+ const right = new DuelHudFeed();
+ right.ingest([hit({ owner: 1, target: 0, fromX: 20, fromZ: 20 })], 0, 0);
+ m = buildHudModel(viewOf(), right, 10, 0);
+ expect(m.damageArcs[0].angleDeg).toBeCloseTo(90, 5);
+ expect(buildHudModel(viewOf(), right, HUD_TIMES.damageArc + 1, 0).damageArcs).toHaveLength(0);
+ });
+
+ it("shows the countdown, the fight call and the round's end", () => {
+ const feed = new DuelHudFeed();
+ expect(buildHudModel(viewOf({ phase: "countdown", countdown: 2.4 }), feed, 0, 0).banner).toEqual({ kind: "countdown", value: 3 });
+ feed.ingest([{ type: "round_start", tick: 1, round: 1 }], 0, 100);
+ expect(buildHudModel(viewOf(), feed, 200, 0).banner).toEqual({ kind: "fight" });
+ expect(buildHudModel(viewOf(), feed, 100 + HUD_TIMES.fight + 1, 0).banner).toBeNull();
+ feed.ingest([{ type: "round_end", tick: 2, round: 1, winner: 1, reason: "kill", scores: [0, 1] }], 0, 3000);
+ expect(buildHudModel(viewOf({ phase: "round_end" }), feed, 3000, 0).banner).toEqual({ kind: "round", outcome: "lost", reason: "kill" });
+ });
+
+ it("calls out the person's parries and perfect vents", () => {
+ const feed = new DuelHudFeed();
+ feed.ingest([{ type: "parry", tick: 1, player: 0, bolt: 3, target: 1, x: 0, y: 1, z: 0 }], 0, 0);
+ expect(buildHudModel(viewOf(), feed, 0, 0).callout?.key).toBe("parry");
+ feed.ingest([{ type: "vent_perfect", tick: 2, player: 0, seq: 5 }], 0, 10);
+ expect(buildHudModel(viewOf(), feed, 10, 0).callout?.key).toBe("perfect_vent");
+ feed.ingest([{ type: "vent_perfect", tick: 3, player: 1, seq: 9 }], 0, 20);
+ expect(buildHudModel(viewOf(), feed, 20, 0).callout?.key).toBe("perfect_vent");
+ });
+});
+
+/** A controller on its own clock, silent, with a fast match (first to one round). */
+function controller(options: Partial<LocalDuelOptions> = {}) {
+ const clock = { now: 0 };
+ const c = new DuelController({
+ sound: null,
+ now: () => clock.now,
+ create: (o) => createLocalDuel({ ...o, seed: 11, config: { roundsToWin: 1, maxRounds: 1 }, ...options }),
+ });
+ const frame = (n = 1, ms = 1000 / 60) => { for (let i = 0; i < n; i++) { clock.now += ms; c.frame(ms); } };
+ return { c, clock, frame };
+}
+
+describe("duel flow", () => {
+ it("starts running with both players placed and the HUD up", () => {
+ const { c, frame } = controller();
+ const phases: string[] = [];
+ c.subscribe(() => phases.push(c.phase));
+ expect(c.phase).toBe("off");
+ c.start("normal");
+ expect(c.phase).toBe("running");
+ expect(phases).toEqual(["running"]);
+ expect(c.view?.players).toHaveLength(2);
+ frame(10);
+ expect(c.view!.match.phase).toBe("countdown");
+ const hud = c.hud();
+ expect(hud?.banner?.kind).toBe("countdown");
+ expect(c.pose.fovDeg).toBeGreaterThan(40);
+ });
+
+ it("aims where the mouse turns the camera", () => {
+ const { c, frame } = controller();
+ c.start("normal");
+ frame(5);
+ const before = c.view!.players[c.view!.slot].yaw;
+ c.camera.look(-300, 0);
+ frame(5);
+ const after = c.view!.players[c.view!.slot].yaw;
+ expect(Math.abs(Math.atan2(Math.sin(after - before), Math.cos(after - before)))).toBeGreaterThan(0.3);
+ });
+
+ it("fires bolts when the fire button is held once the round is live", () => {
+ const { c, frame } = controller();
+ c.start("normal");
+ frame(200);
+ expect(c.view!.match.phase).toBe("live");
+ c.input.mouseDown(0);
+ const seen: string[] = [];
+ for (let i = 0; i < 30; i++) { frame(1); seen.push(...c.visualEvents.map((e) => e.type)); c.visualEvents.length = 0; }
+ expect(seen).toContain("shot");
+ });
+
+ it("freezes the match while paused and goes on after resume", () => {
+ const { c, frame } = controller();
+ c.start("hard");
+ frame(30);
+ c.pause();
+ expect(c.phase).toBe("paused");
+ const tick = c.view!.match.tick;
+ frame(60);
+ expect(c.view!.match.tick).toBe(tick);
+ c.resume();
+ frame(30);
+ expect(c.view!.match.tick).toBeGreaterThan(tick);
+ });
+
+ it("pauses on the first Escape and leaves on a second one, handing the commander back where they stood", () => {
+ const { c, clock, frame } = controller();
+ const exits: (DuelExit | null)[] = [];
+ c.onExit = (at) => exits.push(at);
+ c.start("elite");
+ frame(20);
+ c.escape();
+ expect(c.phase).toBe("paused");
+ // The browser's own Escape (releasing the mouse) right after does not leave.
+ clock.now += 50;
+ c.escape();
+ expect(c.phase).toBe("paused");
+ clock.now += 400;
+ c.escape();
+ expect(c.phase).toBe("off");
+ expect(exits).toHaveLength(1);
+ expect(exits[0]).not.toBeNull();
+ expect(exits[0]!.x).toBeGreaterThan(30);
+ expect(exits[0]!.x).toBeLessThan(85);
+ });
+
+ it("can be left at any moment", () => {
+ const { c, frame } = controller();
+ let left = 0;
+ c.onExit = () => left++;
+ c.start("hard");
+ frame(3);
+ c.leave();
+ expect(c.phase).toBe("off");
+ expect(left).toBe(1);
+ expect(c.hud()).toBeNull();
+ c.leave();
+ expect(left).toBe(1);
+ });
+
+ it("shows the result when the match ends, then rematches or leaves", () => {
+ const { c, frame } = controller();
+ c.start("elite");
+ let frames = 0;
+ while (c.phase === "running" && frames < 60 * 120) { frame(1); frames++; }
+ expect(c.phase).toBe("result");
+ expect(c.result?.outcome).toBe("lost");
+ expect(c.result?.rounds).toEqual([0, 1]);
+ const tick = c.view!.match.tick;
+ frame(30);
+ expect(c.view!.match.tick).toBe(tick);
+ c.rematch();
+ expect(c.phase).toBe("running");
+ expect(c.result).toBeNull();
+ expect(c.difficulty).toBe("elite");
+ let exited = false;
+ c.onExit = () => { exited = true; };
+ c.leave();
+ expect(exited).toBe(true);
+ });
+
+ it("forced QA controls reach the match", () => {
+ const { c, frame } = controller();
+ c.start("normal");
+ frame(200);
+ c.hold({ shield: true });
+ frame(5);
+ expect(c.view!.players[c.view!.slot].shieldUp).toBe(true);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelCamera.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelCamera.ts
new file mode 100644
index 0000000000..1427356d02
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelCamera.ts
@@ -0,0 +1,181 @@
+/**
+ * The duel's over-the-shoulder camera: the combat core's rigs (hip, sights,
+ * sprint, shield; `combat/camera.ts`) eased into each other, turned by the
+ * mouse, kept out of the deck's walls, with the blaster's recoil and a short
+ * shake on top.
+ *
+ * Two directions matter. The *aim* (`yaw`, `pitch`) is what the person
+ * points at with the mouse; the crosshair is solved from it (resolveAim) and
+ * it goes to the simulation. The *view* adds the recoil the simulation put
+ * on the blaster, so the screen kicks with every shot and the crosshair in
+ * the middle stays where the bolts go, as in big shooters.
+ *
+ * Coordinates: the arena's (deck metres, floor at y 0); `floorY` lifts the
+ * camera onto the deck's floor. Pitch is positive up (the combat core's
+ * convention). Pure state and maths.
+ */
+import { cameraRigFor, type CameraRig } from "../combat/camera";
+import { DEG } from "../combat/math";
+import type { PlayerView } from "../combat/view";
+import { MOUSE_LOOK_RATE, lookDelta } from "../engine/realtime/mouseLook";
+import type { SegmentTest, Vec3 } from "../engine/realtime/shoulderRig";
+
+export const DUEL_CAMERA = {
+ /** Radians per pointer-lock pixel at sensitivity 1 (the eye-level views' mouse look); sights turn slower. */
+ lookRate: MOUSE_LOOK_RATE,
+ adsLookFactor: 0.62,
+ /** Pitch limits, radians (positive up). */
+ minPitch: -1.05,
+ maxPitch: 1.05,
+ /** Rig easing time constant, seconds (about 0.15 s to settle). */
+ easeS: 0.05,
+ /** Share of the blaster's recoil the view follows. */
+ recoilView: 1,
+ /** Gap kept between the camera and geometry, metres. */
+ clearance: 0.2,
+ /** Distance regained per second after a wall pulled the camera in, metres. */
+ regainMps: 4,
+ /** Head height the collision tests start from, metres. */
+ headHeight: 1.6,
+ /** Extra sideways offset of the view (metres, to the right) on top of the core's rig, so the body clears the crosshair. */
+ extraRight: 0.2,
+} as const;
+
+export interface DuelCameraPose {
+ position: Vec3;
+ /** A point straight ahead (for lookAt). */
+ target: Vec3;
+ /** The view direction (unit), including recoil and shake. */
+ dir: Vec3;
+ /** The aim ray without recoil: what resolveAim gets. */
+ aimDir: Vec3;
+ /** Vertical field of view, degrees. */
+ fovDeg: number;
+}
+
+function clamp(v: number, lo: number, hi: number): number {
+ return Math.max(lo, Math.min(hi, v));
+}
+
+function wrap(a: number): number {
+ return Math.atan2(Math.sin(a), Math.cos(a));
+}
+
+function dirOf(yaw: number, pitch: number, out: Vec3): Vec3 {
+ const c = Math.cos(pitch);
+ out.x = Math.sin(yaw) * c;
+ out.y = Math.sin(pitch);
+ out.z = Math.cos(yaw) * c;
+ return out;
+}
+
+export class DuelCamera {
+ /** The aim, radians (yaw 0 faces +Z, pitch positive up). */
+ yaw = 0;
+ pitch = 0;
+ sensitivity = 1;
+ invertY = false;
+ readonly pose: DuelCameraPose = {
+ position: { x: 0, y: 0, z: 0 }, target: { x: 0, y: 0, z: 0 }, dir: { x: 0, y: 0, z: 1 }, aimDir: { x: 0, y: 0, z: 1 }, fovDeg: 70,
+ };
+ private rig: CameraRig = { ...cameraRigFor({ sprinting: false, shieldUp: false, ads: 0 } as PlayerView) };
+ private primed = false;
+ private back = 2.5;
+ private shake = 0;
+ private shakeT = 0;
+ private ads = 0;
+ private readonly pivot: Vec3 = { x: 0, y: 0, z: 0 };
+ private readonly head: Vec3 = { x: 0, y: 0, z: 0 };
+ private readonly far: Vec3 = { x: 0, y: 0, z: 0 };
+
+ /** Turn the aim by a mouse movement (CSS px): the same mouse look as the eye-level views (`mouseLook`). */
+ look(dx: number, dy: number): void {
+ const d = lookDelta(dx, dy, this, DUEL_CAMERA.lookRate * (1 - (1 - DUEL_CAMERA.adsLookFactor) * this.ads));
+ this.yaw = wrap(this.yaw - d.yaw);
+ // Pitch here is positive up; the look's is positive down.
+ this.pitch = clamp(this.pitch - d.pitch, DUEL_CAMERA.minPitch, DUEL_CAMERA.maxPitch);
+ }
+
+ /** Face a direction at once (a round's spawn), level. */
+ face(yaw: number, pitch = 0): void {
+ this.yaw = wrap(yaw);
+ this.pitch = clamp(pitch, DUEL_CAMERA.minPitch, DUEL_CAMERA.maxPitch);
+ this.primed = false;
+ }
+
+ /** A short shake (a shot, a hit taken); strength in degrees. */
+ kick(strengthDeg: number): void {
+ this.shake = Math.min(3, this.shake + strengthDeg);
+ }
+
+ /**
+ * Follow the local player: ease the rig for their state, place the camera
+ * behind the right shoulder (pulled in front of walls), add recoil and
+ * shake. `test` is the deck's collision in world coordinates.
+ */
+ update(dtS: number, me: PlayerView, floorY = 0, test?: SegmentTest | null): DuelCameraPose {
+ const dt = clamp(dtS, 0, 0.1);
+ const want = cameraRigFor(me);
+ const k = this.primed ? 1 - Math.exp(-dt / DUEL_CAMERA.easeS) : 1;
+ const r = this.rig;
+ r.right += (want.right - r.right) * k;
+ r.up += (want.up - r.up) * k;
+ r.back += (want.back - r.back) * k;
+ r.fovDeg += (want.fovDeg - r.fovDeg) * k;
+ this.ads = me.ads;
+
+ this.shakeT += dt;
+ this.shake *= Math.exp(-dt / 0.09);
+ const sy = this.shake * DEG * Math.sin(this.shakeT * 71.3) * 0.6;
+ const sp = this.shake * DEG * Math.sin(this.shakeT * 53.9 + 1.3);
+ const recoilYaw = me.aimYaw - me.yaw;
+ const recoilPitch = me.aimPitch - me.pitch;
+ const viewYaw = this.yaw + recoilYaw * DUEL_CAMERA.recoilView + sy;
+ const viewPitch = clamp(this.pitch + recoilPitch * DUEL_CAMERA.recoilView + sp, -1.4, 1.4);
+
+ const pose = this.pose;
+ dirOf(this.yaw, this.pitch, pose.aimDir);
+ const dir = dirOf(viewYaw, viewPitch, pose.dir);
+ // Pivot: beside the head along the view's right; the camera orbits it with the pitch.
+ const rx = -Math.cos(viewYaw);
+ const rz = Math.sin(viewYaw);
+ const head = this.head;
+ head.x = me.x;
+ head.y = floorY + DUEL_CAMERA.headHeight;
+ head.z = me.z;
+ const pivot = this.pivot;
+ const side = r.right + DUEL_CAMERA.extraRight * (1 - 0.4 * this.ads);
+ pivot.x = me.x + rx * side;
+ pivot.y = floorY + r.up;
+ pivot.z = me.z + rz * side;
+ if (test) {
+ const hit = test(head, pivot);
+ if (hit !== null) {
+ const keep = Math.max(0, hit - DUEL_CAMERA.clearance / Math.max(0.05, side));
+ pivot.x = head.x + (pivot.x - head.x) * keep;
+ pivot.z = head.z + (pivot.z - head.z) * keep;
+ }
+ }
+ let reach = r.back;
+ if (test) {
+ const far = this.far;
+ far.x = pivot.x - dir.x * r.back;
+ far.y = pivot.y - dir.y * r.back;
+ far.z = pivot.z - dir.z * r.back;
+ const hit = test(pivot, far);
+ if (hit !== null) reach = Math.max(0.2, hit * r.back - DUEL_CAMERA.clearance);
+ }
+ if (!this.primed) this.back = reach;
+ // In at once (never through a wall), back out smoothly.
+ this.back = reach < this.back ? reach : Math.min(reach, this.back + DUEL_CAMERA.regainMps * dt);
+ this.primed = true;
+ pose.position.x = pivot.x - dir.x * this.back;
+ pose.position.y = pivot.y - dir.y * this.back;
+ pose.position.z = pivot.z - dir.z * this.back;
+ pose.target.x = pivot.x + dir.x * 20;
+ pose.target.y = pivot.y + dir.y * 20;
+ pose.target.z = pivot.z + dir.z * 20;
+ pose.fovDeg = r.fovDeg;
+ return pose;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelController.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelController.ts
new file mode 100644
index 0000000000..8c8043dff5
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelController.ts
@@ -0,0 +1,268 @@
+/**
+ * The duel as the stage runs it: one object per stage that starts a match
+ * against the bot (`combat/createLocalDuel`), feeds it the person's keys and
+ * mouse every frame, keeps the shoulder camera on them, collects the frame's
+ * events for the effects, the HUD and the sounds, and ends it (forfeit,
+ * leave, the match's end) handing control back to the deck.
+ *
+ * Phases:
+ *
+ * off --start()--> running <--pause()/resume()--> paused
+ * | the match ends | leave()
+ * v v
+ * result --rematch()--> running off
+ * | leave()
+ * v
+ * off
+ *
+ * Paused freezes the match (the duel's clock only advances with the frames
+ * it is given), so a released pointer or an opened menu never costs a
+ * round. React-free; the stage subscribes for phase changes.
+ */
+import { resolveAim } from "../combat/camera";
+import { idleControl, type ControlState } from "../combat/input";
+import type { BotTier } from "../combat/bot/tiers";
+import { createLocalDuel, type DuelResult, type LocalDuel, type LocalDuelOptions } from "../combat/session";
+import type { CombatEvent } from "../combat/types";
+import type { ViewState } from "../combat/view";
+import type { SegmentTest } from "../engine/realtime/shoulderRig";
+import { DuelCamera, type DuelCameraPose } from "./duelCamera";
+import { buildHudModel, DuelHudFeed, type HudModel } from "./duelHud";
+import { DuelInput } from "./duelInput";
+import { DuelSound } from "./duelSound";
+
+export type DuelPhase = "off" | "running" | "paused" | "result";
+export type DuelDifficulty = BotTier;
+export const DUEL_DIFFICULTIES: readonly DuelDifficulty[] = ["normal", "hard", "elite"];
+
+/** Where the person stood when the duel ended: the deck takes them back there. */
+export interface DuelExit { x: number; z: number; yaw: number }
+
+export interface DuelControllerOptions {
+ /** Makes the match (tests pass a seeded or scripted one). */
+ create?: (o: LocalDuelOptions) => LocalDuel;
+ sound?: DuelSound | null;
+ now?: () => number;
+}
+
+export class DuelController {
+ phase: DuelPhase = "off";
+ difficulty: DuelDifficulty = "hard";
+ readonly input = new DuelInput();
+ readonly camera = new DuelCamera();
+ readonly feed = new DuelHudFeed();
+ /** The latest frame of the match (null before the first). */
+ view: ViewState | null = null;
+ /** The finished match's result while the result screen shows. */
+ result: DuelResult | null = null;
+ /** Deck floor height under the arena, metres (the arena's y 0). */
+ floorY = 0;
+ /** Effects drain this every frame (the 3D layer); events stay here for one frame. */
+ readonly visualEvents: CombatEvent[] = [];
+ /** Called when the duel hands control back to the deck. */
+ onExit: ((at: DuelExit | null) => void) | null = null;
+ /** The pointer was locked to the stage during this match (losing the lock then pauses it). */
+ hadLock = false;
+ /** What the crosshair covers (the opponent turns it red). */
+ aimTarget: "player" | "world" | "none" = "none";
+ /** QA: held controls forced on top of the person's (`window.__verseDuel.hold`). */
+ forced: Partial<ControlState> = {};
+ private duel: LocalDuel | null = null;
+ private readonly control: ControlState = idleControl();
+ private readonly listeners = new Set<() => void>();
+ private readonly create: (o: LocalDuelOptions) => LocalDuel;
+ private readonly sound: DuelSound | null;
+ private readonly now: () => number;
+ private lastCount = -1;
+ private pausedAt = 0;
+ private forcedPress: { dodge?: boolean; vent?: boolean } = {};
+
+ constructor(o: DuelControllerOptions = {}) {
+ this.create = o.create ?? createLocalDuel;
+ this.sound = o.sound === undefined ? new DuelSound() : o.sound;
+ this.now = o.now ?? (() => performance.now());
+ }
+
+ get active(): boolean {
+ return this.phase !== "off";
+ }
+
+ /** The match takes the person's input right now. */
+ get live(): boolean {
+ return this.phase === "running";
+ }
+
+ subscribe = (fn: () => void): (() => void) => {
+ this.listeners.add(fn);
+ return () => { this.listeners.delete(fn); };
+ };
+
+ getPhase = (): DuelPhase => this.phase;
+
+ private setPhase(next: DuelPhase): void {
+ if (this.phase === next) return;
+ this.phase = next;
+ if (next === "paused") this.pausedAt = this.now();
+ for (const fn of [...this.listeners]) fn();
+ }
+
+ /** A new match against the bot at `difficulty`. Any match in progress is dropped. */
+ start(difficulty: DuelDifficulty = this.difficulty, seed: number = (Math.random() * 0x7fffffff) >>> 0): void {
+ this.duel?.dispose();
+ this.difficulty = difficulty;
+ this.duel = this.create({ difficulty, seed, playerName: "Commander" });
+ this.view = null;
+ this.result = null;
+ this.feed.reset();
+ this.input.clear();
+ this.visualEvents.length = 0;
+ this.lastCount = -1;
+ this.forced = {};
+ this.forcedPress = {};
+ this.hadLock = false;
+ const spawn = this.duel.arena.def.spawns;
+ // The camera faces the first spawn's way until the first frame says which side the person has.
+ this.camera.face(spawn[0].yaw);
+ this.sound?.resume();
+ this.setPhase("running");
+ // The first frame (no time passes) places the players.
+ this.step(0, null);
+ }
+
+ /** Freeze the match (the pointer was released, Escape). */
+ pause(): void {
+ if (this.phase !== "running") return;
+ this.input.clear();
+ this.setPhase("paused");
+ }
+
+ resume(): void {
+ if (this.phase !== "paused") return;
+ this.sound?.resume();
+ this.setPhase("running");
+ }
+
+ /** Escape: pause a running match; a second Escape (not the browser's echo of the first) leaves it. */
+ escape(): void {
+ if (this.phase === "running") { this.pause(); return; }
+ if (this.phase === "paused" && this.now() - this.pausedAt > 250) { this.leave(); return; }
+ if (this.phase === "result") this.leave();
+ }
+
+ /** Forfeit if a match is on, then hand control back to the deck. */
+ leave(): void {
+ if (this.phase === "off") return;
+ const at = this.exitPoint();
+ if (this.duel && !this.duel.finished) this.duel.forfeit();
+ this.duel?.dispose();
+ this.duel = null;
+ this.input.clear();
+ this.visualEvents.length = 0;
+ this.setPhase("off");
+ this.onExit?.(at);
+ }
+
+ /** The same difficulty again, from the result screen. */
+ rematch(): void {
+ this.start(this.difficulty);
+ }
+
+ dispose(): void {
+ this.duel?.dispose();
+ this.duel = null;
+ this.sound?.dispose();
+ this.listeners.clear();
+ this.phase = "off";
+ }
+
+ private exitPoint(): DuelExit | null {
+ const me = this.view?.players[this.view.slot];
+ return me ? { x: me.x, z: me.z, yaw: me.yaw } : null;
+ }
+
+ /** QA hooks: hold controls (fire, shield, ads, moveX...) or press one (dodge, vent) on the next frame. */
+ hold(c: Partial<ControlState>): void {
+ this.forced = { ...this.forced, ...c };
+ }
+
+ press(name: "dodge" | "vent"): void {
+ this.forcedPress[name] = true;
+ }
+
+ /** The camera pose of the last frame (world coordinates), for the renderer. */
+ get pose(): DuelCameraPose {
+ return this.camera.pose;
+ }
+
+ /**
+ * One rendered frame: advance the match by `dtMs` (none while paused or
+ * over), move the camera, solve the crosshair for the next input. `test`
+ * is the deck's collision (world).
+ */
+ frame(dtMs: number, test: SegmentTest | null = null): void {
+ if (this.phase === "off") return;
+ this.step(this.phase === "running" ? dtMs : 0, test);
+ }
+
+ private step(dtMs: number, test: SegmentTest | null): void {
+ const duel = this.duel;
+ if (!duel) return;
+ // The aim solved last frame goes out with this frame's keys.
+ const control = this.control;
+ if (this.phase === "running") {
+ this.input.control(control.yaw, control.pitch, control);
+ Object.assign(control, this.forced);
+ if (this.forcedPress.dodge) control.dodge = true;
+ if (this.forcedPress.vent) control.vent = true;
+ this.forcedPress = {};
+ } else {
+ const { yaw, pitch } = control;
+ Object.assign(control, idleControl(yaw, pitch));
+ }
+ const { view, events } = duel.frame(dtMs, control);
+ const now = this.now();
+ if (view) {
+ const first = !this.view;
+ this.view = view;
+ const me = view.players[view.slot];
+ // Each round (sides swap) starts facing the way the spawn faces.
+ if (me && (first || events.some((e) => e.type === "countdown"))) {
+ const spawn = duel.arena.def.spawns[me.side];
+ this.camera.face(spawn?.yaw ?? me.yaw);
+ }
+ if (me) {
+ const pose = this.camera.update(dtMs / 1000, me, this.floorY, test);
+ // The crosshair converges the blaster on what it covers (arena coordinates: floor at y 0).
+ const aim = resolveAim(duel.ctx, view, { x: pose.position.x, y: pose.position.y - this.floorY, z: pose.position.z }, pose.aimDir);
+ control.yaw = aim.yaw;
+ control.pitch = aim.pitch;
+ this.aimTarget = aim.target;
+ for (const e of events) {
+ if (e.type === "shot" && e.player === view.slot) this.camera.kick(e.ads ? 0.35 : 0.6);
+ if (e.type === "hit" && e.target === view.slot) this.camera.kick(1.1);
+ if (e.type === "parry" && e.player === view.slot) this.camera.kick(0.8);
+ }
+ }
+ this.feed.ingest(events, view.slot, now);
+ const count = view.match.phase === "countdown" ? Math.ceil(view.match.countdown) : -1;
+ if (count !== this.lastCount && count > 0) this.sound?.tick(count === 1);
+ this.lastCount = count;
+ const cam = this.camera.pose.position;
+ this.sound?.play(events, view.slot, { x: cam.x, z: cam.z, yaw: this.camera.yaw });
+ }
+ for (const e of events) this.visualEvents.push(e);
+ // A burst the renderer never drained (a hidden stage) is not kept forever.
+ if (this.visualEvents.length > 400) this.visualEvents.splice(0, this.visualEvents.length - 400);
+ if (duel.finished && this.phase !== "result") {
+ this.result = duel.result;
+ this.setPhase("result");
+ }
+ }
+
+ /** The HUD for this moment, or null when no match is on screen. */
+ hud(): HudModel | null {
+ if (!this.view || this.phase === "off") return null;
+ return buildHudModel(this.view, this.feed, this.now(), this.camera.yaw);
+ }
+}
+
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelHud.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelHud.ts
new file mode 100644
index 0000000000..a9ce720a7e
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelHud.ts
@@ -0,0 +1,238 @@
+/**
+ * What the duel's HUD shows, as plain data: the combat core's per-frame
+ * view (health, shield, heat and vent window, the match clock and score)
+ * plus the short-lived things the events bring (hit markers, the direction
+ * a hit came from, call-outs, round banners). React-free and pure apart
+ * from the feed's own memory of recent events, so it is tested without a
+ * renderer; `hud/DuelHud.tsx` draws it.
+ */
+import type { CombatEvent } from "../combat/types";
+import type { ViewState } from "../combat/view";
+
+/** How long things stay on screen, ms. */
+export const HUD_TIMES = {
+ hitMarker: 260,
+ killMarker: 520,
+ damageArc: 1100,
+ hurt: 380,
+ callout: 900,
+ fight: 900,
+ ping: 1200,
+} as const;
+
+/** Low health: the screen edge pulses below this share. */
+export const LOW_HEALTH = 0.3;
+
+export type HitMarkerKind = "hit" | "head" | "kill";
+export type CalloutKey = "parry" | "parried" | "perfect_vent" | "vent_miss" | "overheat" | "shield_break" | "deflect";
+
+interface Timed { at: number }
+
+/** The events' memory for the HUD: fed every frame with that frame's events. */
+export class DuelHudFeed {
+ hit: (Timed & { kind: HitMarkerKind }) | null = null;
+ damage: (Timed & { fromX: number; fromZ: number; amount: number })[] = [];
+ hurtAt = -Infinity;
+ callout: (Timed & { key: CalloutKey }) | null = null;
+ fightAt = -Infinity;
+ ping: (Timed & { x: number; z: number }) | null = null;
+ /** The last round's end, for its banner while the pause runs. */
+ roundEnd: { round: number; winner: number; reason: "kill" | "time" | "trade" } | null = null;
+
+ reset(): void {
+ this.hit = null;
+ this.damage = [];
+ this.hurtAt = -Infinity;
+ this.callout = null;
+ this.fightAt = -Infinity;
+ this.ping = null;
+ this.roundEnd = null;
+ }
+
+ /** Take one frame's events; `slot` is the person's, `now` ms. */
+ ingest(events: readonly CombatEvent[], slot: number, now: number): void {
+ for (const e of events) {
+ switch (e.type) {
+ case "hit":
+ if (e.owner === slot && e.target !== slot) {
+ const kind: HitMarkerKind = e.health <= 0 ? "kill" : e.headshot ? "head" : "hit";
+ // A kill marker is not replaced by a plain one in the same instant.
+ if (!(this.hit && this.hit.kind === "kill" && now - this.hit.at < HUD_TIMES.killMarker)) this.hit = { at: now, kind };
+ }
+ if (e.target === slot) {
+ this.damage.push({ at: now, fromX: e.fromX, fromZ: e.fromZ, amount: e.damage });
+ if (this.damage.length > 6) this.damage.shift();
+ this.hurtAt = now;
+ }
+ break;
+ case "parry":
+ if (e.player === slot) this.callout = { at: now, key: "parry" };
+ else if (e.target === slot) this.callout = { at: now, key: "parried" };
+ break;
+ case "deflect":
+ if (e.player === slot) this.callout = { at: now, key: "deflect" };
+ break;
+ case "vent_perfect":
+ if (e.player === slot) this.callout = { at: now, key: "perfect_vent" };
+ break;
+ case "vent_miss":
+ if (e.player === slot) this.callout = { at: now, key: "vent_miss" };
+ break;
+ case "overheat":
+ if (e.player === slot) this.callout = { at: now, key: "overheat" };
+ break;
+ case "shield_break":
+ if (e.player === slot) this.callout = { at: now, key: "shield_break" };
+ break;
+ case "round_start":
+ this.fightAt = now;
+ this.roundEnd = null;
+ break;
+ case "round_end":
+ this.roundEnd = { round: e.round, winner: e.winner, reason: e.reason };
+ break;
+ case "ping":
+ if (e.player !== slot) this.ping = { at: now, x: e.x, z: e.z };
+ break;
+ default:
+ break;
+ }
+ }
+ }
+}
+
+export type Banner =
+ | { kind: "countdown"; value: number }
+ | { kind: "fight" }
+ | { kind: "round"; outcome: "won" | "lost" | "draw"; reason: "kill" | "time" | "trade" };
+
+export interface HudModel {
+ phase: string;
+ round: number;
+ myScore: number;
+ theirScore: number;
+ roundsToWin: number;
+ /** Seconds left in the round (whole seconds, live only), null otherwise. */
+ timeLeft: number | null;
+ surge: boolean;
+ health: number;
+ healthFrac: number;
+ lowHealth: boolean;
+ enemyHealthFrac: number;
+ shieldFrac: number;
+ shieldUp: boolean;
+ shieldBroken: boolean;
+ shieldBrokenLeft: number;
+ shieldCanRaise: boolean;
+ parryReady: boolean;
+ heat: number;
+ overheated: boolean;
+ venting: boolean;
+ ventProgress: number;
+ ventWindow: readonly [number, number] | null;
+ ventAttempted: boolean;
+ canFire: boolean;
+ dodgeReady: boolean;
+ dodgeCooldown: number;
+ ads: number;
+ spreadDeg: number;
+ /** Crosshair: the hit marker on it, fading (alpha 0..1). */
+ hitMarker: { kind: HitMarkerKind; alpha: number } | null;
+ /** Where hits came from: clockwise from straight ahead, degrees, fading. */
+ damageArcs: { angleDeg: number; alpha: number }[];
+ /** Red flash at the screen edge after a hit taken, 0..1. */
+ hurt: number;
+ callout: { key: CalloutKey; alpha: number } | null;
+ banner: Banner | null;
+ /** The opponent's pinged position (reactor surge), fading. */
+ ping: { x: number; z: number; alpha: number } | null;
+}
+
+function fade(now: number, at: number, life: number): number {
+ const age = now - at;
+ return age < 0 || age >= life ? 0 : 1 - age / life;
+}
+
+/**
+ * The HUD for this frame. `camYaw` is the camera's heading (the damage
+ * arcs are drawn relative to it), radians, yaw 0 facing +Z.
+ */
+export function buildHudModel(view: ViewState, feed: DuelHudFeed, now: number, camYaw: number): HudModel {
+ const h = view.hud;
+ const m = view.match;
+ const me = view.players[view.slot];
+ const slot = view.slot;
+ const myScore = m.scores[slot] ?? 0;
+ const theirScore = m.scores[1 - slot] ?? 0;
+
+ let hitMarker: HudModel["hitMarker"] = null;
+ if (feed.hit) {
+ const a = fade(now, feed.hit.at, feed.hit.kind === "kill" ? HUD_TIMES.killMarker : HUD_TIMES.hitMarker);
+ if (a > 0) hitMarker = { kind: feed.hit.kind, alpha: a };
+ }
+ const damageArcs: HudModel["damageArcs"] = [];
+ if (me) {
+ for (const d of feed.damage) {
+ const a = fade(now, d.at, HUD_TIMES.damageArc);
+ if (a <= 0) continue;
+ const from = Math.atan2(d.fromX - me.x, d.fromZ - me.z);
+ const rel = Math.atan2(Math.sin(from - camYaw), Math.cos(from - camYaw));
+ damageArcs.push({ angleDeg: (-rel * 180) / Math.PI, alpha: a });
+ }
+ }
+ let callout: HudModel["callout"] = null;
+ if (feed.callout) {
+ const a = fade(now, feed.callout.at, HUD_TIMES.callout);
+ if (a > 0) callout = { key: feed.callout.key, alpha: a };
+ }
+ let banner: Banner | null = null;
+ if (m.phase === "countdown") banner = { kind: "countdown", value: Math.max(1, Math.ceil(m.countdown)) };
+ else if (m.phase === "live" && fade(now, feed.fightAt, HUD_TIMES.fight) > 0) banner = { kind: "fight" };
+ else if (m.phase === "round_end" && feed.roundEnd) {
+ const w = feed.roundEnd.winner;
+ banner = { kind: "round", outcome: w === slot ? "won" : w < 0 ? "draw" : "lost", reason: feed.roundEnd.reason };
+ }
+ let ping: HudModel["ping"] = null;
+ if (feed.ping) {
+ const a = fade(now, feed.ping.at, HUD_TIMES.ping);
+ if (a > 0) ping = { x: feed.ping.x, z: feed.ping.z, alpha: a };
+ }
+ const healthMax = h?.healthMax ?? 100;
+ const health = h?.health ?? 0;
+ return {
+ phase: m.phase,
+ round: m.round,
+ myScore,
+ theirScore,
+ roundsToWin: m.roundsToWin,
+ timeLeft: m.phase === "live" ? Math.ceil(m.roundTimeLeft) : null,
+ surge: m.surge,
+ health: Math.max(0, Math.round(health)),
+ healthFrac: Math.max(0, Math.min(1, health / healthMax)),
+ lowHealth: health > 0 && health / healthMax < LOW_HEALTH,
+ enemyHealthFrac: h ? Math.max(0, Math.min(1, h.enemyHealth / h.enemyHealthMax)) : 0,
+ shieldFrac: h?.shieldEnergy ?? 0,
+ shieldUp: !!h?.shieldUp,
+ shieldBroken: !!h?.shieldBroken,
+ shieldBrokenLeft: h?.shieldBrokenLeft ?? 0,
+ shieldCanRaise: !!h?.shieldCanRaise,
+ parryReady: !!h?.parryReady,
+ heat: h?.heat ?? 0,
+ overheated: !!h?.overheated,
+ venting: !!h?.venting,
+ ventProgress: h?.ventProgress ?? 0,
+ ventWindow: h?.ventWindow ?? null,
+ ventAttempted: !!h?.ventAttempted,
+ canFire: !!h?.canFire,
+ dodgeReady: !!h?.dodgeReady,
+ dodgeCooldown: h?.dodgeCooldown ?? 0,
+ ads: h?.ads ?? 0,
+ spreadDeg: h?.spreadDeg ?? 0,
+ hitMarker,
+ damageArcs,
+ hurt: fade(now, feed.hurtAt, HUD_TIMES.hurt),
+ callout,
+ banner,
+ ping,
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelInput.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelInput.ts
new file mode 100644
index 0000000000..c223920ab3
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelInput.ts
@@ -0,0 +1,208 @@
+/**
+ * The duel's controls (docs/verse/combat.md, "Input mapping"): keys and
+ * mouse buttons held or pressed during a match, turned into the combat
+ * core's ControlState once per frame.
+ *
+ * | Key | Control |
+ * |--------------|-------------------------------------------|
+ * | W A S D | move (strafe / forward, in the aim frame) |
+ * | Shift (hold) | sprint |
+ * | Left button | fire (hold for full auto) |
+ * | Right button | aim down the sights (hold) |
+ * | Q (hold) | energy shield |
+ * | Space | dodge roll (in the move direction) |
+ * | R | vent; again inside the window: perfect |
+ * | Esc | pause (pointer released); again: leave |
+ *
+ * Presses (dodge, vent) are latched until the next `control()` call reads
+ * them, so a tap shorter than a frame is never lost (the client latches
+ * them again until its next tick). Pure apart from its own state; the DOM
+ * binding is `attachDuelInput`.
+ */
+import { idleControl, type ControlState } from "../combat/input";
+
+/** Key codes per control. Arrow keys move too, for people who prefer them. */
+export const DUEL_KEYS = {
+ forward: ["KeyW", "ArrowUp"],
+ back: ["KeyS", "ArrowDown"],
+ left: ["KeyA", "ArrowLeft"],
+ right: ["KeyD", "ArrowRight"],
+ sprint: ["ShiftLeft", "ShiftRight"],
+ shield: ["KeyQ"],
+ dodge: ["Space"],
+ vent: ["KeyR"],
+} as const;
+
+type Held = "forward" | "back" | "left" | "right" | "sprint" | "shield";
+type Pressed = "dodge" | "vent";
+
+const HELD: readonly Held[] = ["forward", "back", "left", "right", "sprint", "shield"];
+const PRESSED: readonly Pressed[] = ["dodge", "vent"];
+
+function controlOf(code: string): Held | Pressed | null {
+ for (const name of [...HELD, ...PRESSED]) if ((DUEL_KEYS[name] as readonly string[]).includes(code)) return name;
+ return null;
+}
+
+/** The key is one the duel uses (the stage must not also act on it). */
+export function isDuelKey(code: string): boolean {
+ return controlOf(code) !== null;
+}
+
+export class DuelInput {
+ private readonly held = new Set<string>();
+ private fire = false;
+ private ads = false;
+ private latched = { dodge: false, vent: false };
+
+ /** A key went down; returns whether the duel uses it. Auto-repeat never presses twice. */
+ keyDown(code: string, repeat = false): boolean {
+ const c = controlOf(code);
+ if (!c) return false;
+ if (c === "dodge" || c === "vent") {
+ if (!repeat) this.latched[c] = true;
+ return true;
+ }
+ this.held.add(code);
+ return true;
+ }
+
+ keyUp(code: string): boolean {
+ if (!controlOf(code)) return false;
+ this.held.delete(code);
+ return true;
+ }
+
+ /** Mouse buttons: 0 fires, 2 aims down the sights. */
+ mouseDown(button: number): void {
+ if (button === 0) this.fire = true;
+ else if (button === 2) this.ads = true;
+ }
+
+ mouseUp(button: number): void {
+ if (button === 0) this.fire = false;
+ else if (button === 2) this.ads = false;
+ }
+
+ /** Everything let go (the window lost focus, the match paused). Latched presses go too. */
+ clear(): void {
+ this.held.clear();
+ this.fire = false;
+ this.ads = false;
+ this.latched = { dodge: false, vent: false };
+ }
+
+ private down(name: Held): boolean {
+ for (const code of DUEL_KEYS[name]) if (this.held.has(code)) return true;
+ return false;
+ }
+
+ /** Movement as the core wants it: x strafes right, y forward, each -1..1 (diagonals are clamped by the core). */
+ move(): { x: number; y: number } {
+ const x = (this.down("right") ? 1 : 0) - (this.down("left") ? 1 : 0);
+ const y = (this.down("forward") ? 1 : 0) - (this.down("back") ? 1 : 0);
+ return { x, y };
+ }
+
+ /**
+ * This frame's control state at the given aim (radians, yaw 0 faces +Z,
+ * pitch positive up). Reading it consumes the latched presses.
+ */
+ control(yaw: number, pitch: number, out?: ControlState): ControlState {
+ const c = out ?? idleControl();
+ const m = this.move();
+ c.moveX = m.x;
+ c.moveY = m.y;
+ c.yaw = yaw;
+ c.pitch = pitch;
+ c.fire = this.fire;
+ c.ads = this.ads;
+ c.shield = this.down("shield");
+ c.sprint = this.down("sprint") && m.y > 0;
+ c.dodge = this.latched.dodge;
+ c.vent = this.latched.vent;
+ c.forfeit = false;
+ this.latched.dodge = false;
+ this.latched.vent = false;
+ return c;
+ }
+}
+
+export interface DuelInputCallbacks {
+ /** Mouse movement while the match runs (CSS px; pointer-lock deltas when locked). */
+ look: (dx: number, dy: number) => void;
+ /** Escape (when the browser delivers it). */
+ escape: () => void;
+ /** The surface was clicked while the pointer is not locked (resume aiming). */
+ relock: () => void;
+ /** The duel takes input now (running, not paused or over). */
+ live: () => boolean;
+}
+
+/**
+ * Binds the keyboard (window) and the mouse (the stage surface) to a
+ * DuelInput while a duel is on. Keys the duel uses never reach the stage's
+ * own handlers (they would walk the commander). The context menu is off on
+ * the surface, so the right button can aim.
+ */
+export function attachDuelInput(el: HTMLElement, input: DuelInput, cb: DuelInputCallbacks): () => void {
+ const typing = (e: KeyboardEvent) => {
+ const t = e.target as HTMLElement | null;
+ return !!t && (t.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(t.tagName));
+ };
+ const keyDown = (e: KeyboardEvent) => {
+ if (typing(e)) return;
+ if (e.code === "Escape") {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ cb.escape();
+ return;
+ }
+ if (!cb.live()) return;
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
+ if (input.keyDown(e.code, e.repeat)) {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ }
+ };
+ const keyUp = (e: KeyboardEvent) => {
+ if (input.keyUp(e.code)) e.stopImmediatePropagation();
+ };
+ const blur = () => input.clear();
+ const locked = () => document.pointerLockElement === el;
+ const down = (e: PointerEvent) => {
+ if (e.pointerType !== "mouse") return;
+ if (!cb.live()) return;
+ if (!locked()) cb.relock();
+ input.mouseDown(e.button);
+ e.preventDefault();
+ };
+ const up = (e: PointerEvent) => {
+ if (e.pointerType !== "mouse") return;
+ input.mouseUp(e.button);
+ };
+ // Mouse movement anywhere turns the aim while the pointer is locked to the surface; unlocked, over the surface only.
+ const move = (e: MouseEvent) => {
+ if (!cb.live()) return;
+ if (!locked() && !el.contains(e.target as Node)) return;
+ cb.look(e.movementX || 0, e.movementY || 0);
+ };
+ const menu = (e: Event) => e.preventDefault();
+ window.addEventListener("keydown", keyDown, true);
+ window.addEventListener("keyup", keyUp, true);
+ window.addEventListener("blur", blur);
+ el.addEventListener("pointerdown", down);
+ window.addEventListener("pointerup", up);
+ document.addEventListener("mousemove", move);
+ el.addEventListener("contextmenu", menu);
+ return () => {
+ window.removeEventListener("keydown", keyDown, true);
+ window.removeEventListener("keyup", keyUp, true);
+ window.removeEventListener("blur", blur);
+ el.removeEventListener("pointerdown", down);
+ window.removeEventListener("pointerup", up);
+ document.removeEventListener("mousemove", move);
+ el.removeEventListener("contextmenu", menu);
+ input.clear();
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelSound.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelSound.ts
new file mode 100644
index 0000000000..1580b6d3a4
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelSound.ts
@@ -0,0 +1,357 @@
+/**
+ * The duel's sound effects, synthesised with WebAudio (no recorded assets):
+ * the blaster shot, impacts and body hits, the shield's block and parry,
+ * overheat alarm, vent hiss and its perfect/missed chimes, roll whoosh,
+ * countdown ticks, the round start and the match's end.
+ *
+ * Sounds from the opponent's side are panned and attenuated by where they
+ * happen relative to the camera. The AudioContext is made on the first
+ * sound after a user gesture (starting the duel is one); without WebAudio
+ * (tests, old browsers) everything is silent.
+ */
+import type { CombatEvent } from "../combat/types";
+
+type Ctx = AudioContext;
+
+/** Listener for positional sounds: the camera's position and heading (yaw 0 faces +Z). */
+export interface Listener { x: number; z: number; yaw: number }
+
+export class DuelSound {
+ private ctx: Ctx | null = null;
+ private master: GainNode | null = null;
+ private noise: AudioBuffer | null = null;
+ private failed = false;
+ volume = 0.55;
+
+ private audio(): Ctx | null {
+ if (this.ctx || this.failed) return this.ctx;
+ try {
+ const AC = (window as unknown as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext }).AudioContext
+ ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
+ if (!AC) { this.failed = true; return null; }
+ const ctx = new AC();
+ const master = ctx.createGain();
+ master.gain.value = this.volume;
+ // A gentle limiter keeps a burst of shots and impacts from clipping.
+ const comp = ctx.createDynamicsCompressor();
+ comp.threshold.value = -14;
+ comp.ratio.value = 6;
+ comp.attack.value = 0.003;
+ comp.release.value = 0.12;
+ master.connect(comp).connect(ctx.destination);
+ const len = Math.floor(ctx.sampleRate * 1.2);
+ const buf = ctx.createBuffer(1, len, ctx.sampleRate);
+ const data = buf.getChannelData(0);
+ let seed = 12345;
+ for (let i = 0; i < len; i++) {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;
+ data[i] = (seed / 0x7fffffff) * 2 - 1;
+ }
+ this.ctx = ctx;
+ this.master = master;
+ this.noise = buf;
+ } catch {
+ this.failed = true;
+ }
+ return this.ctx;
+ }
+
+ /** Wake the audio (call from a user gesture). */
+ resume(): void {
+ const ctx = this.audio();
+ if (ctx && ctx.state === "suspended") void ctx.resume().catch(() => undefined);
+ }
+
+ dispose(): void {
+ if (this.ctx) void this.ctx.close().catch(() => undefined);
+ this.ctx = null;
+ this.master = null;
+ }
+
+ /** An output for a sound at (x, z) heard from the listener; null for a sound at the listener. */
+ private out(ctx: Ctx, gain: number, at?: { x: number; z: number } | null, l?: Listener | null): AudioNode {
+ const g = ctx.createGain();
+ let level = gain;
+ if (at && l) {
+ const dx = at.x - l.x;
+ const dz = at.z - l.z;
+ const d = Math.hypot(dx, dz);
+ level *= 1 / (1 + Math.max(0, d - 2) / 9);
+ if (d > 0.5) {
+ const rel = Math.atan2(dx, dz) - l.yaw;
+ // Right of the heading is negative rel (yaw grows to the left), so the pan is -sin(rel).
+ const pan = ctx.createStereoPanner?.();
+ if (pan) {
+ pan.pan.value = Math.max(-0.85, Math.min(0.85, -Math.sin(rel)));
+ g.connect(pan).connect(this.master as GainNode);
+ g.gain.value = level;
+ return g;
+ }
+ }
+ }
+ g.gain.value = level;
+ g.connect(this.master as GainNode);
+ return g;
+ }
+
+ private env(ctx: Ctx, node: AudioNode, t: number, attack: number, peak: number, decay: number): GainNode {
+ const g = ctx.createGain();
+ g.gain.setValueAtTime(0.0001, t);
+ g.gain.exponentialRampToValueAtTime(Math.max(0.0002, peak), t + attack);
+ g.gain.exponentialRampToValueAtTime(0.0001, t + attack + decay);
+ node.connect(g);
+ return g;
+ }
+
+ private tone(ctx: Ctx, out: AudioNode, type: OscillatorType, f0: number, f1: number, t: number, attack: number, peak: number, decay: number): void {
+ const o = ctx.createOscillator();
+ o.type = type;
+ o.frequency.setValueAtTime(f0, t);
+ if (f1 !== f0) o.frequency.exponentialRampToValueAtTime(Math.max(20, f1), t + attack + decay);
+ this.env(ctx, o, t, attack, peak, decay).connect(out);
+ o.start(t);
+ o.stop(t + attack + decay + 0.05);
+ }
+
+ private hiss(ctx: Ctx, out: AudioNode, kind: BiquadFilterType, f0: number, f1: number, q: number, t: number, attack: number, peak: number, decay: number): void {
+ const src = ctx.createBufferSource();
+ src.buffer = this.noise;
+ src.loop = true;
+ const f = ctx.createBiquadFilter();
+ f.type = kind;
+ f.Q.value = q;
+ f.frequency.setValueAtTime(f0, t);
+ if (f1 !== f0) f.frequency.exponentialRampToValueAtTime(Math.max(20, f1), t + attack + decay);
+ src.connect(f);
+ this.env(ctx, f, t, attack, peak, decay).connect(out);
+ src.start(t, Math.random() * 0.8);
+ src.stop(t + attack + decay + 0.05);
+ }
+
+ /** The blaster: a bright descending zap over a short noise crack and a low thump. */
+ shot(local: boolean, at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, local ? 0.8 : 0.6, local ? null : at, l);
+ const pitch = 0.94 + Math.random() * 0.12;
+ this.tone(ctx, out, "sawtooth", 2400 * pitch, 260 * pitch, t, 0.002, 0.22, 0.14);
+ this.tone(ctx, out, "square", 1300 * pitch, 180 * pitch, t, 0.002, 0.12, 0.11);
+ this.hiss(ctx, out, "bandpass", 5200, 1800, 1.4, t, 0.001, 0.5, 0.06);
+ this.tone(ctx, out, "sine", 150, 48, t, 0.003, local ? 0.6 : 0.35, 0.12);
+ }
+
+ /** A bolt meets a wall or the floor: crack and sizzle. */
+ impact(at: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.55, at, l);
+ this.hiss(ctx, out, "lowpass", 3200, 500, 0.8, t, 0.001, 0.7, 0.16);
+ this.hiss(ctx, out, "highpass", 6000, 6000, 0.7, t + 0.01, 0.01, 0.12, 0.3);
+ this.tone(ctx, out, "triangle", 420, 90, t, 0.001, 0.25, 0.08);
+ }
+
+ /** A bolt hits a body: a dull thud with a burn; the shooter hears a crisp marker tick. */
+ bodyHit(local: boolean, headshot: boolean, at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, local ? 0.75 : 0.5, local ? null : at, l);
+ this.tone(ctx, out, "sine", 210, 60, t, 0.002, 0.7, 0.14);
+ this.hiss(ctx, out, "bandpass", 1800, 700, 1.2, t, 0.002, 0.45, 0.18);
+ if (headshot) this.tone(ctx, out, "triangle", 900, 500, t, 0.002, 0.3, 0.12);
+ }
+
+ /** The shooter's hit confirmation. */
+ marker(kind: "hit" | "head" | "kill"): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.35);
+ if (kind === "kill") {
+ this.tone(ctx, out, "triangle", 880, 880, t, 0.002, 0.5, 0.18);
+ this.tone(ctx, out, "triangle", 1320, 1320, t + 0.07, 0.002, 0.45, 0.32);
+ return;
+ }
+ this.tone(ctx, out, "sine", kind === "head" ? 2600 : 2100, kind === "head" ? 2600 : 2100, t, 0.001, 0.4, 0.05);
+ if (kind === "head") this.tone(ctx, out, "sine", 3300, 3300, t + 0.045, 0.001, 0.35, 0.06);
+ }
+
+ /** The shield absorbs a bolt: an electric crackle with a hum. */
+ block(at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.6, at, l);
+ this.tone(ctx, out, "square", 180, 140, t, 0.002, 0.25, 0.2);
+ this.hiss(ctx, out, "bandpass", 2600, 1200, 3, t, 0.002, 0.6, 0.2);
+ this.tone(ctx, out, "sawtooth", 620, 380, t, 0.002, 0.12, 0.16);
+ }
+
+ /** A deflection glances off with a whine. */
+ deflect(at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.55, at, l);
+ this.tone(ctx, out, "triangle", 900, 2600, t, 0.002, 0.3, 0.22);
+ this.hiss(ctx, out, "bandpass", 3500, 3500, 2, t, 0.002, 0.3, 0.12);
+ }
+
+ /** A perfect parry: a bright bell ring and a rising zing. */
+ parry(at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.75, at, l);
+ this.tone(ctx, out, "sine", 1320, 1320, t, 0.002, 0.55, 0.7);
+ this.tone(ctx, out, "sine", 1980, 1980, t, 0.002, 0.35, 0.55);
+ this.tone(ctx, out, "triangle", 2640, 2700, t, 0.002, 0.2, 0.4);
+ this.tone(ctx, out, "sawtooth", 600, 3200, t, 0.002, 0.12, 0.18);
+ this.hiss(ctx, out, "highpass", 5000, 8000, 1, t, 0.001, 0.3, 0.1);
+ }
+
+ shieldUp(local: boolean): void {
+ const ctx = this.audio();
+ if (!ctx || !local) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.3);
+ this.tone(ctx, out, "sawtooth", 110, 220, t, 0.03, 0.25, 0.18);
+ this.tone(ctx, out, "sine", 440, 660, t, 0.02, 0.12, 0.15);
+ }
+
+ shieldDown(local: boolean): void {
+ const ctx = this.audio();
+ if (!ctx || !local) return;
+ const t = ctx.currentTime;
+ this.tone(ctx, this.out(ctx, 0.22), "sawtooth", 220, 90, t, 0.01, 0.2, 0.14);
+ }
+
+ shieldBreak(at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.6, at, l);
+ this.hiss(ctx, out, "bandpass", 4000, 400, 1.5, t, 0.002, 0.8, 0.45);
+ this.tone(ctx, out, "square", 300, 60, t, 0.002, 0.3, 0.4);
+ }
+
+ /** Overheat: a falling two-tone alarm over a hiss. */
+ overheat(): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.4);
+ for (let i = 0; i < 3; i++) {
+ this.tone(ctx, out, "square", 980, 980, t + i * 0.16, 0.004, 0.28, 0.06);
+ this.tone(ctx, out, "square", 735, 735, t + i * 0.16 + 0.075, 0.004, 0.28, 0.06);
+ }
+ this.hiss(ctx, out, "highpass", 3000, 1500, 0.7, t, 0.02, 0.35, 0.7);
+ }
+
+ vent(seconds: number): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ this.hiss(ctx, this.out(ctx, 0.35), "bandpass", 5000, 1400, 0.9, t, 0.03, 0.5, Math.max(0.3, seconds));
+ }
+
+ ventPerfect(): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.35);
+ this.tone(ctx, out, "triangle", 1046, 1046, t, 0.002, 0.4, 0.15);
+ this.tone(ctx, out, "triangle", 1568, 1568, t + 0.06, 0.002, 0.4, 0.3);
+ }
+
+ ventMiss(): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ this.tone(ctx, this.out(ctx, 0.3), "square", 140, 120, t, 0.004, 0.3, 0.18);
+ }
+
+ dodge(local: boolean, at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ this.hiss(ctx, this.out(ctx, local ? 0.45 : 0.3, local ? null : at, l), "bandpass", 600, 2400, 1.6, t, 0.06, 0.6, 0.22);
+ }
+
+ death(at?: { x: number; z: number }, l?: Listener | null): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.6, at, l);
+ this.tone(ctx, out, "sine", 120, 35, t, 0.005, 0.8, 0.6);
+ this.hiss(ctx, out, "lowpass", 900, 120, 0.7, t, 0.005, 0.5, 0.5);
+ }
+
+ /** One countdown second. */
+ tick(last: boolean): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ this.tone(ctx, this.out(ctx, 0.3), "sine", last ? 880 : 660, last ? 880 : 660, t, 0.003, 0.4, 0.12);
+ }
+
+ /** The round starts: a rising sweep into a bright chord. */
+ roundStart(): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.4);
+ this.tone(ctx, out, "sawtooth", 220, 880, t, 0.02, 0.18, 0.25);
+ for (const f of [523, 659, 784]) this.tone(ctx, out, "triangle", f, f, t + 0.2, 0.01, 0.22, 0.5);
+ }
+
+ roundEnd(won: boolean): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.35);
+ const chord = won ? [523, 659, 784, 1046] : [440, 523, 622];
+ chord.forEach((f, i) => this.tone(ctx, out, "triangle", f, f, t + i * 0.07, 0.01, 0.22, 0.6));
+ }
+
+ surge(): void {
+ const ctx = this.audio();
+ if (!ctx) return;
+ const t = ctx.currentTime;
+ const out = this.out(ctx, 0.35);
+ for (let i = 0; i < 2; i++) this.tone(ctx, out, "sawtooth", 160, 320, t + i * 0.45, 0.05, 0.25, 0.3);
+ }
+
+ /** Play whatever a frame's events call for. `slot` is the person's. */
+ play(events: readonly CombatEvent[], slot: number, l: Listener | null): void {
+ if (events.length === 0) return;
+ for (const e of events) {
+ switch (e.type) {
+ case "shot": this.shot(e.player === slot, e, l); break;
+ case "impact": this.impact(e, l); break;
+ case "hit":
+ this.bodyHit(e.target === slot, e.headshot, e, l);
+ if (e.owner === slot && e.target !== slot) this.marker(e.health <= 0 ? "kill" : e.headshot ? "head" : "hit");
+ break;
+ case "block": this.block(e, l); break;
+ case "deflect": this.deflect(e, l); break;
+ case "parry": this.parry(e, l); break;
+ case "shield_up": this.shieldUp(e.player === slot); break;
+ case "shield_down": this.shieldDown(e.player === slot); break;
+ case "shield_break": this.shieldBreak(undefined, l); break;
+ case "overheat": if (e.player === slot) this.overheat(); break;
+ case "vent_start": if (e.player === slot) this.vent((e.end - e.tick) / 60); break;
+ case "vent_perfect": if (e.player === slot) this.ventPerfect(); break;
+ case "vent_miss": if (e.player === slot) this.ventMiss(); break;
+ case "dodge": this.dodge(e.player === slot); break;
+ case "death": this.death(undefined, l); break;
+ case "round_start": this.roundStart(); break;
+ case "round_end": this.roundEnd(e.winner === slot); break;
+ case "surge": this.surge(); break;
+ default: break;
+ }
+ }
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/effects.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/effects.ts
new file mode 100644
index 0000000000..37a2e2d298
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/effects.ts
@@ -0,0 +1,511 @@
+/**
+ * The duel's light and fire, all pooled (nothing is allocated per shot):
+ *
+ * - bolts: a white-hot core inside a coloured glow with a tapering trail,
+ * bright enough (HDR) for the eye view's bloom and drawn additively so
+ * they read on the low tier too; the person's bolts amber, the opponent's
+ * red, a parried bolt nearly white and thicker;
+ * - sparks: short-lived embers with gravity at impacts, hits and blocks;
+ * - flashes: camera-facing glows for muzzle flashes, impacts and parries;
+ * - scorch marks: dark burns on walls and floor that glow hot for a moment
+ * and fade after a while;
+ * - steam: a venting blaster's plume.
+ *
+ * Coordinates are world (the arena's plus the deck floor height).
+ */
+import {
+ AdditiveBlending, BufferAttribute, BufferGeometry, CanvasTexture, Color, CylinderGeometry, DoubleSide, Group, Mesh,
+ MeshBasicMaterial, NormalBlending, PlaneGeometry, Points, PointsMaterial, Quaternion, ShaderMaterial, Sprite, SpriteMaterial,
+ Vector3, type Texture,
+} from "three";
+import type { BoltView } from "../combat/view";
+import { BOLT_COLOURS } from "./blaster";
+
+/** HDR gain of the glowing parts (the bloom's threshold is 1.5). */
+const CORE_GAIN = 14;
+const GLOW_GAIN = 3.2;
+const TRAIL_M = 3.2;
+
+export function radialTexture(stops: readonly [number, string][], size = 64): Texture {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = size;
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ const g = ctx.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
+ for (const [at, colour] of stops) g.addColorStop(at, colour);
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ }
+ return new CanvasTexture(canvas);
+}
+
+/** A scorch: a dark, ragged burn. */
+function scorchTexture(): Texture {
+ const size = 128;
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = size;
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ const g = ctx.createRadialGradient(size / 2, size / 2, 2, size / 2, size / 2, size / 2);
+ g.addColorStop(0, "rgba(0,0,0,0.95)");
+ g.addColorStop(0.35, "rgba(8,6,5,0.8)");
+ g.addColorStop(0.7, "rgba(12,10,9,0.3)");
+ g.addColorStop(1, "rgba(0,0,0,0)");
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ // Ragged streaks outward.
+ let seed = 7;
+ const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
+ ctx.strokeStyle = "rgba(0,0,0,0.5)";
+ for (let i = 0; i < 18; i++) {
+ const a = rnd() * Math.PI * 2;
+ const r0 = size * 0.12;
+ const r1 = size * (0.3 + rnd() * 0.18);
+ ctx.lineWidth = 1 + rnd() * 3;
+ ctx.beginPath();
+ ctx.moveTo(size / 2 + Math.cos(a) * r0, size / 2 + Math.sin(a) * r0);
+ ctx.lineTo(size / 2 + Math.cos(a) * r1, size / 2 + Math.sin(a) * r1);
+ ctx.stroke();
+ }
+ }
+ return new CanvasTexture(canvas);
+}
+
+const TRAIL_VERTEX = /* glsl */ `
+varying float vAlong;
+void main() {
+ vAlong = uv.y;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+}`;
+const TRAIL_FRAGMENT = /* glsl */ `
+uniform vec3 colour;
+uniform float opacity;
+varying float vAlong;
+void main() {
+ // MSAA can sample the varying just outside the triangle; pow of a negative is NaN, which bloom spreads over the frame.
+ float a = pow(clamp(vAlong, 0.0, 1.0), 1.6) * opacity;
+ gl_FragColor = vec4(colour * a, a);
+}`;
+
+interface BoltSlot {
+ group: Group;
+ core: Mesh;
+ glow: Mesh;
+ trail: Mesh<CylinderGeometry, ShaderMaterial>;
+ coreMat: MeshBasicMaterial;
+ glowMat: MeshBasicMaterial;
+ id: number;
+ kind: string;
+ /** Where the bolt's current leg began (its muzzle or the shield that turned it). */
+ ox: number;
+ oy: number;
+ oz: number;
+ seen: boolean;
+}
+
+export class BoltPool {
+ readonly group = new Group();
+ private readonly slots: BoltSlot[] = [];
+ private readonly byId = new Map<number, BoltSlot>();
+ private readonly coreGeo = new CylinderGeometry(0.022, 0.022, 1, 8, 1).rotateX(Math.PI / 2);
+ private readonly glowGeo = new CylinderGeometry(0.075, 0.075, 1, 10, 1, true).rotateX(Math.PI / 2);
+ // The trail: a cone from the bolt (z 0, wide) back to a point (z -1), uv.y 1 at the front.
+ private readonly trailGeo = new CylinderGeometry(0.05, 0.0, 1, 8, 1, true).rotateX(Math.PI / 2).translate(0, 0, -0.5);
+ private readonly target = new Vector3();
+
+ constructor(size = 48) {
+ this.group.name = "DuelBolts";
+ for (let i = 0; i < size; i++) {
+ const coreMat = new MeshBasicMaterial({ color: 0xffffff, toneMapped: true });
+ const glowMat = new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.55, blending: AdditiveBlending, depthWrite: false, side: DoubleSide });
+ const trailMat = new ShaderMaterial({
+ uniforms: { colour: { value: new Color() }, opacity: { value: 0.9 } },
+ vertexShader: TRAIL_VERTEX, fragmentShader: TRAIL_FRAGMENT,
+ transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide,
+ });
+ const group = new Group();
+ const core = new Mesh(this.coreGeo, coreMat);
+ const glow = new Mesh(this.glowGeo, glowMat);
+ const trail = new Mesh(this.trailGeo, trailMat);
+ for (const m of [core, glow, trail]) { m.frustumCulled = false; m.renderOrder = 40; group.add(m); }
+ group.visible = false;
+ this.group.add(group);
+ this.slots.push({ group, core, glow, trail, coreMat, glowMat, id: -1, kind: "", ox: 0, oy: 0, oz: 0, seen: false });
+ }
+ }
+
+ /** Show this frame's bolts (`floorY` lifts arena heights onto the deck). */
+ update(bolts: readonly BoltView[], mySlot: number, floorY: number): void {
+ for (const s of this.slots) s.seen = false;
+ for (const b of bolts) {
+ let s = this.byId.get(b.id);
+ if (!s) {
+ s = this.slots.find((x) => x.id < 0);
+ if (!s) continue;
+ s.id = b.id;
+ s.kind = "";
+ this.byId.set(b.id, s);
+ // The leg starts where the bolt was fired: back along its flight by its age.
+ const back = (b.speed * b.ageTicks) / 60;
+ s.ox = b.x - b.dx * back;
+ s.oy = b.y - b.dy * back;
+ s.oz = b.z - b.dz * back;
+ }
+ s.seen = true;
+ if (s.kind !== b.kind) {
+ // Turned by a shield: the new leg starts here.
+ if (s.kind) { s.ox = b.x; s.oy = b.y; s.oz = b.z; }
+ s.kind = b.kind;
+ const colour = b.kind === "parry" ? BOLT_COLOURS.parry : b.owner === mySlot ? BOLT_COLOURS.own : BOLT_COLOURS.foe;
+ const tint = b.kind === "parry" ? (b.owner === mySlot ? BOLT_COLOURS.own : BOLT_COLOURS.foe) : colour;
+ s.coreMat.color.copy(colour).lerp(new Color(1, 1, 1), 0.55).multiplyScalar(CORE_GAIN * (b.kind === "parry" ? 1.4 : 1));
+ s.glowMat.color.copy(tint).multiplyScalar(GLOW_GAIN * (b.kind === "deflect" ? 0.6 : 1));
+ s.trail.material.uniforms.colour.value.copy(tint).multiplyScalar(b.kind === "parry" ? 2.6 : 1.8);
+ const thick = b.kind === "parry" ? 1.5 : b.kind === "deflect" ? 0.8 : 1;
+ s.core.scale.set(thick, thick, 1);
+ s.glow.scale.set(thick, thick, 1);
+ }
+ const y = b.y + floorY;
+ s.group.visible = true;
+ s.group.position.set(b.x, y, b.z);
+ this.target.set(b.x + b.dx, y + b.dy, b.z + b.dz);
+ s.group.lookAt(this.target);
+ // The core is a 1.2 m streak behind the bolt's head, never longer than the leg flown so far.
+ const flown = Math.hypot(b.x - s.ox, b.y + floorY - (s.oy + floorY), b.z - s.oz);
+ const coreLen = Math.max(0.15, Math.min(1.2, flown));
+ s.core.scale.z = coreLen;
+ s.core.position.z = -coreLen / 2;
+ s.glow.scale.z = coreLen * 1.1;
+ s.glow.position.z = -coreLen / 2;
+ s.trail.scale.z = Math.max(0.2, Math.min(TRAIL_M, flown));
+ }
+ for (const s of this.slots) {
+ if (s.seen || s.id < 0) continue;
+ this.byId.delete(s.id);
+ s.id = -1;
+ s.group.visible = false;
+ }
+ }
+
+ clear(): void {
+ for (const s of this.slots) { s.id = -1; s.group.visible = false; }
+ this.byId.clear();
+ }
+
+ dispose(): void {
+ this.coreGeo.dispose();
+ this.glowGeo.dispose();
+ this.trailGeo.dispose();
+ for (const s of this.slots) { s.coreMat.dispose(); s.glowMat.dispose(); s.trail.material.dispose(); }
+ }
+}
+
+/** Embers with gravity: impact sparks, hit sparks, the shield's crackle. */
+export class Sparks {
+ readonly points: Points;
+ private readonly pos: Float32Array;
+ private readonly col: Float32Array;
+ private readonly vel: Float32Array;
+ private readonly life: Float32Array;
+ private readonly base: Float32Array;
+ private next = 0;
+ private readonly tex: Texture;
+
+ constructor(private readonly size = 600) {
+ this.pos = new Float32Array(size * 3);
+ this.col = new Float32Array(size * 3);
+ this.vel = new Float32Array(size * 3);
+ this.life = new Float32Array(size);
+ this.base = new Float32Array(size * 3);
+ for (let i = 0; i < size; i++) this.pos[i * 3 + 1] = -1000;
+ const geo = new BufferGeometry();
+ geo.setAttribute("position", new BufferAttribute(this.pos, 3));
+ geo.setAttribute("color", new BufferAttribute(this.col, 3));
+ this.tex = radialTexture([[0, "rgba(255,255,255,1)"], [0.3, "rgba(255,255,255,0.8)"], [1, "rgba(255,255,255,0)"]], 32);
+ const mat = new PointsMaterial({
+ size: 0.05, map: this.tex, vertexColors: true, transparent: true, depthWrite: false, blending: AdditiveBlending, sizeAttenuation: true,
+ });
+ this.points = new Points(geo, mat);
+ this.points.frustumCulled = false;
+ this.points.renderOrder = 41;
+ }
+
+ /** `count` sparks from (x, y, z) around the normal (or in all directions), coloured `colour` × gain. */
+ burst(x: number, y: number, z: number, nx: number, ny: number, nz: number, count: number, colour: Color, speed = 4, spread = 0.9, gain = 6): void {
+ for (let k = 0; k < count; k++) {
+ const i = this.next;
+ this.next = (this.next + 1) % this.size;
+ let vx = nx + (Math.random() * 2 - 1) * spread;
+ let vy = ny + (Math.random() * 2 - 1) * spread + 0.3;
+ let vz = nz + (Math.random() * 2 - 1) * spread;
+ const l = Math.hypot(vx, vy, vz) || 1;
+ const s = speed * (0.35 + Math.random() * 0.9);
+ vx = (vx / l) * s; vy = (vy / l) * s; vz = (vz / l) * s;
+ this.pos[i * 3] = x; this.pos[i * 3 + 1] = y; this.pos[i * 3 + 2] = z;
+ this.vel[i * 3] = vx; this.vel[i * 3 + 1] = vy; this.vel[i * 3 + 2] = vz;
+ this.life[i] = 0.25 + Math.random() * 0.45;
+ const g = gain * (0.6 + Math.random() * 0.8);
+ this.base[i * 3] = colour.r * g; this.base[i * 3 + 1] = colour.g * g; this.base[i * 3 + 2] = colour.b * g;
+ }
+ }
+
+ update(dt: number, floorY: number): void {
+ const p = this.pos;
+ for (let i = 0; i < this.size; i++) {
+ if (this.life[i] <= 0) continue;
+ this.life[i] -= dt;
+ if (this.life[i] <= 0) { p[i * 3 + 1] = -1000; this.col[i * 3] = this.col[i * 3 + 1] = this.col[i * 3 + 2] = 0; continue; }
+ this.vel[i * 3 + 1] -= 9.8 * dt;
+ p[i * 3] += this.vel[i * 3] * dt;
+ p[i * 3 + 1] += this.vel[i * 3 + 1] * dt;
+ p[i * 3 + 2] += this.vel[i * 3 + 2] * dt;
+ if (p[i * 3 + 1] < floorY + 0.01) { p[i * 3 + 1] = floorY + 0.01; this.vel[i * 3 + 1] *= -0.35; this.vel[i * 3] *= 0.6; this.vel[i * 3 + 2] *= 0.6; }
+ const f = Math.min(1, this.life[i] / 0.3);
+ this.col[i * 3] = this.base[i * 3] * f;
+ this.col[i * 3 + 1] = this.base[i * 3 + 1] * f * f;
+ this.col[i * 3 + 2] = this.base[i * 3 + 2] * f * f * f;
+ }
+ this.points.geometry.attributes.position.needsUpdate = true;
+ this.points.geometry.attributes.color.needsUpdate = true;
+ }
+
+ clear(): void {
+ this.life.fill(0);
+ for (let i = 0; i < this.size; i++) this.pos[i * 3 + 1] = -1000;
+ this.points.geometry.attributes.position.needsUpdate = true;
+ }
+
+ dispose(): void {
+ this.points.geometry.dispose();
+ (this.points.material as PointsMaterial).dispose();
+ this.tex.dispose();
+ }
+}
+
+interface FlashSlot { sprite: Sprite; mat: SpriteMaterial; life: number; total: number; size0: number; size1: number; colour: Color; gain: number }
+
+/** Short camera-facing glows: muzzle flashes, impact and hit flashes, the parry burst. */
+export class Flashes {
+ readonly group = new Group();
+ private readonly slots: FlashSlot[] = [];
+ private next = 0;
+ private readonly tex: Texture;
+ private readonly star: Texture;
+
+ constructor(size = 40) {
+ this.tex = radialTexture([[0, "rgba(255,255,255,1)"], [0.18, "rgba(255,255,255,0.75)"], [0.5, "rgba(255,255,255,0.18)"], [1, "rgba(255,255,255,0)"]]);
+ this.star = starTexture();
+ for (let i = 0; i < size; i++) {
+ const mat = new SpriteMaterial({ map: this.tex, color: 0xffffff, transparent: true, blending: AdditiveBlending, depthWrite: false, depthTest: true });
+ const sprite = new Sprite(mat);
+ sprite.visible = false;
+ sprite.renderOrder = 42;
+ sprite.frustumCulled = false;
+ this.group.add(sprite);
+ this.slots.push({ sprite, mat, life: 0, total: 1, size0: 0, size1: 0, colour: new Color(), gain: 1 });
+ }
+ }
+
+ spawn(x: number, y: number, z: number, colour: Color, gain: number, size0: number, size1: number, seconds: number, star = false): void {
+ const s = this.slots[this.next];
+ this.next = (this.next + 1) % this.slots.length;
+ s.sprite.position.set(x, y, z);
+ s.life = s.total = seconds;
+ s.size0 = size0;
+ s.size1 = size1;
+ s.colour.copy(colour);
+ s.gain = gain;
+ s.mat.map = star ? this.star : this.tex;
+ s.mat.rotation = Math.random() * Math.PI;
+ s.sprite.visible = true;
+ }
+
+ update(dt: number): void {
+ for (const s of this.slots) {
+ if (s.life <= 0) continue;
+ s.life -= dt;
+ if (s.life <= 0) { s.sprite.visible = false; continue; }
+ const k = 1 - s.life / s.total;
+ const size = s.size0 + (s.size1 - s.size0) * Math.sqrt(k);
+ s.sprite.scale.set(size, size, 1);
+ s.mat.color.copy(s.colour).multiplyScalar(s.gain * (1 - k) * (1 - k));
+ }
+ }
+
+ clear(): void {
+ for (const s of this.slots) { s.life = 0; s.sprite.visible = false; }
+ }
+
+ dispose(): void {
+ for (const s of this.slots) s.mat.dispose();
+ this.tex.dispose();
+ this.star.dispose();
+ }
+}
+
+function starTexture(): Texture {
+ const size = 64;
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = size;
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ const c = size / 2;
+ const g = ctx.createRadialGradient(c, c, 0, c, c, c);
+ g.addColorStop(0, "rgba(255,255,255,1)");
+ g.addColorStop(0.25, "rgba(255,255,255,0.35)");
+ g.addColorStop(1, "rgba(255,255,255,0)");
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ ctx.globalCompositeOperation = "lighter";
+ for (const [w, h] of [[size, 3], [3, size]] as const) {
+ const lg = ctx.createLinearGradient(c - w / 2, c - h / 2, c + w / 2, c + h / 2);
+ lg.addColorStop(0, "rgba(255,255,255,0)");
+ lg.addColorStop(0.5, "rgba(255,255,255,0.9)");
+ lg.addColorStop(1, "rgba(255,255,255,0)");
+ ctx.fillStyle = lg;
+ ctx.fillRect(c - w / 2, c - h / 2, w, h);
+ }
+ }
+ return new CanvasTexture(canvas);
+}
+
+interface ScorchSlot { mesh: Mesh<PlaneGeometry, MeshBasicMaterial>; glow: Mesh<PlaneGeometry, MeshBasicMaterial>; age: number }
+
+/** Burn marks where bolts strike walls and floor: a hot glow that cools, then a dark mark that fades after a while. */
+export class Scorches {
+ readonly group = new Group();
+ private readonly slots: ScorchSlot[] = [];
+ private next = 0;
+ private readonly geo = new PlaneGeometry(1, 1);
+ private readonly tex = scorchTexture();
+ private readonly glowTex = radialTexture([[0, "rgba(255,255,255,1)"], [0.25, "rgba(255,255,255,0.5)"], [1, "rgba(255,255,255,0)"]]);
+ private readonly q = new Quaternion();
+ private readonly n = new Vector3();
+ static readonly HOT_S = 1.6;
+ static readonly LIFE_S = 24;
+
+ constructor(size = 64) {
+ for (let i = 0; i < size; i++) {
+ const mesh = new Mesh(this.geo, new MeshBasicMaterial({
+ map: this.tex, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2,
+ color: 0xffffff, blending: NormalBlending, toneMapped: false,
+ }));
+ const glow = new Mesh(this.geo, new MeshBasicMaterial({
+ map: this.glowTex, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3,
+ blending: AdditiveBlending, color: 0xffffff,
+ }));
+ mesh.visible = glow.visible = false;
+ mesh.renderOrder = 30;
+ glow.renderOrder = 31;
+ this.group.add(mesh, glow);
+ this.slots.push({ mesh, glow, age: Infinity });
+ }
+ }
+
+ add(x: number, y: number, z: number, nx: number, ny: number, nz: number): void {
+ const s = this.slots[this.next];
+ this.next = (this.next + 1) % this.slots.length;
+ const n = this.n.set(nx, ny, nz);
+ if (n.lengthSq() < 1e-6) n.set(0, 1, 0);
+ n.normalize();
+ this.q.setFromUnitVectors(new Vector3(0, 0, 1), n);
+ const size = 0.32 + Math.random() * 0.18;
+ for (const m of [s.mesh, s.glow]) {
+ m.position.set(x + n.x * 0.012, y + n.y * 0.012, z + n.z * 0.012);
+ m.quaternion.copy(this.q);
+ m.rotateZ(Math.random() * Math.PI * 2);
+ m.visible = true;
+ }
+ s.mesh.scale.setScalar(size);
+ s.glow.scale.setScalar(size * 0.75);
+ s.age = 0;
+ }
+
+ update(dt: number): void {
+ for (const s of this.slots) {
+ if (!Number.isFinite(s.age)) continue;
+ s.age += dt;
+ if (s.age >= Scorches.LIFE_S) { s.age = Infinity; s.mesh.visible = s.glow.visible = false; continue; }
+ const hot = Math.max(0, 1 - s.age / Scorches.HOT_S);
+ s.glow.visible = hot > 0;
+ s.glow.material.color.setRGB(4 * hot, 1.4 * hot * hot, 0.3 * hot * hot * hot);
+ const fadeOut = Math.min(1, (Scorches.LIFE_S - s.age) / 4);
+ s.mesh.material.opacity = 0.85 * fadeOut;
+ }
+ }
+
+ clear(): void {
+ for (const s of this.slots) { s.age = Infinity; s.mesh.visible = s.glow.visible = false; }
+ }
+
+ dispose(): void {
+ this.geo.dispose();
+ this.tex.dispose();
+ this.glowTex.dispose();
+ for (const s of this.slots) { s.mesh.material.dispose(); s.glow.material.dispose(); }
+ }
+}
+
+/** A venting blaster's plume: soft grey puffs rising and spreading. */
+export class Steam {
+ readonly points: Points;
+ private readonly pos: Float32Array;
+ private readonly vel: Float32Array;
+ private readonly life: Float32Array;
+ private next = 0;
+ private readonly tex: Texture;
+
+ constructor(private readonly size = 160) {
+ this.pos = new Float32Array(size * 3);
+ this.vel = new Float32Array(size * 3);
+ this.life = new Float32Array(size);
+ for (let i = 0; i < size; i++) this.pos[i * 3 + 1] = -1000;
+ const geo = new BufferGeometry();
+ geo.setAttribute("position", new BufferAttribute(this.pos, 3));
+ this.tex = radialTexture([[0, "rgba(255,255,255,0.55)"], [0.5, "rgba(255,255,255,0.2)"], [1, "rgba(255,255,255,0)"]], 32);
+ this.points = new Points(geo, new PointsMaterial({
+ size: 0.22, map: this.tex, color: 0x8a9096, transparent: true, opacity: 0.5, depthWrite: false, sizeAttenuation: true,
+ }));
+ this.points.frustumCulled = false;
+ this.points.renderOrder = 43;
+ }
+
+ emit(x: number, y: number, z: number, count: number): void {
+ for (let k = 0; k < count; k++) {
+ const i = this.next;
+ this.next = (this.next + 1) % this.size;
+ this.pos[i * 3] = x + (Math.random() - 0.5) * 0.05;
+ this.pos[i * 3 + 1] = y;
+ this.pos[i * 3 + 2] = z + (Math.random() - 0.5) * 0.05;
+ this.vel[i * 3] = (Math.random() - 0.5) * 0.5;
+ this.vel[i * 3 + 1] = 0.6 + Math.random() * 0.6;
+ this.vel[i * 3 + 2] = (Math.random() - 0.5) * 0.5;
+ this.life[i] = 0.6 + Math.random() * 0.5;
+ }
+ }
+
+ update(dt: number): void {
+ for (let i = 0; i < this.size; i++) {
+ if (this.life[i] <= 0) continue;
+ this.life[i] -= dt;
+ if (this.life[i] <= 0) { this.pos[i * 3 + 1] = -1000; continue; }
+ this.pos[i * 3] += this.vel[i * 3] * dt;
+ this.pos[i * 3 + 1] += this.vel[i * 3 + 1] * dt;
+ this.pos[i * 3 + 2] += this.vel[i * 3 + 2] * dt;
+ this.vel[i * 3 + 1] *= 1 - dt * 0.8;
+ }
+ this.points.geometry.attributes.position.needsUpdate = true;
+ }
+
+ clear(): void {
+ this.life.fill(0);
+ for (let i = 0; i < this.size; i++) this.pos[i * 3 + 1] = -1000;
+ this.points.geometry.attributes.position.needsUpdate = true;
+ }
+
+ dispose(): void {
+ this.points.geometry.dispose();
+ (this.points.material as PointsMaterial).dispose();
+ this.tex.dispose();
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts
new file mode 100644
index 0000000000..80374e4127
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts
@@ -0,0 +1,331 @@
+/**
+ * A duellist's body: a character from the library (the commander's officer
+ * body for the person, the trooper for the bot) with the blaster in its
+ * hands, posed every frame from the combat view.
+ *
+ * The clip set has walk and idle but no aiming, so the upper body is posed
+ * procedurally on top of the clips: the legs walk the way the body moves
+ * (backwards when it backs off), the spine and chest twist and bend toward
+ * the aim, the head follows it, and both arms reach the blaster by two-bone
+ * IK (right hand on the grip, left hand on the shroud). Sprinting carries
+ * the blaster low, the raised shield lowers it and puts the left palm
+ * forward, venting tips it up. A dodge is a tucked roll along the move
+ * direction; a knocked-out body falls backwards.
+ */
+import {
+ AnimationMixer, Color, Group, LoopRepeat, Matrix4, Mesh, MeshBasicMaterial, PlaneGeometry, Quaternion, Vector3,
+ type AnimationAction, type Bone, type Material, type MeshStandardMaterial, type Object3D, type Texture,
+} from "three";
+import type { Deck } from "../content/deck";
+import { disposeInstance, type CharacterInstance } from "../actors/characters";
+import { clipFor } from "../actors/clips";
+import { RoomLight } from "../actors/roomLight";
+import type { PlayerView } from "../combat/view";
+import { buildBlaster, type Blaster } from "./blaster";
+
+const UP = new Vector3(0, 1, 0);
+
+function wrap(a: number): number {
+ return Math.atan2(Math.sin(a), Math.cos(a));
+}
+
+/**
+ * Two-bone IK in world space: where the elbow goes for a shoulder at `s`,
+ * a target `t`, bone lengths `a` (upper) and `b` (lower), bending toward
+ * `pole`. Pure; writes into `out`.
+ */
+export function solveElbow(s: Vector3, t: Vector3, a: number, b: number, pole: Vector3, out: Vector3): Vector3 {
+ const dir = out.subVectors(t, s);
+ let d = dir.length();
+ if (d < 1e-5) return out.copy(s).addScaledVector(pole, a);
+ dir.multiplyScalar(1 / d);
+ d = Math.min(d, (a + b) * 0.999);
+ const along = (a * a - b * b + d * d) / (2 * d);
+ const h = Math.sqrt(Math.max(0, a * a - along * along));
+ // The pole's part across the shoulder-target line.
+ const px = pole.x - dir.x * pole.dot(dir);
+ const py = pole.y - dir.y * pole.dot(dir);
+ const pz = pole.z - dir.z * pole.dot(dir);
+ const pl = Math.hypot(px, py, pz) || 1;
+ return out.set(
+ s.x + dir.x * along + (px / pl) * h,
+ s.y + dir.y * along + (py / pl) * h,
+ s.z + dir.z * along + (pz / pl) * h,
+ );
+}
+
+const tmpA = new Vector3();
+const tmpB = new Vector3();
+const tmpQ = new Quaternion();
+const tmpQ2 = new Quaternion();
+const tmpP = new Quaternion();
+
+/** Turn `bone` so the line from it to `child` points at `target` (world). The bone's parents must be up to date. */
+function aimBone(bone: Object3D, child: Object3D, target: Vector3): void {
+ const from = bone.getWorldPosition(tmpA);
+ const cur = child.getWorldPosition(tmpB).sub(from);
+ const want = target.clone().sub(from);
+ if (cur.lengthSq() < 1e-10 || want.lengthSq() < 1e-10) return;
+ cur.normalize();
+ want.normalize();
+ const delta = tmpQ.setFromUnitVectors(cur, want);
+ const world = bone.getWorldQuaternion(tmpQ2);
+ const parent = bone.parent ? bone.parent.getWorldQuaternion(tmpP).invert() : tmpP.identity();
+ bone.quaternion.copy(parent.multiply(delta.multiply(world)));
+ bone.updateMatrixWorld(true);
+}
+
+/** Rotate a bone about a world axis by `angle` (its parent must be up to date). */
+function turnBone(bone: Object3D, axis: Vector3, angle: number): void {
+ if (Math.abs(angle) < 1e-5) return;
+ const parentInv = bone.parent ? bone.parent.getWorldQuaternion(tmpP).invert() : tmpP.identity();
+ const local = tmpA.copy(axis).applyQuaternion(parentInv).normalize();
+ bone.quaternion.premultiply(tmpQ.setFromAxisAngle(local, angle));
+ bone.updateMatrixWorld(true);
+}
+
+interface Arm { upper: Bone; fore: Bone; hand: Bone; a: number; b: number }
+
+export interface FigureLook {
+ /** Recolour these material names (the trooper's armour and accents). */
+ tint?: Readonly<Record<string, string>>;
+ /** Make these materials glow in the colour (a visor). */
+ glow?: Readonly<Record<string, string>>;
+ /** The blaster's cell colour. */
+ accent: Color;
+}
+
+export class DuelFigure {
+ readonly group = new Group();
+ readonly blaster: Blaster;
+ private readonly mixer: AnimationMixer;
+ private readonly light = new RoomLight();
+ private idle: AnimationAction | null = null;
+ private walk: AnimationAction | null = null;
+ private readonly bones: Record<string, Bone | undefined> = {};
+ private right: Arm | null = null;
+ private left: Arm | null = null;
+ private legsYaw = 0;
+ private walkWeight = 0;
+ private deathT = 0;
+ private primed = false;
+ private readonly shadow: Mesh<PlaneGeometry, MeshBasicMaterial>;
+ private readonly walkSpeed: number;
+ // Scratch, reused every frame.
+ private readonly grip = new Vector3();
+ private readonly fore = new Vector3();
+ private readonly elbow = new Vector3();
+ private readonly pole = new Vector3();
+ private readonly aim = new Vector3();
+ private readonly side = new Vector3();
+ private readonly qRoll = new Quaternion();
+ private readonly qYaw = new Quaternion();
+ private readonly m4 = new Matrix4();
+
+ constructor(readonly instance: CharacterInstance, look: FigureLook, shadow: Texture) {
+ this.mixer = new AnimationMixer(instance.root);
+ this.walkSpeed = instance.walkSpeed || 1.4;
+ for (const name of ["Hips", "Spine", "Chest", "Neck", "Head", "UpperArm_R", "ForeArm_R", "Hand_R", "UpperArm_L", "ForeArm_L", "Hand_L"]) {
+ const o = instance.root.getObjectByName(name) as Bone | undefined;
+ if (o) this.bones[name] = o;
+ }
+ const names = new Set(instance.clips.keys());
+ const idleName = clipFor("idle", names);
+ const walkName = clipFor("walk", names);
+ if (idleName) { this.idle = this.mixer.clipAction(instance.clips.get(idleName)!); this.idle.setLoop(LoopRepeat, Infinity).play(); }
+ if (walkName) { this.walk = this.mixer.clipAction(instance.clips.get(walkName)!); this.walk.setLoop(LoopRepeat, Infinity).play(); this.walk.weight = 0; }
+ for (const [name, colour] of Object.entries(look.tint ?? {})) {
+ for (const m of instance.materials.get(name) ?? []) (m as MeshStandardMaterial).color?.set(colour);
+ }
+ for (const [name, colour] of Object.entries(look.glow ?? {})) {
+ for (const m of instance.materials.get(name) ?? []) {
+ const s = m as MeshStandardMaterial;
+ if (s.emissive) { s.emissive.set(colour); s.emissiveIntensity = 3; }
+ }
+ }
+ this.blaster = buildBlaster(look.accent);
+ this.group.add(instance.root);
+ this.group.add(this.blaster.group);
+ this.light.attach([...[...instance.materials.values()].flat(), ...this.blaster.materials]);
+ this.shadow = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ map: shadow, color: 0x000000, transparent: true, opacity: 0.55, depthWrite: false }));
+ this.shadow.rotation.x = -Math.PI / 2;
+ this.group.add(this.shadow);
+ for (const mesh of instance.meshes) mesh.frustumCulled = false;
+ this.setupArms();
+ }
+
+ get materials(): Material[] {
+ return [...[...this.instance.materials.values()].flat(), ...this.blaster.materials];
+ }
+
+ private setupArms(): void {
+ const b = this.bones;
+ const root = this.instance.root;
+ root.position.set(0, 0, 0);
+ root.rotation.set(0, 0, 0);
+ root.updateMatrixWorld(true);
+ const arm = (u?: Bone, f?: Bone, h?: Bone): Arm | null => {
+ if (!u || !f || !h) return null;
+ const a = u.getWorldPosition(new Vector3()).distanceTo(f.getWorldPosition(new Vector3()));
+ const c = f.getWorldPosition(new Vector3()).distanceTo(h.getWorldPosition(new Vector3()));
+ return a > 0.05 && c > 0.05 ? { upper: u, fore: f, hand: h, a, b: c } : null;
+ };
+ let right = arm(b.UpperArm_R, b.ForeArm_R, b.Hand_R);
+ let left = arm(b.UpperArm_L, b.ForeArm_L, b.Hand_L);
+ // A body facing +Z has its right side toward -X; if the rig's "_R" sits on +X the sides are named the other way.
+ if (right && left && right.upper.getWorldPosition(new Vector3()).x > left.upper.getWorldPosition(new Vector3()).x) [right, left] = [left, right];
+ this.right = right;
+ this.left = left;
+ }
+
+ /**
+ * Pose the body for one frame. `floorY` is the deck floor under the arena;
+ * `deck` lights the body from the room's probe.
+ */
+ update(dtS: number, p: PlayerView, floorY: number, deck: Deck | null, timeS: number): void {
+ const dt = Math.min(0.1, Math.max(0, dtS));
+ const root = this.instance.root;
+ const aimYaw = p.aimYaw;
+ const aimPitch = p.aimPitch;
+
+ // Legs: walk the way the body moves; backing off plays the walk backwards.
+ const moving = p.speed > 0.35 && p.alive && !p.dodging;
+ let reverse = false;
+ if (moving) {
+ const moveYaw = Math.atan2(p.vx, p.vz);
+ let want = moveYaw;
+ if (Math.abs(wrap(moveYaw - aimYaw)) > (100 * Math.PI) / 180) { want = moveYaw + Math.PI; reverse = true; }
+ // Never twist further than the spine can carry.
+ const lim = (80 * Math.PI) / 180;
+ const off = wrap(want - aimYaw);
+ if (Math.abs(off) > lim) want = aimYaw + Math.sign(off) * lim;
+ this.legsYaw = this.primed ? this.legsYaw + wrap(want - this.legsYaw) * Math.min(1, dt * 12) : want;
+ } else {
+ this.legsYaw = this.primed ? this.legsYaw + wrap(aimYaw - this.legsYaw) * Math.min(1, dt * 8) : aimYaw;
+ }
+ this.primed = true;
+ this.walkWeight += ((moving ? 1 : 0) - this.walkWeight) * Math.min(1, dt * 10);
+ if (this.walk && this.idle) {
+ this.walk.weight = this.walkWeight;
+ this.idle.weight = 1 - this.walkWeight;
+ const rate = Math.min(3.2, Math.max(0.6, (p.speed / this.walkSpeed) * 0.72));
+ this.walk.timeScale = reverse ? -rate : rate;
+ }
+ this.mixer.update(dt);
+
+ // Root: on the floor at the player's position, facing the legs' way; a roll or a fall turns it on top.
+ const x = p.x;
+ const z = p.z;
+ this.qYaw.setFromAxisAngle(UP, this.legsYaw);
+ root.position.set(x, floorY, z);
+ root.quaternion.copy(this.qYaw);
+ if (p.dodging) {
+ const sp = Math.hypot(p.vx, p.vz);
+ const dx = sp > 0.1 ? p.vx / sp : Math.sin(aimYaw);
+ const dz = sp > 0.1 ? p.vz / sp : Math.cos(aimYaw);
+ const t = p.dodgeProgress;
+ const e = t * t * (3 - 2 * t);
+ const axis = this.side.set(dz, 0, -dx).normalize();
+ this.qRoll.setFromAxisAngle(axis, e * Math.PI * 2);
+ const pivotY = 0.5;
+ const tuck = Math.sin(t * Math.PI) * 0.18;
+ const off = tmpA.set(0, -pivotY, 0).applyQuaternion(this.qRoll);
+ root.position.set(x + off.x, floorY + pivotY - tuck * 0.5 + off.y, z + off.z);
+ root.quaternion.copy(this.qRoll).multiply(this.qYaw);
+ }
+ if (!p.alive) {
+ this.deathT = Math.min(1, this.deathT + dt / 0.6);
+ const e = 1 - (1 - this.deathT) * (1 - this.deathT);
+ const axis = this.side.set(-Math.cos(aimYaw), 0, Math.sin(aimYaw));
+ this.qRoll.setFromAxisAngle(axis, e * (Math.PI / 2) * 0.96);
+ root.quaternion.copy(this.qRoll).multiply(this.qYaw);
+ root.position.y = floorY + e * 0.12;
+ } else {
+ this.deathT = 0;
+ }
+ root.updateMatrixWorld(true);
+
+ const b = this.bones;
+ const posing = p.alive && !p.dodging;
+ if (posing) {
+ // Upper body toward the aim: twist over spine and chest, bend with the pitch.
+ const twist = wrap(aimYaw - this.legsYaw);
+ if (b.Spine) turnBone(b.Spine, UP, twist * 0.45);
+ if (b.Chest) turnBone(b.Chest, UP, twist * 0.55);
+ const rightAxis = this.side.set(-Math.cos(aimYaw), 0, Math.sin(aimYaw));
+ const bend = p.sprinting ? 0.12 : -aimPitch * 0.5;
+ if (b.Chest) turnBone(b.Chest, rightAxis, -bend * 0.6);
+ if (b.Spine) turnBone(b.Spine, rightAxis, -bend * 0.4);
+ if (b.Head) turnBone(b.Head, rightAxis, aimPitch * 0.35);
+ }
+
+ // The blaster: held at the shoulder along the aim; low while sprinting, lowered behind a raised shield, tipped up venting.
+ const bl = this.blaster.group;
+ bl.visible = p.alive;
+ let yaw = aimYaw;
+ let pitch = aimPitch;
+ let roll = 0;
+ let reach = 0.3;
+ if (p.sprinting) { pitch = -0.55; yaw = aimYaw - 0.5; reach = 0.16; roll = 0.4; }
+ else if (p.shieldUp) { pitch = -0.75; yaw = aimYaw - 0.35; reach = 0.16; roll = 0.2; }
+ else if (p.venting) { pitch = 0.55; yaw = aimYaw - 0.25; roll = -0.7; reach = 0.22; }
+ const dir = this.aim.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch));
+ const rx = -Math.cos(aimYaw);
+ const rz = Math.sin(aimYaw);
+ const shoulderY = floorY + (p.sprinting ? 1.2 : 1.3) + (p.ads > 0.5 ? 0.06 : 0);
+ this.grip.set(x + rx * 0.27 + dir.x * reach, shoulderY - 0.06 + dir.y * reach, z + rz * 0.27 + dir.z * reach);
+ if (posing) {
+ bl.position.copy(this.grip);
+ this.m4.lookAt(tmpA.set(0, 0, 0), tmpB.copy(dir).negate(), UP);
+ bl.quaternion.setFromRotationMatrix(this.m4);
+ if (roll) bl.quaternion.multiply(tmpQ.setFromAxisAngle(tmpA.set(0, 0, 1), roll));
+ bl.updateMatrixWorld(true);
+ this.fore.copy(this.blaster.fore).applyMatrix4(bl.matrixWorld);
+ // Right hand on the grip, elbow out and down; left hand on the shroud (on the shield's face while it is up).
+ const r = this.right;
+ if (r) {
+ const s = r.upper.getWorldPosition(new Vector3());
+ this.pole.set(rx * 0.7, -1, rz * 0.7).addScaledVector(dir, -0.2).normalize();
+ solveElbow(s, this.grip, r.a, r.b, this.pole, this.elbow);
+ aimBone(r.upper, r.fore, this.elbow);
+ aimBone(r.fore, r.hand, this.grip);
+ }
+ const l = this.left;
+ if (l) {
+ const target = p.shieldUp
+ ? tmpB.set(x + Math.sin(aimYaw) * 0.42 - rx * 0.05, floorY + 1.3, z + Math.cos(aimYaw) * 0.42 - rz * 0.05)
+ : this.fore;
+ const s = l.upper.getWorldPosition(new Vector3());
+ this.pole.set(-rx * 0.6, -1, -rz * 0.6).normalize();
+ const t = target.clone();
+ solveElbow(s, t, l.a, l.b, this.pole, this.elbow);
+ aimBone(l.upper, l.fore, this.elbow);
+ aimBone(l.fore, l.hand, t);
+ }
+ } else if (p.alive && b.Hand_R) {
+ // Rolling: the blaster stays in the right hand.
+ b.Hand_R.getWorldPosition(bl.position);
+ bl.quaternion.copy(root.quaternion);
+ bl.updateMatrixWorld(true);
+ }
+ this.blaster.setHeat(p.heat, p.venting, p.overheated, timeS);
+
+ this.shadow.position.set(x, floorY + 0.008, z);
+ this.shadow.scale.setScalar(p.alive ? 0.95 : 1.6);
+ if (deck) this.light.update(deck, x, floorY, z, dt);
+ }
+
+ /** Where the blaster's muzzle is in the world (for the flash). */
+ muzzle(out: Vector3): Vector3 {
+ return out.copy(this.blaster.muzzle).applyMatrix4(this.blaster.group.matrixWorld);
+ }
+
+ dispose(): void {
+ this.mixer.stopAllAction();
+ this.mixer.uncacheRoot(this.instance.root);
+ this.blaster.dispose();
+ this.shadow.geometry.dispose();
+ this.shadow.material.dispose();
+ disposeInstance(this.instance);
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/shield.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/shield.ts
new file mode 100644
index 0000000000..91e2db9df9
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/shield.ts
@@ -0,0 +1,148 @@
+/**
+ * The energy shield as it reads on screen: a translucent curved panel
+ * 0.8 m in front of the body, ±60° around the aim and 2 m high (the combat
+ * core's coverage, docs/verse/combat.md), drawn additively with a fine hex
+ * lattice, bright edges and a slow scan line. Its strength follows the
+ * shield's energy; the parry window shows as a hot rim; a blocked bolt
+ * ripples out from where it struck (blue-white), a parry flashes the whole
+ * panel gold-white, a break shatters it into a red flicker.
+ */
+import { AdditiveBlending, Color, CylinderGeometry, DoubleSide, Mesh, ShaderMaterial, Vector3 } from "three";
+import type { PlayerView } from "../combat/view";
+
+const VERTEX = /* glsl */ `
+varying vec2 vUv;
+varying vec3 vWorld;
+void main() {
+ vUv = uv;
+ vec4 w = modelMatrix * vec4(position, 1.0);
+ vWorld = w.xyz;
+ gl_Position = projectionMatrix * viewMatrix * w;
+}`;
+
+const FRAGMENT = /* glsl */ `
+uniform vec3 colour;
+uniform vec3 flashColour;
+uniform float strength;
+uniform float flash;
+uniform float rim;
+uniform float time;
+uniform vec3 hitPoint;
+uniform float hitAge;
+varying vec2 vUv;
+varying vec3 vWorld;
+
+float hexEdge(vec2 p) {
+ p *= vec2(1.0, 1.1547);
+ vec2 a = mod(p, vec2(1.0, 1.732)) - vec2(0.5, 0.866);
+ vec2 b = mod(p + vec2(0.5, 0.866), vec2(1.0, 1.732)) - vec2(0.5, 0.866);
+ vec2 g = dot(a, a) < dot(b, b) ? a : b;
+ vec2 q = abs(g);
+ float d = max(q.x * 0.866 + q.y * 0.5, q.y);
+ return smoothstep(0.40, 0.47, d);
+}
+
+void main() {
+ // Edges of the panel glow, the middle stays clear.
+ float side = min(vUv.x, 1.0 - vUv.x);
+ float vert = min(vUv.y, 1.0 - vUv.y);
+ float edge = smoothstep(0.08, 0.0, side) + smoothstep(0.06, 0.0, vert) * 0.7;
+ float body = smoothstep(0.0, 0.05, side) * smoothstep(0.0, 0.06, vert);
+ float hex = hexEdge(vec2(vUv.x * 16.0, vUv.y * 13.0));
+ float scan = smoothstep(0.03, 0.0, abs(fract(vUv.y - time * 0.35) - 0.5));
+ float ripple = 0.0;
+ if (hitAge < 0.6) {
+ float d = distance(vWorld, hitPoint);
+ float r = hitAge * 3.2;
+ ripple = smoothstep(0.12, 0.0, abs(d - r)) * (1.0 - hitAge / 0.6) + smoothstep(0.35, 0.0, d) * (1.0 - hitAge / 0.6) * 1.5;
+ }
+ float a = strength * (0.035 * body + 0.1 * hex * body + 0.5 * edge + 0.12 * scan * body) + rim * edge * 1.5 + ripple * 2.0;
+ vec3 c = colour * a + flashColour * flash * (0.25 * body + 0.8 * edge + 0.3 * hex * body);
+ float alpha = clamp(a + flash * 0.5, 0.0, 1.0);
+ gl_FragColor = vec4(max(c, vec3(0.0)), alpha);
+}`;
+
+const BLUE = new Color(0.35, 0.75, 1.6);
+const PARRY = new Color(2.4, 1.9, 0.9);
+const BREAK = new Color(2.2, 0.25, 0.12);
+
+export class ShieldMesh {
+ readonly mesh: Mesh<CylinderGeometry, ShaderMaterial>;
+ private flash = 0;
+ private hitAge = 10;
+ private breakT = 0;
+ private time = 0;
+ private shown = 0;
+
+ constructor(colour: Color) {
+ // ±60° around +Z (three's cylinder starts its angle at +Z), 0.8 m out, 2 m high from the floor.
+ const geo = new CylinderGeometry(0.8, 0.8, 2, 40, 1, true, -Math.PI / 3, (2 * Math.PI) / 3).translate(0, 1, 0);
+ const mat = new ShaderMaterial({
+ uniforms: {
+ colour: { value: colour.clone().multiplyScalar(1.2).add(BLUE).multiplyScalar(0.5) },
+ flashColour: { value: PARRY.clone() },
+ strength: { value: 1 },
+ flash: { value: 0 },
+ rim: { value: 0 },
+ time: { value: 0 },
+ hitPoint: { value: new Vector3() },
+ hitAge: { value: 10 },
+ },
+ vertexShader: VERTEX,
+ fragmentShader: FRAGMENT,
+ transparent: true,
+ depthWrite: false,
+ blending: AdditiveBlending,
+ side: DoubleSide,
+ });
+ this.mesh = new Mesh(geo, mat);
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 45;
+ this.mesh.visible = false;
+ }
+
+ /** A bolt absorbed at (x, y, z) world. */
+ block(x: number, y: number, z: number): void {
+ this.mesh.material.uniforms.hitPoint.value.set(x, y, z);
+ this.hitAge = 0;
+ this.flash = Math.max(this.flash, 0.25);
+ this.mesh.material.uniforms.flashColour.value.copy(BLUE);
+ }
+
+ parry(x: number, y: number, z: number): void {
+ this.mesh.material.uniforms.hitPoint.value.set(x, y, z);
+ this.hitAge = 0;
+ this.flash = 1.4;
+ this.mesh.material.uniforms.flashColour.value.copy(PARRY);
+ }
+
+ shatter(): void {
+ this.breakT = 0.5;
+ this.mesh.material.uniforms.flashColour.value.copy(BREAK);
+ this.flash = 1;
+ }
+
+ update(dt: number, p: PlayerView, floorY: number): void {
+ this.time += dt;
+ this.hitAge += dt;
+ this.flash = Math.max(0, this.flash - dt * 3.2);
+ this.breakT = Math.max(0, this.breakT - dt);
+ const want = p.alive && p.shieldUp ? 1 : 0;
+ this.shown += (want - this.shown) * Math.min(1, dt * (want ? 30 : 14));
+ const u = this.mesh.material.uniforms;
+ const flicker = this.breakT > 0 ? (Math.sin(this.time * 90) > 0 ? 1 : 0.2) : 1;
+ u.strength.value = this.shown * (0.35 + 0.65 * p.shieldEnergy) * flicker;
+ u.flash.value = this.flash;
+ u.rim.value = p.parrying ? 1 : 0;
+ u.time.value = this.time;
+ u.hitAge.value = this.hitAge;
+ this.mesh.visible = this.shown > 0.02 || this.flash > 0.02 || this.breakT > 0;
+ this.mesh.position.set(p.x, floorY, p.z);
+ this.mesh.rotation.set(0, p.aimYaw, 0);
+ }
+
+ dispose(): void {
+ this.mesh.geometry.dispose();
+ this.mesh.material.dispose();
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/BeaconsLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/effects/BeaconsLayer.tsx
index 89c819c993..582509a74c 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/effects/BeaconsLayer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/BeaconsLayer.tsx
@@ -53,6 +53,9 @@ interface Marks {
/** A floor ring is seen at the camera's 60° pitch: scale it up so it reads at its size on screen. */
const FLOOR_SQUASH = Math.sin(Math.PI / 3);
+/** Eye-level view: the beacon's and the floor ring's size in the room, metres. */
+const EYE_BEACON_M = 0.16;
+const EYE_RING_M = 0.9;
export function BeaconsLayer({ runtime, statuses, reduced }: { runtime: StageRuntime; statuses: ReadonlyMap<string, DutyStatus>; reduced: boolean }) {
const scene = useThree((s) => s.scene);
@@ -82,6 +85,8 @@ export function BeaconsLayer({ runtime, statuses, reduced }: { runtime: StageRun
useFrame(() => {
const t = performance.now() / 1000;
const worldPerPx = 1 / Math.max(1e-3, runtime.view.current.scale);
+ // At eye level the marks have a size in the room and walls hide them; on the plate they keep a size on screen.
+ const eye = !!runtime.eye;
const stamp = ++frame.current;
for (const [id, status] of statusRef.current) {
const style = DUTY[status];
@@ -112,13 +117,16 @@ export function BeaconsLayer({ runtime, statuses, reduced }: { runtime: StageRun
if (m.beaconColour !== style.beacon) { m.beacon.material.color.set(style.beacon); m.beaconColour = style.beacon; }
m.beacon.material.opacity = breath;
m.beacon.position.set(pose.x, pose.y + pose.height + 0.22, pose.z);
- m.beacon.scale.setScalar(SIZE_PX * worldPerPx);
+ m.beacon.scale.setScalar(eye ? EYE_BEACON_M : SIZE_PX * worldPerPx);
+ m.beacon.material.depthTest = eye;
}
const ringColour = style.beacon ?? QUIET[status];
if (m.ringColour !== ringColour) { m.ring.material.color.set(ringColour); m.ringColour = ringColour; }
m.ring.material.opacity = style.beacon ? Math.max(0.7, breath) : 0.75;
// The ring lies on the floor; on screen it is foreshortened like the floor itself.
- const size = (RING_PX * worldPerPx) / FLOOR_SQUASH;
+ const size = eye ? EYE_RING_M : (RING_PX * worldPerPx) / FLOOR_SQUASH;
+ m.ring.material.depthTest = eye;
+ m.shade.material.depthTest = eye;
m.ring.position.set(pose.x, pose.y + 0.02, pose.z);
m.ring.scale.setScalar(size);
m.shade.position.set(pose.x, pose.y + 0.02, pose.z);
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/effects/LightsLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/effects/LightsLayer.tsx
index b1a8e1d50f..892424ee4d 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/effects/LightsLayer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/effects/LightsLayer.tsx
@@ -11,11 +11,18 @@
* throws on the floor below.
*
* Everything stays faint: these are the room's own lights, not effects.
+ *
+ * At eye level (`runtime.eye`) the sprites keep their size in metres, are
+ * pulled a little toward the camera so the wall behind a lamp never cuts
+ * them, and are hidden by whatever stands in front. The fixture dips stay
+ * plate-only: there the ceilings are real geometry, and a dark pool sprite
+ * would stand up in the room like a shadow.
*/
import { useEffect, useMemo, useRef } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import { AdditiveBlending, CanvasTexture, Group, NormalBlending, Sprite, SpriteMaterial, type Blending, type Texture } from "three";
import type { Deck, Socket } from "../content/deck";
+import type { StageRuntime } from "../runtime";
import { RENDER_ORDER } from "../engine/renderOrder";
import { hash32 } from "../life/crew";
import { insidePolygon } from "../actors/roomLight";
@@ -69,7 +76,27 @@ export function ceilingPool(deck: Pick<Deck, "rooms">, socket: Socket, seed: num
return { x: (x0 + x1) / 2, y: room.floorY, z: (z0 + z1) / 2 };
}
-export function LightsLayer({ deck, alarm, reduced }: { deck: Deck; alarm: boolean; reduced: boolean }) {
+/** Eye level: a lamp sprite moves this far from its socket toward the camera, metres (a pulsing source half its size). */
+const EYE_PULL_M = 0.3;
+
+/** How far a lamp's sprites move toward the camera at eye level, metres: never more than half the way there. Pure. */
+export function eyePull(kind: LampKind, size: number, distance: number): number {
+ const want = kind === "pulse" ? size * 0.5 : EYE_PULL_M;
+ return Math.max(0, Math.min(want, distance * 0.5));
+}
+
+/** The lamps whose sprites show at eye level (the fixture dips are plate-only). */
+const EYE_KINDS: ReadonlySet<LampKind> = new Set(["blink", "alarm", "pulse"]);
+
+interface Props {
+ deck: Deck;
+ alarm: boolean;
+ reduced: boolean;
+ /** The stage's runtime: at eye level (`runtime.eye`) the sprites face its camera. */
+ runtime?: StageRuntime;
+}
+
+export function LightsLayer({ deck, alarm, reduced, runtime }: Props) {
const scene = useThree((s) => s.scene);
const texture = useMemo(glowTexture, []);
const alarmRef = useRef(alarm);
@@ -113,6 +140,9 @@ export function LightsLayer({ deck, alarm, reduced }: { deck: Deck; alarm: boole
dippers: [], window: -1, pick: null, at: 0, placed: false,
});
+ // The sprites were last placed for the eye-level camera (they go back onto their sockets on the plate).
+ const eyeWas = useRef(false);
+
useFrame(() => {
const t = performance.now() / 1000;
const window = Math.floor(t / FLICKER_EVERY_S);
@@ -124,9 +154,27 @@ export function LightsLayer({ deck, alarm, reduced }: { deck: Deck; alarm: boole
d.at = window * FLICKER_EVERY_S + ((hash32(`t${window}`) % 1000) / 1000) * (FLICKER_EVERY_S - 2);
d.placed = false;
}
- const pick = reduced ? null : d.pick;
+ const cam = runtime?.eye?.camera.position ?? null;
+ const leftEye = eyeWas.current && !cam;
+ eyeWas.current = !!cam;
+ const pick = reduced || cam ? null : d.pick;
const at = d.at;
for (const l of lamps) {
+ if (EYE_KINDS.has(l.kind)) {
+ const p = l.socket;
+ if (cam) {
+ const dx = cam.x - p.x;
+ const dy = cam.y - p.y;
+ const dz = cam.z - p.z;
+ const dist = Math.hypot(dx, dy, dz);
+ const k = dist > 1e-6 ? eyePull(l.kind, l.glow.scale.x, dist) / dist : 0;
+ l.glow.position.set(p.x + dx * k, p.y + dy * k, p.z + dz * k);
+ l.shade.position.copy(l.glow.position);
+ } else if (leftEye) {
+ l.glow.position.set(p.x, p.y, p.z);
+ l.shade.position.set(p.x, p.y, p.z);
+ }
+ }
const g = l.glow.material;
const s = l.shade.material;
switch (l.kind) {
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/DeckBackdrop.tsx b/dodaios/ui/web/frontend/src/components/society/verse/engine/DeckBackdrop.tsx
index d00f04c624..5688457273 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/DeckBackdrop.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/DeckBackdrop.tsx
@@ -18,13 +18,15 @@ interface Props {
debug: boolean;
/** The stage is on screen (a hidden stage gives its full-resolution tiles back). */
awake: boolean;
+ /** The plate is the view on screen; false while the eye-level view renders (the plate then idles). */
+ active?: boolean;
/** The plate's overview is on screen (the stage hides its loading state). */
onReady: (deck: Deck) => void;
onError: (error: Error) => void;
children?: ReactNode;
}
-export function DeckBackdrop({ runtime, deck, debug, awake, onReady, onError, children }: Props) {
+export function DeckBackdrop({ runtime, deck, debug, awake, active = true, onReady, onError, children }: Props) {
const scene = useThree((s) => s.scene);
const invalidate = useThree((s) => s.invalidate);
const [plate, setPlate] = useState<PlateLayer | null>(null);
@@ -48,8 +50,12 @@ export function DeckBackdrop({ runtime, deck, debug, awake, onReady, onError, ch
// Off screen the full-resolution tiles go back; the overview stays for a quick return.
useEffect(() => {
- if (!awake) plate?.trim();
- }, [awake, plate]);
+ if (!awake || !active) plate?.trim();
+ }, [awake, active, plate]);
+ // Only the view on screen draws the plate.
+ useEffect(() => {
+ if (plate) plate.group.visible = active;
+ }, [plate, active]);
useEffect(() => {
if (!deck.occludersUrl) return;
@@ -72,7 +78,7 @@ export function DeckBackdrop({ runtime, deck, debug, awake, onReady, onError, ch
if (!plate) return null;
return (
<>
- <StageRenderer runtime={runtime} deck={deck} plate={plate} debug={debug} />
+ <StageRenderer runtime={runtime} deck={deck} plate={plate} debug={debug} active={active} />
{(occluders || !deck.occludersUrl) && children}
</>
);
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/StageRenderer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/engine/StageRenderer.tsx
index 7ba646ea5c..15b895887c 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/StageRenderer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/StageRenderer.tsx
@@ -25,9 +25,11 @@ interface Props {
deck: Deck;
plate: PlateLayer;
debug: boolean;
+ /** The plate is the view on screen (the eye-level view renders otherwise). */
+ active?: boolean;
}
-export function StageRenderer({ runtime, deck, plate, debug }: Props) {
+export function StageRenderer({ runtime, deck, plate, debug, active = true }: Props) {
const gl = useThree((s) => s.gl);
const scene = useThree((s) => s.scene);
const camera = useThree((s) => s.camera) as OrthographicCamera;
@@ -52,6 +54,7 @@ export function StageRenderer({ runtime, deck, plate, debug }: Props) {
}, -2);
useFrame((_, dt) => {
+ if (!active) return;
const started = performance.now();
plate.update(runtime.view.current, runtime.view.vp, runtime.view.revision, gl, started);
gl.info.reset();
@@ -77,6 +80,7 @@ export function StageRenderer({ runtime, deck, plate, debug }: Props) {
s.tiles = plate.resident;
s.tilesLoading = plate.inFlight;
s.plateLevel = plate.levelName;
+ s.tier = "";
for (const fn of runtime.afterFrame) fn();
}, 1);
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/imageFetch.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/imageFetch.ts
index ecda851831..fb43d2eb5c 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/imageFetch.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/imageFetch.ts
@@ -43,7 +43,11 @@ export class NotAnImage extends Error {
}
}
-export async function fetchImageBitmap(url: string, signal?: AbortSignal): Promise<ImageBitmap> {
+/**
+ * `orientation` "flipY" flips rows at decode time (WebGL ignores flipY for
+ * ImageBitmap uploads); "none" keeps the file's row order.
+ */
+export async function fetchImageBitmap(url: string, signal?: AbortSignal, orientation: "none" | "flipY" = "none"): Promise<ImageBitmap> {
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`Image fetch failed: ${url} (HTTP ${res.status})`);
const bytes = new Uint8Array(await res.arrayBuffer());
@@ -53,5 +57,6 @@ export async function fetchImageBitmap(url: string, signal?: AbortSignal): Promi
return createImageBitmap(new Blob([bytes], { type }), {
premultiplyAlpha: "none",
colorSpaceConversion: "none",
+ ...(orientation === "flipY" ? { imageOrientation: "flipY" as const } : {}),
});
}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/picking.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/picking.ts
index a0331102c5..60c4220e8d 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/picking.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/picking.ts
@@ -14,7 +14,7 @@ const BODY_HALF_W = 0.3;
const STATION_HALF = 0.85;
/** The body under plate point p, nearest the camera first; null when none. */
-export function pickBody(cam: PlateCamera, poses: Iterable<ActorPose>, p: PlatePoint, accept: (id: string) => boolean): string | null {
+export function pickBody(cam: PlateCamera, poses: Iterable<Omit<ActorPose, "yaw">>, p: PlatePoint, accept: (id: string) => boolean): string | null {
let best: string | null = null;
let bestDepth = -Infinity;
const cos = Math.cos((cam.pitchDeg * Math.PI) / 180);
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx
new file mode 100644
index 0000000000..2effdf5580
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/RealtimeBackdrop.tsx
@@ -0,0 +1,285 @@
+/**
+ * The eye-level view of a deck exported for it (docs/verse/realtime.md):
+ * loads the realtime scene into the stage's scene (on its own layer) and,
+ * while `active`, owns the frame: steps the eye-level camera (over the
+ * shoulder or through the eyes) on the commander, renders deck, people and effects through the post chain (HDR
+ * target with MSAA, bloom, AgX at the plate's exposure) and publishes the
+ * camera for the HUD and the pointer (`runtime.eye`).
+ *
+ * Quality tiers: "high" (bloom, 4x MSAA, full resolution) by default; when
+ * frames stay slower than ~45 fps the view drops to "low" (no post chain,
+ * pixel ratio at most 1) for weak GPUs. The person can pin either tier in
+ * the view settings (`quality`).
+ *
+ * The frame path allocates nothing of its own per frame (three.js and the
+ * BVH query aside).
+ */
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useFrame, useThree } from "@react-three/fiber";
+import {
+ AgXToneMapping, Color, DoubleSide, HalfFloatType, PerspectiveCamera, Ray, Vector2, Vector3, WebGLRenderTarget,
+} from "three";
+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
+import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";
+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
+import type { Deck } from "../../content/deck";
+import type { StageRuntime } from "../../runtime";
+import { liveLoad } from "../liveLoad";
+import { REALTIME_LAYER } from "../renderOrder";
+import { loadRealtimeScene, type RealtimeScene } from "./realtimeScene";
+import { DECK_SHARED } from "./deckMaterial";
+import { verticalFov, type SegmentTest } from "./shoulderRig";
+import type { QualityChoice } from "./viewSettings";
+
+interface Props {
+ runtime: StageRuntime;
+ deck: Deck;
+ /** The eye-level view is the one on screen (third person on a full-size stage). */
+ active: boolean;
+ commanderId: string;
+ /** The person's quality setting: "auto" picks the tier from the frame rate. */
+ quality?: QualityChoice;
+ onReady: (deck: Deck) => void;
+ onError: (error: Error) => void;
+}
+
+export type QualityTier = "high" | "low";
+
+/**
+ * Bloom of the emissive fixtures, tuned against Cycles renders from the same
+ * camera: UnrealBloom sums five blur levels, so a small strength already
+ * matches the plate's glow (threshold 1.0, strength 0.12); more veils the
+ * dark deck in grey.
+ */
+const BLOOM = { strength: 0.035, radius: 0.3, threshold: 1.5 };
+/** Slower than this (smoothed frame time, ms) for the window below drops to the low tier. */
+const SLOW_FRAME_MS = 22;
+const SLOW_WINDOW_MS = 2500;
+/** Closer than this behind the pivot (a wall pushed the camera in), the commander is hidden, metres. */
+const HIDE_COMMANDER_BELOW_M = 0.55;
+/** Blended this far into first person, the commander's own body is hidden (the camera is inside the head). */
+const HIDE_COMMANDER_FIRST_SHARE = 0.3;
+/** Frames ignored after the view opens (shader compiles, uploads). */
+const WARMUP_FRAMES = 90;
+
+/**
+ * QA hook: `window.__verseTune = { bloomStrength, bloomRadius, bloomThreshold, envGain,
+ * bakedGain, coatBias, exposureBias }` overrides the look while a run measures it.
+ * Unset (always, outside QA runs) the view uses its built-in values.
+ */
+interface Tuning {
+ bloomStrength?: number;
+ bloomRadius?: number;
+ bloomThreshold?: number;
+ envGain?: number;
+ bakedGain?: number;
+ coatBias?: number;
+ exposureBias?: number;
+ /** Material property overrides by material-name prefix, e.g. { M_Floor: { specularIntensity: 0.05 } }; `visible: 0` hides. */
+ materials?: Record<string, Record<string, number>>;
+}
+
+function tuning(): Tuning | undefined {
+ return (window as unknown as { __verseTune?: Tuning }).__verseTune;
+}
+
+function applyTuning(loaded: RealtimeScene, bloom: UnrealBloomPass, t: Tuning | undefined): void {
+ bloom.strength = t?.bloomStrength ?? BLOOM.strength;
+ bloom.radius = t?.bloomRadius ?? BLOOM.radius;
+ bloom.threshold = t?.bloomThreshold ?? BLOOM.threshold;
+ DECK_SHARED.verseBakedGain.value = t?.bakedGain ?? 1;
+ DECK_SHARED.verseCoatBias.value = t?.coatBias ?? 0;
+ if (t) (window as unknown as { __verseMaterials?: string[] }).__verseMaterials = loaded.materials.map((m) => m.name);
+ const env = t?.envGain ?? 1;
+ for (const m of loaded.materials) {
+ const props = m as unknown as Record<string, unknown> & { userData: { verseBase?: Record<string, number> } };
+ const base = (props.userData.verseBase ??= { envMapIntensity: (props.envMapIntensity as number | undefined) ?? 1 });
+ const override = Object.entries(t?.materials ?? {}).find(([prefix]) => m.name.startsWith(prefix))?.[1] ?? {};
+ m.visible = override.visible === undefined ? true : override.visible !== 0;
+ for (const [key, value] of Object.entries(override)) {
+ if (key === "visible") continue;
+ if (!(key in base) && typeof props[key] === "number") base[key] = props[key] as number;
+ props[key] = value;
+ }
+ for (const [key, value] of Object.entries(base)) if (!(key in override)) props[key] = value;
+ props.envMapIntensity = ((override.envMapIntensity ?? base.envMapIntensity) as number) * env;
+ }
+}
+
+export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality = "auto", onReady, onError }: Props) {
+ const gl = useThree((s) => s.gl);
+ const scene = useThree((s) => s.scene);
+ const size = useThree((s) => s.size);
+ const dpr = useThree((s) => s.viewport.dpr);
+ const setDpr = useThree((s) => s.setDpr);
+ const [loaded, setLoaded] = useState<RealtimeScene | null>(null);
+ /** The tier "auto" settled on; a pinned quality overrides it. */
+ const [autoTier, setAutoTier] = useState<QualityTier>("high");
+ const tier: QualityTier = quality === "auto" ? autoTier : quality;
+ // Back to "auto": measure again from the high tier.
+ useEffect(() => { if (quality === "auto") setAutoTier("high"); }, [quality]);
+
+ useEffect(() => {
+ const content = deck.realtime;
+ if (!content) return;
+ const abort = new AbortController();
+ let own: RealtimeScene | null = null;
+ const stop = liveLoad(loadRealtimeScene(gl, content, abort.signal), (s) => {
+ own = s;
+ scene.add(s.group);
+ setLoaded(s);
+ onReady(deck);
+ }, onError);
+ return () => {
+ stop();
+ abort.abort();
+ if (own) { scene.remove(own.group); own.dispose(); }
+ setLoaded(null);
+ };
+ // The callbacks are the stage's and stable enough; a new deck is what reloads.
+ }, [deck, gl, scene]);
+
+ const camera = useMemo(() => {
+ const c = new PerspectiveCamera(50, 1, 0.05, 500);
+ c.layers.enable(0);
+ c.layers.enable(REALTIME_LAYER);
+ return c;
+ }, []);
+
+ const { composer, bloom } = useMemo(() => {
+ const target = new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples: 4 });
+ const c = new EffectComposer(gl, target);
+ c.addPass(new RenderPass(scene, camera));
+ const pass = new UnrealBloomPass(new Vector2(1, 1), BLOOM.strength, BLOOM.radius, BLOOM.threshold);
+ c.addPass(pass);
+ c.addPass(new OutputPass());
+ return { composer: c, bloom: pass };
+ }, [gl, scene, camera]);
+ useEffect(() => () => composer.dispose(), [composer]);
+
+ useEffect(() => {
+ const w = Math.max(1, size.width);
+ const h = Math.max(1, size.height);
+ composer.setPixelRatio(dpr);
+ composer.setSize(w, h);
+ camera.aspect = w / h;
+ camera.fov = verticalFov(camera.aspect, runtime.shoulder.hfov());
+ camera.updateProjectionMatrix();
+ }, [composer, camera, size.width, size.height, dpr, runtime]);
+
+ // The low tier renders at a pixel ratio of at most 1.
+ useEffect(() => {
+ if (tier !== "low" || !active) return;
+ const previous = gl.getPixelRatio();
+ if (previous > 1) setDpr(1);
+ return () => { if (previous > 1) setDpr(previous); };
+ }, [tier, active, gl, setDpr]);
+
+ const clearColour = useMemo(() => new Color(), []);
+ const direction = useMemo(() => new Vector3(), []);
+ const ray = useMemo(() => new Ray(), []);
+ const test = useMemo<SegmentTest>(() => (from, to) => {
+ const bvh = loaded?.collider;
+ if (!bvh) return null;
+ direction.set(to.x - from.x, to.y - from.y, to.z - from.z);
+ const length = direction.length();
+ if (length < 1e-6) return null;
+ ray.origin.set(from.x, from.y, from.z);
+ ray.direction.copy(direction).multiplyScalar(1 / length);
+ const hit = bvh.raycastFirst(ray, DoubleSide, 0, length);
+ return hit ? hit.distance / length : null;
+ }, [loaded, ray, direction]);
+
+ // Publish the eye-level camera while it is the view on screen.
+ useEffect(() => {
+ if (!active || !loaded) return;
+ const eye = { camera, collider: loaded.collider, test };
+ runtime.eye = eye;
+ runtime.control.reframe = true;
+ return () => { if (runtime.eye === eye) runtime.eye = null; };
+ }, [active, loaded, runtime, camera, test]);
+
+ const frames = useRef({ count: 0, slowSince: 0 });
+ useEffect(() => { frames.current = { count: 0, slowSince: 0 }; }, [active, loaded, quality]);
+ // The QA look hook was applied last frame: unset again, the built-in look is put back once.
+ const tuned = useRef(false);
+ // The commander's pose as the rig reads it, refilled every frame.
+ const body = useMemo(() => ({ x: 0, y: 0, z: 0, heading: 0, moving: false }), []);
+
+ useFrame((_, dt) => {
+ if (!active || !loaded) return;
+ const started = performance.now();
+ const rig = runtime.shoulder;
+ const control = runtime.control;
+ const pose = runtime.poses.get(commanderId);
+ const override = runtime.cameraOverride;
+ if (override) {
+ // Another mode drives the camera (the duel's shoulder camera); the rig waits where it was.
+ camera.position.set(override.position.x, override.position.y, override.position.z);
+ camera.lookAt(override.target.x, override.target.y, override.target.z);
+ if (Math.abs(camera.fov - override.fovDeg) > 1e-3) { camera.fov = override.fovDeg; camera.updateProjectionMatrix(); }
+ runtime.commanderHidden = false;
+ } else if (pose) {
+ if (control.reframe) {
+ rig.snapBehind(pose.yaw);
+ control.reframe = false;
+ }
+ body.x = pose.x;
+ body.y = pose.y;
+ body.z = pose.z;
+ body.heading = pose.yaw;
+ body.moving = pose.moving;
+ rig.update(dt, body, test);
+ }
+ if (!override) {
+ runtime.commanderHidden = rig.actual < HIDE_COMMANDER_BELOW_M || rig.firstShare > HIDE_COMMANDER_FIRST_SHARE;
+ camera.position.set(rig.position.x, rig.position.y, rig.position.z);
+ camera.lookAt(rig.target.x, rig.target.y, rig.target.z);
+ const fov = verticalFov(camera.aspect, rig.hfov());
+ if (Math.abs(camera.fov - fov) > 1e-3) { camera.fov = fov; camera.updateProjectionMatrix(); }
+ }
+ camera.updateMatrixWorld();
+ gl.info.reset();
+ const tune = tuning();
+ if (tune || tuned.current) applyTuning(loaded, bloom, tune);
+ tuned.current = !!tune;
+ gl.toneMapping = AgXToneMapping;
+ gl.toneMappingExposure = Math.pow(2, deck.exposure + (tune?.exposureBias ?? 0));
+ gl.autoClear = true;
+ // True black behind everything: AgX lifts the plate view's near-black clear colour to a visible grey.
+ gl.getClearColor(clearColour);
+ const clearAlpha = gl.getClearAlpha();
+ gl.setClearColor(0x000000, 1);
+ if (tier === "high") {
+ composer.render(dt);
+ } else {
+ gl.setRenderTarget(null);
+ gl.render(scene, camera);
+ }
+ gl.setClearColor(clearColour, clearAlpha);
+ const s = runtime.stats;
+ s.drawCalls = gl.info.render.calls;
+ s.triangles = gl.info.render.triangles;
+ s.cpuMs = s.cpuMs * 0.9 + (performance.now() - started) * 0.1;
+ s.frameMs = s.frameMs * 0.9 + dt * 1000 * 0.1;
+ s.plateLevel = "3D";
+ s.tiles = 0;
+ s.tilesLoading = 0;
+ s.tier = tier;
+ // A GPU that cannot hold ~45 fps at the high tier gets the low one.
+ const f = frames.current;
+ f.count++;
+ if (quality === "auto" && tier === "high" && f.count > WARMUP_FRAMES && document.visibilityState === "visible") {
+ if (s.frameMs > SLOW_FRAME_MS) {
+ if (!f.slowSince) f.slowSince = started;
+ else if (started - f.slowSince > SLOW_WINDOW_MS) setAutoTier("low");
+ } else {
+ f.slowSince = 0;
+ }
+ }
+ for (const fn of runtime.afterFrame) fn();
+ }, 1);
+
+ return null;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/deckMaterial.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/deckMaterial.ts
new file mode 100644
index 0000000000..05925cb929
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/deckMaterial.ts
@@ -0,0 +1,250 @@
+/**
+ * Materials of the eye-level deck: the light Cycles baked plus a live
+ * specular layer.
+ *
+ * The bake holds all diffuse light, albedo included (`radiance = albedo ×
+ * irradiance + emission`, scene linear, "rgbm2" in the lightmap pages), so
+ * every surface draws that radiance and adds only what depends on the eye:
+ * reflections of its room's probe, box-projected so ceiling panels mirror in
+ * the black deck where they hang, with the material's roughness, metalness,
+ * specular level and clear coat. Dielectrics get a black base colour (their
+ * diffuse light is already in the bake); metals keep their tint for the
+ * specular. Deck floors add their plate seams and smudged coat close up.
+ *
+ * `patchDeckShader` is a pure string transform of three.js's physical
+ * shader (tested in deckMaterial.test.ts); `makeDeckMaterial` builds one
+ * material instance per (material, room, page) chunk.
+ */
+import {
+ Color, CustomBlending, DoubleSide, MeshPhysicalMaterial, MeshStandardMaterial, OneFactor, OneMinusSrcAlphaFactor, ShaderChunk, Vector3,
+ type Texture, type WebGLProgramParametersWithUniforms,
+} from "three";
+import type { RealtimeMaterial } from "../../content/deck";
+
+/** Runtime close-up layers (`detail` in the manifest). */
+export const DETAIL_KINDS = ["none", "deck_plates", "painted", "metal"] as const;
+
+const LIGHTS_FRAGMENT_MAPS = [
+ "#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )",
+ " radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );",
+ " #ifdef USE_CLEARCOAT",
+ " clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );",
+ " #endif",
+ "#endif",
+].join("\n");
+
+const FRAGMENT_HEAD = /* glsl */ `
+varying vec3 vVerseWorld;
+uniform float verseRange;
+uniform float verseBakedGain;
+uniform float verseCoatBias;
+uniform float verseBoxOn;
+uniform vec3 verseBoxMin;
+uniform vec3 verseBoxMax;
+uniform vec3 verseProbePos;
+
+// rgbm2: m = a^2 * range, rgb = c^2 * m.
+vec3 verseDecode( vec4 t ) {
+ return t.rgb * t.rgb * ( t.a * t.a * verseRange );
+}
+
+// Parallax-corrected reflection direction (world space) inside the room's box.
+vec3 verseBoxProject( vec3 dir, float roughness ) {
+ if ( verseBoxOn < 0.5 ) return dir;
+ vec3 p = vVerseWorld;
+ if ( any( lessThan( p, verseBoxMin - 0.05 ) ) || any( greaterThan( p, verseBoxMax + 0.05 ) ) ) return dir;
+ vec3 d = vec3(
+ abs( dir.x ) < 1e-5 ? 1e-5 : dir.x,
+ abs( dir.y ) < 1e-5 ? 1e-5 : dir.y,
+ abs( dir.z ) < 1e-5 ? 1e-5 : dir.z
+ );
+ vec3 far = max( ( verseBoxMax - p ) / d, ( verseBoxMin - p ) / d );
+ float t = max( 0.0, min( min( far.x, far.y ), far.z ) );
+ vec3 projected = normalize( p + dir * t - verseProbePos );
+ return normalize( mix( projected, dir, roughness * roughness ) );
+}
+
+float verseHash( vec2 p ) {
+ p = fract( p * vec2( 123.34, 456.21 ) );
+ p += dot( p, p + 45.32 );
+ return fract( p.x * p.y );
+}
+
+float verseNoise( vec2 p ) {
+ vec2 i = floor( p );
+ vec2 f = fract( p );
+ vec2 u = f * f * ( 3.0 - 2.0 * f );
+ return mix( mix( verseHash( i ), verseHash( i + vec2( 1.0, 0.0 ) ), u.x ),
+ mix( verseHash( i + vec2( 0.0, 1.0 ) ), verseHash( i + vec2( 1.0, 1.0 ) ), u.x ), u.y );
+}
+
+float verseFbm( vec2 p ) {
+ return 0.5 * verseNoise( p ) + 0.3 * verseNoise( p * 2.03 + 7.1 ) + 0.2 * verseNoise( p * 4.11 + 3.7 );
+}
+
+#ifdef VERSE_DECK_PLATES
+// Deck plates 2.4 m (x) by 1.2 m (z) on the ship's world grid: satin steel joints and bolts.
+float verseSeam( vec3 w ) {
+ vec2 cell = vec2( w.x / 2.4, w.z / 1.2 );
+ vec2 f = fract( cell );
+ vec2 edge = min( f, 1.0 - f ) * vec2( 2.4, 1.2 );
+ float d = min( edge.x, edge.y );
+ float aa = max( fwidth( d ), 1e-4 );
+ float seam = 1.0 - smoothstep( 0.0025 - aa, 0.0025 + aa, d );
+ float bolt = length( abs( edge - vec2( 0.05 ) ) );
+ float baa = max( fwidth( bolt ), 1e-4 );
+ return max( seam, 1.0 - smoothstep( 0.0085 - baa, 0.0085 + baa, bolt ) );
+}
+#endif
+`;
+
+const DETAIL_PROPERTIES = /* glsl */ `
+#ifdef VERSE_DECK_PLATES
+ float verseJoint = verseSeam( vVerseWorld );
+ roughnessFactor = mix( roughnessFactor, 0.32, verseJoint );
+ metalnessFactor = mix( metalnessFactor, 1.0, verseJoint );
+ diffuseColor.rgb = mix( diffuseColor.rgb, vec3( 0.2, 0.2, 0.205 ), verseJoint );
+#endif
+#if defined( VERSE_PAINTED ) || defined( VERSE_METAL )
+ {
+ // Satin paint breaks its reflections up softly; steel in fine streaks along the piece.
+ vec3 verseFace = abs( normalize( cross( dFdx( vVerseWorld ), dFdy( vVerseWorld ) ) ) );
+ vec2 q = verseFace.x > verseFace.y && verseFace.x > verseFace.z ? vVerseWorld.zy
+ : ( verseFace.y > verseFace.z ? vVerseWorld.xz : vVerseWorld.xy );
+ #ifdef VERSE_METAL
+ float verseBreak = verseFbm( vec2( q.x * 36.0, q.y * 1.4 ) );
+ #else
+ float verseBreak = verseFbm( q * 2.6 );
+ #endif
+ roughnessFactor = clamp( roughnessFactor * ( 0.8 + 0.4 * verseBreak ), 0.04, 1.0 );
+ }
+#endif
+`;
+
+const DETAIL_COAT = /* glsl */ `
+#if defined( VERSE_DECK_PLATES ) && defined( USE_CLEARCOAT )
+ {
+ // Smudges, wipe marks and dust blur and dim the mirror (as the plate's coat does).
+ vec2 q = vVerseWorld.xz;
+ float smudge = smoothstep( 0.42, 0.78, verseFbm( q * 0.7 ) );
+ float wipe = smoothstep( 0.52, 0.76, verseFbm( vec2( q.x * 2.2, q.y * 15.4 ) ) );
+ float dust = smoothstep( 0.55, 0.8, verseFbm( q * 6.0 + 11.0 ) ) * 0.4;
+ material.clearcoatRoughness = clamp( material.clearcoatRoughness + 0.03 * smudge + 0.04 * wipe + 0.08 * dust - 0.02 + verseCoatBias, 0.02, 1.0 );
+ material.clearcoat *= ( 1.0 - verseJoint ) * mix( 1.0, 0.8, max( smudge * 0.85, wipe * 0.75 ) );
+ }
+#endif
+`;
+
+const BAKED = /* glsl */ `
+#ifdef USE_LIGHTMAP
+ totalEmissiveRadiance += verseDecode( texture2D( lightMap, vLightMapUv ) ) * verseBakedGain;
+#endif
+`;
+
+function replaceOnce(source: string, find: string, replacement: string): string {
+ const at = source.indexOf(find);
+ if (at < 0) throw new Error(`deck shader: "${find}" not found`);
+ if (source.indexOf(find, at + find.length) >= 0) throw new Error(`deck shader: "${find}" found twice`);
+ return source.slice(0, at) + replacement + source.slice(at + find.length);
+}
+
+/**
+ * The physical material's shaders with the baked radiance, box-projected
+ * reflections and the close-up detail. Works on the templates three hands
+ * to onBeforeCompile (the `#include` lines still unexpanded). Pure.
+ */
+export function patchDeckShader(vertexShader: string, fragmentShader: string): { vertexShader: string; fragmentShader: string } {
+ let vs = replaceOnce(vertexShader, "#include <common>", "#include <common>\nvarying vec3 vVerseWorld;");
+ vs = replaceOnce(vs, "#include <project_vertex>", "#include <project_vertex>\nvVerseWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;");
+ let fs = replaceOnce(fragmentShader, "#include <common>", `#include <common>\n${FRAGMENT_HEAD}`);
+ const envPars = replaceOnce(
+ ShaderChunk.envmap_physical_pars_fragment,
+ "reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );",
+ "reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );\n\t\t\treflectVec = verseBoxProject( reflectVec, roughness );",
+ );
+ fs = replaceOnce(fs, "#include <envmap_physical_pars_fragment>", envPars);
+ fs = replaceOnce(fs, "#include <metalnessmap_fragment>", `#include <metalnessmap_fragment>\n${DETAIL_PROPERTIES}`);
+ fs = replaceOnce(fs, "#include <lights_physical_fragment>", `#include <lights_physical_fragment>\n${DETAIL_COAT}`);
+ fs = replaceOnce(fs, "#include <emissivemap_fragment>", `#include <emissivemap_fragment>\n${BAKED}`);
+ fs = replaceOnce(fs, "#include <lights_fragment_maps>", LIGHTS_FRAGMENT_MAPS);
+ return { vertexShader: vs, fragmentShader: fs };
+}
+
+/**
+ * Values every deck material shares (one uniform object each), for the whole
+ * view at once: the baked radiance's gain (1), a bias on the deck coat's
+ * roughness (0). QA runs tune them through `window.__verseTune`.
+ */
+export const DECK_SHARED = {
+ verseBakedGain: { value: 1 },
+ verseCoatBias: { value: 0 },
+};
+
+export interface ProbeBinding {
+ env: Texture;
+ position: readonly [number, number, number];
+ boxMin: readonly [number, number, number];
+ boxMax: readonly [number, number, number];
+}
+
+export interface DeckMaterialInputs {
+ name: string;
+ params: RealtimeMaterial;
+ /** The lightmap page (rgbm2, flipY false, glTF UVs). */
+ page: Texture;
+ range: number;
+ probe: ProbeBinding | null;
+}
+
+/** Physical when the material needs a clear coat, a specular level other than 4 % or transparency; standard otherwise. */
+export function needsPhysical(p: RealtimeMaterial): boolean {
+ return p.clearcoat > 0 || p.transparent || Math.abs(p.specular - 0.5) > 0.05;
+}
+
+export function makeDeckMaterial({ name, params, page, range, probe }: DeckMaterialInputs): MeshStandardMaterial {
+ const physical = needsPhysical(params);
+ const m = physical ? new MeshPhysicalMaterial() : new MeshStandardMaterial();
+ m.name = name;
+ m.color = params.metalness > 0 ? new Color(params.color[0], params.color[1], params.color[2]) : new Color(0, 0, 0);
+ m.roughness = params.roughness;
+ m.metalness = params.metalness;
+ m.lightMap = page;
+ m.lightMapIntensity = 0; // the patch decodes the page as radiance, never as irradiance
+ // Cycles renders both sides of a face; builders leave open quads (star fields, decals) facing either way.
+ m.side = DoubleSide;
+ m.envMap = probe?.env ?? null;
+ m.envMapIntensity = params.specular <= 0 ? 0 : 1;
+ if (m instanceof MeshPhysicalMaterial) {
+ m.clearcoat = params.clearcoat;
+ m.clearcoatRoughness = params.clearcoatRoughness;
+ m.specularIntensity = Math.max(0, Math.min(1, params.specular * 2));
+ }
+ if (params.transparent) {
+ // Glass: its own reflection plus what lies behind it, dimmed by its tint.
+ m.transparent = true;
+ m.opacity = params.opacity;
+ m.depthWrite = false;
+ m.premultipliedAlpha = false;
+ m.blending = CustomBlending;
+ m.blendSrc = OneFactor;
+ m.blendDst = OneMinusSrcAlphaFactor;
+ }
+ const uniforms = {
+ ...DECK_SHARED,
+ verseRange: { value: range },
+ verseBoxOn: { value: probe ? 1 : 0 },
+ verseBoxMin: { value: new Vector3(...(probe?.boxMin ?? [0, 0, 0])) },
+ verseBoxMax: { value: new Vector3(...(probe?.boxMax ?? [0, 0, 0])) },
+ verseProbePos: { value: new Vector3(...(probe?.position ?? [0, 0, 0])) },
+ };
+ const detailDefine = { deck_plates: "VERSE_DECK_PLATES", painted: "VERSE_PAINTED", metal: "VERSE_METAL" }[params.detail];
+ if (detailDefine) m.defines = { ...(m.defines ?? {}), [detailDefine]: "" };
+ m.onBeforeCompile = (shader: WebGLProgramParametersWithUniforms) => {
+ Object.assign(shader.uniforms, uniforms);
+ const patched = patchDeckShader(shader.vertexShader, shader.fragmentShader);
+ shader.vertexShader = patched.vertexShader;
+ shader.fragmentShader = patched.fragmentShader;
+ };
+ m.customProgramCacheKey = () => `verse-deck-${physical ? "p" : "s"}-${params.detail}`;
+ return m;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/eyeLevelGame.test.tsx b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/eyeLevelGame.test.tsx
new file mode 100644
index 0000000000..651ed7dc89
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/eyeLevelGame.test.tsx
@@ -0,0 +1,369 @@
+/**
+ * The game at eye level (docs/verse/realtime.md, "Runtime"): projection of
+ * labels through the perspective camera and their occlusion, picking by
+ * raycast against real BVH geometry, the station the use key works, the
+ * camera rig's settings, the pointer-lock input, the view fallbacks and the
+ * person's view settings.
+ */
+import { act, cleanup, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { BoxGeometry, PerspectiveCamera, PlaneGeometry } from "three";
+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";
+import { MeshBVH } from "three-mesh-bvh";
+import { StageRuntime, type FrameStats } from "../../runtime";
+import { syntheticDeck } from "../../testing/syntheticDeck";
+import { worldToPlate } from "../plateMath";
+import { plateToScreen } from "../view";
+import { eyeCapable, stageView } from "../stageView";
+import { CommanderControl, stationWithin } from "../../life/control";
+import type { Station } from "../../content/deck";
+import { FloatingLabels, PROMPT_AT } from "../../hud/FloatingLabels";
+import { statsText } from "../../hud/DeckBar";
+import { eyePull } from "../../effects/LightsLayer";
+import { eyePick } from "./eyePick";
+import { attachOrbitInput } from "./orbitInput";
+import { LOOK_SENSITIVITY, SHOULDER, ShoulderRig } from "./shoulderRig";
+import { normalizeViewPrefs, useViewSettings, VIEW_DEFAULTS, VIEW_SETTINGS_KEY } from "./viewSettings";
+
+const W = 1600;
+const H = 900;
+
+/** A 40 × 40 m floor at y = 0 and a wall 3 m high across x −3..3, its front face at z = −4.9. */
+function room(): MeshBVH {
+ const floor = new PlaneGeometry(40, 40).rotateX(-Math.PI / 2);
+ const wall = new BoxGeometry(6, 3, 0.2).translate(0, 1.5, -5);
+ const merged = mergeGeometries([floor, wall], false);
+ if (!merged) throw new Error("merge failed");
+ return new MeshBVH(merged);
+}
+
+/** A stage looking down −Z from behind the commander's shoulder, at the room. */
+function eyeStage(): StageRuntime {
+ const runtime = new StageRuntime();
+ runtime.deck = syntheticDeck();
+ runtime.view.resize({ width: W, height: H, dpr: 1 });
+ const camera = new PerspectiveCamera(50, W / H, 0.05, 500);
+ camera.position.set(0, 1.8, 3);
+ camera.lookAt(0, 1.5, -10);
+ camera.updateMatrixWorld();
+ camera.updateProjectionMatrix();
+ runtime.eye = { camera, collider: room() };
+ return runtime;
+}
+
+describe("projection through the eye-level camera", () => {
+ it("puts the point the camera looks at in the middle of the screen", () => {
+ const at = eyeStage().toScreen(0, 1.5, -10)!;
+ expect(at.x).toBeCloseTo(W / 2, 3);
+ expect(at.y).toBeCloseTo(H / 2, 3);
+ });
+
+ it("puts points left and above where they belong on screen", () => {
+ const r = eyeStage();
+ const left = r.toScreen(-2, 1.5, -10)!;
+ const up = r.toScreen(0, 3.5, -10)!;
+ expect(left.x).toBeLessThan(W / 2);
+ expect(up.y).toBeLessThan(H / 2);
+ });
+
+ it("gives nothing for a point behind the camera", () => {
+ expect(eyeStage().toScreen(0, 1.8, 10)).toBeNull();
+ });
+
+ it("writes into the point it is given, so the frame loop allocates nothing", () => {
+ const out = { x: 0, y: 0 };
+ expect(eyeStage().toScreen(0, 1.5, -10, out)).toBe(out);
+ });
+
+ it("projects through the plate when the eye-level view is off", () => {
+ const r = eyeStage();
+ r.eye = null;
+ const deck = r.deck!;
+ const p = worldToPlate(deck.camera, 3, 1, -2);
+ const want = plateToScreen(r.view.current, r.view.vp, p.u, p.v);
+ expect(r.toScreen(3, 1, -2)).toEqual(want);
+ expect(r.ray(10, 10)).toBeNull();
+ });
+});
+
+describe("line of sight", () => {
+ it("hides points behind the wall and keeps those in front", () => {
+ const r = eyeStage();
+ expect(r.inSight(0, 1.5, -8)).toBe(false);
+ expect(r.inSight(0, 1.5, -3)).toBe(true);
+ // Beside the wall there is nothing in the way.
+ expect(r.inSight(6, 1.5, -8)).toBe(true);
+ });
+
+ it("forgives geometry just at the point (a head against a wall)", () => {
+ const r = eyeStage();
+ expect(r.inSight(0, 1.5, -5)).toBe(true);
+ expect(r.inSight(0, 1.5, -5, 0)).toBe(false);
+ });
+
+ it("sees everything on the plate and without collision geometry", () => {
+ const r = eyeStage();
+ r.eye = { camera: r.eye!.camera, collider: null };
+ expect(r.inSight(0, 1.5, -8)).toBe(true);
+ r.eye = null;
+ expect(r.inSight(0, 1.5, -8)).toBe(true);
+ });
+});
+
+describe("picking by raycast through the screen", () => {
+ const stations: Station[] = [{ id: "helm", kind: "agents_list", room: null, x: 2, y: 0, z: -2, sockets: {} }];
+ const pick = (r: StageRuntime, x: number, y: number, z: number, bodies: { id: string; x: number; y: number; z: number; height: number }[] = []) => {
+ const at = r.toScreen(x, y, z)!;
+ const ray = r.ray(at.x, at.y)!;
+ return eyePick(ray.ray, stations, bodies, () => true, r.eye!.collider);
+ };
+
+ it("walks to a floor point clicked", () => {
+ const hit = pick(eyeStage(), -4, 0, -1);
+ expect(hit?.kind).toBe("floor");
+ if (hit?.kind !== "floor") return;
+ expect(hit.x).toBeCloseTo(-4, 2);
+ expect(hit.z).toBeCloseTo(-1, 2);
+ });
+
+ it("uses a station clicked on or near its spot", () => {
+ expect(pick(eyeStage(), 2.6, 0, -2.4)).toEqual({ kind: "station", id: "helm" });
+ });
+
+ it("picks a crew member in plain view, never one behind the wall", () => {
+ const r = eyeStage();
+ const near = { id: "near", x: -1, y: 0, z: -1, height: 1.8 };
+ const hidden = { id: "hidden", x: 0, y: 0, z: -8, height: 1.8 };
+ expect(pick(r, -1, 1, -1, [near, hidden])).toEqual({ kind: "crew", id: "near" });
+ expect(pick(r, 0, 1, -8, [near, hidden])?.kind).not.toBe("crew");
+ });
+
+ it("does nothing on a wall", () => {
+ expect(pick(eyeStage(), -1, 2, -4.9)).toBeNull();
+ });
+});
+
+describe("which view the stage shows", () => {
+ const base = { compact: false, realtime: true, failed: false };
+
+ it("walks an exported deck at eye level on the full-size stage, bird's-eye on the plate", () => {
+ expect(stageView({ ...base, mode: "follow" })).toBe("eye");
+ expect(stageView({ ...base, mode: "overview" })).toBe("plate");
+ });
+
+ it("keeps the IDE panel, decks without an export and failed decks on the plate", () => {
+ expect(stageView({ ...base, compact: true, mode: "follow" })).toBe("plate");
+ expect(stageView({ ...base, realtime: false, mode: "follow" })).toBe("plate");
+ expect(stageView({ ...base, failed: true, mode: "follow" })).toBe("plate");
+ expect(eyeCapable(base)).toBe(true);
+ expect(eyeCapable({ ...base, failed: true })).toBe(false);
+ });
+});
+
+describe("the use key", () => {
+ // The commander at the origin: a console 1 m behind them, another 1.6 m ahead (−Z).
+ const behind: Station = { id: "behind", kind: "games", room: null, x: 0, y: 0, z: 1, sockets: {} };
+ const ahead: Station = { id: "ahead", kind: "agents_list", room: null, x: 0, y: 0, z: -1.6, sockets: {} };
+
+ it("works the nearest station without a facing, the one in front with one", () => {
+ expect(stationWithin([behind, ahead], 0, 0)?.id).toBe("behind");
+ expect(stationWithin([behind, ahead], 0, 0, undefined, { x: 0, z: -1 })?.id).toBe("ahead");
+ expect(stationWithin([behind, ahead], 0, 0, undefined, { x: 0, z: 1 })?.id).toBe("behind");
+ });
+
+ it("still works a station behind when it is the only one in reach", () => {
+ expect(stationWithin([behind], 0, 0, undefined, { x: 0, z: -1 })?.id).toBe("behind");
+ });
+});
+
+describe("camera rig settings", () => {
+ it("turns faster with a higher sensitivity and clamps it", () => {
+ const a = new ShoulderRig();
+ const b = new ShoulderRig();
+ b.sensitivity = 2;
+ a.look(10, 0);
+ b.look(10, 0);
+ expect(Math.PI - b.yaw).toBeCloseTo(2 * (Math.PI - a.yaw), 9);
+ const c = new ShoulderRig();
+ c.sensitivity = 100;
+ c.look(10, 0);
+ expect(Math.PI - c.yaw).toBeCloseTo(10 * SHOULDER.dragRate * LOOK_SENSITIVITY.max, 9);
+ });
+
+ it("looks up when the mouse moves down with the vertical axis inverted", () => {
+ const rig = new ShoulderRig();
+ rig.look(0, 10);
+ expect(rig.pitch).toBeGreaterThan(SHOULDER.pitch);
+ const inverted = new ShoulderRig();
+ inverted.invertY = true;
+ inverted.look(0, 10);
+ expect(inverted.pitch).toBeLessThan(SHOULDER.pitch);
+ });
+
+ it("turns toward a crew member and reuses the direction it is given", () => {
+ const rig = new ShoulderRig();
+ rig.faceToward(0, 0, 3, 0);
+ expect(rig.yaw).toBeCloseTo(Math.PI / 2);
+ const out = { x: 0, z: 0 };
+ expect(rig.walkDirection(0, -1, out)).toBe(out);
+ expect(out.x).toBeCloseTo(1);
+ const control = new CommanderControl();
+ control.setKey("up", true);
+ expect(control.directionFrom(rig, out)).toBe(out);
+ expect(control.direction(out)).toBe(out);
+ expect(out).toEqual({ x: 0, z: -1 });
+ });
+
+ it("frames the same shot whatever object carries the pose", () => {
+ const a = new ShoulderRig();
+ const b = new ShoulderRig();
+ a.snapBehind(1);
+ b.snapBehind(1);
+ const pose = { x: 2, y: 0, z: 1, heading: 1, moving: false };
+ a.update(1 / 60, pose);
+ pose.x = 2;
+ b.update(1 / 60, { ...pose });
+ expect(a.position).toEqual(b.position);
+ expect(a.target).toEqual(b.target);
+ });
+});
+
+describe("view settings", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ useViewSettings.getState().reset();
+ });
+
+ it("reads anything stored as valid settings", () => {
+ expect(normalizeViewPrefs(null)).toEqual(VIEW_DEFAULTS);
+ expect(normalizeViewPrefs({ sensitivity: 99, invertY: "yes", quality: "ultra", fovThird: 400, fovFirst: "wide", view: "top" })).toEqual({
+ ...VIEW_DEFAULTS, sensitivity: LOOK_SENSITIVITY.max, fovThird: SHOULDER.maxHfovDeg,
+ });
+ expect(normalizeViewPrefs({ sensitivity: 0.5, invertY: true, quality: "low", fovThird: 64, fovFirst: 95, view: "first" })).toEqual({
+ sensitivity: 0.5, invertY: true, quality: "low", fovThird: 64, fovFirst: 95, view: "first",
+ });
+ });
+
+ it("keeps the person's choice in this browser and resets it", () => {
+ useViewSettings.getState().set({ invertY: true, sensitivity: 1.5, view: "first" });
+ expect(JSON.parse(window.localStorage.getItem(VIEW_SETTINGS_KEY)!)).toEqual({ ...VIEW_DEFAULTS, sensitivity: 1.5, invertY: true, view: "first" });
+ expect(useViewSettings.getState().invertY).toBe(true);
+ useViewSettings.getState().reset();
+ expect(useViewSettings.getState().sensitivity).toBe(1);
+ // Reset puts the settings back, never the view on screen.
+ expect(useViewSettings.getState().view).toBe("first");
+ });
+});
+
+describe("eye-level effects and readout", () => {
+ it("pulls lamp sprites toward the camera, never more than half the way", () => {
+ expect(eyePull("blink", 0.6, 10)).toBeCloseTo(0.3);
+ expect(eyePull("pulse", 6, 20)).toBeCloseTo(3);
+ expect(eyePull("pulse", 6, 2)).toBeCloseTo(1);
+ });
+
+ it("shows the frame rate and the eye level's tier in the development readout", () => {
+ const stats: FrameStats = { drawCalls: 250, triangles: 812_000, frameMs: 16.7, cpuMs: 1.4, tiles: 0, tilesLoading: 0, plateLevel: "3D", actors: 9, tier: "high" };
+ expect(statsText(stats)).toBe("60 fps 16.7 ms (1.4 cpu) 250 calls 812.0k tris\neye level, high tier 9 actors");
+ expect(statsText({ ...stats, plateLevel: "M2", tiles: 12, tier: "" })).toContain("12 tiles M2 (0 loading)");
+ });
+});
+
+describe("pointer input at eye level", () => {
+ let el: HTMLDivElement;
+ let lockedTo: Element | null = null;
+
+ beforeEach(() => {
+ el = document.createElement("div");
+ Object.defineProperty(el, "clientWidth", { value: 800 });
+ Object.defineProperty(el, "clientHeight", { value: 600 });
+ el.getBoundingClientRect = () => ({ left: 0, top: 0, right: 800, bottom: 600, width: 800, height: 600, x: 0, y: 0, toJSON: () => ({}) });
+ el.setPointerCapture = vi.fn();
+ el.hasPointerCapture = () => false;
+ el.releasePointerCapture = vi.fn();
+ document.body.appendChild(el);
+ Object.defineProperty(document, "pointerLockElement", { configurable: true, get: () => lockedTo });
+ });
+ afterEach(() => {
+ el.remove();
+ lockedTo = null;
+ });
+
+ const pointer = (type: string, init: Record<string, number | string>) => {
+ const e = new MouseEvent(type, { bubbles: true, clientX: Number(init.clientX ?? 0), clientY: Number(init.clientY ?? 0), button: Number(init.button ?? 0) });
+ for (const key of ["pointerId", "pointerType", "movementX", "movementY"]) {
+ if (key in init) Object.defineProperty(e, key, { value: init[key] });
+ }
+ el.dispatchEvent(e);
+ };
+
+ it("taps where the pointer was pressed and released, and turns on a drag", () => {
+ const rig = new ShoulderRig();
+ const cb = { tap: vi.fn(), hover: vi.fn(), leave: vi.fn(), moved: vi.fn() };
+ const detach = attachOrbitInput(el, rig, cb);
+ pointer("pointerdown", { clientX: 100, clientY: 120, pointerId: 1, pointerType: "mouse" });
+ pointer("pointerup", { clientX: 100, clientY: 120, pointerId: 1, pointerType: "mouse" });
+ expect(cb.tap).toHaveBeenCalledWith(100, 120);
+ const yaw = rig.yaw;
+ pointer("pointerdown", { clientX: 100, clientY: 120, pointerId: 2, pointerType: "mouse" });
+ pointer("pointermove", { clientX: 160, clientY: 120, pointerId: 2, pointerType: "mouse" });
+ pointer("pointerup", { clientX: 160, clientY: 120, pointerId: 2, pointerType: "mouse" });
+ expect(rig.yaw).not.toBe(yaw);
+ expect(cb.moved).toHaveBeenCalled();
+ expect(cb.tap).toHaveBeenCalledTimes(1);
+ detach();
+ });
+
+ it("with the pointer locked turns on plain movement and works what is under the reticle", () => {
+ const rig = new ShoulderRig();
+ const cb = { tap: vi.fn(), hover: vi.fn(), leave: vi.fn(), moved: vi.fn() };
+ const detach = attachOrbitInput(el, rig, cb);
+ lockedTo = el;
+ const yaw = rig.yaw;
+ pointer("pointermove", { movementX: 40, movementY: 0, pointerId: 1, pointerType: "mouse" });
+ expect(rig.yaw).toBeCloseTo(yaw - 40 * SHOULDER.lockRate);
+ expect(cb.hover).toHaveBeenCalledWith(400, 300);
+ pointer("pointerdown", { clientX: 5, clientY: 5, pointerId: 1, pointerType: "mouse", button: 0 });
+ expect(cb.tap).toHaveBeenCalledWith(400, 300);
+ detach();
+ });
+});
+
+describe("floating labels at eye level", () => {
+ afterEach(cleanup);
+
+ it("places a visible crew member's plate over their head and hides one behind the wall", () => {
+ const runtime = eyeStage();
+ runtime.poses.set("seen", { id: "seen", x: -1, y: 0, z: -2, yaw: 0, height: 1.7, moving: false });
+ runtime.poses.set("hidden", { id: "hidden", x: 0, y: 0, z: -9, yaw: 0, height: 1.7, moving: false });
+ const plate = (id: string) => ({ id, name: id, rank: "Ensign", status: "On duty", statusKey: "working", accent: null });
+ const { container } = render(<FloatingLabels runtime={runtime} plates={[plate("seen"), plate("hidden")]} station={null} deck={runtime.deck} />);
+ act(() => { for (const fn of runtime.afterFrame) fn(); });
+ const [seen, hidden] = [...container.querySelectorAll<HTMLElement>(".verse-plate")];
+ const head = runtime.toScreen(-1, 1.82, -2)!;
+ expect(seen.style.transform).toBe(`translate(${Math.round(head.x)}px, ${Math.round(head.y)}px)`);
+ expect(hidden.style.transform).toBe("translate(-9999px, -9999px)");
+ });
+
+ it("offers the station within reach as a prompt below the middle of the view, never on the commander's back", () => {
+ const runtime = eyeStage();
+ const station: Station = { id: "lift", kind: "lift", room: null, x: 0, y: 0, z: 0, sockets: {} };
+ const { container, rerender } = render(<FloatingLabels runtime={runtime} plates={[]} station={{ station, name: "Turbolift", action: "Ride", key: "E" }} deck={runtime.deck} />);
+ act(() => { for (const fn of runtime.afterFrame) fn(); });
+ const label = container.querySelector<HTMLElement>(".verse-plate")!;
+ expect(label.style.transform).toBe(`translate(${W / 2}px, ${Math.round(H * PROMPT_AT)}px)`);
+ // Pointed at (no key), it rides on the station's spot.
+ rerender(<FloatingLabels runtime={runtime} plates={[]} station={{ station, name: "Turbolift", action: "Ride", key: null }} deck={runtime.deck} />);
+ act(() => { for (const fn of runtime.afterFrame) fn(); });
+ const spot = runtime.toScreen(0, 1.2, 0)!;
+ expect(label.style.transform).toBe(`translate(${Math.round(spot.x)}px, ${Math.round(spot.y)}px)`);
+ });
+
+ it("hides a pointed-at station label whose spot is behind the camera", () => {
+ const runtime = eyeStage();
+ const station: Station = { id: "aft", kind: "games", room: null, x: 0, y: 0, z: 8, sockets: {} };
+ const { container } = render(<FloatingLabels runtime={runtime} plates={[]} station={{ station, name: "Simulator", action: "Play", key: null }} deck={runtime.deck} />);
+ act(() => { for (const fn of runtime.afterFrame) fn(); });
+ expect(container.querySelector<HTMLElement>(".verse-plate")!.style.transform).toBe("translate(-9999px, -9999px)");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/eyePick.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/eyePick.ts
new file mode 100644
index 0000000000..8bb7eb324f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/eyePick.ts
@@ -0,0 +1,91 @@
+/**
+ * What the pointer is on in the eye-level view: a crew member (an upright
+ * cylinder around each body), a station (the deck point hit lies near it,
+ * on its console or its floor), or a floor point to walk to. Bodies hidden
+ * behind the deck's geometry are not picked. Pure apart from the BVH query.
+ */
+import { DoubleSide, type Ray } from "three";
+import type { MeshBVH } from "three-mesh-bvh";
+import type { Station } from "../../content/deck";
+
+export type EyeHit =
+ | { kind: "crew"; id: string }
+ | { kind: "station"; id: string }
+ | { kind: "floor"; x: number; y: number; z: number }
+ | null;
+
+export interface BodyPose { id: string; x: number; y: number; z: number; height: number }
+
+/** Bodies are picked within this radius of their axis, metres. */
+export const BODY_PICK_RADIUS = 0.34;
+/** A deck point this close (horizontally) to a station's anchor picks the station, metres. */
+export const STATION_PICK_RADIUS = 1.5;
+
+/** Distance along the ray to where it enters an upright cylinder (x, z, radius, y0..y1), or null. Pure. */
+export function rayCylinder(
+ origin: { x: number; y: number; z: number },
+ dir: { x: number; y: number; z: number },
+ x: number, z: number, radius: number, y0: number, y1: number,
+): number | null {
+ const ox = origin.x - x;
+ const oz = origin.z - z;
+ const a = dir.x * dir.x + dir.z * dir.z;
+ let t0: number;
+ let t1: number;
+ if (a < 1e-9) {
+ if (ox * ox + oz * oz > radius * radius) return null;
+ t0 = -Infinity;
+ t1 = Infinity;
+ } else {
+ const b = 2 * (ox * dir.x + oz * dir.z);
+ const c = ox * ox + oz * oz - radius * radius;
+ const disc = b * b - 4 * a * c;
+ if (disc < 0) return null;
+ const s = Math.sqrt(disc);
+ t0 = (-b - s) / (2 * a);
+ t1 = (-b + s) / (2 * a);
+ }
+ // The span of t where the ray is between the heights.
+ let h0 = -Infinity;
+ let h1 = Infinity;
+ if (Math.abs(dir.y) < 1e-9) {
+ if (origin.y < y0 || origin.y > y1) return null;
+ } else {
+ const ta = (y0 - origin.y) / dir.y;
+ const tb = (y1 - origin.y) / dir.y;
+ h0 = Math.min(ta, tb);
+ h1 = Math.max(ta, tb);
+ }
+ const enter = Math.max(t0, h0, 0);
+ const leave = Math.min(t1, h1);
+ return enter <= leave ? enter : null;
+}
+
+export function eyePick(
+ ray: Ray,
+ stations: readonly Station[],
+ bodies: Iterable<BodyPose>,
+ pickable: (id: string) => boolean,
+ collider: MeshBVH | null,
+): EyeHit {
+ const hit = collider ? collider.raycastFirst(ray, DoubleSide) : null;
+ const wall = hit ? hit.distance : Infinity;
+ let best: { id: string; t: number } | null = null;
+ for (const body of bodies) {
+ if (!pickable(body.id)) continue;
+ const t = rayCylinder(ray.origin, ray.direction, body.x, body.z, BODY_PICK_RADIUS, body.y, body.y + body.height + 0.1);
+ if (t !== null && t < wall && (!best || t < best.t)) best = { id: body.id, t };
+ }
+ if (best) return { kind: "crew", id: best.id };
+ if (!hit) return null;
+ const p = hit.point;
+ let station: Station | null = null;
+ let near = STATION_PICK_RADIUS;
+ for (const s of stations) {
+ const d = Math.hypot(s.x - p.x, s.z - p.z);
+ if (d <= near && Math.abs(p.y - s.y) < 2.2) { near = d; station = s; }
+ }
+ if (station) return { kind: "station", id: station.id };
+ const up = hit.face ? hit.face.normal.y : 0;
+ return up > 0.6 ? { kind: "floor", x: p.x, y: p.y, z: p.z } : null;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/mouseLook.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/mouseLook.ts
new file mode 100644
index 0000000000..99c755a8a5
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/mouseLook.ts
@@ -0,0 +1,73 @@
+/**
+ * Shooter mouse look, shared by the eye-level views (third and first person)
+ * and the duel: one turn rate per pointer-lock pixel, the person's
+ * sensitivity and inverted vertical axis applied the same way everywhere,
+ * and one way to take the mouse (pointer lock, raw movement where the
+ * browser offers it).
+ *
+ * Sign conventions differ between the callers, so `lookDelta` returns the
+ * plain turn: `yaw` positive for a move to the right (the deck's yaw turns
+ * the other way, so the callers subtract it) and `pitch` positive for "look
+ * down" (the mouse moved toward the person); a caller whose pitch is
+ * positive up subtracts it.
+ */
+
+/** The range of the turn-rate multiplier (the person's mouse sensitivity, `viewSettings`). */
+export const LOOK_SENSITIVITY = { min: 0.25, max: 3 } as const;
+
+/** Radians per pointer-lock pixel at sensitivity 1 (about 0.13° per count: a middle-of-the-road shooter default). */
+export const MOUSE_LOOK_RATE = 0.0022;
+
+export interface LookPrefs {
+ sensitivity: number;
+ invertY: boolean;
+}
+
+/** The sensitivity as used: finite and inside LOOK_SENSITIVITY. Pure. */
+export function clampSensitivity(s: number): number {
+ return Math.max(LOOK_SENSITIVITY.min, Math.min(LOOK_SENSITIVITY.max, Number.isFinite(s) ? s : 1));
+}
+
+/**
+ * The turn for a mouse movement of (dx, dy) px at `rate` rad/px: `yaw` grows
+ * with a move to the right, `pitch` grows with a move down (toward the
+ * person), flipped by `invertY`. Pure.
+ */
+export function lookDelta(dx: number, dy: number, prefs: LookPrefs, rate: number = MOUSE_LOOK_RATE): { yaw: number; pitch: number } {
+ const r = rate * clampSensitivity(prefs.sensitivity);
+ return { yaw: dx * r, pitch: (prefs.invertY ? -dy : dy) * r };
+}
+
+/** The element holds the pointer lock (mouse look is on). */
+export function hasMouseLook(el: Element | null | undefined): boolean {
+ return !!el && document.pointerLockElement === el;
+}
+
+/**
+ * Take the mouse for shooter look: pointer lock on `el`, asking for raw
+ * (unaccelerated) movement first and falling back to a plain lock where the
+ * browser refuses that. Needs a user gesture (a click, a key press). Never
+ * throws; a refused request simply leaves the mouse free.
+ */
+export function requestMouseLook(el: HTMLElement): void {
+ if (document.pointerLockElement === el || typeof el.requestPointerLock !== "function") return;
+ const plain = () => {
+ try {
+ const p = el.requestPointerLock() as unknown;
+ if (p && typeof (p as Promise<void>).catch === "function") (p as Promise<void>).catch(() => undefined);
+ } catch {
+ /* refused: the mouse stays free */
+ }
+ };
+ try {
+ const p = (el.requestPointerLock as (o?: { unadjustedMovement?: boolean }) => unknown)({ unadjustedMovement: true });
+ if (p && typeof (p as Promise<void>).catch === "function") (p as Promise<void>).catch(plain);
+ } catch {
+ plain();
+ }
+}
+
+/** Give the mouse back (Esc does the same in the browser). */
+export function releaseMouseLook(el: Element | null | undefined): void {
+ if (hasMouseLook(el)) document.exitPointerLock?.();
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/orbitInput.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/orbitInput.ts
new file mode 100644
index 0000000000..443c422bb2
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/orbitInput.ts
@@ -0,0 +1,156 @@
+/**
+ * Mouse, touch and pen input in the eye-level views (third and first person).
+ *
+ * Mouse: shooter look. With the pointer locked to the stage (`requestMouseLook`;
+ * entering the view or clicking the stage takes it) plain mouse movement
+ * turns the view, the left button works whatever the centre crosshair is on
+ * (`aim`), and Esc (the browser) gives the mouse back, so the HUD's buttons
+ * work again. With the mouse free, a click on the stage takes it again
+ * (`capture`); a drag still turns the view, for browsers that refuse the
+ * lock.
+ *
+ * Touch and pen: a drag turns the camera, a pinch zooms, a tap picks what
+ * is under the finger (`tap`).
+ *
+ * The wheel and the pinch zoom through `zoom`, so the stage can hand over
+ * between third and first person.
+ */
+import type { ShoulderRig } from "./shoulderRig";
+
+/** A press that moved less than this (CSS px) is a click, not a drag. */
+const TAP_SLOP_PX = 5;
+/** Log zoom per wheel pixel: one 100 px notch is a factor of about 1.13. */
+export const WHEEL_ZOOM = 0.0012;
+/** With the pointer locked, what is under the crosshair is looked up at most this often, ms. */
+const LOCKED_HOVER_MS = 90;
+
+export interface OrbitCallbacks {
+ /** A tap or click on a screen point (touch, pen, or a mouse where the stage does not take the pointer). */
+ tap: (sx: number, sy: number) => void;
+ hover: (sx: number, sy: number) => void;
+ leave: () => void;
+ /** The camera began to turn: hover labels hide. */
+ moved: () => void;
+ /** Left button with the pointer locked: work what the centre crosshair is on (screen centre, CSS px). */
+ aim?: (sx: number, sy: number) => void;
+ /** A mouse click on the stage while the mouse is free: take it for mouse look. Absent: the click taps. */
+ capture?: () => void;
+ /** Zoom by a factor (> 1 moves out). Absent: the rig zooms itself. */
+ zoom?: (factor: number) => void;
+}
+
+interface Press { x: number; y: number; startX: number; startY: number; mouse: boolean }
+
+/** The zoom factor of a wheel event. Pure. */
+export function wheelFactor(deltaY: number, deltaMode: number): number {
+ const unit = deltaMode === 1 ? 16 : deltaMode === 2 ? 400 : 1;
+ return Math.exp(deltaY * unit * WHEEL_ZOOM);
+}
+
+export function attachOrbitInput(el: HTMLElement, rig: ShoulderRig, cb: OrbitCallbacks): () => void {
+ const presses = new Map<number, Press>();
+ let dragging = false;
+ let pinch = 0;
+
+ const local = (e: { clientX: number; clientY: number }) => {
+ const r = el.getBoundingClientRect();
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
+ };
+ const locked = () => document.pointerLockElement === el;
+ const centre = () => ({ x: el.clientWidth / 2, y: el.clientHeight / 2 });
+ const zoom = (factor: number) => { if (cb.zoom) cb.zoom(factor); else rig.zoom(factor); };
+ let lockedHoverAt = -Infinity;
+
+ const onDown = (e: PointerEvent) => {
+ if (locked()) {
+ if (e.button === 0) {
+ const c = centre();
+ (cb.aim ?? cb.tap)(c.x, c.y);
+ }
+ return;
+ }
+ const mouse = e.pointerType === "mouse";
+ if (e.button !== 0 && mouse) return;
+ const p = local(e);
+ presses.set(e.pointerId, { x: p.x, y: p.y, startX: p.x, startY: p.y, mouse });
+ el.setPointerCapture(e.pointerId);
+ if (presses.size === 2) {
+ const [a, b] = [...presses.values()];
+ pinch = Math.hypot(a.x - b.x, a.y - b.y);
+ dragging = true;
+ }
+ };
+
+ const onMove = (e: PointerEvent) => {
+ if (locked()) {
+ rig.look(e.movementX || 0, e.movementY || 0, true);
+ const now = performance.now();
+ if (now - lockedHoverAt >= LOCKED_HOVER_MS) {
+ lockedHoverAt = now;
+ const c = centre();
+ cb.hover(c.x, c.y);
+ }
+ return;
+ }
+ const p = local(e);
+ const press = presses.get(e.pointerId);
+ if (!press) {
+ if (presses.size === 0) cb.hover(p.x, p.y);
+ return;
+ }
+ if (presses.size === 2) {
+ press.x = p.x;
+ press.y = p.y;
+ const [a, b] = [...presses.values()];
+ const d = Math.hypot(a.x - b.x, a.y - b.y);
+ if (pinch > 0 && d > 0) zoom(pinch / d);
+ pinch = d;
+ return;
+ }
+ if (!dragging && Math.hypot(p.x - press.startX, p.y - press.startY) > TAP_SLOP_PX) {
+ dragging = true;
+ cb.moved();
+ }
+ if (dragging) rig.look(p.x - press.x, p.y - press.y);
+ press.x = p.x;
+ press.y = p.y;
+ };
+
+ const onUp = (e: PointerEvent) => {
+ const press = presses.get(e.pointerId);
+ if (!press) return;
+ presses.delete(e.pointerId);
+ if (el.hasPointerCapture(e.pointerId)) el.releasePointerCapture(e.pointerId);
+ if (presses.size > 0) return;
+ if (!dragging && e.type === "pointerup") {
+ // A mouse click takes the mouse for shooter look; a finger or a pen taps.
+ if (press.mouse && cb.capture) cb.capture();
+ else cb.tap(press.x, press.y);
+ }
+ dragging = false;
+ pinch = 0;
+ };
+
+ const onWheel = (e: WheelEvent) => {
+ e.preventDefault();
+ zoom(wheelFactor(e.deltaY, e.deltaMode));
+ cb.moved();
+ };
+
+ const onLeave = () => { if (presses.size === 0 && !locked()) cb.leave(); };
+
+ el.addEventListener("pointerdown", onDown);
+ el.addEventListener("pointermove", onMove);
+ el.addEventListener("pointerup", onUp);
+ el.addEventListener("pointercancel", onUp);
+ el.addEventListener("pointerleave", onLeave);
+ el.addEventListener("wheel", onWheel, { passive: false });
+ return () => {
+ el.removeEventListener("pointerdown", onDown);
+ el.removeEventListener("pointermove", onMove);
+ el.removeEventListener("pointerup", onUp);
+ el.removeEventListener("pointercancel", onUp);
+ el.removeEventListener("pointerleave", onLeave);
+ el.removeEventListener("wheel", onWheel);
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtime.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtime.test.ts
new file mode 100644
index 0000000000..d504a2fe3f
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtime.test.ts
@@ -0,0 +1,199 @@
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { describe, expect, it } from "vitest";
+import { Ray, ShaderLib, Vector3 } from "three";
+import { parseDeckManifest, ManifestError } from "../../content/manifest";
+import { realtimeContent } from "../../content/loadDeck";
+import { CommanderControl } from "../../life/control";
+import { arrivalYaw } from "../../actors/ActorsLayer";
+import { SHOULDER, ShoulderRig, verticalFov, type SegmentTest } from "./shoulderRig";
+import { needsPhysical, patchDeckShader } from "./deckMaterial";
+import { eyePick, rayCylinder } from "./eyePick";
+
+const BRIDGE = resolve(__dirname, "../../../../../../public/verse/decks/bridge/manifest.json");
+
+const body = (x: number, z: number, heading = Math.PI, moving = false) => ({ x, y: 0, z, heading, moving });
+
+describe("shoulder rig", () => {
+ it("frames the commander from behind, offset so they stand right of centre", () => {
+ const rig = new ShoulderRig();
+ rig.snapBehind(Math.PI); // facing −Z
+ rig.update(1 / 60, body(0, 0));
+ // Behind (+Z), above the head, a little to the left (−X) of the commander.
+ expect(rig.position.z).toBeGreaterThan(1.8);
+ expect(rig.position.z).toBeLessThan(2.6);
+ expect(rig.position.x).toBeCloseTo(SHOULDER.side, 5);
+ expect(rig.position.y).toBeGreaterThan(SHOULDER.pivotHeight);
+ expect(rig.position.y).toBeLessThan(2.3);
+ // The commander (x = 0) is right of the view axis: positive along the camera's right.
+ const right = rig.right();
+ const toBody = { x: 0 - rig.position.x, z: 0 - rig.position.z };
+ expect(toBody.x * right.x + toBody.z * right.z).toBeGreaterThan(0.3);
+ // Looking slightly down.
+ expect(rig.target.y).toBeLessThan(rig.position.y);
+ });
+
+ it("walks W away from the camera and D to its right", () => {
+ const rig = new ShoulderRig();
+ rig.snapBehind(Math.PI);
+ const w = rig.walkDirection(0, -1)!;
+ expect(w.x).toBeCloseTo(0);
+ expect(w.z).toBeCloseTo(-1);
+ const d = rig.walkDirection(1, 0)!;
+ expect(d.x).toBeCloseTo(1);
+ expect(d.z).toBeCloseTo(0);
+ rig.yaw = Math.PI / 2; // looking toward +X
+ const w2 = rig.walkDirection(0, -1)!;
+ expect(w2.x).toBeCloseTo(1);
+ expect(rig.walkDirection(0, 0)).toBeNull();
+ });
+
+ it("turns with the mouse and clamps the pitch", () => {
+ const rig = new ShoulderRig();
+ const yaw = rig.yaw;
+ rig.look(100, 0);
+ expect(rig.yaw).toBeCloseTo(yaw - 100 * SHOULDER.dragRate);
+ rig.look(0, 1e6);
+ expect(rig.pitch).toBeCloseTo(SHOULDER.maxPitch);
+ rig.look(0, -1e6);
+ expect(rig.pitch).toBeCloseTo(SHOULDER.minPitch);
+ });
+
+ it("pulls in at once in front of a wall and eases back out", () => {
+ const rig = new ShoulderRig();
+ rig.snapBehind(Math.PI);
+ let wall = true;
+ // A wall 1.2 m behind the commander (z = 1.2).
+ const test: SegmentTest = (from, to) => {
+ if (!wall || to.z <= 1.2 || from.z >= 1.2) return null;
+ return (1.2 - from.z) / (to.z - from.z);
+ };
+ rig.update(1 / 60, body(0, 0), test);
+ expect(rig.position.z).toBeLessThan(1.2);
+ wall = false;
+ rig.update(1 / 60, body(0, 0), test);
+ const after = rig.actual;
+ expect(after).toBeLessThan(SHOULDER.distance);
+ for (let i = 0; i < 120; i++) rig.update(1 / 60, body(0, 0), test);
+ expect(rig.actual).toBeCloseTo(SHOULDER.distance);
+ });
+
+ it("follows smoothly without jumping and never turns the view on its own", () => {
+ const rig = new ShoulderRig();
+ rig.snapBehind(Math.PI);
+ rig.update(1 / 60, body(0, 0));
+ rig.update(1 / 60, body(1, 0));
+ expect(rig.position.x).toBeLessThan(SHOULDER.side + 1); // lags behind the 1 m jump
+ // Shooter look: only the mouse turns the view, however the commander walks.
+ for (let i = 0; i < 300; i++) rig.update(1 / 60, body(1, 0, Math.PI / 2, true));
+ expect(rig.yaw).toBeCloseTo(Math.PI);
+ });
+
+ it("keeps a 70 degree horizontal field of view on wide frames", () => {
+ const aspect = 2560 / 1392;
+ const v = (verticalFov(aspect) * Math.PI) / 180;
+ expect((2 * Math.atan(Math.tan(v / 2) * aspect) * 180) / Math.PI).toBeCloseTo(70, 1);
+ expect(verticalFov(0.6)).toBeGreaterThanOrEqual(SHOULDER.minVfovDeg);
+ });
+});
+
+describe("camera-relative keys", () => {
+ it("turns the held keys into a floor direction relative to the camera", () => {
+ const control = new CommanderControl();
+ const rig = new ShoulderRig();
+ rig.yaw = Math.PI / 2;
+ control.setKey("up", true);
+ const dir = control.directionFrom(rig)!;
+ expect(dir.x).toBeCloseTo(1);
+ expect(dir.z).toBeCloseTo(0);
+ });
+});
+
+describe("deck shader patch", () => {
+ const physical = ShaderLib.physical;
+
+ it("adds baked radiance, box projection and the plate detail to the physical shader", () => {
+ const { vertexShader, fragmentShader } = patchDeckShader(physical.vertexShader, physical.fragmentShader);
+ expect(vertexShader).toContain("vVerseWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;");
+ expect(fragmentShader).toContain("totalEmissiveRadiance += verseDecode( texture2D( lightMap, vLightMapUv ) ) * verseBakedGain;");
+ expect(fragmentShader).toContain("reflectVec = verseBoxProject( reflectVec, roughness );");
+ expect(fragmentShader).toContain("float verseJoint = verseSeam( vVerseWorld );");
+ // The lightmap never adds irradiance, and the environment adds no diffuse: the bake holds it.
+ expect(fragmentShader).not.toContain("#include <lights_fragment_maps>");
+ expect(fragmentShader).not.toContain("irradiance += lightMapIrradiance");
+ expect(fragmentShader).not.toContain("iblIrradiance += getIBLIrradiance");
+ });
+
+ it("fails loudly when three's templates change", () => {
+ expect(() => patchDeckShader("void main() {}", physical.fragmentShader)).toThrow(/not found/);
+ });
+
+ it("uses the physical material only where a coat, a specular level or glass needs it", () => {
+ const base = { roughness: 0.4, metalness: 0, color: [0, 0, 0] as const, clearcoat: 0, clearcoatRoughness: 0, specular: 0.5, detail: "none", transparent: false, opacity: 1, collide: true };
+ expect(needsPhysical(base)).toBe(false);
+ expect(needsPhysical({ ...base, clearcoat: 1 })).toBe(true);
+ expect(needsPhysical({ ...base, specular: 0.12 })).toBe(true);
+ expect(needsPhysical({ ...base, transparent: true })).toBe(true);
+ });
+});
+
+describe("eye-level picking", () => {
+ it("enters an upright body cylinder from the side and from above", () => {
+ expect(rayCylinder({ x: -5, y: 1, z: 0 }, { x: 1, y: 0, z: 0 }, 0, 0, 0.3, 0, 1.8)).toBeCloseTo(4.7);
+ expect(rayCylinder({ x: 0, y: 5, z: 0 }, { x: 0, y: -1, z: 0 }, 0, 0, 0.3, 0, 1.8)).toBeCloseTo(3.2);
+ expect(rayCylinder({ x: -5, y: 3, z: 0 }, { x: 1, y: 0, z: 0 }, 0, 0, 0.3, 0, 1.8)).toBeNull();
+ expect(rayCylinder({ x: -5, y: 1, z: 1 }, { x: 1, y: 0, z: 0 }, 0, 0, 0.3, 0, 1.8)).toBeNull();
+ });
+
+ it("picks the nearest crew member in the way, and nothing without geometry or bodies", () => {
+ const ray = new Ray(new Vector3(0, 1.6, 5), new Vector3(0, 0, -1));
+ const bodies = [
+ { id: "far", x: 0, y: 0, z: -3, height: 1.8 },
+ { id: "near", x: 0.1, y: 0, z: 0, height: 1.8 },
+ ];
+ expect(eyePick(ray, [], bodies, () => true, null)).toEqual({ kind: "crew", id: "near" });
+ expect(eyePick(ray, [], bodies, (id) => id === "far", null)).toEqual({ kind: "crew", id: "far" });
+ expect(eyePick(ray, [], [], () => true, null)).toBeNull();
+ });
+});
+
+describe("spawn facing", () => {
+ it("faces a body along the spawn or lift it stands at, else toward the deck's forward", () => {
+ const sockets = [
+ { kind: "spawn", x: 0, z: 0, yaw: 1 },
+ { kind: "lift", x: 10, z: 0, yaw: 2 },
+ ] as unknown as Parameters<typeof arrivalYaw>[0]["sockets"];
+ expect(arrivalYaw({ sockets }, 0.3, 0)).toBe(1);
+ expect(arrivalYaw({ sockets }, 9.5, 0.5)).toBe(2);
+ expect(arrivalYaw({ sockets }, 5, 5)).toBeCloseTo(Math.PI);
+ });
+});
+
+describe("realtime manifest block", () => {
+ const bridge = existsSync(BRIDGE) ? JSON.parse(readFileSync(BRIDGE, "utf8")) : null;
+ const run = bridge?.realtime ? it : it.skip;
+
+ run("reads the cooked bridge's realtime block with absolute URLs", () => {
+ const m = parseDeckManifest(bridge);
+ const content = realtimeContent(m.realtime, (r) => `/verse/decks/bridge/${r}`);
+ expect(content).not.toBeNull();
+ expect(content!.sceneUrl).toBe("/verse/decks/bridge/realtime/scene.glb");
+ expect(content!.pages.length).toBeGreaterThan(0);
+ expect(content!.materials.M_Floor_GlossBlack.detail).toBe("deck_plates");
+ expect(content!.probes.map((p) => p.room)).toContain("bridge");
+ });
+
+ run("names the bad field of a broken realtime block, and ignores a newer version", () => {
+ const broken = structuredClone(bridge);
+ broken.realtime.lightmaps.encoding = "rgbe";
+ expect(() => parseDeckManifest(broken)).toThrow(ManifestError);
+ expect(() => parseDeckManifest(broken)).toThrow(/realtime\.lightmaps\.encoding/);
+ const newer = structuredClone(bridge);
+ newer.realtime.version = 2;
+ expect(realtimeContent(parseDeckManifest(newer).realtime, (r) => r)).toBeNull();
+ });
+
+ it("leaves decks without a realtime block on the plate", () => {
+ expect(realtimeContent(undefined, (r) => r)).toBeNull();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts
new file mode 100644
index 0000000000..feefbe2dab
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/realtimeScene.ts
@@ -0,0 +1,238 @@
+/**
+ * Loads a deck's eye-level scene (docs/verse/realtime.md): the meshopt glTF,
+ * its lightmap pages and the rooms' reflection probes, and dresses every
+ * chunk with its deck material. Also builds the collision structure the
+ * camera and the pointer use (a BVH over the chunks whose material collides,
+ * in world space).
+ *
+ * Images arrive as RGBA WebP in the "rgbm2" encoding and are decoded without
+ * premultiplication or colour conversion. Lightmap pages stay encoded (the
+ * deck shader decodes them); each probe panorama is decoded once on the GPU
+ * into a half-float equirect and prefiltered with PMREM.
+ */
+import {
+ BufferAttribute, BufferGeometry, Group, HalfFloatType, LinearFilter, LinearMipmapLinearFilter, Mesh, NoColorSpace,
+ OrthographicCamera, PlaneGeometry, PMREMGenerator, RGBAFormat, Scene, ShaderMaterial, Texture, Vector3, WebGLRenderTarget,
+ type Material, type WebGLRenderer,
+} from "three";
+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
+import { MeshBVH } from "three-mesh-bvh";
+import type { RealtimeContent, RealtimeProbe } from "../../content/deck";
+import { fetchImageBitmap } from "../imageFetch";
+import { REALTIME_LAYER } from "../renderOrder";
+import { makeDeckMaterial, type ProbeBinding } from "./deckMaterial";
+
+export interface RealtimeScene {
+ group: Group;
+ /** Every deck material (one per chunk key). */
+ materials: readonly Material[];
+ /** World-space collision of the solid chunks, or null when there are none. */
+ collider: MeshBVH | null;
+ /** Draw chunks and triangles, for the stats. */
+ chunks: number;
+ triangles: number;
+ dispose(): void;
+}
+
+interface ChunkInfo { material: string; room: string; page: number }
+
+function chunkInfo(extras: unknown): ChunkInfo | null {
+ const e = extras as Partial<ChunkInfo> | undefined;
+ if (!e || typeof e.material !== "string" || typeof e.room !== "string" || typeof e.page !== "number") return null;
+ return { material: e.material, room: e.room, page: e.page };
+}
+
+async function pageTexture(url: string, anisotropy: number, signal: AbortSignal): Promise<Texture> {
+ const bitmap = await fetchImageBitmap(url, signal, "none");
+ const texture = new Texture(bitmap);
+ texture.flipY = false; // glTF UVs: v = 0 is the top row
+ texture.colorSpace = NoColorSpace;
+ texture.premultiplyAlpha = false;
+ texture.format = RGBAFormat;
+ texture.generateMipmaps = true;
+ texture.minFilter = LinearMipmapLinearFilter;
+ texture.magFilter = LinearFilter;
+ texture.anisotropy = anisotropy;
+ texture.needsUpdate = true;
+ return texture;
+}
+
+const DECODE_VERTEX = /* glsl */ `
+varying vec2 vUv;
+void main() {
+ vUv = uv;
+ gl_Position = vec4( position.xy, 0.0, 1.0 );
+}
+`;
+
+const DECODE_FRAGMENT = /* glsl */ `
+uniform sampler2D source;
+uniform float range;
+varying vec2 vUv;
+void main() {
+ vec4 t = texture2D( source, vUv );
+ gl_FragColor = vec4( t.rgb * t.rgb * ( t.a * t.a * range ), 1.0 );
+}
+`;
+
+/** Decode an rgbm2 panorama into a half-float equirect and prefilter it (PMREM). */
+async function probeTexture(gl: WebGLRenderer, probe: RealtimeProbe, signal: AbortSignal): Promise<Texture> {
+ // Flipped at decode time: equirect textures have v = 1 at the top, as three expects.
+ const bitmap = await fetchImageBitmap(probe.url, signal, "flipY");
+ const source = new Texture(bitmap);
+ source.flipY = false;
+ source.colorSpace = NoColorSpace;
+ source.premultiplyAlpha = false;
+ source.generateMipmaps = false;
+ source.minFilter = LinearFilter;
+ source.magFilter = LinearFilter;
+ source.needsUpdate = true;
+ const target = new WebGLRenderTarget(probe.width, probe.height, { type: HalfFloatType, depthBuffer: false });
+ const material = new ShaderMaterial({
+ uniforms: { source: { value: source }, range: { value: probe.range } },
+ vertexShader: DECODE_VERTEX,
+ fragmentShader: DECODE_FRAGMENT,
+ depthTest: false,
+ depthWrite: false,
+ });
+ const quad = new Mesh(new PlaneGeometry(2, 2), material);
+ const scene = new Scene();
+ scene.add(quad);
+ const camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ const previous = gl.getRenderTarget();
+ const toneMapping = gl.toneMapping;
+ try {
+ gl.toneMapping = 0;
+ gl.setRenderTarget(target);
+ gl.render(scene, camera);
+ } finally {
+ gl.setRenderTarget(previous);
+ gl.toneMapping = toneMapping;
+ }
+ const pmrem = new PMREMGenerator(gl);
+ const env = pmrem.fromEquirectangular(target.texture).texture;
+ pmrem.dispose();
+ target.dispose();
+ material.dispose();
+ quad.geometry.dispose();
+ source.dispose();
+ bitmap.close();
+ return env;
+}
+
+/** Everything solid, merged into one world-space geometry for the BVH. */
+function buildCollider(meshes: readonly Mesh[]): MeshBVH | null {
+ let vertexCount = 0;
+ let indexCount = 0;
+ for (const mesh of meshes) {
+ vertexCount += mesh.geometry.getAttribute("position").count;
+ indexCount += mesh.geometry.index?.count ?? mesh.geometry.getAttribute("position").count;
+ }
+ if (vertexCount === 0) return null;
+ const positions = new Float32Array(vertexCount * 3);
+ const indices = new Uint32Array(indexCount);
+ const v = new Vector3();
+ let vo = 0;
+ let io = 0;
+ for (const mesh of meshes) {
+ mesh.updateWorldMatrix(true, false);
+ const position = mesh.geometry.getAttribute("position");
+ const base = vo / 3;
+ for (let i = 0; i < position.count; i++) {
+ v.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
+ positions[vo++] = v.x;
+ positions[vo++] = v.y;
+ positions[vo++] = v.z;
+ }
+ const index = mesh.geometry.index;
+ if (index) for (let i = 0; i < index.count; i++) indices[io++] = base + index.getX(i);
+ else for (let i = 0; i < position.count; i++) indices[io++] = base + i;
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
+ geometry.setIndex(new BufferAttribute(indices, 1));
+ return new MeshBVH(geometry);
+}
+
+export async function loadRealtimeScene(gl: WebGLRenderer, content: RealtimeContent, signal: AbortSignal): Promise<RealtimeScene> {
+ const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(MeshoptDecoder);
+ const anisotropy = Math.min(8, gl.capabilities.getMaxAnisotropy());
+ const [gltfBuffer, pages] = await Promise.all([
+ fetch(content.sceneUrl, { signal }).then((res) => {
+ if (!res.ok) throw new Error(`Realtime scene: HTTP ${res.status}`);
+ return res.arrayBuffer();
+ }),
+ Promise.all(content.pages.map((p) => pageTexture(p.url, anisotropy, signal))),
+ ]);
+ signal.throwIfAborted();
+ const gltf = await loader.parseAsync(gltfBuffer, "");
+ signal.throwIfAborted();
+ const probes = new Map<string, ProbeBinding>();
+ const envs: Texture[] = [];
+ for (const probe of content.probes) {
+ try {
+ const env = await probeTexture(gl, probe, signal);
+ envs.push(env);
+ probes.set(probe.room, { env, position: probe.position, boxMin: probe.boxMin, boxMax: probe.boxMax });
+ } catch (error) {
+ if (signal.aborted) throw error;
+ // A room without its probe still draws its baked light; only its reflections go.
+ console.warn("Verse realtime probe unavailable", probe.room, error);
+ }
+ }
+ signal.throwIfAborted();
+ const materials = new Map<string, Material>();
+ const solid: Mesh[] = [];
+ let triangles = 0;
+ let chunks = 0;
+ const group = gltf.scene;
+ group.name = "verse-realtime";
+ const unused: Material[] = [];
+ group.traverse((object) => {
+ const mesh = object as Mesh;
+ if (!mesh.isMesh) return;
+ const info = chunkInfo(mesh.userData) ?? chunkInfo(mesh.parent?.userData);
+ const params = info ? content.materials[info.material] : undefined;
+ const page = info ? pages[info.page] : undefined;
+ if (!info || !params || !page) {
+ mesh.visible = false;
+ return;
+ }
+ const key = `${info.material}|${info.room}|${info.page}`;
+ let material = materials.get(key);
+ if (!material) {
+ material = makeDeckMaterial({ name: key, params, page, range: content.range, probe: probes.get(info.room) ?? null });
+ materials.set(key, material);
+ }
+ for (const old of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) unused.push(old);
+ mesh.material = material;
+ mesh.layers.set(REALTIME_LAYER);
+ mesh.renderOrder = params.transparent ? 5 : 0;
+ mesh.matrixAutoUpdate = false;
+ chunks++;
+ triangles += (mesh.geometry.index?.count ?? mesh.geometry.getAttribute("position").count) / 3;
+ if (params.collide) solid.push(mesh);
+ });
+ for (const m of new Set(unused)) m.dispose();
+ group.updateMatrixWorld(true);
+ const collider = buildCollider(solid);
+ return {
+ group,
+ materials: [...materials.values()],
+ collider,
+ chunks,
+ triangles,
+ dispose() {
+ group.traverse((object) => {
+ const mesh = object as Mesh;
+ if (mesh.isMesh) mesh.geometry.dispose();
+ });
+ for (const m of materials.values()) m.dispose();
+ for (const t of pages) t.dispose();
+ for (const t of envs) t.dispose();
+ collider?.geometry.dispose();
+ },
+ };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/shoulderRig.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/shoulderRig.ts
new file mode 100644
index 0000000000..c1eabcf05c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/shoulderRig.ts
@@ -0,0 +1,341 @@
+/**
+ * The eye-level camera: over the commander's shoulder (third person) or
+ * through their eyes (first person), turned by shooter mouse look.
+ *
+ * Third-person framing (docs/verse/realtime.md, "Camera"): the camera looks
+ * past the commander's head from behind, offset sideways so they stand in
+ * the lower right third of the frame; a little above their head, looking
+ * slightly down. The wheel moves it between 1.2 and 5 m (eased); pushing in
+ * past the closest distance hands over to first person (`viewMode.zoomStep`)
+ * and scrolling out of first person comes back.
+ *
+ * First person: the camera sits at eye height (1.65 m) just in front of the
+ * face, with no follow lag sideways (it is the head) and the vertical lag of
+ * the third-person pivot (stairs stay smooth); a segment test keeps it out
+ * of walls. The two cameras blend over about a fifth of a second when the
+ * person changes, field of view included.
+ *
+ * The mouse turns the view (yaw, clamped pitch); the commander walks
+ * relative to it (W away from the camera) and faces it while walking, so
+ * the camera never turns on its own. The third-person camera never clips
+ * through walls: a segment test pulls it in at once and it eases back out.
+ *
+ * Pure state and maths: the renderer calls `update` once per frame with the
+ * commander's pose and a collision test; the input calls `look` and `zoom`.
+ */
+import { LOOK_SENSITIVITY, MOUSE_LOOK_RATE, lookDelta } from "./mouseLook";
+import { zoomStep, type Person } from "./viewMode";
+
+export { LOOK_SENSITIVITY };
+
+export interface Vec3 { x: number; y: number; z: number }
+
+/** First hit along the segment from → to as a fraction of its length (0..1), or null when it is clear. */
+export type SegmentTest = (from: Vec3, to: Vec3) => number | null;
+
+const DEG = Math.PI / 180;
+
+export const SHOULDER = {
+ /** Horizontal field of view in third person, degrees (the person's setting overrides it). */
+ hfovDeg: 70,
+ /** ... and in first person. */
+ firstHfovDeg: 85,
+ /** The range the person may set either field of view in, degrees. */
+ minHfovDeg: 55,
+ maxHfovDeg: 110,
+ /** Narrow (portrait) frames keep at least this vertical field of view, degrees. */
+ minVfovDeg: 40,
+ /** Camera distance behind the pivot, metres, and the wheel's range. */
+ distance: 2.4,
+ minDistance: 1.2,
+ maxDistance: 5,
+ /** Time constant of the eased zoom, seconds. */
+ zoomS: 0.09,
+ /** Log zoom pushed past the closest distance (or out of first person) that changes the person: about one wheel notch. */
+ handover: 0.1,
+ /** Pivot height above the commander's feet, metres (about the top of the head). */
+ pivotHeight: 1.74,
+ /** First person: eye height above the feet and how far in front of the body's axis the eyes are, metres. */
+ eyeHeight: 1.65,
+ eyeForward: 0.1,
+ /**
+ * Sideways offset of the pivot, metres, along the camera's right: negative
+ * puts the camera to the commander's left, so they stand right of centre.
+ */
+ side: -0.47,
+ /** Default pitch, radians (positive looks down). */
+ pitch: 7 * DEG,
+ /** Pitch limits in third person and in first person, radians. */
+ minPitch: -35 * DEG,
+ maxPitch: 60 * DEG,
+ firstMinPitch: -80 * DEG,
+ firstMaxPitch: 80 * DEG,
+ /** Radians per CSS pixel of drag (touch, or a mouse without pointer lock), and per pixel of pointer-lock movement. */
+ dragRate: 0.0042,
+ lockRate: MOUSE_LOOK_RATE,
+ /** Lag of the pivot behind the commander, seconds (horizontal, vertical). */
+ followS: 0.07,
+ followYS: 0.16,
+ /** Time constant of the third ↔ first person blend, seconds. */
+ personS: 0.07,
+ /** Gap kept between the camera and geometry, metres. */
+ clearance: 0.24,
+ /** First person: gap kept between the eyes and a wall in front, metres. */
+ eyeClearance: 0.12,
+ /** Distance regained per second after a pull-in, metres. */
+ regainMps: 3.2,
+} as const;
+
+function wrap(a: number): number {
+ return Math.atan2(Math.sin(a), Math.cos(a));
+}
+
+function clamp(v: number, lo: number, hi: number): number {
+ return Math.max(lo, Math.min(hi, v));
+}
+
+/** Vertical field of view (degrees) for a frame of `aspect` (width / height) at a horizontal one. Pure. */
+export function verticalFov(aspect: number, hfovDeg: number = SHOULDER.hfovDeg, minVfovDeg: number = SHOULDER.minVfovDeg): number {
+ const h = (hfovDeg * Math.PI) / 180;
+ const v = 2 * Math.atan(Math.tan(h / 2) / Math.max(1e-3, aspect));
+ return Math.max(minVfovDeg, (v * 180) / Math.PI);
+}
+
+/** A horizontal field of view as the person may set it, degrees. Pure. */
+export function clampHfov(deg: number, fallback: number): number {
+ return Number.isFinite(deg) ? clamp(deg, SHOULDER.minHfovDeg, SHOULDER.maxHfovDeg) : fallback;
+}
+
+export class ShoulderRig {
+ /** View heading: the floor direction the camera looks along is (sin yaw, cos yaw); π looks toward −Z. */
+ yaw = Math.PI;
+ pitch: number = SHOULDER.pitch;
+ /** The wanted distance (the wheel sets it); collisions shorten the actual one. */
+ distance: number = SHOULDER.distance;
+ /** Over the shoulder or through the eyes. */
+ person: Person = "third";
+ /** Multiplies the turn rate of drags and mouse look (the person's setting, 0.25–3). */
+ sensitivity = 1;
+ /** Moving the mouse up looks down (the person's setting). */
+ invertY = false;
+ /** Horizontal fields of view, degrees (the person's settings). */
+ fovThird: number = SHOULDER.hfovDeg;
+ fovFirst: number = SHOULDER.firstHfovDeg;
+ /** Camera position and the point it looks at, world metres (valid after `update`). */
+ readonly position: Vec3 = { x: 0, y: 0, z: 0 };
+ readonly target: Vec3 = { x: 0, y: 0, z: 0 };
+ /** The third-person distance in use after easing and collisions. */
+ actual: number = SHOULDER.distance;
+ /** How far the camera has blended into first person (0 third .. 1 first, eased), after `update`. */
+ firstShare = 0;
+ private zoomed: number = SHOULDER.distance;
+ private push = 0;
+ private blend = 0;
+ private readonly pivot: Vec3 = { x: 0, y: 0, z: 0 };
+ // Scratch points reused every frame, so `update` allocates nothing.
+ private readonly shoulderPoint: Vec3 = { x: 0, y: 0, z: 0 };
+ private readonly farPoint: Vec3 = { x: 0, y: 0, z: 0 };
+ private readonly head: Vec3 = { x: 0, y: 0, z: 0 };
+ private readonly eye: Vec3 = { x: 0, y: 0, z: 0 };
+ private readonly dir: Vec3 = { x: 0, y: 0, z: 0 };
+ private primed = false;
+
+ /** The pitch limits of the current person, radians. */
+ pitchLimits(): { min: number; max: number } {
+ return this.person === "first"
+ ? { min: SHOULDER.firstMinPitch, max: SHOULDER.firstMaxPitch }
+ : { min: SHOULDER.minPitch, max: SHOULDER.maxPitch };
+ }
+
+ /** Turn the view by a pointer movement (CSS px); `locked` for pointer-lock deltas (shooter look), else a drag. */
+ look(dx: number, dy: number, locked = false): void {
+ const d = lookDelta(dx, dy, this, locked ? SHOULDER.lockRate : SHOULDER.dragRate);
+ const { min, max } = this.pitchLimits();
+ this.yaw = wrap(this.yaw - d.yaw);
+ this.pitch = clamp(this.pitch + d.pitch, min, max);
+ }
+
+ /**
+ * Zoom by `factor` (> 1 moves out): the third-person distance, and the
+ * hand-over to and from first person. Returns the new person when it
+ * changed, else null.
+ */
+ zoom(factor: number): Person | null {
+ const next = zoomStep({ person: this.person, distance: this.distance, push: this.push }, factor, {
+ min: SHOULDER.minDistance, max: SHOULDER.maxDistance, handover: SHOULDER.handover,
+ });
+ const changed = next.person !== this.person ? next.person : null;
+ this.person = next.person;
+ this.distance = next.distance;
+ this.push = next.push;
+ return changed;
+ }
+
+ /** Switch the person (the view switch); the camera blends over. */
+ setPerson(person: Person): void {
+ if (person === this.person) return;
+ this.person = person;
+ this.push = 0;
+ }
+
+ /** The horizontal field of view to render now (blended between the persons), degrees. */
+ hfov(): number {
+ const third = clampHfov(this.fovThird, SHOULDER.hfovDeg);
+ const first = clampHfov(this.fovFirst, SHOULDER.firstHfovDeg);
+ return third + (first - third) * this.firstShare;
+ }
+
+ /** Put the camera straight behind a body facing `heading` (radians, the actor's yaw), at the default pitch. */
+ snapBehind(heading: number): void {
+ this.yaw = wrap(heading);
+ this.pitch = this.person === "first" ? 0 : SHOULDER.pitch;
+ this.primed = false;
+ }
+
+ /** Turn the view toward a floor point seen from (fromX, fromZ), keeping the pitch (the crew card's "show"). */
+ faceToward(fromX: number, fromZ: number, x: number, z: number): void {
+ if (Math.hypot(x - fromX, z - fromZ) < 1e-6) return;
+ this.yaw = Math.atan2(x - fromX, z - fromZ);
+ }
+
+ /** The floor direction the camera looks along (unit). */
+ forward(): { x: number; z: number } {
+ return { x: Math.sin(this.yaw), z: Math.cos(this.yaw) };
+ }
+
+ /** The floor direction of the screen's right (unit). */
+ right(): { x: number; z: number } {
+ return { x: -Math.cos(this.yaw), z: Math.sin(this.yaw) };
+ }
+
+ /**
+ * World walking direction for held screen keys: `ix` right (+1) / left
+ * (−1), `iz` toward the camera (+1, S) / away (−1, W). Unit length or null;
+ * written into `out` when given (the frame loop allocates nothing).
+ */
+ walkDirection(ix: number, iz: number, out?: { x: number; z: number }): { x: number; z: number } | null {
+ if (ix === 0 && iz === 0) return null;
+ const fx = Math.sin(this.yaw);
+ const fz = Math.cos(this.yaw);
+ // The screen's right on the floor is (−cos yaw, sin yaw) = (−fz, fx).
+ const x = -fz * ix - fx * iz;
+ const z = fx * ix - fz * iz;
+ const n = Math.hypot(x, z);
+ if (n <= 1e-9) return null;
+ const o = out ?? { x: 0, z: 0 };
+ o.x = x / n;
+ o.z = z / n;
+ return o;
+ }
+
+ /**
+ * Follow the body at (x, y, z) facing `heading`; `moving` while it walks.
+ * `test` checks segments against the deck's geometry (the points it gets
+ * are only valid during the call).
+ */
+ update(dtS: number, body: Readonly<Vec3> & { readonly heading: number; readonly moving: boolean }, test?: SegmentTest | null): void {
+ const dt = clamp(dtS, 0, 0.1);
+ const pivot = this.pivot;
+ const gx = body.x;
+ const gy = body.y + SHOULDER.pivotHeight;
+ const gz = body.z;
+ const wantFirst = this.person === "first" ? 1 : 0;
+ /** How far the eased zoom moved out this frame: the camera follows it on top of the wall regain. */
+ let zoomOut = 0;
+ if (!this.primed) {
+ pivot.x = gx;
+ pivot.y = gy;
+ pivot.z = gz;
+ this.zoomed = this.distance;
+ this.actual = this.distance;
+ this.blend = wantFirst;
+ this.primed = true;
+ } else {
+ const kx = 1 - Math.exp(-dt / SHOULDER.followS);
+ const ky = 1 - Math.exp(-dt / SHOULDER.followYS);
+ pivot.x += (gx - pivot.x) * kx;
+ pivot.y += (gy - pivot.y) * ky;
+ pivot.z += (gz - pivot.z) * kx;
+ const before = this.zoomed;
+ this.zoomed += (this.distance - this.zoomed) * (1 - Math.exp(-dt / SHOULDER.zoomS));
+ zoomOut = Math.max(0, this.zoomed - before);
+ this.blend += (wantFirst - this.blend) * (1 - Math.exp(-dt / SHOULDER.personS));
+ if (Math.abs(wantFirst - this.blend) < 1e-3) this.blend = wantFirst;
+ }
+ // Back in third person a pitch beyond its limits comes inside them.
+ const { min, max } = this.pitchLimits();
+ this.pitch = clamp(this.pitch, min, max);
+ const s = this.blend * this.blend * (3 - 2 * this.blend);
+ this.firstShare = s;
+
+ const fx = Math.sin(this.yaw);
+ const fz = Math.cos(this.yaw);
+ const cp = Math.cos(this.pitch);
+ const dir = this.dir;
+ dir.x = fx * cp;
+ dir.y = -Math.sin(this.pitch);
+ dir.z = fz * cp;
+
+ // Third person. The shoulder point: sideways from the head along the screen's right (−fz, fx), pulled in when a
+ // wall is that close.
+ const shoulder = this.shoulderPoint;
+ shoulder.x = pivot.x - fz * SHOULDER.side;
+ shoulder.y = pivot.y;
+ shoulder.z = pivot.z + fx * SHOULDER.side;
+ if (test && s < 1) {
+ const hit = test(pivot, shoulder);
+ if (hit !== null) {
+ const keep = Math.max(0, hit - SHOULDER.clearance / Math.abs(SHOULDER.side));
+ shoulder.x = pivot.x + (shoulder.x - pivot.x) * keep;
+ shoulder.z = pivot.z + (shoulder.z - pivot.z) * keep;
+ }
+ }
+ let reach = this.zoomed;
+ if (test && s < 1) {
+ const far = this.farPoint;
+ far.x = shoulder.x - dir.x * this.zoomed;
+ far.y = shoulder.y - dir.y * this.zoomed;
+ far.z = shoulder.z - dir.z * this.zoomed;
+ const hit = test(shoulder, far);
+ if (hit !== null) reach = Math.max(0.15, hit * this.zoomed - SHOULDER.clearance);
+ }
+ // In at once (never through a wall), back out smoothly; a wheel zoom out is followed as fast as it eases.
+ this.actual = reach < this.actual ? reach : Math.min(reach, this.actual + SHOULDER.regainMps * dt + zoomOut);
+ const tx = shoulder.x - dir.x * this.actual;
+ const ty = shoulder.y - dir.y * this.actual;
+ const tz = shoulder.z - dir.z * this.actual;
+
+ // First person: the eyes, on the body's axis horizontally (no lag: it is the head), the pivot's eased height.
+ const head = this.head;
+ head.x = gx;
+ head.y = pivot.y - (SHOULDER.pivotHeight - SHOULDER.eyeHeight);
+ head.z = gz;
+ const eye = this.eye;
+ eye.x = gx + fx * SHOULDER.eyeForward;
+ eye.y = head.y;
+ eye.z = gz + fz * SHOULDER.eyeForward;
+ if (test && s > 0) {
+ // Never past a wall the face is against: the eyes stay a little short of it.
+ const probeX = gx + fx * (SHOULDER.eyeForward + SHOULDER.eyeClearance);
+ const probeZ = gz + fz * (SHOULDER.eyeForward + SHOULDER.eyeClearance);
+ const far = this.farPoint;
+ far.x = probeX;
+ far.y = head.y;
+ far.z = probeZ;
+ const hit = test(head, far);
+ if (hit !== null) {
+ const reachEye = Math.max(0, hit * (SHOULDER.eyeForward + SHOULDER.eyeClearance) - SHOULDER.eyeClearance);
+ eye.x = gx + fx * reachEye;
+ eye.z = gz + fz * reachEye;
+ }
+ }
+
+ this.position.x = tx + (eye.x - tx) * s;
+ this.position.y = ty + (eye.y - ty) * s;
+ this.position.z = tz + (eye.z - tz) * s;
+ // Both cameras look along the same direction; the point ahead follows the blended position.
+ this.target.x = this.position.x + dir.x * 10;
+ this.target.y = this.position.y + dir.y * 10;
+ this.target.z = this.position.z + dir.z * 10;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/viewMode.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/viewMode.ts
new file mode 100644
index 0000000000..a24beb5778
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/viewMode.ts
@@ -0,0 +1,138 @@
+/**
+ * The three ways to see the deck and how they hand over to each other
+ * (docs/verse/realtime.md, "Views"):
+ *
+ * - bird's-eye (`overview`): the plate from above, WASD pans, clicks walk;
+ * - third person (`third`): over the commander's shoulder, shooter mouse look;
+ * - first person (`first`): through the commander's eyes, shooter mouse look.
+ *
+ * V cycles bird's-eye → third → first → bird's-eye; 1, 2 and 3 pick one
+ * directly. The wheel moves the third-person camera in and out; pushing on
+ * past the closest distance hands over to first person, and scrolling out of
+ * first person comes back to third. Where a deck has no eye-level scene (the
+ * compact panel, decks without an export) first person is not offered and
+ * third person is the plate's follow camera.
+ *
+ * Pure: the stage keeps the chosen view and the rig its distance.
+ */
+import type { ControlMode } from "../../life/control";
+
+export type VerseView = "overview" | "third" | "first";
+
+/** The order of the tool rail's switch and of V's cycle. */
+export const VIEW_ORDER: readonly VerseView[] = ["overview", "third", "first"];
+
+/** The keys that pick a view directly (top row and keypad). */
+const DIRECT_KEYS: Readonly<Record<string, VerseView>> = {
+ Digit1: "overview", Numpad1: "overview",
+ Digit2: "third", Numpad2: "third",
+ Digit3: "first", Numpad3: "first",
+};
+
+/** The view a key picks directly, or null. Pure. */
+export function viewForKey(code: string): VerseView | null {
+ return DIRECT_KEYS[code] ?? null;
+}
+
+/** The key shown on each view's button. */
+export function keyForView(view: VerseView): string {
+ return String(VIEW_ORDER.indexOf(view) + 1);
+}
+
+/** The view that can actually be shown: first person needs the eye-level scene. Pure. */
+export function resolveView(wanted: VerseView, eyeCapable: boolean): VerseView {
+ return wanted === "first" && !eyeCapable ? "third" : wanted;
+}
+
+/** The view after V: the next one in VIEW_ORDER that can be shown. Pure. */
+export function cycleView(current: VerseView, eyeCapable: boolean): VerseView {
+ const from = VIEW_ORDER.indexOf(resolveView(current, eyeCapable));
+ for (let i = 1; i <= VIEW_ORDER.length; i++) {
+ const next = VIEW_ORDER[(from + i) % VIEW_ORDER.length];
+ if (resolveView(next, eyeCapable) === next) return next;
+ }
+ return current;
+}
+
+/** How the movement keys work in a view: the commander's (third, first) or the map's (bird's-eye). Pure. */
+export function controlModeOf(view: VerseView): ControlMode {
+ return view === "overview" ? "overview" : "follow";
+}
+
+/** The views with shooter mouse look (pointer lock, a centre crosshair). Pure. */
+export function isShooterView(view: VerseView, eyeCapable: boolean): boolean {
+ return eyeCapable && view !== "overview";
+}
+
+/** Anything stored as a view, valid (third person when unknown). Pure. */
+export function normalizeView(raw: unknown): VerseView {
+ return raw === "overview" || raw === "third" || raw === "first" ? raw : "third";
+}
+
+/** The person (camera) of the eye-level views. */
+export type Person = "third" | "first";
+
+export interface ZoomState {
+ person: Person;
+ /** The wanted third-person distance, metres. */
+ distance: number;
+ /** How far the wheel has pushed past a hand-over point, as a log of the zoom factor (in: negative, out: positive). */
+ push: number;
+}
+
+export interface ZoomLimits {
+ min: number;
+ max: number;
+ /** Log zoom past the end that hands over (about one wheel notch). */
+ handover: number;
+}
+
+/**
+ * One wheel or key zoom step: `factor` < 1 moves in, > 1 moves out. Third
+ * person scales the distance inside [min, max]; pushing in past `min` by
+ * `handover` goes to first person (at `min`, so the way back starts there),
+ * and in first person a push out of `handover` returns to third person at
+ * `min`. A step the other way clears the push. Pure.
+ */
+export function zoomStep(s: ZoomState, factor: number, limits: ZoomLimits): ZoomState {
+ if (!(factor > 0) || !Number.isFinite(factor) || factor === 1) return s;
+ const log = Math.log(factor);
+ if (s.person === "first") {
+ if (log < 0) return { person: "first", distance: limits.min, push: 0 };
+ const push = Math.max(0, s.push) + log;
+ return push >= limits.handover ? { person: "third", distance: limits.min, push: 0 } : { person: "first", distance: limits.min, push };
+ }
+ const wanted = s.distance * factor;
+ if (wanted >= limits.min) return { person: "third", distance: Math.min(limits.max, wanted), push: 0 };
+ // Already at (or pushed past) the closest distance: what is left of the step pushes toward first person.
+ const over = Math.log(wanted / limits.min);
+ const push = Math.min(0, s.push) + over;
+ return push <= -limits.handover ? { person: "first", distance: limits.min, push: 0 } : { person: "third", distance: limits.min, push };
+}
+
+/** How far off the view direction the body may face while walking (radians): a strafe leans into it, no more. */
+export const STRAFE_LEAN = (45 * Math.PI) / 180;
+/** Moving further off the view than this (radians) is walking backwards. */
+const BACKPEDAL_BEYOND = (110 * Math.PI) / 180;
+
+function wrap(a: number): number {
+ return Math.atan2(Math.sin(a), Math.cos(a));
+}
+
+/**
+ * Which way a body walking along `move` (unit, on the floor) faces in a
+ * shooter view looking along `viewYaw`: toward the view, leaning at most
+ * STRAFE_LEAN into a sideways step; walking backwards it keeps facing the
+ * view and plays its walk in reverse (`reverse`). Written into `out` when
+ * given (the frame loop allocates nothing). Pure.
+ */
+export function bodyFacing(
+ viewYaw: number, move: { x: number; z: number }, out?: { yaw: number; reverse: boolean },
+): { yaw: number; reverse: boolean } {
+ const o = out ?? { yaw: 0, reverse: false };
+ const off = wrap(Math.atan2(move.x, move.z) - viewYaw);
+ o.reverse = Math.abs(off) > BACKPEDAL_BEYOND;
+ const lean = o.reverse ? wrap(off - Math.PI) : off;
+ o.yaw = wrap(viewYaw + Math.max(-STRAFE_LEAN, Math.min(STRAFE_LEAN, lean)));
+ return o;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/viewSettings.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/viewSettings.ts
new file mode 100644
index 0000000000..3fa15e293a
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/viewSettings.ts
@@ -0,0 +1,90 @@
+/**
+ * The person's own settings for the eye-level views: mouse sensitivity, an
+ * inverted vertical axis, the field of view in third and in first person,
+ * the render quality, and the view they last chose (bird's-eye, third or
+ * first person). Cosmetic and local to this browser (localStorage, every
+ * access guarded); never synced. Without storage the defaults apply and
+ * changes last for the session.
+ */
+import { create } from "zustand";
+import { LOOK_SENSITIVITY } from "./mouseLook";
+import { SHOULDER, clampHfov } from "./shoulderRig";
+import { normalizeView, type VerseView } from "./viewMode";
+
+/** "auto" starts at high and drops to low on a GPU that cannot hold ~45 fps. */
+export type QualityChoice = "auto" | "high" | "low";
+
+export interface ViewPrefs {
+ /** Turn-rate multiplier, LOOK_SENSITIVITY.min–max, 1 by default. */
+ sensitivity: number;
+ /** Moving the mouse up looks down. */
+ invertY: boolean;
+ quality: QualityChoice;
+ /** Horizontal field of view in third and in first person, degrees (SHOULDER.minHfovDeg–maxHfovDeg). */
+ fovThird: number;
+ fovFirst: number;
+ /** The view the person last chose. */
+ view: VerseView;
+}
+
+export interface ViewSettings extends ViewPrefs {
+ set: (patch: Partial<ViewPrefs>) => void;
+ reset: () => void;
+}
+
+export const VIEW_SETTINGS_KEY = "dodaios.verse.view.v1";
+export const VIEW_DEFAULTS: Readonly<ViewPrefs> = {
+ sensitivity: 1, invertY: false, quality: "auto", fovThird: SHOULDER.hfovDeg, fovFirst: SHOULDER.firstHfovDeg, view: "third",
+};
+
+/** Whatever was stored (or nothing), as valid settings. Pure. */
+export function normalizeViewPrefs(raw: unknown): ViewPrefs {
+ const o = typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>) : {};
+ const s = o.sensitivity;
+ return {
+ sensitivity: typeof s === "number" && Number.isFinite(s)
+ ? Math.min(LOOK_SENSITIVITY.max, Math.max(LOOK_SENSITIVITY.min, s))
+ : VIEW_DEFAULTS.sensitivity,
+ invertY: o.invertY === true,
+ quality: o.quality === "high" || o.quality === "low" ? o.quality : "auto",
+ fovThird: typeof o.fovThird === "number" ? clampHfov(o.fovThird, VIEW_DEFAULTS.fovThird) : VIEW_DEFAULTS.fovThird,
+ fovFirst: typeof o.fovFirst === "number" ? clampHfov(o.fovFirst, VIEW_DEFAULTS.fovFirst) : VIEW_DEFAULTS.fovFirst,
+ view: normalizeView(o.view),
+ };
+}
+
+function read(): ViewPrefs {
+ try {
+ const raw = window.localStorage.getItem(VIEW_SETTINGS_KEY);
+ return normalizeViewPrefs(raw ? JSON.parse(raw) : null);
+ } catch {
+ return { ...VIEW_DEFAULTS };
+ }
+}
+
+function write(prefs: ViewPrefs): void {
+ try {
+ window.localStorage.setItem(VIEW_SETTINGS_KEY, JSON.stringify(prefs));
+ } catch {
+ /* not kept, still applied */
+ }
+}
+
+const prefsOf = (s: ViewPrefs): ViewPrefs => ({
+ sensitivity: s.sensitivity, invertY: s.invertY, quality: s.quality, fovThird: s.fovThird, fovFirst: s.fovFirst, view: s.view,
+});
+
+export const useViewSettings = create<ViewSettings>((set, get) => ({
+ ...read(),
+ set: (patch) => {
+ const next = normalizeViewPrefs({ ...prefsOf(get()), ...patch });
+ write(next);
+ set(next);
+ },
+ // Reset puts the settings back; the view on screen stays what it is.
+ reset: () => {
+ const next = { ...VIEW_DEFAULTS, view: get().view };
+ write(next);
+ set(next);
+ },
+}));
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/views.test.tsx b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/views.test.tsx
new file mode 100644
index 0000000000..524ce70449
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/realtime/views.test.tsx
@@ -0,0 +1,344 @@
+/**
+ * The three views (bird's-eye, third and first person): the switch's state
+ * machine and keys, the wheel's hand-over between third and first person,
+ * the first-person camera, the shared shooter mouse look (eye level and
+ * duel), the body facing the view while walking, the input mapping with the
+ * pointer locked or free, and the tool rail's switch.
+ */
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { DuelCamera, DUEL_CAMERA } from "../../duel/duelCamera";
+import { Toolbar } from "../../hud/DeckBar";
+import { CommanderControl } from "../../life/control";
+import { LOOK_SENSITIVITY, MOUSE_LOOK_RATE, clampSensitivity, lookDelta, requestMouseLook } from "./mouseLook";
+import { attachOrbitInput, wheelFactor } from "./orbitInput";
+import { SHOULDER, ShoulderRig, type SegmentTest } from "./shoulderRig";
+import {
+ STRAFE_LEAN, VIEW_ORDER, bodyFacing, controlModeOf, cycleView, isShooterView, keyForView, normalizeView, resolveView,
+ viewForKey, zoomStep,
+} from "./viewMode";
+
+const body = (x: number, z: number, heading = Math.PI, moving = false) => ({ x, y: 0, z, heading, moving });
+const LIMITS = { min: SHOULDER.minDistance, max: SHOULDER.maxDistance, handover: SHOULDER.handover };
+/** One 100 px wheel notch in and out. */
+const IN = wheelFactor(-100, 0);
+const OUT = wheelFactor(100, 0);
+const settle = (rig: ShoulderRig, seconds = 1, test?: SegmentTest) => {
+ for (let i = 0; i < seconds * 60; i++) rig.update(1 / 60, body(0, 0), test);
+};
+
+describe("view state machine", () => {
+ it("cycles bird's-eye, third and first person with V, skipping first person without an eye-level scene", () => {
+ expect(VIEW_ORDER).toEqual(["overview", "third", "first"]);
+ expect(cycleView("overview", true)).toBe("third");
+ expect(cycleView("third", true)).toBe("first");
+ expect(cycleView("first", true)).toBe("overview");
+ expect(cycleView("overview", false)).toBe("third");
+ expect(cycleView("third", false)).toBe("overview");
+ // A remembered first person on a deck without the scene counts as third.
+ expect(cycleView("first", false)).toBe("overview");
+ });
+
+ it("picks a view directly with 1, 2 and 3 (top row and keypad) and shows those keys", () => {
+ expect(viewForKey("Digit1")).toBe("overview");
+ expect(viewForKey("Numpad2")).toBe("third");
+ expect(viewForKey("Digit3")).toBe("first");
+ expect(viewForKey("KeyV")).toBeNull();
+ expect(VIEW_ORDER.map(keyForView)).toEqual(["1", "2", "3"]);
+ });
+
+ it("shows first person only where it can, and gives shooter look to the eye-level views", () => {
+ expect(resolveView("first", false)).toBe("third");
+ expect(resolveView("first", true)).toBe("first");
+ expect(controlModeOf("overview")).toBe("overview");
+ expect(controlModeOf("third")).toBe("follow");
+ expect(controlModeOf("first")).toBe("follow");
+ expect(isShooterView("third", true)).toBe(true);
+ expect(isShooterView("first", true)).toBe(true);
+ expect(isShooterView("overview", true)).toBe(false);
+ expect(isShooterView("third", false)).toBe(false);
+ expect(normalizeView("first")).toBe("first");
+ expect(normalizeView("ego")).toBe("third");
+ expect(normalizeView(undefined)).toBe("third");
+ });
+});
+
+describe("zoom and the hand-over between third and first person", () => {
+ it("scales the third-person distance inside its range", () => {
+ let s = zoomStep({ person: "third", distance: 2.4, push: 0 }, OUT, LIMITS);
+ expect(s.distance).toBeCloseTo(2.4 * OUT);
+ for (let i = 0; i < 30; i++) s = zoomStep(s, OUT, LIMITS);
+ expect(s).toEqual({ person: "third", distance: SHOULDER.maxDistance, push: 0 });
+ expect(zoomStep(s, 1, LIMITS)).toBe(s);
+ expect(zoomStep(s, Number.NaN, LIMITS)).toBe(s);
+ });
+
+ it("goes to first person only when pushed on past the closest distance", () => {
+ let s = zoomStep({ person: "third", distance: 1.25, push: 0 }, IN, LIMITS);
+ // The notch that reaches the closest distance stops there.
+ expect(s.person).toBe("third");
+ expect(s.distance).toBe(SHOULDER.minDistance);
+ // A step back out clears the push.
+ expect(zoomStep(s, OUT, LIMITS).push).toBe(0);
+ s = zoomStep(s, IN, LIMITS);
+ expect(s).toEqual({ person: "first", distance: SHOULDER.minDistance, push: 0 });
+ });
+
+ it("stays in first person scrolling in and comes back out to third at the closest distance", () => {
+ const first = { person: "first" as const, distance: SHOULDER.minDistance, push: 0 };
+ expect(zoomStep(first, IN, LIMITS).person).toBe("first");
+ // A small trackpad nudge out is not enough; a notch is.
+ const nudge = zoomStep(first, wheelFactor(20, 0), LIMITS);
+ expect(nudge.person).toBe("first");
+ expect(zoomStep(nudge, wheelFactor(80, 0), LIMITS)).toEqual({ person: "third", distance: SHOULDER.minDistance, push: 0 });
+ expect(zoomStep(first, OUT, LIMITS).person).toBe("third");
+ });
+
+ it("hands over through the rig and reports the new person", () => {
+ const rig = new ShoulderRig();
+ rig.distance = 1.3;
+ expect(rig.zoom(IN)).toBeNull();
+ expect(rig.zoom(IN)).toBe("first");
+ expect(rig.person).toBe("first");
+ expect(rig.zoom(IN)).toBeNull();
+ expect(rig.zoom(OUT)).toBe("third");
+ expect(rig.distance).toBe(SHOULDER.minDistance);
+ });
+
+ it("eases the wheel's distance instead of jumping", () => {
+ const rig = new ShoulderRig();
+ rig.snapBehind(Math.PI);
+ rig.update(1 / 60, body(0, 0));
+ rig.distance = 4;
+ rig.update(1 / 60, body(0, 0));
+ expect(rig.actual).toBeGreaterThan(SHOULDER.distance);
+ expect(rig.actual).toBeLessThan(3);
+ settle(rig);
+ expect(rig.actual).toBeCloseTo(4, 2);
+ rig.distance = 1.5;
+ rig.update(1 / 60, body(0, 0));
+ expect(rig.actual).toBeGreaterThan(3);
+ settle(rig);
+ expect(rig.actual).toBeCloseTo(1.5, 2);
+ });
+});
+
+describe("first-person camera", () => {
+ it("sits at eye height just in front of the face and looks where the mouse points", () => {
+ const rig = new ShoulderRig();
+ rig.setPerson("first");
+ rig.snapBehind(Math.PI);
+ rig.update(1 / 60, body(2, 3));
+ expect(rig.firstShare).toBe(1);
+ expect(rig.position.x).toBeCloseTo(2);
+ expect(rig.position.y).toBeCloseTo(SHOULDER.eyeHeight);
+ expect(rig.position.z).toBeCloseTo(3 - SHOULDER.eyeForward);
+ // Level and straight ahead (−Z).
+ expect(rig.target.y).toBeCloseTo(rig.position.y);
+ expect(rig.target.z).toBeLessThan(rig.position.z);
+ });
+
+ it("blends from the shoulder into the eyes, field of view included", () => {
+ const rig = new ShoulderRig();
+ rig.snapBehind(Math.PI);
+ settle(rig, 0.2);
+ expect(rig.hfov()).toBeCloseTo(SHOULDER.hfovDeg);
+ rig.setPerson("first");
+ rig.update(1 / 60, body(0, 0));
+ expect(rig.firstShare).toBeGreaterThan(0);
+ expect(rig.firstShare).toBeLessThan(1);
+ expect(rig.position.z).toBeGreaterThan(0.2);
+ settle(rig, 0.6);
+ expect(rig.firstShare).toBe(1);
+ expect(rig.position.z).toBeCloseTo(-SHOULDER.eyeForward);
+ expect(rig.hfov()).toBeCloseTo(SHOULDER.firstHfovDeg);
+ rig.fovFirst = 100;
+ expect(rig.hfov()).toBeCloseTo(100);
+ rig.fovFirst = 500;
+ expect(rig.hfov()).toBeCloseTo(SHOULDER.maxHfovDeg);
+ });
+
+ it("looks further up and down than third person, and comes back inside third person's limits", () => {
+ const rig = new ShoulderRig();
+ rig.setPerson("first");
+ rig.look(0, 1e6, true);
+ expect(rig.pitch).toBeCloseTo(SHOULDER.firstMaxPitch);
+ rig.setPerson("third");
+ rig.update(1 / 60, body(0, 0));
+ expect(rig.pitch).toBeCloseTo(SHOULDER.maxPitch);
+ });
+
+ it("never puts the eyes through a wall the face is against", () => {
+ const rig = new ShoulderRig();
+ rig.setPerson("first");
+ rig.snapBehind(Math.PI);
+ // A wall 0.08 m in front of the body's axis (z = −0.08).
+ const test: SegmentTest = (from, to) => (to.z < -0.08 && from.z >= -0.08 ? (from.z + 0.08) / (from.z - to.z) : null);
+ rig.update(1 / 60, body(0, 0), test);
+ expect(rig.position.z).toBeGreaterThanOrEqual(-0.08);
+ });
+});
+
+describe("shooter mouse look", () => {
+ it("applies the sensitivity and the inverted axis the same way everywhere", () => {
+ expect(lookDelta(10, 10, { sensitivity: 1, invertY: false })).toEqual({ yaw: 10 * MOUSE_LOOK_RATE, pitch: 10 * MOUSE_LOOK_RATE });
+ expect(lookDelta(10, 10, { sensitivity: 2, invertY: true })).toEqual({ yaw: 20 * MOUSE_LOOK_RATE, pitch: -20 * MOUSE_LOOK_RATE });
+ expect(clampSensitivity(99)).toBe(LOOK_SENSITIVITY.max);
+ expect(clampSensitivity(Number.NaN)).toBe(1);
+ });
+
+ it("turns the eye-level views and the duel by the same angle for the same mouse movement", () => {
+ const rig = new ShoulderRig();
+ const duel = new DuelCamera();
+ rig.sensitivity = duel.sensitivity = 1.7;
+ const yaw0 = rig.yaw;
+ rig.look(50, 0, true);
+ duel.look(50, 0);
+ expect(DUEL_CAMERA.lookRate).toBe(SHOULDER.lockRate);
+ expect(yaw0 - rig.yaw).toBeCloseTo(-duel.yaw, 9);
+ // Mouse down looks down in both (the duel's pitch is positive up).
+ rig.look(0, 30, true);
+ duel.look(0, 30);
+ expect(rig.pitch).toBeGreaterThan(SHOULDER.pitch);
+ expect(duel.pitch).toBeLessThan(0);
+ });
+
+ it("asks for raw mouse movement and falls back to a plain lock where it is refused", async () => {
+ const el = document.createElement("div");
+ const calls: unknown[] = [];
+ el.requestPointerLock = vi.fn((options?: unknown) => {
+ calls.push(options);
+ return options ? Promise.reject(new Error("not supported")) : Promise.resolve();
+ }) as unknown as typeof el.requestPointerLock;
+ requestMouseLook(el);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(calls).toEqual([{ unadjustedMovement: true }, undefined]);
+ });
+});
+
+describe("the commander faces the view while walking", () => {
+ const view = Math.PI; // looking toward −Z
+
+ it("faces the view walking forward and leans at most 45 degrees into a strafe", () => {
+ expect(bodyFacing(view, { x: 0, z: -1 })).toEqual({ yaw: Math.PI, reverse: false });
+ const right = bodyFacing(view, { x: 1, z: 0 }); // the view's right is +X
+ expect(right.reverse).toBe(false);
+ expect(Math.abs(Math.atan2(Math.sin(right.yaw - view), Math.cos(right.yaw - view)))).toBeCloseTo(STRAFE_LEAN);
+ });
+
+ it("walks backwards facing the view, the walk played in reverse", () => {
+ const back = bodyFacing(view, { x: 0, z: 1 });
+ expect(back.reverse).toBe(true);
+ expect(Math.cos(back.yaw - view)).toBeCloseTo(1);
+ const out = { yaw: 0, reverse: false };
+ expect(bodyFacing(view, { x: 0, z: 1 }, out)).toBe(out);
+ });
+
+ it("walks relative to the view in first person as in third (strafing with A and D)", () => {
+ const rig = new ShoulderRig();
+ rig.setPerson("first");
+ rig.yaw = Math.PI / 2; // looking toward +X
+ const control = new CommanderControl();
+ control.setKey("right", true);
+ // Looking toward +X, the screen's right is +Z.
+ const d = control.directionFrom(rig)!;
+ expect(d.x).toBeCloseTo(0);
+ expect(d.z).toBeCloseTo(1);
+ });
+});
+
+describe("shooter input mapping", () => {
+ let el: HTMLDivElement;
+ let lockedTo: Element | null = null;
+
+ beforeEach(() => {
+ el = document.createElement("div");
+ Object.defineProperty(el, "clientWidth", { value: 800 });
+ Object.defineProperty(el, "clientHeight", { value: 600 });
+ el.getBoundingClientRect = () => ({ left: 0, top: 0, right: 800, bottom: 600, width: 800, height: 600, x: 0, y: 0, toJSON: () => ({}) });
+ el.setPointerCapture = vi.fn();
+ el.hasPointerCapture = () => false;
+ el.releasePointerCapture = vi.fn();
+ document.body.appendChild(el);
+ Object.defineProperty(document, "pointerLockElement", { configurable: true, get: () => lockedTo });
+ });
+ afterEach(() => {
+ el.remove();
+ lockedTo = null;
+ });
+
+ const pointer = (type: string, init: Record<string, number | string>) => {
+ const e = new MouseEvent(type, { bubbles: true, clientX: Number(init.clientX ?? 0), clientY: Number(init.clientY ?? 0), button: Number(init.button ?? 0) });
+ for (const key of ["pointerId", "pointerType", "movementX", "movementY"]) {
+ if (key in init) Object.defineProperty(e, key, { value: init[key] });
+ }
+ el.dispatchEvent(e);
+ };
+ const callbacks = () => ({ tap: vi.fn(), hover: vi.fn(), leave: vi.fn(), moved: vi.fn(), aim: vi.fn(), capture: vi.fn(), zoom: vi.fn() });
+
+ it("takes the mouse on a click with the mouse free; a finger still taps", () => {
+ const rig = new ShoulderRig();
+ const cb = callbacks();
+ const detach = attachOrbitInput(el, rig, cb);
+ pointer("pointerdown", { clientX: 100, clientY: 120, pointerId: 1, pointerType: "mouse" });
+ pointer("pointerup", { clientX: 100, clientY: 120, pointerId: 1, pointerType: "mouse" });
+ expect(cb.capture).toHaveBeenCalledTimes(1);
+ expect(cb.tap).not.toHaveBeenCalled();
+ pointer("pointerdown", { clientX: 100, clientY: 120, pointerId: 2, pointerType: "touch" });
+ pointer("pointerup", { clientX: 100, clientY: 120, pointerId: 2, pointerType: "touch" });
+ expect(cb.tap).toHaveBeenCalledWith(100, 120);
+ detach();
+ });
+
+ it("with the mouse taken: movement turns the view, the left button aims at the crosshair, the right does nothing", () => {
+ const rig = new ShoulderRig();
+ const cb = callbacks();
+ const detach = attachOrbitInput(el, rig, cb);
+ lockedTo = el;
+ const yaw = rig.yaw;
+ pointer("pointermove", { movementX: -40, movementY: 0, pointerId: 1, pointerType: "mouse" });
+ const turned = rig.yaw - yaw;
+ expect(Math.atan2(Math.sin(turned), Math.cos(turned))).toBeCloseTo(40 * SHOULDER.lockRate);
+ pointer("pointerdown", { clientX: 5, clientY: 5, pointerId: 1, pointerType: "mouse", button: 2 });
+ expect(cb.aim).not.toHaveBeenCalled();
+ pointer("pointerdown", { clientX: 5, clientY: 5, pointerId: 1, pointerType: "mouse", button: 0 });
+ expect(cb.aim).toHaveBeenCalledWith(400, 300);
+ expect(cb.tap).not.toHaveBeenCalled();
+ expect(cb.capture).not.toHaveBeenCalled();
+ detach();
+ });
+
+ it("zooms through the stage so it can hand over (wheel down moves out)", () => {
+ const rig = new ShoulderRig();
+ const cb = callbacks();
+ const detach = attachOrbitInput(el, rig, cb);
+ el.dispatchEvent(new WheelEvent("wheel", { deltaY: 100, cancelable: true }));
+ expect(cb.zoom).toHaveBeenCalledWith(OUT);
+ expect(OUT).toBeGreaterThan(1);
+ expect(rig.distance).toBe(SHOULDER.distance);
+ detach();
+ });
+});
+
+describe("the view switch on the tool rail", () => {
+ afterEach(cleanup);
+ const t = (key: string) => key;
+ const props = { t, onLift: vi.fn(), onCommander: vi.fn(), onHelp: vi.fn() };
+
+ it("shows the three views with their keys, the one on screen pressed", () => {
+ const onView = vi.fn();
+ render(<Toolbar {...props} view="first" firstAvailable onView={onView} />);
+ const buttons = screen.getByRole("group", { name: "verse.tools.view" }).querySelectorAll("button");
+ expect([...buttons].map((b) => b.dataset.view)).toEqual(["overview", "third", "first"]);
+ expect([...buttons].map((b) => b.getAttribute("aria-pressed"))).toEqual(["false", "false", "true"]);
+ expect([...buttons].map((b) => b.querySelector("kbd")?.textContent)).toEqual(["1", "2", "3"]);
+ fireEvent.click(buttons[0]);
+ expect(onView).toHaveBeenCalledWith("overview");
+ });
+
+ it("offers first person only where the deck can show it", () => {
+ render(<Toolbar {...props} view="third" firstAvailable={false} onView={vi.fn()} />);
+ const first = screen.getByTitle("verse.tools.first_unavailable") as HTMLButtonElement;
+ expect(first.disabled).toBe(true);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/renderOrder.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/renderOrder.ts
index 7e8645f2ec..03a59a7ae4 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/engine/renderOrder.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/renderOrder.ts
@@ -32,3 +32,5 @@ export const BACKDROP_LAYER = 4;
export const XRAY_LAYER = 1;
/** Development overlays (socket markers, occluder wireframes). */
export const DEBUG_LAYER = 2;
+/** The eye-level deck (realtime geometry); only the eye-level renderer draws it. */
+export const REALTIME_LAYER = 5;
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/engine/stageView.ts b/dodaios/ui/web/frontend/src/components/society/verse/engine/stageView.ts
new file mode 100644
index 0000000000..7f1c480d4c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/engine/stageView.ts
@@ -0,0 +1,29 @@
+/**
+ * Which view the stage shows (docs/verse/realtime.md): the eye-level 3D view
+ * behind the commander's shoulder, or the deck's plate. The plate is the
+ * bird's-eye view, the compact IDE panel's view, and the fallback for decks
+ * without an eye-level export or whose export failed to load. Pure.
+ */
+import type { ControlMode } from "../life/control";
+
+export type StageView = "eye" | "plate";
+
+export interface ViewInputs {
+ /** The compact IDE side panel. */
+ compact: boolean;
+ /** The deck has an eye-level export this runtime reads. */
+ realtime: boolean;
+ /** Its eye-level scene failed to load on this stage. */
+ failed: boolean;
+ /** Third person ("follow") or bird's-eye ("overview"). */
+ mode: ControlMode;
+}
+
+/** The deck can be walked at eye level on this stage; its scene stays loaded while the bird's-eye view is on. */
+export function eyeCapable(v: Omit<ViewInputs, "mode">): boolean {
+ return !v.compact && v.realtime && !v.failed;
+}
+
+export function stageView(v: ViewInputs): StageView {
+ return eyeCapable(v) && v.mode === "follow" ? "eye" : "plate";
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/DeckBar.tsx b/dodaios/ui/web/frontend/src/components/society/verse/hud/DeckBar.tsx
index 063cd069e5..b0035a333f 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/hud/DeckBar.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/DeckBar.tsx
@@ -1,13 +1,14 @@
/**
* The HUD's fixed parts: the deck title top left (number, name, who is on
* duty) with the commander's rank card beside it, and the tool rail top right
- * (bird's-eye on or off, turbolift, bring the camera to the commander, help). Development builds
- * add a frame readout bottom right.
+ * (the view: bird's-eye, third or first person; turbolift; bring the camera to the
+ * commander; the eye-level view's settings; help). Development builds add a
+ * frame readout under the rail.
*/
import { useEffect, useRef, type ReactNode } from "react";
import { deckNumber, type DeckId } from "../decks";
-import type { StageRuntime } from "../runtime";
-import type { ControlMode } from "../life/control";
+import type { FrameStats, StageRuntime } from "../runtime";
+import { VIEW_ORDER, keyForView, type VerseView } from "../engine/realtime/viewMode";
interface TitleProps {
deck: DeckId;
@@ -44,11 +45,17 @@ export function DeckTitle({ deck, t, counts, rankCard }: TitleProps) {
interface ToolProps {
t: (key: string) => string;
- /** Third person (the commander under the keys) or bird's-eye. */
- mode: ControlMode;
- onToggleView: () => void;
+ /** The view on screen: bird's-eye, third or first person. */
+ view: VerseView;
+ /** First person needs the deck's eye-level scene on the full-size stage. */
+ firstAvailable: boolean;
+ onView: (view: VerseView) => void;
onLift: () => void;
onCommander: () => void;
+ /** The eye-level view's settings; absent where the deck has no eye-level view on this stage. */
+ onSettings?: () => void;
+ /** Start a duel (absent where duels cannot run: the compact panel). */
+ onDuel?: () => void;
onHelp: () => void;
}
@@ -56,14 +63,39 @@ const icon = (d: string) => (
<svg width="13" height="13" viewBox="0 0 13 13" aria-hidden fill="none" stroke="currentColor" strokeWidth="1.2"><path d={d} /></svg>
);
-export function Toolbar({ t, mode, onToggleView, onLift, onCommander, onHelp }: ToolProps) {
+const VIEW_LOOKS: Readonly<Record<VerseView, { label: string; path: string }>> = {
+ overview: { label: "verse.tools.overview", path: "M1 3.5l3.8-1.5 3.4 1.5L12 2v7.5L8.2 11 4.8 9.5 1 11zM4.8 2v7.5M8.2 3.5V11" },
+ third: { label: "verse.tools.follow", path: "M6.5 1.5a2 2 0 1 0 0 4a2 2 0 1 0 0-4M2.5 11.5c0-2.4 1.8-4.2 4-4.2s4 1.8 4 4.2" },
+ first: { label: "verse.tools.first", path: "M1 6.5c1.6-2.6 3.4-3.9 5.5-3.9s3.9 1.3 5.5 3.9c-1.6 2.6-3.4 3.9-5.5 3.9S2.6 9.1 1 6.5zM6.5 5a1.5 1.5 0 1 0 0 3a1.5 1.5 0 1 0 0-3" },
+};
+
+export function Toolbar({ t, view, firstAvailable, onView, onLift, onCommander, onSettings, onDuel, onHelp }: ToolProps) {
return (
<nav className="verse-tools" aria-label={t("verse.stage.title")}>
- <button type="button" className="verse-tool" onClick={onToggleView} aria-pressed={mode === "overview"} title={`${t("verse.tools.overview")} (V)`}>
- {icon("M1 3.5l3.8-1.5 3.4 1.5L12 2v7.5L8.2 11 4.8 9.5 1 11zM4.8 2v7.5M8.2 3.5V11")}
- <span className="verse-tool-text">{t("verse.tools.overview")}</span>
- <kbd aria-hidden>V</kbd>
- </button>
+ {/* The three views side by side, the one on screen pressed; 1, 2 and 3 pick one, V cycles them. */}
+ <div className="verse-view-switch" role="group" aria-label={t("verse.tools.view")}>
+ {VIEW_ORDER.map((v) => {
+ const look = VIEW_LOOKS[v];
+ const key = keyForView(v);
+ const off = v === "first" && !firstAvailable;
+ return (
+ <button
+ key={v}
+ type="button"
+ className="verse-tool"
+ data-view={v}
+ aria-pressed={view === v}
+ disabled={off}
+ onClick={() => onView(v)}
+ title={off ? t("verse.tools.first_unavailable") : `${t(look.label)} (${key}, V)`}
+ >
+ {icon(look.path)}
+ <span className="verse-tool-text">{t(look.label)}</span>
+ <kbd aria-hidden>{key}</kbd>
+ </button>
+ );
+ })}
+ </div>
<button type="button" className="verse-tool" onClick={onLift} title={t("verse.tools.lift")}>
{icon("M3.5 1.5v10M1 4l2.5-2.5L6 4M9.5 11.5v-10M7 9l2.5 2.5L12 9")}
<span className="verse-tool-text">{t("verse.tools.lift")}</span>
@@ -72,6 +104,17 @@ export function Toolbar({ t, mode, onToggleView, onLift, onCommander, onHelp }:
{icon("M6.5 1v3M6.5 9v3M1 6.5h3M9 6.5h3M6.5 4.5a2 2 0 1 0 0 4a2 2 0 1 0 0-4")}
<span className="verse-tool-text">{t("verse.tools.commander")}</span>
</button>
+ {onDuel && (
+ <button type="button" className="verse-tool" onClick={onDuel} title={t("verse.duel.start")}>
+ {icon("M6.5 1v2.6M6.5 9.4V12M1 6.5h2.6M9.4 6.5H12M6.5 3.6a2.9 2.9 0 1 0 0 5.8a2.9 2.9 0 1 0 0-5.8")}
+ <span className="verse-tool-text">{t("verse.tools.duel")}</span>
+ </button>
+ )}
+ {onSettings && (
+ <button type="button" className="verse-tool" onClick={onSettings} title={t("verse.tools.settings")} aria-label={t("verse.tools.settings")}>
+ {icon("M1 3.5h6.5M10.5 3.5H12M7.5 2v3M10.5 2v3M1 9.5h1.5M5.5 9.5H12M2.5 8v3M5.5 8v3")}
+ </button>
+ )}
<button type="button" className="verse-tool" onClick={onHelp} title={t("verse.tools.help")}>
{icon("M4.6 4.6a1.9 1.9 0 1 1 2.6 1.8c-.5.2-.7.6-.7 1.1v.6M6.5 10v.4")}
<span className="verse-tool-text">{t("verse.tools.help")}</span>
@@ -80,7 +123,20 @@ export function Toolbar({ t, mode, onToggleView, onLift, onCommander, onHelp }:
);
}
-/** Development readout: frame time, draw calls, triangles, tiles and the plate level streamed, actors. */
+/**
+ * The development readout's text: frame rate and time, render cost, then
+ * the view (the eye level's quality tier, or the plate's tiles and level)
+ * and the actors. Pure.
+ */
+export function statsText(s: FrameStats): string {
+ const fps = s.frameMs > 0 ? Math.round(1000 / s.frameMs) : 0;
+ const view = s.plateLevel === "3D"
+ ? `eye level, ${s.tier || "?"} tier`
+ : `${s.tiles} tiles ${s.plateLevel} (${s.tilesLoading} loading)`;
+ return `${fps} fps ${s.frameMs.toFixed(1)} ms (${s.cpuMs.toFixed(1)} cpu) ${s.drawCalls} calls ${(s.triangles / 1000).toFixed(1)}k tris\n${view} ${s.actors} actors`;
+}
+
+/** Development readout under the tool rail (`statsText`), refreshed twice a second. */
export function StatsReadout({ runtime }: { runtime: StageRuntime }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -89,8 +145,7 @@ export function StatsReadout({ runtime }: { runtime: StageRuntime }) {
const now = performance.now();
if (now - last < 500 || !ref.current) return;
last = now;
- const s = runtime.stats;
- ref.current.textContent = `${s.frameMs.toFixed(1)} ms (${s.cpuMs.toFixed(1)} cpu) ${s.drawCalls} calls ${(s.triangles / 1000).toFixed(1)}k tris\n${s.tiles} tiles ${s.plateLevel} (${s.tilesLoading} loading) ${s.actors} actors`;
+ ref.current.textContent = statsText(runtime.stats);
};
runtime.afterFrame.add(show);
return () => { runtime.afterFrame.delete(show); };
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/DuelHud.tsx b/dodaios/ui/web/frontend/src/components/society/verse/hud/DuelHud.tsx
new file mode 100644
index 0000000000..c6d65694a8
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/DuelHud.tsx
@@ -0,0 +1,236 @@
+/**
+ * The duel's HUD, in the Verse's own look (thin lines, mono numerals,
+ * amber and red on near-black): the score and round clock top centre with
+ * the opponent's health under them, a spread-aware crosshair that kicks
+ * with the recoil and marks hits (headshots gold, the knockout red), arcs
+ * showing where hits came from, the commander's health, shield and roll top
+ * of the bottom left, the blaster's heat with the vent's gold window bottom
+ * right, call-outs (parry, perfect vent), the countdown and round banners,
+ * and the pause and result screens.
+ *
+ * The model comes from the controller once per rendered frame
+ * (`buildHudModel`); this component only draws it.
+ */
+import { useEffect, useState, type CSSProperties } from "react";
+import { fill } from "@/i18n";
+import { crosshairRadiusPx } from "../combat/camera";
+import type { DuelController, DuelPhase } from "../duel/duelController";
+import type { HudModel } from "../duel/duelHud";
+import type { StageRuntime } from "../runtime";
+import { DUEL_CONTROLS } from "./DuelPanel";
+import "./duel.css";
+
+interface Props {
+ runtime: StageRuntime;
+ controller: DuelController;
+ phase: DuelPhase;
+ /** The pointer is locked to the stage (mouse aim). */
+ locked: boolean;
+ t: (key: string) => string;
+ onResume: () => void;
+ onLeave: () => void;
+ onRematch: () => void;
+}
+
+interface Frame {
+ model: HudModel;
+ radius: number;
+ /** Crosshair offset by the recoil the view has not followed, px. */
+ ping: { x: number; y: number; alpha: number } | null;
+ onTarget: boolean;
+}
+
+function clock(seconds: number): string {
+ const s = Math.max(0, seconds);
+ return `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;
+}
+
+function Bar({ value, tone, segments = 10, label }: { value: number; tone: string; segments?: number; label?: string }) {
+ return (
+ <div className="verse-duel-bar" data-tone={tone} role="meter" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(value * 100)} aria-label={label}>
+ <i style={{ transform: `scaleX(${Math.max(0, Math.min(1, value))})` }} />
+ <span aria-hidden>{Array.from({ length: segments - 1 }, (_, k) => <b key={k} style={{ left: `${((k + 1) / segments) * 100}%` }} />)}</span>
+ </div>
+ );
+}
+
+export function DuelHud({ runtime, controller, phase, locked, t, onResume, onLeave, onRematch }: Props) {
+ const [frame, setFrame] = useState<Frame | null>(null);
+ const [hints, setHints] = useState(true);
+
+ useEffect(() => {
+ const refresh = () => {
+ const model = controller.hud();
+ if (!model) { setFrame(null); return; }
+ const vh = runtime.view.vp.height || 1;
+ const radius = crosshairRadiusPx(model.spreadDeg, controller.pose.fovDeg, vh);
+ let ping: Frame["ping"] = null;
+ if (model.ping) {
+ const at = runtime.toScreen(model.ping.x, controller.floorY + 1.3, model.ping.z);
+ if (at) ping = { x: at.x, y: at.y, alpha: model.ping.alpha };
+ }
+ setFrame({ model, radius, ping, onTarget: controller.aimTarget === "player" });
+ };
+ refresh();
+ runtime.afterFrame.add(refresh);
+ return () => { runtime.afterFrame.delete(refresh); };
+ }, [runtime, controller]);
+
+ // The key hints stay for the first seconds of a match.
+ useEffect(() => {
+ if (phase !== "running") return;
+ setHints(true);
+ const timer = setTimeout(() => setHints(false), 9000);
+ return () => clearTimeout(timer);
+ }, [phase, controller.result]);
+
+ const m = frame?.model;
+ const result = controller.result;
+ return (
+ <div className="verse-duel" data-phase={phase} aria-live="off">
+ {m && (
+ <>
+ <div className="verse-duel-hurt" style={{ opacity: Math.max(m.hurt * 0.9, m.lowHealth ? 0.35 : 0) }} data-low={m.lowHealth} aria-hidden />
+ <div className="verse-duel-top">
+ <div className="verse-duel-score">
+ <span className="verse-duel-side" data-side="own"><span className="verse-label">{t("verse.duel.hud.you")}</span><b className="verse-num">{m.myScore}</b></span>
+ <span className="verse-duel-round">
+ <span className="verse-label">{fill(t("verse.duel.hud.round"), { n: m.round })}</span>
+ <b className="verse-num">{m.timeLeft !== null ? clock(m.timeLeft) : "--:--"}</b>
+ <span className="verse-duel-pips" aria-hidden>
+ {Array.from({ length: m.roundsToWin }, (_, k) => <i key={`a${k}`} data-on={k < m.myScore} data-side="own" />)}
+ <em />
+ {Array.from({ length: m.roundsToWin }, (_, k) => <i key={`b${k}`} data-on={k < m.theirScore} data-side="foe" />)}
+ </span>
+ </span>
+ <span className="verse-duel-side" data-side="foe"><b className="verse-num">{m.theirScore}</b><span className="verse-label">{t("verse.duel.hud.bot")}</span></span>
+ </div>
+ <Bar value={m.enemyHealthFrac} tone="foe" label={t("verse.duel.hud.bot")} />
+ {m.surge && <div className="verse-duel-surge verse-label">{t("verse.duel.hud.surge")}</div>}
+ </div>
+
+ {/* Crosshair: four ticks at the spread, a centre dot; red over the opponent. */}
+ {phase === "running" && (
+ <div className="verse-duel-cross" data-target={frame!.onTarget} data-ads={m.ads > 0.5} data-blocked={!m.canFire}
+ style={{ "--r": `${Math.max(4, frame!.radius)}px` } as CSSProperties} aria-hidden>
+ <i data-d="u" /><i data-d="d" /><i data-d="l" /><i data-d="r" /><b />
+ {m.hitMarker && <span className="verse-duel-hit" data-kind={m.hitMarker.kind} style={{ opacity: m.hitMarker.alpha }}><s /><s /><s /><s /></span>}
+ </div>
+ )}
+ {m.damageArcs.map((a, k) => (
+ <div key={k} className="verse-duel-arc" style={{ transform: `translate(-50%, -50%) rotate(${a.angleDeg}deg)`, opacity: a.alpha }} aria-hidden><i /></div>
+ ))}
+ {m.callout && <div className="verse-duel-callout" data-key={m.callout.key} style={{ opacity: Math.min(1, m.callout.alpha * 1.6) }}>{t(`verse.duel.callout.${m.callout.key}`)}</div>}
+ {frame!.ping && <div className="verse-duel-ping" style={{ transform: `translate(${frame!.ping.x}px, ${frame!.ping.y}px)`, opacity: frame!.ping.alpha }} aria-hidden />}
+
+ {m.banner && phase !== "result" && (
+ <div className="verse-duel-banner" data-kind={m.banner.kind} data-outcome={m.banner.kind === "round" ? m.banner.outcome : undefined} role="status">
+ {m.banner.kind === "countdown" && <b className="verse-num" key={m.banner.value}>{m.banner.value}</b>}
+ {m.banner.kind === "fight" && <b>{t("verse.duel.hud.fight")}</b>}
+ {m.banner.kind === "round" && (
+ <>
+ <b>{t(`verse.duel.round.${m.banner.outcome}`)}</b>
+ <span className="verse-label">{t(`verse.duel.round.${m.banner.reason}`)}</span>
+ </>
+ )}
+ </div>
+ )}
+
+ <div className="verse-duel-vitals verse-panel">
+ <div className="verse-duel-row">
+ <span className="verse-label">{t("verse.duel.hud.health")}</span>
+ <b className="verse-num" data-low={m.lowHealth}>{m.health}</b>
+ </div>
+ <Bar value={m.healthFrac} tone={m.lowHealth ? "low" : "own"} label={t("verse.duel.hud.health")} />
+ <div className="verse-duel-row">
+ <span className="verse-label">{t("verse.duel.hud.shield")}</span>
+ <span className="verse-label" data-tone={m.shieldBroken ? "bad" : m.parryReady ? "good" : "dim"}>
+ {m.shieldBroken ? fill(t("verse.duel.hud.shield_down"), { s: m.shieldBrokenLeft.toFixed(1) }) : m.parryReady ? t("verse.duel.hud.parry_ready") : t("verse.duel.hud.parry_locked")}
+ </span>
+ </div>
+ <Bar value={m.shieldFrac} tone={m.shieldBroken ? "bad" : m.shieldUp ? "shield-up" : "shield"} label={t("verse.duel.hud.shield")} />
+ <div className="verse-duel-row verse-duel-roll" data-ready={m.dodgeReady}>
+ <span className="verse-label">{t("verse.duel.hud.roll")}</span>
+ <span className="verse-duel-cool"><i style={{ transform: `scaleX(${1 - m.dodgeCooldown})` }} /></span>
+ <kbd className="verse-key">{t("verse.duel.controls.space")}</kbd>
+ </div>
+ </div>
+
+ <div className="verse-duel-gun verse-panel" data-overheated={m.overheated} data-venting={m.venting}>
+ <div className="verse-duel-row">
+ <span className="verse-label">{t("verse.duel.hud.heat")}</span>
+ <span className="verse-label" data-tone={m.overheated ? "bad" : m.venting ? "gold" : "dim"}>
+ {m.overheated ? t("verse.duel.hud.overheated") : m.venting ? t("verse.duel.hud.venting") : `${Math.round(m.heat * 100)}%`}
+ </span>
+ </div>
+ <div className="verse-duel-heat" aria-hidden>
+ <i style={{ transform: `scaleX(${m.venting ? 1 - m.ventProgress : m.heat})` }} data-hot={m.heat > 0.75} />
+ {m.ventWindow && (
+ <span className="verse-duel-window" data-used={m.ventAttempted}
+ style={{ left: `${(1 - m.ventWindow[1]) * 100}%`, width: `${(m.ventWindow[1] - m.ventWindow[0]) * 100}%` }} />
+ )}
+ {m.venting && <em style={{ left: `${(1 - m.ventProgress) * 100}%` }} />}
+ </div>
+ <div className="verse-duel-row">
+ <span className="verse-label" data-tone={m.venting && !m.ventAttempted ? "gold" : "dim"}>
+ {m.venting && !m.ventAttempted ? t("verse.duel.hud.vent_hint") : t("verse.duel.hud.vent")}
+ </span>
+ <kbd className="verse-key">R</kbd>
+ </div>
+ </div>
+
+ {hints && phase === "running" && (
+ <div className="verse-duel-hints" aria-hidden>
+ {DUEL_CONTROLS.map(([key, action]) => (
+ <span key={action}><kbd className="verse-key">{key.startsWith("verse.") ? t(key) : key}</kbd>{t(action)}</span>
+ ))}
+ </div>
+ )}
+ {phase === "running" && !locked && (
+ <button type="button" className="verse-duel-aim verse-label" onClick={onResume}>{t("verse.duel.hud.click_to_aim")}</button>
+ )}
+ </>
+ )}
+
+ {phase === "paused" && (
+ <div className="verse-duel-overlay" role="dialog" aria-label={t("verse.duel.pause.title")}>
+ <div className="verse-duel-card verse-panel">
+ <div className="verse-dialog-title">{t("verse.duel.pause.title")}</div>
+ <p>{t("verse.duel.pause.hint")}</p>
+ <div className="verse-duel-actions">
+ <button type="button" className="verse-tool" data-primary onClick={onResume} autoFocus>{t("verse.duel.pause.resume")}</button>
+ <button type="button" className="verse-tool" onClick={onLeave}>{t("verse.duel.pause.leave")}</button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {phase === "result" && result && (
+ <div className="verse-duel-overlay" role="dialog" aria-label={t(`verse.duel.result.${result.outcome}`)}>
+ <div className="verse-duel-card verse-panel" data-outcome={result.outcome}>
+ <div className="verse-duel-outcome">{t(`verse.duel.result.${result.outcome}`)}</div>
+ <div className="verse-label">
+ {fill(t("verse.duel.result.rounds"), { me: result.rounds[0], them: result.rounds[1] })}
+ {" · "}
+ {fill(t("verse.duel.result.against"), { tier: t(`verse.duel.difficulty.${controller.difficulty}`) })}
+ </div>
+ {result.stats && (
+ <dl className="verse-duel-stats">
+ <div><dt className="verse-label">{t("verse.duel.result.accuracy")}</dt><dd className="verse-num">{result.stats.player.shots ? Math.round((100 * result.stats.player.hits) / result.stats.player.shots) : 0}%</dd></div>
+ <div><dt className="verse-label">{t("verse.duel.result.damage")}</dt><dd className="verse-num">{Math.round(result.stats.player.damageDealt)}</dd></div>
+ <div><dt className="verse-label">{t("verse.duel.result.headshots")}</dt><dd className="verse-num">{result.stats.player.headshots}</dd></div>
+ <div><dt className="verse-label">{t("verse.duel.result.parries")}</dt><dd className="verse-num">{result.stats.player.parries}</dd></div>
+ <div><dt className="verse-label">{t("verse.duel.result.blocks")}</dt><dd className="verse-num">{result.stats.player.blocks}</dd></div>
+ <div><dt className="verse-label">{t("verse.duel.result.perfect_vents")}</dt><dd className="verse-num">{result.stats.player.perfectVents}</dd></div>
+ </dl>
+ )}
+ <div className="verse-duel-actions">
+ <button type="button" className="verse-tool" data-primary onClick={onRematch} autoFocus>{t("verse.duel.result.rematch")}</button>
+ <button type="button" className="verse-tool" onClick={onLeave}>{t("verse.duel.result.leave")}</button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/DuelPanel.tsx b/dodaios/ui/web/frontend/src/components/society/verse/hud/DuelPanel.tsx
new file mode 100644
index 0000000000..2b8fe98966
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/DuelPanel.tsx
@@ -0,0 +1,68 @@
+/**
+ * The duel's start panel: what the duel is, the three opponents (normal,
+ * hard, elite) and the controls. Choosing an opponent starts the match at
+ * once (riding the turbolift down to Reactor Engineering first when the
+ * commander is elsewhere).
+ */
+import { useRef } from "react";
+import { DUEL_DIFFICULTIES, type DuelDifficulty } from "../duel/duelController";
+import { VerseDialog } from "./VerseDialog";
+import "./duel.css";
+
+interface Props {
+ t: (key: string) => string;
+ /** The commander is on another deck: the lift ride comes first. */
+ ride: boolean;
+ /** The difficulty chosen last time (focused first). */
+ last: DuelDifficulty;
+ onStart: (difficulty: DuelDifficulty) => void;
+ onClose: () => void;
+}
+
+/** The controls as [key label, action] pairs; key labels are i18n keys when they start with "verse.". */
+export const DUEL_CONTROLS: readonly (readonly [string, string])[] = [
+ ["W A S D", "verse.duel.controls.move"],
+ ["verse.duel.controls.shift", "verse.duel.controls.sprint"],
+ ["verse.duel.controls.lmb", "verse.duel.controls.fire"],
+ ["verse.duel.controls.rmb", "verse.duel.controls.ads"],
+ ["Q", "verse.duel.controls.shield"],
+ ["verse.duel.controls.space", "verse.duel.controls.dodge"],
+ ["R", "verse.duel.controls.vent"],
+ ["verse.duel.controls.esc", "verse.duel.controls.pause"],
+];
+
+export function DuelPanel({ t, ride, last, onStart, onClose }: Props) {
+ const first = useRef<HTMLButtonElement>(null);
+ return (
+ <VerseDialog title={t("verse.duel.title")} closeLabel={t("verse.card.close")} onClose={onClose} initialFocus={first} className="verse-duel-panel">
+ <p className="verse-duel-intro">{t("verse.duel.intro")}{ride ? ` ${t("verse.duel.ride")}` : ""}</p>
+ <div className="verse-duel-section verse-label">{t("verse.duel.choose")}</div>
+ {DUEL_DIFFICULTIES.map((d, i) => (
+ <button
+ key={d}
+ ref={d === last ? first : undefined}
+ type="button"
+ className="verse-lift-row verse-duel-tier"
+ data-tier={d}
+ onClick={() => onStart(d)}
+ >
+ <b>{String(i + 1).padStart(2, "0")}</b>
+ <span className="verse-lift-name">
+ <span>{t(`verse.duel.difficulty.${d}`)}</span>
+ <small>{t(`verse.duel.difficulty.${d}_about`)}</small>
+ </span>
+ <span className="verse-duel-pips" aria-hidden>{[0, 1, 2].map((k) => <i key={k} data-on={k <= i} />)}</span>
+ </button>
+ ))}
+ <div className="verse-duel-section verse-label">{t("verse.duel.controls.title")}</div>
+ <dl className="verse-duel-keys">
+ {DUEL_CONTROLS.map(([key, action]) => (
+ <div key={action}>
+ <dt><kbd className="verse-key">{key.startsWith("verse.") ? t(key) : key}</kbd></dt>
+ <dd>{t(action)}</dd>
+ </div>
+ ))}
+ </dl>
+ </VerseDialog>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/FloatingLabels.tsx b/dodaios/ui/web/frontend/src/components/society/verse/hud/FloatingLabels.tsx
index fc8d474dfa..5385612027 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/hud/FloatingLabels.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/FloatingLabels.tsx
@@ -1,8 +1,13 @@
/**
* Labels that ride on the scene: the name plate of the crew member under the
- * pointer (or selected), and the label of the station under the pointer.
- * React renders their text; their position is written straight into the DOM
- * after every frame, so a walking officer's plate never lags behind them.
+ * pointer (or selected), and the label of the station under the pointer (or
+ * within the commander's reach). React renders their text; their position is
+ * written straight into the DOM after every frame, so a walking officer's
+ * plate never lags behind them. They project through the view on screen
+ * (`runtime.toScreen`: the plate, or the eye-level camera); at eye level a
+ * label whose anchor is behind a wall, or behind the camera, is hidden, and
+ * the station within reach is offered as a prompt below the middle of the
+ * view, as games do.
*/
import { useEffect, useRef, type CSSProperties } from "react";
import type { StageRuntime } from "../runtime";
@@ -25,24 +30,61 @@ interface Props {
deck: Deck | null;
}
+/** Where a label element was put last (CSS px, rounded), so an unmoved label is not written again. */
+interface Placed { x: number; y: number; shown: boolean }
+
+const OFF = "translate(-9999px, -9999px)";
+
+/** Move a label to (x, y), or off screen when `shown` is false; writes the DOM only when that changes. */
+function put(el: HTMLElement, placed: WeakMap<HTMLElement, Placed>, shown: boolean, x: number, y: number): void {
+ let last = placed.get(el);
+ if (!last) { last = { x: NaN, y: NaN, shown: false }; placed.set(el, last); el.style.transform = OFF; }
+ const rx = Math.round(x);
+ const ry = Math.round(y);
+ if (shown === last.shown && (!shown || (rx === last.x && ry === last.y))) return;
+ last.shown = shown;
+ last.x = rx;
+ last.y = ry;
+ el.style.transform = shown ? `translate(${rx}px, ${ry}px)` : OFF;
+}
+
+/** Height of a station label above the point the commander stands at to use it, metres. */
+const STATION_LABEL_M = 1.2;
+/**
+ * At eye level the station within reach is offered as a prompt under the
+ * middle of the view (its spot is where the commander stands, so a label
+ * there would sit on their back): its anchor, as a fraction of the height.
+ */
+export const PROMPT_AT = 0.8;
+
export function FloatingLabels({ runtime, plates, station, deck }: Props) {
const plateRefs = useRef(new Map<string, HTMLDivElement>());
const stationRef = useRef<HTMLDivElement>(null);
const stationAt = useRef<Station | null>(null);
stationAt.current = station?.station ?? null;
+ /** The station is offered with its key (within the commander's reach), not pointed at. */
+ const keyed = useRef(false);
+ keyed.current = !!station?.key;
useEffect(() => {
+ const placed = new WeakMap<HTMLElement, Placed>();
+ const at = { x: 0, y: 0 };
+ // Projected through the view on screen; at eye level a label whose anchor a wall hides goes too.
const place = () => {
for (const [id, el] of plateRefs.current) {
const pose = runtime.poses.get(id);
- const at = pose ? runtime.toScreen(pose.x, pose.y + pose.height + 0.12, pose.z) : null;
- el.style.transform = at ? `translate(${Math.round(at.x)}px, ${Math.round(at.y)}px)` : "translate(-9999px, -9999px)";
+ const y = pose ? pose.y + pose.height + 0.12 : 0;
+ const shown = !!pose && !!runtime.toScreen(pose.x, y, pose.z, at) && runtime.inSight(pose.x, y, pose.z);
+ put(el, placed, shown, at.x, at.y);
}
const s = stationAt.current;
const el = stationRef.current;
- if (el) {
- const at = s ? runtime.toScreen(s.x, s.y + 1.2, s.z) : null;
- el.style.transform = at ? `translate(${Math.round(at.x)}px, ${Math.round(at.y)}px)` : "translate(-9999px, -9999px)";
+ if (el && s && runtime.eye && keyed.current) {
+ put(el, placed, true, runtime.view.vp.width / 2, runtime.view.vp.height * PROMPT_AT);
+ } else if (el) {
+ const y = s ? s.y + STATION_LABEL_M : 0;
+ const shown = !!s && !!runtime.toScreen(s.x, y, s.z, at) && runtime.inSight(s.x, y, s.z);
+ put(el, placed, shown, at.x, at.y);
}
};
runtime.afterFrame.add(place);
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/ViewSettingsPanel.tsx b/dodaios/ui/web/frontend/src/components/society/verse/hud/ViewSettingsPanel.tsx
new file mode 100644
index 0000000000..904d885292
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/ViewSettingsPanel.tsx
@@ -0,0 +1,104 @@
+/**
+ * The eye-level views' settings: mouse sensitivity, an inverted vertical
+ * axis, the field of view in third and in first person, and the render
+ * quality. Changes apply at once and stay in this
+ * browser (`viewSettings`).
+ */
+import { useId, useRef } from "react";
+import { fill } from "@/i18n";
+import { LOOK_SENSITIVITY, SHOULDER } from "../engine/realtime/shoulderRig";
+import { useViewSettings, type QualityChoice } from "../engine/realtime/viewSettings";
+import { VerseDialog } from "./VerseDialog";
+
+const QUALITIES: readonly QualityChoice[] = ["auto", "high", "low"];
+
+interface Props {
+ t: (key: string) => string;
+ /** The tier the eye-level view renders at now ("high" or "low"); empty while it is not on screen. */
+ tier: string;
+ onClose: () => void;
+}
+
+export function ViewSettingsPanel({ t, tier, onClose }: Props) {
+ const sensitivity = useViewSettings((s) => s.sensitivity);
+ const invertY = useViewSettings((s) => s.invertY);
+ const quality = useViewSettings((s) => s.quality);
+ const fovThird = useViewSettings((s) => s.fovThird);
+ const fovFirst = useViewSettings((s) => s.fovFirst);
+ const set = useViewSettings((s) => s.set);
+ const reset = useViewSettings((s) => s.reset);
+ const first = useRef<HTMLInputElement>(null);
+ const id = useId();
+ return (
+ <VerseDialog title={t("verse.settings.title")} closeLabel={t("verse.card.close")} onClose={onClose} className="verse-form" initialFocus={first}>
+ <div className="verse-form-body">
+ <div className="verse-field">
+ <label className="verse-setting-head" htmlFor={`${id}-sensitivity`}>
+ <span className="verse-label">{t("verse.settings.sensitivity")}</span>
+ <span className="verse-setting-value">{sensitivity.toFixed(2)}×</span>
+ </label>
+ <input
+ ref={first}
+ id={`${id}-sensitivity`}
+ type="range"
+ className="verse-range"
+ min={LOOK_SENSITIVITY.min}
+ max={LOOK_SENSITIVITY.max}
+ step={0.05}
+ value={sensitivity}
+ onChange={(e) => set({ sensitivity: Number(e.target.value) })}
+ />
+ </div>
+ <div className="verse-setting-row">
+ <span className="verse-label" id={`${id}-invert`}>{t("verse.settings.invert_y")}</span>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={invertY}
+ aria-labelledby={`${id}-invert`}
+ className="verse-switch"
+ onClick={() => set({ invertY: !invertY })}
+ >
+ <i aria-hidden />
+ </button>
+ </div>
+ {([["fovThird", fovThird, "verse.settings.fov_third"], ["fovFirst", fovFirst, "verse.settings.fov_first"]] as const).map(([key, value, label]) => (
+ <div className="verse-field" key={key}>
+ <label className="verse-setting-head" htmlFor={`${id}-${key}`}>
+ <span className="verse-label">{t(label)}</span>
+ <span className="verse-setting-value">{Math.round(value)}°</span>
+ </label>
+ <input
+ id={`${id}-${key}`}
+ type="range"
+ className="verse-range"
+ min={SHOULDER.minHfovDeg}
+ max={SHOULDER.maxHfovDeg}
+ step={1}
+ value={value}
+ onChange={(e) => set({ [key]: Number(e.target.value) })}
+ />
+ </div>
+ ))}
+ <div className="verse-field">
+ <span className="verse-label" id={`${id}-quality`}>{t("verse.settings.quality")}</span>
+ <div className="verse-seg" role="group" aria-labelledby={`${id}-quality`}>
+ {QUALITIES.map((q) => (
+ <button key={q} type="button" className="verse-btn" aria-pressed={quality === q} onClick={() => set({ quality: q })}>
+ {t(`verse.settings.quality_${q}`)}
+ </button>
+ ))}
+ </div>
+ <p className="verse-form-note">
+ {t("verse.settings.quality_note")}
+ {(tier === "high" || tier === "low") && <> {fill(t("verse.settings.quality_now"), { tier: t(`verse.settings.quality_${tier}`) })}</>}
+ </p>
+ </div>
+ <p className="verse-form-note">{t("verse.settings.mouse_lock")}</p>
+ </div>
+ <footer className="verse-form-foot">
+ <button type="button" className="verse-btn" onClick={reset}>{t("verse.settings.reset")}</button>
+ </footer>
+ </VerseDialog>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/duel.css b/dodaios/ui/web/frontend/src/components/society/verse/hud/duel.css
new file mode 100644
index 0000000000..e64cd7a09c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/duel.css
@@ -0,0 +1,284 @@
+/* The duel's HUD and start panel (hud/DuelHud.tsx, hud/DuelPanel.tsx), in the Verse HUD's tokens (verse.css). */
+
+/* Start panel. */
+.verse-duel-panel { width: min(480px, calc(100% - 32px)); }
+.verse-duel-intro { margin: 0; padding: 12px 14px; font-size: 12px; line-height: 1.5; color: var(--verse-ink-dim); border-bottom: 1px solid var(--verse-line); }
+.verse-duel-section { padding: 10px 14px 6px; }
+.verse-duel-tier[data-tier="elite"] b { color: var(--verse-red); }
+.verse-duel-tier[data-tier="hard"] b { color: var(--verse-amber); }
+.verse-duel-pips { display: inline-flex; gap: 3px; align-items: center; }
+.verse-duel-pips i { width: 10px; height: 4px; background: var(--verse-line-strong); }
+.verse-duel-pips i[data-on="true"] { background: var(--verse-amber); }
+.verse-duel-tier[data-tier="elite"] .verse-duel-pips i[data-on="true"] { background: var(--verse-red); }
+.verse-duel-keys { margin: 0; padding: 4px 14px 14px; display: grid; grid-template-columns: 1fr 1fr; gap: 6px 14px; }
+.verse-duel-keys div { display: flex; align-items: center; gap: 8px; min-width: 0; }
+.verse-duel-keys dt, .verse-duel-keys dd { margin: 0; }
+.verse-duel-keys dd { font-size: 11px; color: var(--verse-ink-dim); }
+.verse-duel-keys .verse-key { margin-left: 0; white-space: nowrap; }
+
+/* In the match: the whole HUD layer; only its buttons and cards take the pointer. */
+.verse-hud > .verse-duel { pointer-events: none; }
+.verse-duel { position: absolute; inset: 0; font-family: var(--verse-sans); color: var(--verse-ink); user-select: none; }
+.verse-duel button { pointer-events: auto; }
+
+.verse-duel-hurt {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 52%, rgba(160, 20, 12, 0.55) 100%);
+ transition: opacity 80ms linear;
+}
+.verse-duel-hurt[data-low="true"] { animation: verse-duel-pulse 1.1s ease-in-out infinite; }
+@keyframes verse-duel-pulse { 50% { filter: brightness(1.6); } }
+
+.verse-duel-top {
+ position: absolute;
+ top: 14px;
+ left: 50%;
+ transform: translateX(-50%);
+ width: min(420px, calc(100% - 32px));
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 6px;
+}
+.verse-duel-score {
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ gap: 14px;
+ padding: 6px 12px;
+ background: var(--verse-panel);
+ border: 1px solid var(--verse-line);
+ border-top: 2px solid var(--verse-red);
+}
+.verse-duel-side { display: flex; align-items: baseline; gap: 8px; }
+.verse-duel-side[data-side="foe"] { justify-content: flex-end; }
+.verse-duel-side b { font-size: 24px; font-weight: 400; line-height: 1; }
+.verse-duel-side[data-side="own"] b { color: var(--verse-amber); }
+.verse-duel-side[data-side="foe"] b { color: #e0483b; }
+.verse-duel-round { display: flex; flex-direction: column; align-items: center; gap: 2px; }
+.verse-duel-round b { font-size: 15px; font-weight: 400; }
+.verse-duel-round .verse-duel-pips em { width: 8px; }
+.verse-duel-round .verse-duel-pips i { width: 12px; height: 3px; }
+.verse-duel-round .verse-duel-pips i[data-side="foe"][data-on="true"] { background: #e0483b; }
+.verse-duel-surge {
+ align-self: center;
+ padding: 4px 10px;
+ color: #ffd2cc;
+ background: rgba(150, 24, 16, 0.55);
+ border: 1px solid rgba(196, 55, 45, 0.8);
+ animation: verse-duel-blink 1.5s steps(2, jump-none) infinite;
+}
+@keyframes verse-duel-blink { 50% { opacity: 0.55; } }
+
+/* Bars: a thin track with segment ticks; tones for own, foe, shield, low and broken. */
+.verse-duel-bar { position: relative; height: 6px; background: rgba(217, 222, 227, 0.08); border: 1px solid var(--verse-line); overflow: hidden; }
+.verse-duel-bar > i { position: absolute; inset: 0; transform-origin: left center; background: var(--verse-ink); transition: transform 90ms linear; }
+.verse-duel-bar > span b { position: absolute; top: 0; bottom: 0; width: 1px; background: rgba(5, 6, 7, 0.65); }
+.verse-duel-bar[data-tone="own"] > i { background: linear-gradient(90deg, #b8862b, var(--verse-amber)); }
+.verse-duel-bar[data-tone="foe"] > i { background: linear-gradient(90deg, #8f241c, #e0483b); }
+.verse-duel-bar[data-tone="low"] > i { background: linear-gradient(90deg, #8f241c, #ff5a45); }
+.verse-duel-bar[data-tone="shield"] > i { background: linear-gradient(90deg, #2c6f9e, #79c7ff); }
+.verse-duel-bar[data-tone="shield-up"] > i { background: linear-gradient(90deg, #5fb4ff, #d6efff); box-shadow: 0 0 10px rgba(121, 199, 255, 0.8); }
+.verse-duel-bar[data-tone="bad"] > i { background: rgba(196, 55, 45, 0.45); }
+.verse-duel-top .verse-duel-bar { height: 4px; }
+
+/* Crosshair. --r is the spread radius in px. */
+.verse-duel-cross { position: absolute; left: 50%; top: 50%; width: 0; height: 0; --c: rgba(236, 240, 244, 0.92); }
+.verse-duel-cross[data-target="true"] { --c: #ff4b3a; }
+.verse-duel-cross[data-blocked="true"] { --c: rgba(236, 240, 244, 0.35); }
+.verse-duel-cross > i {
+ position: absolute;
+ background: var(--c);
+ box-shadow: 0 0 0 1px rgba(5, 6, 7, 0.55);
+ transition: transform 60ms linear;
+}
+.verse-duel-cross > i[data-d="u"], .verse-duel-cross > i[data-d="d"] { width: 2px; height: 9px; left: -1px; }
+.verse-duel-cross > i[data-d="l"], .verse-duel-cross > i[data-d="r"] { width: 9px; height: 2px; top: -1px; }
+.verse-duel-cross > i[data-d="u"] { top: -9px; transform: translateY(calc(-1 * var(--r))); }
+.verse-duel-cross > i[data-d="d"] { top: 0; transform: translateY(var(--r)); }
+.verse-duel-cross > i[data-d="l"] { left: -9px; transform: translateX(calc(-1 * var(--r))); }
+.verse-duel-cross > i[data-d="r"] { left: 0; transform: translateX(var(--r)); }
+.verse-duel-cross[data-ads="true"] > i[data-d="u"], .verse-duel-cross[data-ads="true"] > i[data-d="d"] { height: 6px; }
+.verse-duel-cross[data-ads="true"] > i[data-d="l"], .verse-duel-cross[data-ads="true"] > i[data-d="r"] { width: 6px; }
+.verse-duel-cross > b {
+ position: absolute;
+ left: -2px;
+ top: -2px;
+ width: 4px;
+ height: 4px;
+ border-radius: 50%;
+ background: var(--c);
+ box-shadow: 0 0 0 1px rgba(5, 6, 7, 0.55);
+}
+/* Hit marker: four short diagonal strokes round the centre. */
+.verse-duel-hit { position: absolute; left: 0; top: 0; --h: #ffffff; }
+.verse-duel-hit[data-kind="head"] { --h: var(--verse-amber); }
+.verse-duel-hit[data-kind="kill"] { --h: #ff4b3a; }
+.verse-duel-hit s {
+ position: absolute;
+ left: -1px;
+ top: -4px;
+ width: 2px;
+ height: 8px;
+ background: var(--h);
+ box-shadow: 0 0 6px var(--h);
+}
+.verse-duel-hit[data-kind="kill"] s { height: 12px; top: -6px; }
+.verse-duel-hit s:nth-child(1) { transform: rotate(45deg) translateY(-12px); }
+.verse-duel-hit s:nth-child(2) { transform: rotate(135deg) translateY(-12px); }
+.verse-duel-hit s:nth-child(3) { transform: rotate(225deg) translateY(-12px); }
+.verse-duel-hit s:nth-child(4) { transform: rotate(315deg) translateY(-12px); }
+
+/* Where a hit came from: a red arc on a ring round the crosshair. */
+.verse-duel-arc { position: absolute; left: 50%; top: 50%; width: 220px; height: 220px; pointer-events: none; }
+.verse-duel-arc i {
+ position: absolute;
+ left: 50%;
+ top: 0;
+ width: 70px;
+ height: 22px;
+ margin-left: -35px;
+ border-top: 4px solid rgba(255, 70, 50, 0.95);
+ border-radius: 50% 50% 0 0 / 100% 100% 0 0;
+ filter: drop-shadow(0 0 6px rgba(255, 50, 30, 0.8));
+}
+
+.verse-duel-callout {
+ position: absolute;
+ left: 50%;
+ top: calc(50% + 46px);
+ transform: translateX(-50%);
+ font-size: 12px;
+ font-weight: 700;
+ letter-spacing: 0.22em;
+ text-transform: uppercase;
+ color: var(--verse-ink);
+ text-shadow: 0 0 10px rgba(0, 0, 0, 0.9);
+ white-space: nowrap;
+}
+.verse-duel-callout[data-key="parry"], .verse-duel-callout[data-key="perfect_vent"] { color: #ffe3a3; text-shadow: 0 0 12px rgba(214, 160, 60, 0.9); }
+.verse-duel-callout[data-key="parried"], .verse-duel-callout[data-key="overheat"],
+.verse-duel-callout[data-key="shield_break"], .verse-duel-callout[data-key="vent_miss"] { color: #ff8a7d; }
+
+.verse-duel-ping {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 22px;
+ height: 22px;
+ margin: -11px 0 0 -11px;
+ border: 2px solid #ff4b3a;
+ box-shadow: 0 0 12px rgba(255, 60, 40, 0.8);
+}
+.verse-duel-ping::after { content: ""; position: absolute; inset: 7px; background: #ff4b3a; }
+
+/* Countdown and round banners. */
+.verse-duel-banner {
+ position: absolute;
+ left: 50%;
+ top: 34%;
+ transform: translate(-50%, -50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ text-align: center;
+ pointer-events: none;
+}
+.verse-duel-banner b {
+ font-size: 34px;
+ font-weight: 700;
+ letter-spacing: 0.3em;
+ text-transform: uppercase;
+ text-shadow: 0 0 18px rgba(0, 0, 0, 0.85);
+ animation: verse-duel-in 260ms ease-out;
+}
+.verse-duel-banner[data-kind="countdown"] b { font-size: 64px; font-weight: 300; letter-spacing: 0; color: var(--verse-amber); }
+.verse-duel-banner[data-kind="fight"] b { color: var(--verse-amber); }
+.verse-duel-banner[data-outcome="won"] b { color: var(--verse-amber); }
+.verse-duel-banner[data-outcome="lost"] b { color: #ff5a45; }
+@keyframes verse-duel-in { from { opacity: 0; transform: scale(1.25); } to { opacity: 1; transform: none; } }
+
+/* Vitals bottom left, the blaster bottom right. */
+.verse-duel-vitals, .verse-duel-gun {
+ position: absolute;
+ bottom: 16px;
+ width: 240px;
+ max-width: calc(50% - 24px);
+ padding: 10px 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+.verse-duel-vitals { left: 16px; border-left: 2px solid var(--verse-amber); }
+.verse-duel-gun { right: 16px; border-right: 2px solid var(--verse-amber); }
+.verse-duel-gun[data-overheated="true"] { border-right-color: var(--verse-red); animation: verse-duel-blink 0.4s steps(2, jump-none) infinite; }
+.verse-duel-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+.verse-duel-row .verse-num { font-size: 22px; line-height: 1; }
+.verse-duel-row .verse-num[data-low="true"] { color: #ff5a45; }
+.verse-duel-row [data-tone="good"] { color: #9ad4ff; }
+.verse-duel-row [data-tone="bad"] { color: #ff8a7d; }
+.verse-duel-row [data-tone="gold"] { color: #ffd27a; }
+.verse-duel-roll .verse-duel-cool { flex: 1; height: 3px; background: rgba(217, 222, 227, 0.1); overflow: hidden; }
+.verse-duel-roll .verse-duel-cool i { display: block; height: 100%; background: var(--verse-ink-dim); transform-origin: left; }
+.verse-duel-roll[data-ready="true"] .verse-duel-cool i { background: var(--verse-ink); }
+.verse-duel-roll .verse-key { margin-left: 0; }
+.verse-duel-heat { position: relative; height: 10px; background: rgba(217, 222, 227, 0.08); border: 1px solid var(--verse-line); overflow: hidden; }
+.verse-duel-heat > i { position: absolute; inset: 0; transform-origin: left; background: linear-gradient(90deg, #6fb8e8, #d6a03c 65%, #e0483b); transition: transform 60ms linear; }
+.verse-duel-heat > i[data-hot="true"] { box-shadow: 0 0 10px rgba(224, 72, 59, 0.8); }
+.verse-duel-gun[data-venting="true"] .verse-duel-heat > i { background: rgba(217, 222, 227, 0.35); transition: none; }
+.verse-duel-window { position: absolute; top: 0; bottom: 0; background: rgba(214, 160, 60, 0.55); border-left: 1px solid #ffd27a; border-right: 1px solid #ffd27a; }
+.verse-duel-window[data-used="true"] { background: rgba(217, 222, 227, 0.12); border-color: var(--verse-line-strong); }
+.verse-duel-heat > em { position: absolute; top: -2px; bottom: -2px; width: 2px; margin-left: -1px; background: #ffffff; box-shadow: 0 0 6px #ffffff; }
+
+.verse-duel-hints {
+ position: absolute;
+ left: 50%;
+ bottom: 18px;
+ transform: translateX(-50%);
+ width: max-content;
+ max-width: calc(100% - 560px);
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 6px 14px;
+ font-size: 11px;
+ color: var(--verse-ink-dim);
+ text-shadow: 0 0 6px rgba(0, 0, 0, 0.9);
+}
+.verse-duel-hints span { display: inline-flex; align-items: center; gap: 6px; }
+.verse-duel-hints .verse-key { margin-left: 0; }
+@media (max-width: 900px) { .verse-duel-hints { display: none; } }
+
+.verse-duel-aim {
+ position: absolute;
+ left: 50%;
+ top: calc(50% + 120px);
+ transform: translateX(-50%);
+ padding: 6px 12px;
+ color: var(--verse-ink);
+ background: var(--verse-panel);
+ border: 1px solid var(--verse-amber);
+ cursor: pointer;
+}
+
+/* Pause and result. */
+.verse-duel-overlay { position: absolute; inset: 0; display: grid; place-items: center; background: rgba(3, 4, 5, 0.55); pointer-events: auto; }
+.verse-duel-card { width: min(420px, calc(100% - 32px)); padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; background: var(--verse-panel-solid); border-top: 2px solid var(--verse-red); }
+.verse-duel-card p { margin: 0; font-size: 12px; color: var(--verse-ink-dim); }
+.verse-duel-card[data-outcome="won"] { border-top-color: var(--verse-amber); }
+.verse-duel-outcome { font-size: 30px; font-weight: 700; letter-spacing: 0.26em; text-transform: uppercase; }
+.verse-duel-card[data-outcome="won"] .verse-duel-outcome { color: var(--verse-amber); }
+.verse-duel-card[data-outcome="lost"] .verse-duel-outcome { color: #ff5a45; }
+.verse-duel-stats { margin: 4px 0 0; display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
+.verse-duel-stats div { display: flex; flex-direction: column; gap: 3px; padding-top: 6px; border-top: 1px solid var(--verse-line); }
+.verse-duel-stats dt, .verse-duel-stats dd { margin: 0; }
+.verse-duel-stats dd { font-size: 18px; color: var(--verse-ink); }
+.verse-duel-actions { display: flex; margin-top: 6px; }
+.verse-duel-actions .verse-tool[data-primary] { color: var(--verse-ink); border-color: var(--verse-amber); }
+
+@media (prefers-reduced-motion: reduce) {
+ .verse-duel-banner b, .verse-duel-surge, .verse-duel-hurt[data-low="true"], .verse-duel-gun[data-overheated="true"] { animation: none; }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/hud/duelHud.test.tsx b/dodaios/ui/web/frontend/src/components/society/verse/hud/duelHud.test.tsx
new file mode 100644
index 0000000000..55cb5219b7
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/hud/duelHud.test.tsx
@@ -0,0 +1,103 @@
+/**
+ * The duel's HUD and start panel: choosing an opponent starts that duel,
+ * the in-match HUD shows the score and the vitals, the pause screen resumes
+ * or leaves, the result screen offers a rematch or the way back.
+ */
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createLocalDuel } from "../combat/session";
+import { DuelController } from "../duel/duelController";
+import { StageRuntime } from "../runtime";
+import { DuelHud } from "./DuelHud";
+import { DuelPanel } from "./DuelPanel";
+
+const t = (key: string) => key;
+
+afterEach(cleanup);
+
+function setup() {
+ const runtime = new StageRuntime();
+ runtime.view.resize({ width: 1600, height: 900, dpr: 1 });
+ const clock = { now: 0 };
+ const controller = new DuelController({
+ sound: null,
+ now: () => clock.now,
+ create: (o) => createLocalDuel({ ...o, seed: 5, config: { roundsToWin: 1, maxRounds: 1 } }),
+ });
+ const frame = (n: number) => {
+ for (let i = 0; i < n; i++) {
+ clock.now += 1000 / 60;
+ controller.frame(1000 / 60);
+ for (const fn of runtime.afterFrame) fn();
+ }
+ };
+ return { runtime, controller, frame };
+}
+
+describe("duel start panel", () => {
+ it("starts the chosen difficulty and says when the lift ride comes first", () => {
+ const onStart = vi.fn();
+ render(<DuelPanel t={t} ride last="hard" onStart={onStart} onClose={() => undefined} />);
+ expect(screen.getByText(/verse\.duel\.ride/)).toBeTruthy();
+ fireEvent.click(screen.getByText("verse.duel.difficulty.elite"));
+ expect(onStart).toHaveBeenCalledWith("elite");
+ });
+
+ it("lists every control", () => {
+ render(<DuelPanel t={t} ride={false} last="normal" onStart={() => undefined} onClose={() => undefined} />);
+ for (const key of ["fire", "ads", "shield", "dodge", "vent", "pause"]) expect(screen.getByText(`verse.duel.controls.${key}`)).toBeTruthy();
+ expect(screen.queryByText(/verse\.duel\.ride/)).toBeNull();
+ });
+});
+
+describe("duel HUD", () => {
+ it("draws the score, the vitals and the countdown while the match runs", () => {
+ const { runtime, controller, frame } = setup();
+ controller.start("normal");
+ render(<DuelHud runtime={runtime} controller={controller} phase="running" locked t={t} onResume={() => undefined} onLeave={() => undefined} onRematch={() => undefined} />);
+ act(() => frame(20));
+ expect(screen.getByText("verse.duel.hud.you")).toBeTruthy();
+ expect(screen.getByText("verse.duel.hud.health")).toBeTruthy();
+ expect(screen.getByText("verse.duel.hud.heat")).toBeTruthy();
+ expect(document.querySelector(".verse-duel-banner[data-kind='countdown']")).toBeTruthy();
+ expect(document.querySelector(".verse-duel-cross")).toBeTruthy();
+ // Without the pointer lock the HUD offers to take it.
+ cleanup();
+ const onResume = vi.fn();
+ render(<DuelHud runtime={runtime} controller={controller} phase="running" locked={false} t={t} onResume={onResume} onLeave={() => undefined} onRematch={() => undefined} />);
+ act(() => frame(1));
+ fireEvent.click(screen.getByText("verse.duel.hud.click_to_aim"));
+ expect(onResume).toHaveBeenCalled();
+ });
+
+ it("pauses with resume and leave", () => {
+ const { runtime, controller, frame } = setup();
+ controller.start("hard");
+ act(() => frame(5));
+ controller.pause();
+ const onResume = vi.fn();
+ const onLeave = vi.fn();
+ render(<DuelHud runtime={runtime} controller={controller} phase="paused" locked={false} t={t} onResume={onResume} onLeave={onLeave} onRematch={() => undefined} />);
+ fireEvent.click(screen.getByText("verse.duel.pause.resume"));
+ fireEvent.click(screen.getByText("verse.duel.pause.leave"));
+ expect(onResume).toHaveBeenCalled();
+ expect(onLeave).toHaveBeenCalled();
+ });
+
+ it("shows the result with stats, a rematch and the way back", () => {
+ const { runtime, controller, frame } = setup();
+ controller.start("elite");
+ let n = 0;
+ while (controller.phase === "running" && n < 60 * 120) { frame(1); n++; }
+ expect(controller.phase).toBe("result");
+ const onRematch = vi.fn();
+ const onLeave = vi.fn();
+ render(<DuelHud runtime={runtime} controller={controller} phase="result" locked={false} t={t} onResume={() => undefined} onLeave={onLeave} onRematch={onRematch} />);
+ expect(screen.getByText("verse.duel.result.lost")).toBeTruthy();
+ expect(screen.getByText("verse.duel.result.accuracy")).toBeTruthy();
+ fireEvent.click(screen.getByText("verse.duel.result.rematch"));
+ fireEvent.click(screen.getByText("verse.duel.result.leave"));
+ expect(onRematch).toHaveBeenCalled();
+ expect(onLeave).toHaveBeenCalled();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/life/control.ts b/dodaios/ui/web/frontend/src/components/society/verse/life/control.ts
index 30880f3bb3..6fdda20c88 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/life/control.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/life/control.ts
@@ -7,9 +7,11 @@
* - bird's-eye (`overview`): the camera pulls back over the whole deck and
* the movement keys pan it, as in a map.
*
- * Clicking the floor sends the commander walking in both. The keys are read
- * screen-relative: the plate camera looks toward −Z, so "up" is −Z and
- * "right" is +X. Pure apart from the held-key state.
+ * Clicking the floor sends the commander walking in both. On the plate the
+ * keys are read screen-relative: the plate camera looks toward −Z, so "up"
+ * is −Z and "right" is +X; in the eye-level view they are read relative to
+ * the camera behind the commander (`directionFrom`). Pure apart from the
+ * held-key state.
*/
import type { Station } from "../content/deck";
import type { PanKey } from "../engine/viewController";
@@ -41,23 +43,69 @@ export class CommanderControl {
this.run = false;
}
- /** The wanted walking direction on the floor, unit length, or null when no movement key is held (or they cancel out). */
- direction(): Point | null {
- const x = (this.keys.has("right") ? 1 : 0) - (this.keys.has("left") ? 1 : 0);
- const z = (this.keys.has("down") ? 1 : 0) - (this.keys.has("up") ? 1 : 0);
+ /** The held keys as screen axes: x right (+1) / left (−1), z down or toward the camera (+1) / up or away (−1). */
+ axes(): { x: number; z: number } {
+ return { x: this.axisX(), z: this.axisZ() };
+ }
+
+ private axisX(): number {
+ return (this.keys.has("right") ? 1 : 0) - (this.keys.has("left") ? 1 : 0);
+ }
+
+ private axisZ(): number {
+ return (this.keys.has("down") ? 1 : 0) - (this.keys.has("up") ? 1 : 0);
+ }
+
+ /**
+ * The wanted walking direction on the floor, unit length, or null when no
+ * movement key is held (or they cancel out); written into `out` when given.
+ */
+ direction(out?: Point): Point | null {
+ const x = this.axisX();
+ const z = this.axisZ();
if (x === 0 && z === 0) return null;
const n = Math.hypot(x, z);
- return { x: x / n, z: z / n };
+ const o = out ?? { x: 0, z: 0 };
+ o.x = x / n;
+ o.z = z / n;
+ return o;
}
+
+ /**
+ * The eye-level view: the held keys relative to the camera (W walks away
+ * from it), unit length or null; written into `out` when given (the frame
+ * loop allocates nothing).
+ */
+ directionFrom(camera: CameraFrame, out?: Point): Point | null {
+ return camera.walkDirection(this.axisX(), this.axisZ(), out);
+ }
+}
+
+/** A camera that turns screen keys into a floor direction (the eye-level view's shoulder rig). */
+export interface CameraFrame {
+ walkDirection(ix: number, iz: number, out?: Point): Point | null;
}
-/** The station nearest to (x, z) within reach, or null. */
-export function stationWithin(stations: readonly Station[], x: number, z: number, reach = STATION_REACH_M): Station | null {
+/**
+ * The station within reach of (x, z), or null: the nearest one, or, given
+ * the direction the person looks along (`facing`, unit, on the floor), the
+ * one most in front of them, so the use key works what they see when two
+ * are in reach. A station straight behind counts as twice as far. Pure.
+ */
+export function stationWithin(
+ stations: readonly Station[], x: number, z: number, reach = STATION_REACH_M, facing?: Point | null,
+): Station | null {
let best: Station | null = null;
- let bestD = reach;
+ let bestScore = Infinity;
for (const s of stations) {
- const d = Math.hypot(s.x - x, s.z - z);
- if (d <= bestD) { bestD = d; best = s; }
+ const dx = s.x - x;
+ const dz = s.z - z;
+ const d = Math.hypot(dx, dz);
+ if (d > reach) continue;
+ // One under the commander's feet counts as in front.
+ const cos = facing && d > 0.3 ? (dx * facing.x + dz * facing.z) / d : 1;
+ const score = d * (1.5 - 0.5 * cos);
+ if (score < bestScore) { bestScore = score; best = s; }
}
return best;
}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/runtime.ts b/dodaios/ui/web/frontend/src/components/society/verse/runtime.ts
index 98c62207fc..0b03196b60 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/runtime.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/runtime.ts
@@ -4,11 +4,18 @@
* actor stands, the frame statistics. One instance per mounted stage (the
* Agents view and the IDE side panel each have their own), handed to the
* scene and the HUD by reference.
+ *
+ * Two views share it: the plate (the deck's photograph, bird's-eye and the
+ * compact panel) and, on decks exported for it, the eye-level 3D view behind
+ * the commander's shoulder (`eye`, set while that view is on screen).
*/
+import { DoubleSide, Ray, Raycaster, Vector2, Vector3, type PerspectiveCamera } from "three";
+import type { MeshBVH } from "three-mesh-bvh";
import type { Deck } from "./content/deck";
import { worldToPlate } from "./engine/plateMath";
import { plateToScreen } from "./engine/view";
import { ViewController } from "./engine/viewController";
+import { ShoulderRig, type SegmentTest, type Vec3 } from "./engine/realtime/shoulderRig";
import { CommanderControl } from "./life/control";
/** Where a body is; updated in place every frame. */
@@ -17,6 +24,8 @@ export interface ActorPose {
x: number;
y: number;
z: number;
+ /** Facing, radians about +Y (0 faces +Z). */
+ yaw: number;
/** Height of the head above the feet, metres (name plates sit above it). */
height: number;
moving: boolean;
@@ -31,26 +40,114 @@ export interface FrameStats {
cpuMs: number;
tiles: number;
tilesLoading: number;
- /** The plate level the view streams: "overview", "M4", "M2" or "L0". */
+ /** The plate level the view streams: "overview", "M4", "M2" or "L0"; "3D" in the eye-level view. */
plateLevel: string;
actors: number;
+ /** The eye-level view's quality tier ("high", "low"), empty on the plate. */
+ tier: string;
}
+/** The eye-level view while it is on screen: its camera and the deck's collision. */
+export interface EyeView {
+ camera: PerspectiveCamera;
+ collider: MeshBVH | null;
+ /** Segment test against the deck's collision (first hit as a fraction of the segment), when there is collision. */
+ test?: SegmentTest | null;
+}
+
+/** A camera another mode drives (the duel's shoulder camera): world position, a point it looks at, vertical field of view. */
+export interface CameraOverride {
+ position: Vec3;
+ target: Vec3;
+ fovDeg: number;
+}
+
+/** A screen point (CSS px). */
+export interface ScreenPoint { x: number; y: number }
+
+/**
+ * Geometry this close in front of a point (metres) still counts as seeing it:
+ * a name plate on a head against a wall, a station label above a console.
+ */
+export const SIGHT_SLACK_M = 0.25;
+
export class StageRuntime {
readonly view = new ViewController();
/** Third person or bird's-eye, and the movement keys held for the commander. */
readonly control = new CommanderControl();
+ /** The over-the-shoulder camera of the eye-level view (kept across view switches). */
+ readonly shoulder = new ShoulderRig();
deck: Deck | null = null;
+ /** The eye-level view, while it is the one on screen. */
+ eye: EyeView | null = null;
+ /** The eye-level camera is so close behind the commander (a wall pushed it in) that their body would fill the frame. */
+ commanderHidden = false;
+ /** While set, the eye-level view renders from this camera instead of the shoulder rig (a duel). */
+ cameraOverride: CameraOverride | null = null;
+ /** A duel holds the commander: the deck neither walks nor shows their usual body. */
+ duelActive = false;
+ /** The duel's hall while a duel runs: crew standing in it are not drawn (nobody walks into the line of fire). */
+ duelArea: { x0: number; x1: number; z0: number; z1: number } | null = null;
+ /** Put the commander here on the next frame (a duel ended), snapped onto the deck's nav grid. */
+ placeCommander: { x: number; z: number; yaw: number } | null = null;
/** Live poses of every actor on the deck, crew and commander alike, by id. */
readonly poses = new Map<string, ActorPose>();
- readonly stats: FrameStats = { drawCalls: 0, triangles: 0, frameMs: 0, cpuMs: 0, tiles: 0, tilesLoading: 0, plateLevel: "overview", actors: 0 };
+ readonly stats: FrameStats = { drawCalls: 0, triangles: 0, frameMs: 0, cpuMs: 0, tiles: 0, tilesLoading: 0, plateLevel: "overview", actors: 0, tier: "" };
/** Called after each rendered frame (the HUD moves its plates here). */
readonly afterFrame = new Set<() => void>();
+ private readonly projected = new Vector3();
+ private readonly raycaster = new Raycaster();
+ private readonly ndc = new Vector2();
+ private readonly sight = new Ray();
- /** Screen position (CSS px) of a world point under the current view. */
- toScreen(x: number, y: number, z: number): { x: number; y: number } | null {
+ /**
+ * Screen position (CSS px) of a world point under the view on screen: the
+ * eye-level camera's perspective or the plate's projection. Null when the
+ * point is behind the eye-level camera (or nearer than its near plane).
+ * Written into `out` when given, so per-frame callers allocate nothing.
+ */
+ toScreen(x: number, y: number, z: number, out?: ScreenPoint): ScreenPoint | null {
if (!this.deck) return null;
+ const o = out ?? { x: 0, y: 0 };
+ if (this.eye) {
+ const p = this.projected.set(x, y, z).project(this.eye.camera);
+ if (!(p.z >= -1 && p.z <= 1)) return null;
+ o.x = ((p.x + 1) / 2) * this.view.vp.width;
+ o.y = ((1 - p.y) / 2) * this.view.vp.height;
+ return o;
+ }
const p = worldToPlate(this.deck.camera, x, y, z);
- return plateToScreen(this.view.current, this.view.vp, p.u, p.v);
+ const s = plateToScreen(this.view.current, this.view.vp, p.u, p.v);
+ o.x = s.x;
+ o.y = s.y;
+ return o;
+ }
+
+ /**
+ * The eye-level camera sees the world point: none of the deck's geometry
+ * lies on the line between them (up to `slack` short of the point). Always
+ * true on the plate, where labels ride over the photograph, and while the
+ * deck has no collision geometry.
+ */
+ inSight(x: number, y: number, z: number, slack = SIGHT_SLACK_M): boolean {
+ const eye = this.eye;
+ if (!eye?.collider) return true;
+ const from = eye.camera.position;
+ const ray = this.sight;
+ ray.origin.copy(from);
+ ray.direction.set(x - from.x, y - from.y, z - from.z);
+ const length = ray.direction.length();
+ if (length <= slack + 1e-3) return true;
+ ray.direction.multiplyScalar(1 / length);
+ return !eye.collider.raycastFirst(ray, DoubleSide, 0, length - slack);
+ }
+
+ /** The eye-level camera's ray through a screen point (CSS px), or null on the plate. */
+ ray(sx: number, sy: number): Raycaster | null {
+ if (!this.eye) return null;
+ const { width, height } = this.view.vp;
+ this.ndc.set((sx / Math.max(1, width)) * 2 - 1, 1 - (sy / Math.max(1, height)) * 2);
+ this.raycaster.setFromCamera(this.ndc, this.eye.camera);
+ return this.raycaster;
}
}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/testing/syntheticDeck.ts b/dodaios/ui/web/frontend/src/components/society/verse/testing/syntheticDeck.ts
index 083a50fd11..d43b33d15f 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/testing/syntheticDeck.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/testing/syntheticDeck.ts
@@ -110,5 +110,6 @@ export function syntheticDeck(): Deck {
],
rooms: [],
probes: [],
+ realtime: null,
};
}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/verse.css b/dodaios/ui/web/frontend/src/components/society/verse/verse.css
index c150c6c695..cd742672cc 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/verse.css
+++ b/dodaios/ui/web/frontend/src/components/society/verse/verse.css
@@ -409,3 +409,106 @@
.verse-form-note { margin: 0; font-size: 12px; color: var(--verse-ink-dim); }
.verse-form-foot { display: flex; justify-content: flex-end; gap: 0; padding: 0 14px 14px; }
.verse-btn:disabled { opacity: 0.45; cursor: default; }
+
+/* The view switch on the tool rail: bird's-eye, third and first person side by side; the one on screen pressed and
+ named, the others an icon and their key (the name is in the tooltip). */
+.verse-view-switch { display: flex; }
+.verse-view-switch + .verse-tool { border-left: none; }
+.verse-view-switch .verse-tool[aria-pressed="false"] .verse-tool-text { display: none; }
+.verse-view-switch .verse-tool:disabled { opacity: 0.4; cursor: default; }
+.verse-view-switch .verse-tool:disabled:hover { color: var(--verse-ink-dim); border-color: var(--verse-line); }
+
+/* Shooter look (third and first person): a small mark in the middle of the view; the left button or E works what is
+ under it. Dimmer while the mouse is free, amber over something it can work. */
+.verse-reticle {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 14px;
+ height: 14px;
+ margin: -7px 0 0 -7px;
+ pointer-events: none;
+ border: 1px solid rgba(217, 222, 227, 0.55);
+ border-radius: 50%;
+ box-shadow: 0 0 0 1px rgba(5, 6, 7, 0.45);
+}
+.verse-reticle::after {
+ content: "";
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 2px;
+ height: 2px;
+ margin: -1px 0 0 -1px;
+ background: var(--verse-ink);
+}
+.verse-reticle[data-locked="false"] { opacity: 0.45; }
+.verse-reticle[data-on] { border-color: var(--verse-amber); }
+.verse-reticle[data-on]::after { background: var(--verse-amber); }
+
+/* With the mouse free in third or first person: how to take it back. */
+.verse-look-hint {
+ position: absolute;
+ left: 50%;
+ top: calc(50% + 22px);
+ transform: translateX(-50%);
+ padding: 4px 10px;
+ pointer-events: none;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ white-space: nowrap;
+ color: var(--verse-ink-dim);
+ background: var(--verse-panel);
+ border: 1px solid var(--verse-line);
+}
+
+/* View settings. */
+.verse-setting-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
+.verse-setting-value { font-family: var(--verse-mono); font-size: 11px; color: var(--verse-ink); font-variant-numeric: tabular-nums; }
+.verse-setting-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
+
+.verse-range {
+ width: 100%;
+ height: 18px;
+ margin: 0;
+ background: transparent;
+ accent-color: var(--verse-amber);
+ cursor: pointer;
+}
+.verse-range:focus-visible { outline: 1px solid var(--verse-amber); outline-offset: 2px; }
+
+.verse-switch {
+ position: relative;
+ flex: none;
+ width: 34px;
+ height: 18px;
+ padding: 0;
+ background: transparent;
+ border: 1px solid var(--verse-line-strong);
+ border-radius: 0;
+ cursor: pointer;
+}
+.verse-switch i {
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ width: 10px;
+ height: 10px;
+ background: var(--verse-ink-dim);
+ transition: transform 120ms ease;
+}
+.verse-switch[aria-checked="true"] { border-color: var(--verse-amber); }
+.verse-switch[aria-checked="true"] i { transform: translateX(16px); background: var(--verse-amber); }
+.verse-switch:focus-visible { outline: 1px solid var(--verse-amber); outline-offset: 1px; }
+
+.verse-seg { display: flex; }
+.verse-seg .verse-btn { flex: 1; color: var(--verse-ink-dim); }
+.verse-seg .verse-btn[aria-pressed="true"] { color: var(--verse-ink); border-color: var(--verse-amber); box-shadow: inset 0 -2px 0 var(--verse-amber); }
+.verse-seg .verse-btn + .verse-btn { border-left: 1px solid var(--verse-line-strong); margin-left: -1px; }
+.verse-seg .verse-btn[aria-pressed="true"] { position: relative; z-index: 1; border-left-color: var(--verse-amber); }
+
+@media (prefers-reduced-motion: reduce) {
+ .verse-switch i { transition: none; }
+}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.de.json
index d32b900057..8e6fe4e8cb 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.de.json
@@ -5,7 +5,8 @@
"loading": "Deck wird geladen",
"unavailable": "Das Schiff braucht WebGL, das dieses Fenster gerade nicht starten kann.",
"deck_missing": "Dieses Deck ist noch nicht gebaut.",
- "help": "Third Person: WASD oder Pfeiltasten steuern den Kommandanten, Shift läuft schneller, E benutzt die Station in Reichweite. V schaltet in die Vogelperspektive und zurück. Ziehen verschiebt die Ansicht, Scrollen zoomt. Ein Klick auf das Deck schickt dich dorthin, ein Klick auf ein Crewmitglied öffnet seine Akte."
+ "help": "Third Person: WASD oder Pfeiltasten steuern den Kommandanten, Shift läuft schneller, E benutzt die Station in Reichweite. 1, 2 und 3 wählen Vogelperspektive, Third Person oder Ego-Perspektive; V schaltet der Reihe nach durch. Ziehen verschiebt die Ansicht, Scrollen zoomt. Ein Klick auf das Deck schickt dich dorthin, ein Klick auf ein Crewmitglied öffnet seine Akte.",
+ "help_eye": "Third Person und Ego-Perspektive steuern sich wie ein Shooter: Ein Klick in die Ansicht fängt die Maus, Bewegen dreht die Kamera, Esc gibt sie frei. WASD läuft relativ zur Blickrichtung, Shift läuft schneller; die linke Maustaste oder E benutzt, worauf das Fadenkreuz zeigt (ein Crewmitglied, eine Station), sonst benutzt E die Station in Reichweite. Scrollen holt die Kamera näher heran oder weiter weg: ganz heran ist die Ego-Perspektive, wieder herausscrollen kehrt zurück. 1, 2 und 3 wählen Vogelperspektive, Third Person oder Ego-Perspektive; V schaltet der Reihe nach durch. Der Einstellungsknopf in der Werkzeugleiste regelt Mausempfindlichkeit, umgekehrte Achse, Sichtfeld und Qualität."
},
"deck": {
"label": "Deck {n}",
@@ -90,10 +91,32 @@
"elsewhere": "Woanders an Bord"
},
"tools": {
+ "view": "Ansicht",
+ "follow": "Third Person",
"overview": "Vogelperspektive",
"lift": "Turbolift",
"commander": "Kommandant",
- "help": "Hilfe"
+ "settings": "Ansichtseinstellungen",
+ "help": "Hilfe",
+ "duel": "Duell",
+ "first": "Ego-Perspektive",
+ "first_unavailable": "Die Ego-Perspektive braucht die 3D-Szene dieses Decks auf der großen Bühne.",
+ "click_to_look": "Klicken zum Umsehen"
+ },
+ "settings": {
+ "title": "Ansichtseinstellungen",
+ "sensitivity": "Mausempfindlichkeit",
+ "invert_y": "Vertikale Mausachse umkehren",
+ "quality": "Grafikqualität",
+ "quality_auto": "Automatisch",
+ "quality_high": "Hoch",
+ "quality_low": "Niedrig",
+ "quality_note": "Automatisch startet hoch und senkt die Qualität, wenn die Grafikkarte keine 45 Bilder pro Sekunde schafft.",
+ "quality_now": "Aktuell: {tier}.",
+ "mouse_lock": "In Third Person und Ego-Perspektive fängt ein Klick in die Ansicht die Maus: Bewegen dreht die Kamera, die linke Maustaste benutzt, worauf das Fadenkreuz zeigt. Esc gibt sie frei; L fängt sie oder gibt sie ebenfalls frei.",
+ "reset": "Zurücksetzen",
+ "fov_third": "Sichtfeld, Third Person",
+ "fov_first": "Sichtfeld, Ego-Perspektive"
},
"lift": {
"title": "Turbolift",
@@ -104,8 +127,11 @@
"mess_nobody": "Gerade hat niemand dienstfrei.",
"mess_ended": "Die Crew kehrt zu ihrer Routine zurück.",
"no_team": "An diesem Tisch trifft sich noch kein Team. Lege eins in der Crewliste an.",
- "view_overview": "Vogelperspektive: WASD verschiebt die Karte. V bringt dich zurück hinter den Kommandanten.",
- "view_follow": "Third Person: WASD steuert den Kommandanten, E benutzt die Station in Reichweite. V wechselt in die Vogelperspektive."
+ "view_overview": "Vogelperspektive: WASD verschiebt die Karte. 2 oder 3 bringt dich zurück zum Kommandanten.",
+ "view_follow": "Third Person: WASD steuert den Kommandanten, E benutzt die Station in Reichweite. V schaltet durch die Ansichten.",
+ "view_follow_eye": "Third Person: Die Maus richtet den Blick, WASD läuft, das Mausrad zoomt (ganz heran ist die Ego-Perspektive). Esc gibt die Maus frei.",
+ "mouse_look": "Maussteuerung: Bewege die Maus, um die Kamera zu drehen; ein Klick benutzt, worauf das Fadenkreuz zeigt. Esc gibt die Maus wieder frei.",
+ "view_first": "Ego-Perspektive: Die Maus richtet den Blick, WASD läuft, Herausscrollen kehrt zu Third Person zurück. Esc gibt die Maus frei."
},
"screen": {
"standby": "BEREIT",
@@ -130,6 +156,102 @@
"games": {
"title": "Simulatorraum",
"loading": "Simulation wird geladen …"
+ },
+ "duel": {
+ "tool": "Duell",
+ "terminal": "Duell-Terminal",
+ "start": "Duell starten",
+ "title": "Reaktor-Duell",
+ "intro": "Ein Blaster-Duell eins gegen eins im Reaktorschacht gegen einen Kampfbot. Zwei Gewinnrunden entscheiden; du kannst jederzeit aufhören.",
+ "ride": "Der Turbolift bringt dich zuerst hinunter in die Reaktortechnik.",
+ "choose": "Gegner wählen",
+ "difficulty": {
+ "normal": "Normal",
+ "normal_about": "Blaster, Schild und Entlüften kennenlernen.",
+ "hard": "Schwer",
+ "hard_about": "Ein fairer Kampf für gute Spieler.",
+ "elite": "Elite",
+ "elite_about": "Schnell und präzise: pariert, bestraft Fehler, liest dein Ausweichen."
+ },
+ "controls": {
+ "title": "Steuerung",
+ "move": "Bewegen",
+ "sprint": "Sprinten",
+ "fire": "Feuern",
+ "ads": "Über Kimme und Korn zielen",
+ "shield": "Energieschild (halten)",
+ "dodge": "Ausweichrolle",
+ "vent": "Hitze ablassen; nochmal im Fenster: sofort fertig",
+ "pause": "Pause; nochmal: verlassen",
+ "lmb": "Linke Maustaste",
+ "rmb": "Rechte Maustaste",
+ "space": "Leertaste",
+ "shift": "Umschalt",
+ "esc": "Esc"
+ },
+ "hud": {
+ "you": "Du",
+ "bot": "Bot",
+ "round": "Runde {n}",
+ "health": "Gesundheit",
+ "shield": "Schild",
+ "heat": "Hitze",
+ "roll": "Rolle",
+ "ready": "Bereit",
+ "overheated": "Überhitzt",
+ "venting": "Entlüftet",
+ "vent_hint": "R im goldenen Fenster",
+ "shield_down": "Weg {s} s",
+ "parry_ready": "Parade bereit",
+ "parry_locked": "Parade lädt",
+ "surge": "Reaktorschub: Positionen sichtbar",
+ "fight": "Kampf",
+ "click_to_aim": "Klicken zum Zielen",
+ "vent": "Entlüften"
+ },
+ "callout": {
+ "parry": "Pariert",
+ "parried": "Abgewehrt",
+ "perfect_vent": "Perfekt entlüftet",
+ "vent_miss": "Entlüften verpasst",
+ "overheat": "Überhitzt",
+ "shield_break": "Schild zerstört",
+ "deflect": "Abgelenkt"
+ },
+ "round": {
+ "won": "Runde gewonnen",
+ "lost": "Runde verloren",
+ "draw": "Unentschieden",
+ "kill": "K. o.",
+ "time": "Zeit: mehr Gesundheit gewinnt",
+ "trade": "Beide getroffen"
+ },
+ "pause": {
+ "title": "Pause",
+ "resume": "Weiter",
+ "leave": "Duell verlassen",
+ "hint": "Das Match wartet. Nochmal Esc verlässt es."
+ },
+ "result": {
+ "won": "Sieg",
+ "lost": "Niederlage",
+ "draw": "Unentschieden",
+ "cancelled": "Duell beendet",
+ "rounds": "Runden {me} : {them}",
+ "against": "Gegen den Bot ({tier})",
+ "accuracy": "Trefferquote",
+ "damage": "Schaden verursacht",
+ "headshots": "Kopftreffer",
+ "parries": "Paraden",
+ "blocks": "Blocks",
+ "perfect_vents": "Perfekt entlüftet",
+ "rematch": "Revanche",
+ "leave": "Zurück aufs Schiff"
+ },
+ "notice": {
+ "needs_eye": "Duelle brauchen die 3D-Ansicht in der dritten Person.",
+ "left": "Du hast das Duell verlassen."
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.en.json
index 15e709f3cf..62c2f806b4 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.en.json
@@ -5,7 +5,8 @@
"loading": "Loading deck",
"unavailable": "The ship needs WebGL, which this window cannot start right now.",
"deck_missing": "This deck has not been built yet.",
- "help": "Third person: WASD or the arrow keys walk the commander, Shift hurries, E works the station within reach. V switches to the bird's-eye view and back. Drag to look around, scroll to zoom. Click the deck to walk there, click a crew member for their record."
+ "help": "Third person: WASD or the arrow keys walk the commander, Shift hurries, E works the station within reach. 1, 2 and 3 pick the bird's-eye view, third or first person; V cycles them. Drag to look around, scroll to zoom. Click the deck to walk there, click a crew member for their record.",
+ "help_eye": "Third and first person play like a shooter: a click on the view takes the mouse, moving it turns the camera, Esc gives it back. WASD walks relative to the view, Shift hurries; the left button or E works what the crosshair is on (a crew member, a station), else E works the station within reach. Scroll to move the camera in or out: all the way in is first person, scrolling out of it comes back. 1, 2 and 3 pick the bird's-eye view, third or first person; V cycles them. The settings button on the tool rail sets mouse sensitivity, inverted look, field of view and quality."
},
"deck": {
"label": "Deck {n}",
@@ -90,10 +91,32 @@
"elsewhere": "Elsewhere aboard"
},
"tools": {
+ "view": "View",
+ "follow": "Third person",
"overview": "Bird's-eye",
"lift": "Turbolift",
"commander": "Commander",
- "help": "Help"
+ "settings": "View settings",
+ "help": "Help",
+ "duel": "Duel",
+ "first": "First person",
+ "first_unavailable": "First person needs this deck's eye-level scene on the full-size stage.",
+ "click_to_look": "Click to look around"
+ },
+ "settings": {
+ "title": "View settings",
+ "sensitivity": "Mouse sensitivity",
+ "invert_y": "Invert vertical look",
+ "quality": "Render quality",
+ "quality_auto": "Auto",
+ "quality_high": "High",
+ "quality_low": "Low",
+ "quality_note": "Auto starts high and lowers the quality on a graphics card that cannot keep about 45 frames per second.",
+ "quality_now": "Now rendering: {tier}.",
+ "mouse_lock": "In third and first person a click on the view takes the mouse: moving it turns the camera, the left button works what the crosshair is on. Esc gives it back; L takes or releases it too.",
+ "reset": "Reset",
+ "fov_third": "Field of view, third person",
+ "fov_first": "Field of view, first person"
},
"lift": {
"title": "Turbolift",
@@ -104,8 +127,11 @@
"mess_nobody": "Nobody is off duty right now.",
"mess_ended": "The crew goes back to their routine.",
"no_team": "No team meets at this table yet. Create one in the crew list.",
- "view_overview": "Bird's-eye view: WASD pans the map. V takes you back to the commander.",
- "view_follow": "Third person: WASD walks the commander, E works the station within reach. V switches to the bird's-eye view."
+ "view_overview": "Bird's-eye view: WASD pans the map. 2 or 3 takes you back to the commander.",
+ "view_follow": "Third person: WASD walks the commander, E works the station within reach. V cycles the views.",
+ "view_follow_eye": "Third person: the mouse aims the view, WASD walks, the wheel zooms (all the way in is first person). Esc frees the mouse.",
+ "mouse_look": "Mouse look: move the mouse to turn the camera, click to work what the crosshair is on. Esc releases the mouse.",
+ "view_first": "First person: the mouse aims the view, WASD walks, scrolling out returns to third person. Esc frees the mouse."
},
"screen": {
"standby": "STANDBY",
@@ -130,6 +156,102 @@
"games": {
"title": "Simulator room",
"loading": "Loading the simulation…"
+ },
+ "duel": {
+ "tool": "Duel",
+ "terminal": "Duel terminal",
+ "start": "Start a duel",
+ "title": "Reactor duel",
+ "intro": "A one-on-one blaster duel in the Reactor Shaft against a combat bot. Best of three rounds; leave at any time.",
+ "ride": "The turbolift takes you down to Reactor Engineering first.",
+ "choose": "Choose the opponent",
+ "difficulty": {
+ "normal": "Normal",
+ "normal_about": "Learn the blaster, the shield and the vent.",
+ "hard": "Hard",
+ "hard_about": "A fair fight for a good player.",
+ "elite": "Elite",
+ "elite_about": "Fast and precise: parries, punishes, reads your strafing."
+ },
+ "controls": {
+ "title": "Controls",
+ "move": "Move",
+ "sprint": "Sprint",
+ "fire": "Fire",
+ "ads": "Aim down the sights",
+ "shield": "Energy shield (hold)",
+ "dodge": "Dodge roll",
+ "vent": "Vent heat; again inside the window vents at once",
+ "pause": "Pause; again to leave",
+ "lmb": "Left mouse",
+ "rmb": "Right mouse",
+ "space": "Space",
+ "shift": "Shift",
+ "esc": "Esc"
+ },
+ "hud": {
+ "you": "You",
+ "bot": "Bot",
+ "round": "Round {n}",
+ "health": "Health",
+ "shield": "Shield",
+ "heat": "Heat",
+ "roll": "Roll",
+ "ready": "Ready",
+ "overheated": "Overheated",
+ "venting": "Venting",
+ "vent_hint": "R in the gold window",
+ "shield_down": "Down {s} s",
+ "parry_ready": "Parry ready",
+ "parry_locked": "Parry cooling",
+ "surge": "Reactor surge: positions revealed",
+ "fight": "Fight",
+ "click_to_aim": "Click to aim",
+ "vent": "Vent"
+ },
+ "callout": {
+ "parry": "Parry",
+ "parried": "Parried",
+ "perfect_vent": "Perfect vent",
+ "vent_miss": "Vent missed",
+ "overheat": "Overheated",
+ "shield_break": "Shield broken",
+ "deflect": "Deflected"
+ },
+ "round": {
+ "won": "Round won",
+ "lost": "Round lost",
+ "draw": "Round drawn",
+ "kill": "Knockout",
+ "time": "Time: more health wins",
+ "trade": "Both down"
+ },
+ "pause": {
+ "title": "Paused",
+ "resume": "Resume",
+ "leave": "Leave the duel",
+ "hint": "The match waits. Esc again leaves it."
+ },
+ "result": {
+ "won": "Victory",
+ "lost": "Defeat",
+ "draw": "Draw",
+ "cancelled": "Duel ended",
+ "rounds": "Rounds {me} : {them}",
+ "against": "Against the {tier} bot",
+ "accuracy": "Accuracy",
+ "damage": "Damage dealt",
+ "headshots": "Headshots",
+ "parries": "Parries",
+ "blocks": "Blocks",
+ "perfect_vents": "Perfect vents",
+ "rematch": "Rematch",
+ "leave": "Back to the ship"
+ },
+ "notice": {
+ "needs_eye": "Duels need the third-person 3D view.",
+ "left": "You left the duel."
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.es.json
index e15d11ba33..34ed1ecc3d 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.es.json
@@ -5,7 +5,8 @@
"loading": "Cargando cubierta",
"unavailable": "La nave necesita WebGL y esta ventana no puede iniciarlo ahora.",
"deck_missing": "Esta cubierta aún no está construida.",
- "help": "Tercera persona: WASD o las flechas mueven al comandante, Mayús para ir más rápido, E usa la estación al alcance. V cambia a vista de pájaro y vuelve. Arrastra para mirar alrededor, usa la rueda para el zoom. Haz clic en la cubierta para caminar hasta allí y en un tripulante para ver su ficha."
+ "help": "Tercera persona: WASD o las flechas mueven al comandante, Shift acelera, E usa la estación al alcance. 1, 2 y 3 eligen vista de pájaro, tercera o primera persona; V las recorre. Arrastra para mirar, desplaza para hacer zoom. Haz clic en la cubierta para ir allí, en un tripulante para ver su ficha.",
+ "help_eye": "La tercera y la primera persona se juegan como un shooter: un clic en la vista captura el ratón, moverlo gira la cámara, Esc lo libera. WASD camina según la vista, Shift acelera; el botón izquierdo o E usa lo que señala la mira (un tripulante, una estación); si no, E usa la estación al alcance. La rueda acerca o aleja la cámara: del todo cerca es primera persona y alejarse vuelve. 1, 2 y 3 eligen vista de pájaro, tercera o primera persona; V las recorre. El botón de ajustes de la barra regula la sensibilidad del ratón, el eje invertido, el campo de visión y la calidad."
},
"deck": {
"label": "Cubierta {n}",
@@ -90,10 +91,32 @@
"elsewhere": "En otro lugar de la nave"
},
"tools": {
+ "view": "Vista",
+ "follow": "Tercera persona",
"overview": "Vista de pájaro",
"lift": "Turboascensor",
"commander": "Comandante",
- "help": "Ayuda"
+ "settings": "Ajustes de vista",
+ "help": "Ayuda",
+ "duel": "Duelo",
+ "first": "Primera persona",
+ "first_unavailable": "La primera persona necesita la escena 3D de esta cubierta en el escenario completo.",
+ "click_to_look": "Haz clic para mirar"
+ },
+ "settings": {
+ "title": "Ajustes de vista",
+ "sensitivity": "Sensibilidad del ratón",
+ "invert_y": "Invertir el eje vertical",
+ "quality": "Calidad gráfica",
+ "quality_auto": "Automática",
+ "quality_high": "Alta",
+ "quality_low": "Baja",
+ "quality_note": "Automática empieza en alta y baja la calidad si la tarjeta gráfica no mantiene unos 45 fotogramas por segundo.",
+ "quality_now": "Ahora: {tier}.",
+ "mouse_lock": "En tercera y primera persona un clic en la vista captura el ratón: moverlo gira la cámara y el botón izquierdo usa lo que señala la mira. Esc lo libera; L también lo captura o lo libera.",
+ "reset": "Restablecer",
+ "fov_third": "Campo de visión, tercera persona",
+ "fov_first": "Campo de visión, primera persona"
},
"lift": {
"title": "Turboascensor",
@@ -104,8 +127,11 @@
"mess_nobody": "Ahora nadie está franco de servicio.",
"mess_ended": "La tripulación vuelve a su rutina.",
"no_team": "Ningún equipo se reúne aún en esta mesa. Crea uno en la lista de tripulantes.",
- "view_overview": "Vista de pájaro: WASD desplaza el mapa. V te devuelve al comandante.",
- "view_follow": "Tercera persona: WASD mueve al comandante, E usa la estación al alcance. V cambia a vista de pájaro."
+ "view_overview": "Vista de pájaro: WASD desplaza el mapa. 2 o 3 te devuelve al comandante.",
+ "view_follow": "Tercera persona: WASD mueve al comandante, E usa la estación al alcance. V recorre las vistas.",
+ "view_follow_eye": "Tercera persona: el ratón apunta la vista, WASD camina, la rueda hace zoom (del todo cerca es primera persona). Esc libera el ratón.",
+ "mouse_look": "Control con ratón: mueve el ratón para girar la cámara, haz clic para usar lo que señala la mira. Esc libera el ratón.",
+ "view_first": "Primera persona: el ratón apunta la vista, WASD camina, alejar con la rueda vuelve a tercera persona. Esc libera el ratón."
},
"screen": {
"standby": "EN ESPERA",
@@ -130,6 +156,102 @@
"games": {
"title": "Sala de simuladores",
"loading": "Cargando la simulación…"
+ },
+ "duel": {
+ "tool": "Duelo",
+ "terminal": "Terminal de duelo",
+ "start": "Iniciar un duelo",
+ "title": "Duelo en el reactor",
+ "intro": "Un duelo de bláster uno contra uno en el pozo del reactor contra un bot de combate. Al mejor de tres rondas; puedes salir cuando quieras.",
+ "ride": "El turboascensor te lleva primero a Ingeniería del reactor.",
+ "choose": "Elige al rival",
+ "difficulty": {
+ "normal": "Normal",
+ "normal_about": "Aprende el bláster, el escudo y la ventilación.",
+ "hard": "Difícil",
+ "hard_about": "Un combate justo para un buen jugador.",
+ "elite": "Élite",
+ "elite_about": "Rápido y preciso: para, castiga y lee tus esquivas."
+ },
+ "controls": {
+ "title": "Controles",
+ "move": "Moverse",
+ "sprint": "Correr",
+ "fire": "Disparar",
+ "ads": "Apuntar con la mira",
+ "shield": "Escudo de energía (mantener)",
+ "dodge": "Voltereta",
+ "vent": "Ventilar calor; otra vez dentro de la ventana: al instante",
+ "pause": "Pausa; otra vez para salir",
+ "lmb": "Botón izquierdo",
+ "rmb": "Botón derecho",
+ "space": "Espacio",
+ "shift": "Mayús",
+ "esc": "Esc"
+ },
+ "hud": {
+ "you": "Tú",
+ "bot": "Bot",
+ "round": "Ronda {n}",
+ "health": "Salud",
+ "shield": "Escudo",
+ "heat": "Calor",
+ "roll": "Voltereta",
+ "ready": "Lista",
+ "overheated": "Sobrecalentado",
+ "venting": "Ventilando",
+ "vent_hint": "R en la ventana dorada",
+ "shield_down": "Caído {s} s",
+ "parry_ready": "Parada lista",
+ "parry_locked": "Parada recargando",
+ "surge": "Sobrecarga del reactor: posiciones visibles",
+ "fight": "Lucha",
+ "click_to_aim": "Haz clic para apuntar",
+ "vent": "Ventilar"
+ },
+ "callout": {
+ "parry": "Parada",
+ "parried": "Te la devolvieron",
+ "perfect_vent": "Ventilación perfecta",
+ "vent_miss": "Ventilación fallida",
+ "overheat": "Sobrecalentado",
+ "shield_break": "Escudo roto",
+ "deflect": "Desviado"
+ },
+ "round": {
+ "won": "Ronda ganada",
+ "lost": "Ronda perdida",
+ "draw": "Ronda empatada",
+ "kill": "Fuera de combate",
+ "time": "Tiempo: gana quien tiene más salud",
+ "trade": "Ambos caídos"
+ },
+ "pause": {
+ "title": "Pausa",
+ "resume": "Continuar",
+ "leave": "Salir del duelo",
+ "hint": "La partida espera. Esc otra vez la abandona."
+ },
+ "result": {
+ "won": "Victoria",
+ "lost": "Derrota",
+ "draw": "Empate",
+ "cancelled": "Duelo terminado",
+ "rounds": "Rondas {me} : {them}",
+ "against": "Contra el bot ({tier})",
+ "accuracy": "Precisión",
+ "damage": "Daño causado",
+ "headshots": "Disparos a la cabeza",
+ "parries": "Paradas",
+ "blocks": "Bloqueos",
+ "perfect_vents": "Ventilaciones perfectas",
+ "rematch": "Revancha",
+ "leave": "Volver a la nave"
+ },
+ "notice": {
+ "needs_eye": "Los duelos necesitan la vista 3D en tercera persona.",
+ "left": "Has salido del duelo."
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.pt.json
index 36ebf2af54..f0a15e2807 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.pt.json
@@ -5,7 +5,8 @@
"loading": "Carregando o convés",
"unavailable": "A nave precisa de WebGL, que esta janela não consegue iniciar agora.",
"deck_missing": "Este convés ainda não foi construído.",
- "help": "Terceira pessoa: WASD ou as setas movem o comandante, Shift para ir mais rápido, E usa a estação ao alcance. V alterna para a vista aérea e volta. Arraste para olhar em volta, use a roda para o zoom. Clique no convés para caminhar até lá e num tripulante para ver a ficha."
+ "help": "Terceira pessoa: WASD ou as setas movem o comandante, Shift acelera, E usa a estação ao alcance. 1, 2 e 3 escolhem vista aérea, terceira ou primeira pessoa; V alterna entre elas. Arraste para olhar, role para dar zoom. Clique no convés para ir até lá, num tripulante para ver a ficha.",
+ "help_eye": "A terceira e a primeira pessoa funcionam como um shooter: um clique na vista captura o mouse, movê-lo gira a câmera, Esc o libera. WASD anda conforme a vista, Shift acelera; o botão esquerdo ou E usa o que a mira aponta (um tripulante, uma estação); senão, E usa a estação ao alcance. A roda aproxima ou afasta a câmera: tudo perto é primeira pessoa, e afastar volta. 1, 2 e 3 escolhem vista aérea, terceira ou primeira pessoa; V alterna entre elas. O botão de ajustes da barra define a sensibilidade do mouse, o eixo invertido, o campo de visão e a qualidade."
},
"deck": {
"label": "Convés {n}",
@@ -90,10 +91,32 @@
"elsewhere": "Em outro lugar da nave"
},
"tools": {
+ "view": "Vista",
+ "follow": "Terceira pessoa",
"overview": "Vista aérea",
"lift": "Turboelevador",
"commander": "Comandante",
- "help": "Ajuda"
+ "settings": "Ajustes de visualização",
+ "help": "Ajuda",
+ "duel": "Duelo",
+ "first": "Primeira pessoa",
+ "first_unavailable": "A primeira pessoa precisa da cena 3D deste convés no palco completo.",
+ "click_to_look": "Clique para olhar"
+ },
+ "settings": {
+ "title": "Ajustes de visualização",
+ "sensitivity": "Sensibilidade do mouse",
+ "invert_y": "Inverter o eixo vertical",
+ "quality": "Qualidade gráfica",
+ "quality_auto": "Automática",
+ "quality_high": "Alta",
+ "quality_low": "Baixa",
+ "quality_note": "Automática começa em alta e reduz a qualidade se a placa de vídeo não mantiver cerca de 45 quadros por segundo.",
+ "quality_now": "Agora: {tier}.",
+ "mouse_lock": "Em terceira e primeira pessoa um clique na vista captura o mouse: movê-lo gira a câmera e o botão esquerdo usa o que a mira aponta. Esc o libera; L também o captura ou libera.",
+ "reset": "Redefinir",
+ "fov_third": "Campo de visão, terceira pessoa",
+ "fov_first": "Campo de visão, primeira pessoa"
},
"lift": {
"title": "Turboelevador",
@@ -104,8 +127,11 @@
"mess_nobody": "Ninguém está de folga agora.",
"mess_ended": "A tripulação volta à rotina.",
"no_team": "Nenhuma equipe se reúne nesta mesa ainda. Crie uma na lista da tripulação.",
- "view_overview": "Vista aérea: WASD move o mapa. V leva você de volta ao comandante.",
- "view_follow": "Terceira pessoa: WASD move o comandante, E usa a estação ao alcance. V alterna para a vista aérea."
+ "view_overview": "Vista aérea: WASD move o mapa. 2 ou 3 leva você de volta ao comandante.",
+ "view_follow": "Terceira pessoa: WASD move o comandante, E usa a estação ao alcance. V alterna as vistas.",
+ "view_follow_eye": "Terceira pessoa: o mouse aponta a vista, WASD anda, a roda dá zoom (tudo perto é primeira pessoa). Esc libera o mouse.",
+ "mouse_look": "Controle pelo mouse: mova o mouse para girar a câmera, clique para usar o que a mira aponta. Esc libera o mouse.",
+ "view_first": "Primeira pessoa: o mouse aponta a vista, WASD anda, afastar com a roda volta à terceira pessoa. Esc libera o mouse."
},
"screen": {
"standby": "EM ESPERA",
@@ -130,6 +156,102 @@
"games": {
"title": "Sala de simuladores",
"loading": "Carregando a simulação…"
+ },
+ "duel": {
+ "tool": "Duelo",
+ "terminal": "Terminal de duelo",
+ "start": "Iniciar um duelo",
+ "title": "Duelo no reator",
+ "intro": "Um duelo de blaster um contra um no poço do reator contra um bot de combate. Melhor de três rodadas; saia quando quiser.",
+ "ride": "O turboelevador leva você primeiro à Engenharia do reator.",
+ "choose": "Escolha o adversário",
+ "difficulty": {
+ "normal": "Normal",
+ "normal_about": "Aprenda o blaster, o escudo e a ventilação.",
+ "hard": "Difícil",
+ "hard_about": "Uma luta justa para um bom jogador.",
+ "elite": "Elite",
+ "elite_about": "Rápido e preciso: apara, pune e lê suas esquivas."
+ },
+ "controls": {
+ "title": "Controles",
+ "move": "Mover",
+ "sprint": "Correr",
+ "fire": "Atirar",
+ "ads": "Mirar pela mira",
+ "shield": "Escudo de energia (segurar)",
+ "dodge": "Rolamento",
+ "vent": "Ventilar calor; de novo dentro da janela: na hora",
+ "pause": "Pausa; de novo para sair",
+ "lmb": "Botão esquerdo",
+ "rmb": "Botão direito",
+ "space": "Espaço",
+ "shift": "Shift",
+ "esc": "Esc"
+ },
+ "hud": {
+ "you": "Você",
+ "bot": "Bot",
+ "round": "Rodada {n}",
+ "health": "Vida",
+ "shield": "Escudo",
+ "heat": "Calor",
+ "roll": "Rolamento",
+ "ready": "Pronto",
+ "overheated": "Superaquecido",
+ "venting": "Ventilando",
+ "vent_hint": "R na janela dourada",
+ "shield_down": "Fora {s} s",
+ "parry_ready": "Aparo pronto",
+ "parry_locked": "Aparo recarregando",
+ "surge": "Surto do reator: posições reveladas",
+ "fight": "Lute",
+ "click_to_aim": "Clique para mirar",
+ "vent": "Ventilar"
+ },
+ "callout": {
+ "parry": "Aparo",
+ "parried": "Devolvido",
+ "perfect_vent": "Ventilação perfeita",
+ "vent_miss": "Ventilação perdida",
+ "overheat": "Superaquecido",
+ "shield_break": "Escudo quebrado",
+ "deflect": "Desviado"
+ },
+ "round": {
+ "won": "Rodada vencida",
+ "lost": "Rodada perdida",
+ "draw": "Rodada empatada",
+ "kill": "Nocaute",
+ "time": "Tempo: vence quem tem mais vida",
+ "trade": "Ambos caíram"
+ },
+ "pause": {
+ "title": "Pausa",
+ "resume": "Continuar",
+ "leave": "Sair do duelo",
+ "hint": "A partida espera. Esc de novo sai dela."
+ },
+ "result": {
+ "won": "Vitória",
+ "lost": "Derrota",
+ "draw": "Empate",
+ "cancelled": "Duelo encerrado",
+ "rounds": "Rodadas {me} : {them}",
+ "against": "Contra o bot ({tier})",
+ "accuracy": "Precisão",
+ "damage": "Dano causado",
+ "headshots": "Tiros na cabeça",
+ "parries": "Aparos",
+ "blocks": "Bloqueios",
+ "perfect_vents": "Ventilações perfeitas",
+ "rematch": "Revanche",
+ "leave": "Voltar à nave"
+ },
+ "notice": {
+ "needs_eye": "Duelos precisam da visão 3D em terceira pessoa.",
+ "left": "Você saiu do duelo."
+ }
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.zh.json
index f5e0836552..af08384b40 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/verse.zh.json
@@ -5,7 +5,8 @@
"loading": "正在载入甲板",
"unavailable": "飞船需要 WebGL,但此窗口目前无法启动它。",
"deck_missing": "这层甲板尚未建成。",
- "help": "第三人称:WASD 或方向键操控指挥官,按住 Shift 加速,E 使用附近的工作站。V 在鸟瞰视角和第三人称之间切换。拖动环顾四周,滚轮缩放。点击甲板即可走过去,点击船员查看其档案。"
+ "help": "第三人称:WASD 或方向键操控指挥官,Shift 加速,E 使用附近的工作站。1、2、3 分别选择鸟瞰、第三人称或第一人称;V 依次切换。拖动环顾四周,滚轮缩放。点击甲板走过去,点击船员查看其档案。",
+ "help_eye": "第三人称和第一人称的操作与射击游戏相同:点击画面锁定鼠标,移动鼠标转动镜头,Esc 释放。WASD 按视角方向行走,Shift 加速;鼠标左键或 E 使用准星所指的对象(船员或工作站),否则 E 使用附近的工作站。滚轮拉近或拉远镜头:拉到最近即进入第一人称,向外滚动则返回。1、2、3 分别选择鸟瞰、第三人称或第一人称;V 依次切换。工具栏中的设置按钮可调整鼠标灵敏度、反转视角、视野和画质。"
},
"deck": {
"label": "第 {n} 层甲板",
@@ -90,10 +91,32 @@
"elsewhere": "船上其他地方"
},
"tools": {
+ "view": "视角",
+ "follow": "第三人称",
"overview": "鸟瞰",
"lift": "升降梯",
"commander": "指挥官",
- "help": "帮助"
+ "settings": "视角设置",
+ "help": "帮助",
+ "duel": "决斗",
+ "first": "第一人称",
+ "first_unavailable": "第一人称需要在完整舞台上加载本甲板的 3D 场景。",
+ "click_to_look": "点击以环顾"
+ },
+ "settings": {
+ "title": "视角设置",
+ "sensitivity": "鼠标灵敏度",
+ "invert_y": "反转垂直视角",
+ "quality": "画质",
+ "quality_auto": "自动",
+ "quality_high": "高",
+ "quality_low": "低",
+ "quality_note": "自动模式以高画质启动;若显卡无法保持约每秒 45 帧,会自动降低画质。",
+ "quality_now": "当前:{tier}。",
+ "mouse_lock": "在第三人称和第一人称下,点击画面即锁定鼠标:移动鼠标转动镜头,左键使用准星所指的对象。Esc 释放;L 也可锁定或释放。",
+ "reset": "重置",
+ "fov_third": "视野(第三人称)",
+ "fov_first": "视野(第一人称)"
},
"lift": {
"title": "升降梯",
@@ -104,8 +127,11 @@
"mess_nobody": "目前没有人休班。",
"mess_ended": "船员回到日常作息。",
"no_team": "还没有团队在这张桌子开会。请在船员名单中创建一个。",
- "view_overview": "鸟瞰视角:WASD 平移地图。按 V 回到指挥官身后。",
- "view_follow": "第三人称:WASD 操控指挥官,E 使用附近的工作站。按 V 切换到鸟瞰视角。"
+ "view_overview": "鸟瞰视角:WASD 平移地图。按 2 或 3 回到指挥官身边。",
+ "view_follow": "第三人称:WASD 操控指挥官,E 使用附近的工作站。按 V 切换视角。",
+ "view_follow_eye": "第三人称:鼠标控制视角,WASD 行走,滚轮缩放(拉到最近即第一人称)。Esc 释放鼠标。",
+ "mouse_look": "鼠标视角:移动鼠标转动镜头,点击使用准星所指的对象。Esc 释放鼠标。",
+ "view_first": "第一人称:鼠标控制视角,WASD 行走,向外滚动返回第三人称。Esc 释放鼠标。"
},
"screen": {
"standby": "待命",
@@ -130,6 +156,102 @@
"games": {
"title": "模拟舱",
"loading": "正在载入模拟……"
+ },
+ "duel": {
+ "tool": "决斗",
+ "terminal": "决斗终端",
+ "start": "开始决斗",
+ "title": "反应堆决斗",
+ "intro": "在反应堆竖井中与战斗机器人进行一对一的爆能枪决斗。三局两胜,随时可以退出。",
+ "ride": "涡轮电梯会先带你下到反应堆工程甲板。",
+ "choose": "选择对手",
+ "difficulty": {
+ "normal": "普通",
+ "normal_about": "熟悉爆能枪、护盾和散热。",
+ "hard": "困难",
+ "hard_about": "对优秀玩家来说是一场公平的较量。",
+ "elite": "精英",
+ "elite_about": "迅速而精准:会完美格挡、抓住破绽、看穿你的左右闪避。"
+ },
+ "controls": {
+ "title": "操作",
+ "move": "移动",
+ "sprint": "冲刺",
+ "fire": "射击",
+ "ads": "瞄准镜瞄准",
+ "shield": "能量护盾(按住)",
+ "dodge": "闪避翻滚",
+ "vent": "散热;在窗口内再按一次立即完成",
+ "pause": "暂停;再按一次退出",
+ "lmb": "鼠标左键",
+ "rmb": "鼠标右键",
+ "space": "空格",
+ "shift": "Shift",
+ "esc": "Esc"
+ },
+ "hud": {
+ "you": "你",
+ "bot": "机器人",
+ "round": "第 {n} 局",
+ "health": "生命",
+ "shield": "护盾",
+ "heat": "热量",
+ "roll": "翻滚",
+ "ready": "就绪",
+ "overheated": "过热",
+ "venting": "散热中",
+ "vent_hint": "在金色窗口内按 R",
+ "shield_down": "失效 {s} 秒",
+ "parry_ready": "可完美格挡",
+ "parry_locked": "格挡冷却中",
+ "surge": "反应堆涌动:位置暴露",
+ "fight": "开战",
+ "click_to_aim": "点击以瞄准",
+ "vent": "散热"
+ },
+ "callout": {
+ "parry": "完美格挡",
+ "parried": "被反弹",
+ "perfect_vent": "完美散热",
+ "vent_miss": "散热失误",
+ "overheat": "过热",
+ "shield_break": "护盾破碎",
+ "deflect": "偏转"
+ },
+ "round": {
+ "won": "本局胜利",
+ "lost": "本局失利",
+ "draw": "本局平局",
+ "kill": "击倒",
+ "time": "时间到:生命多者胜",
+ "trade": "同归于尽"
+ },
+ "pause": {
+ "title": "已暂停",
+ "resume": "继续",
+ "leave": "退出决斗",
+ "hint": "比赛暂停中。再按 Esc 退出。"
+ },
+ "result": {
+ "won": "胜利",
+ "lost": "失败",
+ "draw": "平局",
+ "cancelled": "决斗结束",
+ "rounds": "局数 {me} : {them}",
+ "against": "对手:{tier}机器人",
+ "accuracy": "命中率",
+ "damage": "造成伤害",
+ "headshots": "爆头",
+ "parries": "完美格挡",
+ "blocks": "格挡",
+ "perfect_vents": "完美散热",
+ "rematch": "再来一局",
+ "leave": "返回飞船"
+ },
+ "notice": {
+ "needs_eye": "决斗需要第三人称 3D 视图。",
+ "left": "你已退出决斗。"
+ }
}
}
}
diff --git a/scripts/verse/_eyeview_entry.py b/scripts/verse/_eyeview_entry.py
new file mode 100644
index 0000000000..139a5d97ef
--- /dev/null
+++ b/scripts/verse/_eyeview_entry.py
@@ -0,0 +1,181 @@
+"""Blender-side eye-level view job: build a deck and render perspective views
+with every ceiling and ceiling ghost visible, as the realtime export sees it.
+
+Run by scripts/verse/eyeview.py through scripts/verse/blender.py:
+ _eyeview_entry.py <deck_id> <out_dir> <views.json> [--samples N] [--size WxH]
+
+views.json: a list of views. Each view is either
+ {"name", "rooms": true} every room: 4 headings per point
+ {"name", "rig": [x, z, yaw_deg, floor]} the shoulder rig's camera behind a
+ commander at three.js (x, floor, z)
+ facing yaw (0 = +Z, 90 = +X)
+ {"name", "eye": [x, y, z, yaw_deg, pitch_deg]} a free camera (three.js)
+Output: `<name>.png` per view and `views.json` with what each one shows.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+import time
+from pathlib import Path
+
+import bpy
+from _cook_entry import load_builder
+from lib import cook, realtime, scene
+from mathutils import Euler, Vector
+
+HFOV_DEG = 72.0
+# The realtime view's shoulder rig (SHOULDER in engine/realtime/shoulderRig.ts).
+RIG_DISTANCE = 2.4
+RIG_SIDE = -0.47
+RIG_PIVOT = 1.74
+RIG_PITCH_DEG = 7.0
+ROOM_EYE_M = 1.9 # camera height above the floor for the room views
+ROOM_STEP_M = 22.0 # long rooms get a point every this many metres
+HEADINGS = (("n", 180.0), ("e", 90.0), ("s", 0.0), ("w", 270.0))
+
+
+def _realtime_visibility() -> None:
+ """Show what the realtime export shows: ceilings, ghosts and fixtures as
+ normal geometry (ghosts cast shadows), mirror-only emitters lit; helper
+ collections stay hidden."""
+ for name in ("Occluders", "Sockets", "NavOnly"):
+ scene.collection(name).hide_render = True
+ for obj in cook._camera_hidden_objects():
+ obj.visible_camera = True
+ if obj.get("ceiling_ghost"):
+ obj.visible_shadow = True
+ obj.visible_diffuse = True
+ obj.visible_glossy = True
+ for obj in scene.objects_in("Lights"):
+ if obj.type == "MESH":
+ obj.visible_camera = True
+ realtime.light_glossy_emitters(bpy.data.materials)
+
+
+def _camera(bpy_scene) -> bpy.types.Object:
+ data = bpy.data.cameras.new("CAM_eye")
+ data.lens_unit = "FOV"
+ data.sensor_fit = "HORIZONTAL"
+ data.angle = math.radians(HFOV_DEG)
+ data.clip_start = 0.05
+ data.clip_end = 400.0
+ camera = bpy.data.objects.new("CAM_eye", data)
+ bpy_scene.collection.objects.link(camera)
+ bpy_scene.camera = camera
+ return camera
+
+
+def _aim(camera: bpy.types.Object, position: Vector, yaw_deg: float, pitch_deg: float) -> None:
+ """Blender camera at `position` looking along three.js heading `yaw_deg`
+ (0 = +Z, 90 = +X), `pitch_deg` down."""
+ camera.location = position
+ camera.rotation_euler = Euler(
+ (math.radians(90.0 - pitch_deg), 0.0, math.radians(yaw_deg) - math.pi)
+ )
+
+
+def _rig_position(x: float, z: float, yaw_deg: float, floor: float) -> Vector:
+ yaw, pitch = math.radians(yaw_deg), math.radians(RIG_PITCH_DEG)
+ fx, fz = math.sin(yaw), math.cos(yaw)
+ rx, rz = -math.cos(yaw), math.sin(yaw)
+ px, py, pz = x + rx * RIG_SIDE, floor + RIG_PIVOT, z + rz * RIG_SIDE
+ dx, dy, dz = fx * math.cos(pitch), -math.sin(pitch), fz * math.cos(pitch)
+ cx, cy, cz = px - dx * RIG_DISTANCE, py - dy * RIG_DISTANCE, pz - dz * RIG_DISTANCE
+ return Vector((cx, -cz, cy))
+
+
+def _room_points(room: cook.Room) -> list[tuple[float, float]]:
+ """The room's inside centre, plus points along its long axis for long rooms."""
+ xs = [p[0] for p in room.polygon]
+ ys = [p[1] for p in room.polygon]
+ points = [room.centre]
+ span_x, span_y = max(xs) - min(xs), max(ys) - min(ys)
+ steps = int(max(span_x, span_y) // ROOM_STEP_M)
+ for k in range(steps):
+ t = (k + 1) / (steps + 1)
+ if span_x >= span_y:
+ p = (min(xs) + span_x * t, room.centre[1])
+ else:
+ p = (room.centre[0], min(ys) + span_y * t)
+ if cook._point_in_polygon(p[0], p[1], room.polygon) and all(
+ (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 > 36.0 for q in points
+ ):
+ points.append(p)
+ return points
+
+
+def _expand(views: list[dict]) -> list[dict]:
+ """Turn {"rooms": true} into explicit eye views per room point and heading."""
+ out = []
+ for view in views:
+ if not view.get("rooms"):
+ out.append(view)
+ continue
+ only = set(view.get("only", []))
+ for room in cook._rooms():
+ if only and room.id not in only:
+ continue
+ for index, (bx, by) in enumerate(_room_points(room)):
+ for tag, yaw in HEADINGS:
+ out.append(
+ {
+ "name": f"{room.id}_{index}{tag}",
+ "eye": [bx, room.z + ROOM_EYE_M, -by, yaw, 7.0],
+ "room": room.id,
+ }
+ )
+ return out
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("deck_id")
+ parser.add_argument("out_dir", type=Path)
+ parser.add_argument("views", type=Path)
+ parser.add_argument("--samples", type=int, default=64)
+ parser.add_argument("--size", default="960x522")
+ options = parser.parse_args(sys.argv[1:])
+ started = time.monotonic()
+ load_builder(options.deck_id).build()
+ print(f"[verse] stage build: {time.monotonic() - started:.1f} s", flush=True)
+ bpy.context.view_layer.update()
+ bpy_scene = bpy.context.scene
+ _realtime_visibility()
+ width, height = (int(v) for v in options.size.lower().split("x"))
+ render = bpy_scene.render
+ render.resolution_x, render.resolution_y = width, height
+ render.resolution_percentage = 100
+ render.use_compositing = False
+ bpy_scene.cycles.samples = options.samples
+ bpy_scene.cycles.adaptive_threshold = 0.03
+ bpy_scene.cycles.adaptive_min_samples = 16
+ settings = render.image_settings
+ settings.file_format = "PNG"
+ settings.color_mode = "RGB"
+ settings.color_depth = "8"
+ camera = _camera(bpy_scene)
+ views = _expand(json.loads(options.views.read_text(encoding="utf-8")))
+ options.out_dir.mkdir(parents=True, exist_ok=True)
+ done = []
+ for view in views:
+ if "rig" in view:
+ x, z, yaw, floor = (list(view["rig"]) + [0.0])[:4]
+ _aim(camera, _rig_position(x, z, yaw, floor), yaw, RIG_PITCH_DEG)
+ else:
+ x, y, z, yaw, pitch = view["eye"]
+ _aim(camera, Vector((x, -z, y)), yaw, pitch)
+ render.filepath = str(options.out_dir / f"{view['name']}.png")
+ t0 = time.monotonic()
+ bpy.ops.render.render(write_still=True)
+ view["render_s"] = round(time.monotonic() - t0, 1)
+ done.append(view)
+ print(f"[verse] eye view {view['name']}: {view['render_s']} s", flush=True)
+ (options.out_dir / "views.json").write_text(json.dumps(done, indent=1), encoding="utf-8")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/verse/_realtime_entry.py b/scripts/verse/_realtime_entry.py
new file mode 100644
index 0000000000..e314a0432f
--- /dev/null
+++ b/scripts/verse/_realtime_entry.py
@@ -0,0 +1,38 @@
+"""Blender-side realtime export job: build a deck, bake and export it for the
+eye-level view (docs/verse/realtime.md).
+
+Run by scripts/verse/cook.py through scripts/verse/blender.py:
+ _realtime_entry.py <deck_id> <raw_dir> <quality> [--blend <path.blend>]
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+import time
+from pathlib import Path
+
+import bpy
+from _cook_entry import load_builder
+from lib import realtime
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("deck_id")
+ parser.add_argument("raw_dir", type=Path)
+ parser.add_argument("quality")
+ parser.add_argument("--blend", type=Path)
+ options = parser.parse_args(sys.argv[1:])
+ started = time.monotonic()
+ load_builder(options.deck_id).build()
+ print(f"[verse] stage build: {time.monotonic() - started:.1f} s", flush=True)
+ result = realtime.export_realtime(options.deck_id, options.raw_dir, options.quality)
+ if options.blend:
+ options.blend.parent.mkdir(parents=True, exist_ok=True)
+ bpy.ops.wm.save_as_mainfile(filepath=str(options.blend), compress=True)
+ print(f"[verse] realtime {options.deck_id}: {result['stats']}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/verse/cook.py b/scripts/verse/cook.py
index 9ec8912db0..2c1085120a 100644
--- a/scripts/verse/cook.py
+++ b/scripts/verse/cook.py
@@ -2,11 +2,18 @@
python scripts/verse/cook.py deck <id> [--quality preview|final] [--keep-blend]
[--device auto|optix|cuda|cpu] [--out DIR]
+ [--realtime]
Runs `art/verse/decks/<id>/build.py` and `lib.cook.cook_deck()` inside headless
Blender (holding the GPU lock), then packages the raw output into
`dodaios/ui/web/frontend/public/verse/decks/<id>/` and validates it.
--keep-blend saves the built scene to art/verse/.cache/blend/LV_<id>.blend.
+
+--realtime runs the realtime (eye-level) export instead of the plate cook:
+`lib.realtime.export_realtime()` bakes the lightmaps and reflection probes
+and `package_realtime.py` writes `<deck>/realtime/` and the manifest's
+`realtime` block (docs/verse/realtime.md). The plate stays as it is; the
+deck must have been cooked once.
"""
from __future__ import annotations
@@ -20,11 +27,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
import blender # noqa: E402
import package # noqa: E402
+import package_realtime # noqa: E402
import validate # noqa: E402
PUBLIC_VERSE = blender.REPO_ROOT / "dodaios" / "ui" / "web" / "frontend" / "public" / "verse"
PUBLIC_DECKS = PUBLIC_VERSE / "decks"
ENTRY = Path(__file__).resolve().with_name("_cook_entry.py")
+REALTIME_ENTRY = Path(__file__).resolve().with_name("_realtime_entry.py")
def cook_deck(
@@ -51,6 +60,32 @@ def cook_deck(
return manifest
+def cook_realtime(
+ deck_id: str,
+ quality: str = "final",
+ *,
+ keep_blend: bool = False,
+ device: str = "auto",
+ out_dir: Path | None = None,
+) -> dict:
+ """Run the realtime export of one deck end to end and return its manifest block."""
+ raw_dir = blender.CACHE_ROOT / "cook" / deck_id / f"realtime-{quality}"
+ shutil.rmtree(raw_dir, ignore_errors=True)
+ raw_dir.mkdir(parents=True)
+ args = [deck_id, str(raw_dir), quality]
+ if keep_blend:
+ args += ["--blend", str(blender.CACHE_ROOT / "blend" / f"RT_{deck_id}.blend")]
+ result = blender.run(REALTIME_ENTRY, args, device=device, timeout=4 * 3600)
+ out_dir = out_dir or PUBLIC_DECKS / deck_id
+ block = package_realtime.package_realtime(
+ raw_dir, out_dir, {"blender_s": round(result.seconds, 1)}
+ )
+ problems = validate.validate_deck_dir(out_dir)
+ if problems:
+ raise SystemExit("realtime export failed validation:\n " + "\n ".join(problems))
+ return block
+
+
def _main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
@@ -64,7 +99,30 @@ def _main(argv: list[str] | None = None) -> int:
deck.add_argument(
"--out", type=Path, help="output directory (default: public/verse/decks/<id>)"
)
+ deck.add_argument(
+ "--realtime", action="store_true", help="realtime (eye-level) export instead of the plate"
+ )
options = parser.parse_args(argv)
+ if options.realtime:
+ try:
+ block = cook_realtime(
+ options.deck_id,
+ options.quality,
+ keep_blend=options.keep_blend,
+ device=options.device,
+ out_dir=options.out,
+ )
+ except blender.BlenderError as error:
+ print(error, file=sys.stderr)
+ return 1
+ scene, stats = block["scene"], block["stats"]
+ print(
+ f"[verse] {options.deck_id} realtime ({block['quality']}): {scene['triangles']} "
+ f"triangles in {scene['chunks']} chunks, {len(block['lightmaps']['pages'])} lightmap "
+ f"page(s) at {stats.get('density')} px/m, {block['bytes'] / 1e6:.2f} MB; "
+ f"blender {stats.get('blender_s')} s, package {stats.get('package_s')} s"
+ )
+ return 0
try:
manifest = cook_deck(
options.deck_id,
diff --git a/scripts/verse/eyeview.py b/scripts/verse/eyeview.py
new file mode 100644
index 0000000000..1a09b260fa
--- /dev/null
+++ b/scripts/verse/eyeview.py
@@ -0,0 +1,122 @@
+"""Render eye-level Cycles views of a deck as the realtime export sees it.
+
+ python scripts/verse/eyeview.py <deck_id> <out_dir> [--rooms] [--only ROOM]
+ [--rig X,Z,YAW[,FLOOR]] [--eye X,Y,Z,YAW,PITCH] [--size 960x522]
+ [--samples 64] [--device auto|optix|cuda|cpu]
+
+Builds the deck in headless Blender (GPU lock) with every ceiling and
+ceiling ghost visible (ghosts cast shadows, as in the realtime export) and
+renders perspective views at the realtime view's 72 deg field of view:
+
+- `--rooms` (the default without other views): in every room (`--only`
+ narrows it) four headings from the inside centre at 1.9 m, plus more
+ points along long rooms. Use it to find black voids above cut walls,
+ missing ceilings and hull gaps before a realtime export
+ (docs/verse/realtime.md, "Exporting another deck").
+- `--rig x,z,yaw[,floor]`: the shoulder rig's camera behind a commander at
+ three.js (x, floor, z) facing `yaw` degrees (0 = +Z, 90 = +X); the truth
+ render to compare the browser against.
+- `--eye x,y,z,yaw,pitch`: a free camera in three.js metres (pitch down).
+
+Writes `<out_dir>/<name>.png` per view and `<out_dir>/sheet.png`, a labelled
+contact sheet of all of them.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+import blender # noqa: E402
+
+ENTRY = Path(__file__).resolve().with_name("_eyeview_entry.py")
+SHEET_TILE = (480, 261)
+SHEET_COLUMNS = 4
+
+
+def _floats(text: str) -> list[float]:
+ return [float(part) for part in text.split(",")]
+
+
+def render_views(
+ deck_id: str,
+ out_dir: Path,
+ views: list[dict],
+ *,
+ samples: int = 64,
+ size: str = "960x522",
+ device: str = "auto",
+) -> list[Path]:
+ """Render `views` of deck `deck_id`; return the PNG paths (sheet last)."""
+ out_dir = out_dir.resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ spec = out_dir / "views_in.json"
+ spec.write_text(json.dumps(views), encoding="utf-8")
+ args = [deck_id, str(out_dir), str(spec), "--samples", str(samples), "--size", size]
+ result = blender.run(ENTRY, args, device=device, timeout=3 * 3600)
+ done = json.loads((out_dir / "views.json").read_text(encoding="utf-8"))
+ paths = [out_dir / f"{view['name']}.png" for view in done]
+ sheet = out_dir / "sheet.png"
+ contact_sheet(paths, sheet)
+ print(f"[verse] {len(paths)} eye views in {result.seconds:.0f} s; sheet {sheet}")
+ return [*paths, sheet]
+
+
+def contact_sheet(paths: list[Path], target: Path) -> None:
+ """Tile the views into one labelled image."""
+ tw, th = SHEET_TILE
+ rows = max(1, -(-len(paths) // SHEET_COLUMNS))
+ sheet = Image.new("RGB", (tw * SHEET_COLUMNS, (th + 18) * rows), (12, 12, 14))
+ draw = ImageDraw.Draw(sheet)
+ for index, path in enumerate(paths):
+ x, y = (index % SHEET_COLUMNS) * tw, (index // SHEET_COLUMNS) * (th + 18)
+ with Image.open(path) as image:
+ sheet.paste(image.convert("RGB").resize((tw, th)), (x, y + 18))
+ draw.text((x + 4, y + 3), path.stem, fill=(220, 220, 220))
+ sheet.save(target)
+
+
+def _main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
+ )
+ parser.add_argument("deck_id")
+ parser.add_argument("out_dir", type=Path)
+ parser.add_argument("--rooms", action="store_true")
+ parser.add_argument("--only", action="append", default=[], help="room id (repeatable)")
+ parser.add_argument("--rig", action="append", default=[])
+ parser.add_argument("--eye", action="append", default=[])
+ parser.add_argument("--size", default="960x522")
+ parser.add_argument("--samples", type=int, default=64)
+ parser.add_argument("--device", choices=blender.DEVICES, default="auto")
+ options = parser.parse_args(argv)
+ views: list[dict] = []
+ if options.rooms or options.only or not (options.rig or options.eye):
+ views.append({"name": "rooms", "rooms": True, "only": options.only})
+ for index, text in enumerate(options.rig):
+ views.append({"name": f"rig_{index}", "rig": _floats(text)})
+ for index, text in enumerate(options.eye):
+ views.append({"name": f"eye_{index}", "eye": _floats(text)})
+ try:
+ render_views(
+ options.deck_id,
+ options.out_dir,
+ views,
+ samples=options.samples,
+ size=options.size,
+ device=options.device,
+ )
+ except blender.BlenderError as error:
+ print(error, file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(_main())
diff --git a/scripts/verse/meshopt_pack.mjs b/scripts/verse/meshopt_pack.mjs
new file mode 100644
index 0000000000..ec2a8ca838
--- /dev/null
+++ b/scripts/verse/meshopt_pack.mjs
@@ -0,0 +1,84 @@
+// Meshopt encoding for the Verse realtime export (run by scripts/verse/package_realtime.py).
+//
+// node scripts/verse/meshopt_pack.mjs <in.json> <in.bin> <out.json> <out.bin>
+//
+// in.json: { primitives: [{ vertexCount, indexOffset, indexCount, streams: [{ offset, stride }] }] }
+// in.bin: the raw (already quantised) vertex streams and uint32 indices the offsets point at.
+//
+// For every primitive the vertices are reordered for the GPU vertex cache and
+// vertex fetch (meshopt_optimizeVertexCache + optimizeVertexFetchRemap), the
+// indices narrowed to 16 bit when they fit, and every stream encoded with the
+// EXT_meshopt_compression codecs (vertex codec version 0, which every
+// decoder reads). out.json lists the encoded byte ranges in out.bin.
+//
+// The encoder is the meshoptimizer npm package the frontend already ships
+// (dodaios/ui/web/frontend/node_modules/meshoptimizer), so cooks need no
+// extra install.
+
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const encoderPath = join(here, "..", "..", "dodaios", "ui", "web", "frontend", "node_modules", "meshoptimizer", "meshopt_encoder.js");
+const { MeshoptEncoder } = await import(pathToFileURL(encoderPath).href);
+await MeshoptEncoder.ready;
+
+const [inJson, inBin, outJson, outBin] = process.argv.slice(2);
+if (!outBin) {
+ console.error("usage: meshopt_pack.mjs <in.json> <in.bin> <out.json> <out.bin>");
+ process.exit(2);
+}
+const spec = JSON.parse(readFileSync(inJson, "utf8"));
+const raw = readFileSync(inBin);
+const source = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
+
+const parts = [];
+let offset = 0;
+const push = (bytes) => {
+ const at = offset;
+ parts.push(bytes);
+ offset += bytes.byteLength;
+ const pad = (4 - (offset % 4)) % 4;
+ if (pad) {
+ parts.push(new Uint8Array(pad));
+ offset += pad;
+ }
+ return { offset: at, length: bytes.byteLength };
+};
+
+const out = [];
+for (const prim of spec.primitives) {
+ const indices = new Uint32Array(prim.indexCount);
+ new Uint8Array(indices.buffer).set(source.subarray(prim.indexOffset, prim.indexOffset + prim.indexCount * 4));
+ const [remap, unique] = MeshoptEncoder.reorderMesh(indices, true, false);
+ const streams = prim.streams.map((s) => {
+ const reordered = new Uint8Array(unique * s.stride);
+ for (let v = 0; v < prim.vertexCount; v++) {
+ const to = remap[v];
+ if (to === 0xffffffff) continue;
+ reordered.set(source.subarray(s.offset + v * s.stride, s.offset + (v + 1) * s.stride), to * s.stride);
+ }
+ const encoded = MeshoptEncoder.encodeGltfBuffer(reordered, unique, s.stride, "ATTRIBUTES");
+ return { stride: s.stride, ...push(encoded) };
+ });
+ const indexSize = unique <= 65536 ? 2 : 4;
+ const indexBytes = indexSize === 2 ? new Uint8Array(Uint16Array.from(indices).buffer) : new Uint8Array(indices.buffer);
+ const index = push(MeshoptEncoder.encodeGltfBuffer(indexBytes, indices.length, indexSize, "TRIANGLES"));
+ out.push({
+ vertexCount: unique,
+ indexCount: indices.length,
+ indexSize,
+ streams,
+ index,
+ });
+}
+
+const total = new Uint8Array(offset);
+let at = 0;
+for (const part of parts) {
+ total.set(part, at);
+ at += part.byteLength;
+}
+writeFileSync(outBin, total);
+writeFileSync(outJson, JSON.stringify({ primitives: out }));
diff --git a/scripts/verse/package.py b/scripts/verse/package.py
index a157ff9f63..723e0afd65 100644
--- a/scripts/verse/package.py
+++ b/scripts/verse/package.py
@@ -27,6 +27,7 @@ L1_DIVISOR = 8 # whole-plate overview (~24 px/m at the final density)
L0_TILE_URL = "plate/L0_{col}_{row}.avif"
MIP_TILE_URL = "plate/M{divisor}_{{col}}_{{row}}.avif"
L1_URL = "plate/L1.avif"
+REALTIME_DIR = "realtime" # written by package_realtime.py, kept by plate cooks
@dataclass(frozen=True)
@@ -186,7 +187,11 @@ def package_deck(raw_dir: Path, out_dir: Path, extra_stats: dict | None = None)
shutil.rmtree(staging, ignore_errors=True)
staging.mkdir(parents=True)
try:
- manifest = _write_deck(raw_dir, staging, cook, extra_stats or {}, started)
+ # A deck's realtime export (docs/verse/realtime.md) survives a plate cook.
+ realtime = _previous_realtime(out_dir)
+ if realtime is not None:
+ shutil.copytree(out_dir / REALTIME_DIR, staging / REALTIME_DIR)
+ manifest = _write_deck(raw_dir, staging, cook, extra_stats or {}, started, realtime)
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
raise
@@ -196,14 +201,32 @@ def package_deck(raw_dir: Path, out_dir: Path, extra_stats: dict | None = None)
return manifest
+def _previous_realtime(out_dir: Path) -> dict | None:
+ """The realtime block of the deck already at `out_dir`, if it has one and its folder."""
+ path = out_dir / "manifest.json"
+ if not path.is_file() or not (out_dir / REALTIME_DIR).is_dir():
+ return None
+ try:
+ return json.loads(path.read_text(encoding="utf-8")).get("realtime")
+ except json.JSONDecodeError:
+ return None
+
+
def _write_deck(
- raw_dir: Path, staging: Path, cook: dict, extra_stats: dict, started: float
+ raw_dir: Path,
+ staging: Path,
+ cook: dict,
+ extra_stats: dict,
+ started: float,
+ realtime: dict | None = None,
) -> dict:
plate = _encode_plate(assemble_plate(raw_dir, cook), staging)
nav = _encode_nav(raw_dir / "nav.npy", staging, cook["nav"])
shutil.copyfile(raw_dir / "occluders.glb", staging / "occluders.glb")
shutil.copyfile(raw_dir / "env.hdr", staging / "env.hdr")
manifest = build_manifest(cook, plate, nav)
+ if realtime is not None:
+ manifest["realtime"] = realtime
stats = manifest["stats"]
stats.update(extra_stats)
stats["package_s"] = round(time.monotonic() - started, 2)
diff --git a/scripts/verse/package_realtime.py b/scripts/verse/package_realtime.py
new file mode 100644
index 0000000000..7e467e9f65
--- /dev/null
+++ b/scripts/verse/package_realtime.py
@@ -0,0 +1,371 @@
+"""Realtime package step (outside Blender): raw realtime export -> runtime files.
+
+Turns `lib.realtime.export_realtime()` output (lightmap pages, reflection
+panoramas, geometry chunks, realtime.json) into
+
+ public/verse/decks/<id>/realtime/scene.glb meshopt-compressed glTF, one node per chunk
+ public/verse/decks/<id>/realtime/lm_<page>.webp lightmap pages, RGBM ("rgbm2") in RGBA WebP
+ public/verse/decks/<id>/realtime/probe_<room>.webp reflection panoramas, same encoding
+
+and the manifest's `realtime` block (schema verse.deck/1, optional). The
+folder is replaced atomically and the deck's plate content stays untouched.
+Format: docs/verse/realtime.md.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+REALTIME_DIR = "realtime"
+VERSION = 1
+ENCODING = "rgbm2"
+LM_QUALITY = 90
+PROBE_QUALITY = 94
+MESHOPT_SCRIPT = Path(__file__).with_name("meshopt_pack.mjs")
+
+# glTF constants
+BYTE, UNSIGNED_SHORT, SHORT, UNSIGNED_INT = 5120, 5123, 5122, 5125
+ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER = 34962, 34963
+
+
+def _load_lightmap():
+ path = REPO_ROOT / "art" / "verse" / "lib" / "lightmap.py"
+ spec = importlib.util.spec_from_file_location("verse_lightmap", path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules.setdefault(spec.name, module)
+ spec.loader.exec_module(module)
+ return module
+
+
+lightmap = _load_lightmap()
+
+
+# ---------------------------------------------------------------- images
+
+
+def write_rgbm_webp(radiance: np.ndarray, path: Path, span: float, quality: int) -> None:
+ """Encode linear HDR RGB as "rgbm2" in an RGBA WebP: lossy colour, lossless alpha."""
+ rgba = lightmap.rgbm_encode(radiance, span)
+ Image.fromarray(rgba, mode="RGBA").save(
+ path, format="WEBP", quality=quality, alpha_quality=100, method=6, exact=True
+ )
+
+
+# ---------------------------------------------------------------- geometry
+
+
+def _quantise(chunk: dict, arrays) -> dict:
+ """Quantised vertex streams of one chunk (KHR_mesh_quantization layout).
+
+ Positions: int16 with one uniform scale and an offset (the node's
+ transform), so world normals stay correct; normals: int8 normalised;
+ lightmap UV: uint16 normalised, glTF orientation (v down).
+ """
+ index = chunk["index"]
+ pos = np.asarray(arrays[f"{index}_pos"], dtype=np.float64)
+ nrm = np.asarray(arrays[f"{index}_nrm"], dtype=np.float64)
+ uv = np.asarray(arrays[f"{index}_uv"], dtype=np.float64)
+ idx = np.asarray(arrays[f"{index}_idx"], dtype=np.uint32)
+ low, high = pos.min(axis=0), pos.max(axis=0)
+ scale = max(float((high - low).max()), 1e-4) / 65534.0
+ offset = low + 32767.0 * scale
+ q = np.clip(np.round((pos - offset) / scale), -32767, 32767).astype(np.int16)
+ positions = np.zeros((len(pos), 4), dtype=np.int16)
+ positions[:, :3] = q
+ normals = np.zeros((len(nrm), 4), dtype=np.int8)
+ normals[:, :3] = np.clip(np.round(nrm * 127.0), -127, 127).astype(np.int8)
+ uvs = np.stack([uv[:, 0], 1.0 - uv[:, 1]], axis=1)
+ uvs = np.clip(np.round(uvs * 65535.0), 0, 65535).astype(np.uint16)
+ return {
+ "positions": positions,
+ "normals": normals,
+ "uvs": uvs,
+ "indices": idx,
+ "translation": [float(v) for v in offset],
+ "scale": scale,
+ "qmin": [int(v) for v in q.min(axis=0)],
+ "qmax": [int(v) for v in q.max(axis=0)],
+ }
+
+
+def _meshopt(quantised: list[dict], work: Path) -> tuple[dict, bytes]:
+ """Run the Node meshopt encoder over every chunk; returns (layout, encoded bytes)."""
+ blob = bytearray()
+ primitives = []
+
+ def add(data: np.ndarray) -> int:
+ at = len(blob)
+ blob.extend(np.ascontiguousarray(data).tobytes())
+ blob.extend(b"\0" * ((4 - len(blob) % 4) % 4))
+ return at
+
+ for q in quantised:
+ primitives.append(
+ {
+ "vertexCount": len(q["positions"]),
+ "indexCount": len(q["indices"]),
+ "indexOffset": add(q["indices"]),
+ "streams": [
+ {"offset": add(q["positions"]), "stride": 8},
+ {"offset": add(q["normals"]), "stride": 4},
+ {"offset": add(q["uvs"]), "stride": 4},
+ ],
+ }
+ )
+ (work / "in.json").write_text(json.dumps({"primitives": primitives}), encoding="utf-8")
+ (work / "in.bin").write_bytes(bytes(blob))
+ node = shutil.which("node")
+ if node is None:
+ raise RuntimeError("node is required for the realtime package step (meshopt encoder)")
+ subprocess.run(
+ [
+ node,
+ str(MESHOPT_SCRIPT),
+ str(work / "in.json"),
+ str(work / "in.bin"),
+ str(work / "out.json"),
+ str(work / "out.bin"),
+ ],
+ check=True,
+ )
+ layout = json.loads((work / "out.json").read_text(encoding="utf-8"))
+ return layout, (work / "out.bin").read_bytes()
+
+
+def write_glb(chunks: list[dict], arrays, path: Path, work: Path) -> dict:
+ """Write the chunks as one meshopt-compressed GLB; returns its stats."""
+ quantised = [_quantise(chunk, arrays) for chunk in chunks]
+ layout, encoded = _meshopt(quantised, work)
+ materials = sorted({chunk["material"] for chunk in chunks})
+ gltf: dict = {
+ "asset": {"version": "2.0", "generator": "Dodaios Verse realtime export"},
+ "extensionsUsed": ["EXT_meshopt_compression", "KHR_mesh_quantization"],
+ "extensionsRequired": ["EXT_meshopt_compression", "KHR_mesh_quantization"],
+ "scene": 0,
+ "scenes": [{"nodes": list(range(len(chunks)))}],
+ "nodes": [],
+ "meshes": [],
+ "materials": [{"name": name} for name in materials],
+ "accessors": [],
+ "bufferViews": [],
+ }
+ fallback = 0
+
+ def view(stream: dict, count: int, stride: int, mode: str, target: int) -> int:
+ nonlocal fallback
+ length = count * stride
+ entry = {
+ "buffer": 1,
+ "byteOffset": fallback,
+ "byteLength": length,
+ "target": target,
+ "extensions": {
+ "EXT_meshopt_compression": {
+ "buffer": 0,
+ "byteOffset": stream["offset"],
+ "byteLength": stream["length"],
+ "byteStride": stride,
+ "count": count,
+ "mode": mode,
+ }
+ },
+ }
+ if mode == "ATTRIBUTES":
+ entry["byteStride"] = stride
+ fallback += (length + 3) // 4 * 4
+ gltf["bufferViews"].append(entry)
+ return len(gltf["bufferViews"]) - 1
+
+ def accessor(**fields) -> int:
+ gltf["accessors"].append(fields)
+ return len(gltf["accessors"]) - 1
+
+ vertices = triangles = 0
+ for chunk, q, prim in zip(chunks, quantised, layout["primitives"], strict=True):
+ count = prim["vertexCount"]
+ pos_s, nrm_s, uv_s = prim["streams"]
+ position = accessor(
+ bufferView=view(pos_s, count, 8, "ATTRIBUTES", ARRAY_BUFFER),
+ componentType=SHORT,
+ count=count,
+ type="VEC3",
+ min=q["qmin"],
+ max=q["qmax"],
+ )
+ normal = accessor(
+ bufferView=view(nrm_s, count, 4, "ATTRIBUTES", ARRAY_BUFFER),
+ componentType=BYTE,
+ normalized=True,
+ count=count,
+ type="VEC3",
+ )
+ texcoord = accessor(
+ bufferView=view(uv_s, count, 4, "ATTRIBUTES", ARRAY_BUFFER),
+ componentType=UNSIGNED_SHORT,
+ normalized=True,
+ count=count,
+ type="VEC2",
+ )
+ size = prim["indexSize"]
+ indices = accessor(
+ bufferView=view(
+ prim["index"], prim["indexCount"], size, "TRIANGLES", ELEMENT_ARRAY_BUFFER
+ ),
+ componentType=UNSIGNED_SHORT if size == 2 else UNSIGNED_INT,
+ count=prim["indexCount"],
+ type="SCALAR",
+ )
+ gltf["meshes"].append(
+ {
+ "name": f"RT_{chunk['index']}",
+ "primitives": [
+ {
+ "attributes": {
+ "POSITION": position,
+ "NORMAL": normal,
+ "TEXCOORD_0": texcoord,
+ },
+ "indices": indices,
+ "material": materials.index(chunk["material"]),
+ }
+ ],
+ }
+ )
+ gltf["nodes"].append(
+ {
+ "name": f"RT_{chunk['index']}",
+ "mesh": len(gltf["meshes"]) - 1,
+ "translation": q["translation"],
+ "scale": [q["scale"]] * 3,
+ "extras": {
+ "material": chunk["material"],
+ "room": chunk["room"],
+ "page": chunk["page"],
+ },
+ }
+ )
+ vertices += count
+ triangles += prim["indexCount"] // 3
+ gltf["buffers"] = [
+ {"byteLength": len(encoded)},
+ {"byteLength": fallback, "extensions": {"EXT_meshopt_compression": {"fallback": True}}},
+ ]
+ _write_glb_file(path, gltf, encoded)
+ return {"vertices": vertices, "triangles": triangles, "chunks": len(chunks)}
+
+
+def _write_glb_file(path: Path, gltf: dict, binary: bytes) -> None:
+ text = json.dumps(gltf, separators=(",", ":")).encode("utf-8")
+ text += b" " * ((4 - len(text) % 4) % 4)
+ binary = binary + b"\0" * ((4 - len(binary) % 4) % 4)
+ total = 12 + 8 + len(text) + 8 + len(binary)
+ with path.open("wb") as handle:
+ handle.write(struct.pack("<4sII", b"glTF", 2, total))
+ handle.write(struct.pack("<I4s", len(text), b"JSON"))
+ handle.write(text)
+ handle.write(struct.pack("<I4s", len(binary), b"BIN\0"))
+ handle.write(binary)
+
+
+# ---------------------------------------------------------------- package
+
+
+def _bytes(folder: Path) -> int:
+ return sum(p.stat().st_size for p in folder.rglob("*") if p.is_file())
+
+
+def package_realtime(raw_dir: Path, deck_dir: Path, extra_stats: dict | None = None) -> dict:
+ """Write `<deck_dir>/realtime/` from the raw export and add the manifest block.
+
+ The deck must already be cooked (its manifest exists). Everything is
+ written to `realtime.staging` first and swapped in at the end.
+ """
+ started = time.monotonic()
+ manifest_path = deck_dir / "manifest.json"
+ if not manifest_path.is_file():
+ raise FileNotFoundError(f"{manifest_path} missing: cook the deck's plate first")
+ raw = json.loads((raw_dir / "realtime.json").read_text(encoding="utf-8"))
+ staging = deck_dir / f"{REALTIME_DIR}.staging"
+ shutil.rmtree(staging, ignore_errors=True)
+ staging.mkdir(parents=True)
+ try:
+ block = _write_realtime(raw_dir, staging, raw)
+ except BaseException:
+ shutil.rmtree(staging, ignore_errors=True)
+ raise
+ target = deck_dir / REALTIME_DIR
+ if target.exists():
+ shutil.rmtree(target)
+ staging.rename(target)
+ block["bytes"] = _bytes(target)
+ block["stats"].update(extra_stats or {})
+ block["stats"]["package_s"] = round(time.monotonic() - started, 2)
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ manifest["realtime"] = block
+ for _ in range(3): # the byte count includes the manifest that states it
+ manifest_path.write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
+ manifest["stats"]["bytes"] = _bytes(deck_dir)
+ manifest_path.write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
+ return block
+
+
+def _write_realtime(raw_dir: Path, out_dir: Path, raw: dict) -> dict:
+ peak = max(page["max"] for page in raw["pages"])
+ span = lightmap.rgbm_range(peak)
+ pages = []
+ for index, page in enumerate(raw["pages"]):
+ radiance = np.load(raw_dir / page["file"]).astype(np.float32)
+ name = f"lm_{index}.webp"
+ write_rgbm_webp(radiance, out_dir / name, span, LM_QUALITY)
+ pages.append(
+ {
+ "url": f"{REALTIME_DIR}/{name}",
+ "size": int(radiance.shape[0]),
+ "density": page["density"],
+ }
+ )
+ probes = []
+ for probe in raw["probes"]:
+ radiance = np.load(raw_dir / probe["file"]).astype(np.float32)
+ probe_span = lightmap.rgbm_range(float(radiance.max()))
+ name = f"probe_{probe['room']}.webp"
+ write_rgbm_webp(radiance, out_dir / name, probe_span, PROBE_QUALITY)
+ probes.append(
+ {
+ "room": probe["room"],
+ "url": f"{REALTIME_DIR}/{name}",
+ "w": int(radiance.shape[1]),
+ "h": int(radiance.shape[0]),
+ "range": probe_span,
+ "position": probe["position"],
+ "box_min": probe["box_min"],
+ "box_max": probe["box_max"],
+ }
+ )
+ with (
+ tempfile.TemporaryDirectory(prefix="verse-meshopt-") as work,
+ np.load(raw_dir / "geometry.npz") as arrays,
+ ):
+ scene = write_glb(raw["chunks"], arrays, out_dir / "scene.glb", Path(work))
+ return {
+ "version": VERSION,
+ "quality": raw["quality"],
+ "scene": {"url": f"{REALTIME_DIR}/scene.glb", **scene},
+ "lightmaps": {"encoding": ENCODING, "range": span, "pages": pages},
+ "probes": probes,
+ "materials": raw["materials"],
+ "bytes": 0,
+ "stats": dict(raw["stats"]),
+ }
diff --git a/scripts/verse/validate.py b/scripts/verse/validate.py
index 2fdb78f943..a2f08da6e4 100644
--- a/scripts/verse/validate.py
+++ b/scripts/verse/validate.py
@@ -4,8 +4,9 @@
Checks every deck manifest against art/verse/schema/deck.schema.json, file
existence and image sizes (L0 tiles, the M2/M4 mip tiles, L1), naming, cross
-references, that every socket lies inside the plate frame, and the content
-budgets.
+references, that every socket lies inside the plate frame, the optional
+realtime (eye-level) export of a deck (glTF chunks, lightmap pages, probes,
+docs/verse/realtime.md), and the content budgets.
"""
from __future__ import annotations
@@ -27,8 +28,9 @@ SCHEMA_PATH = REPO_ROOT / "art" / "verse" / "schema" / "deck.schema.json"
PUBLIC_VERSE = REPO_ROOT / "dodaios" / "ui" / "web" / "frontend" / "public" / "verse"
MB = 1024 * 1024
-BUDGET_TOTAL = 90 * MB
+BUDGET_TOTAL = 160 * MB # plates, characters and up to four realtime exports
BUDGET_PLATE = 16 * MB # L0 + mips + L1 of one deck
+BUDGET_REALTIME = 25 * MB # realtime/ of one deck: scene.glb, lightmap pages, probes
BUDGET_CHARACTER_GLB = 2 * MB
MIP_DIVISORS = (2, 4) # the tiled mip levels every cooked deck carries
CHARACTER_PREFIXES = ("SK_", "SM_", "A_", "T_")
@@ -128,6 +130,7 @@ def validate_deck_dir(deck_dir: Path, validator: Draft202012Validator | None = N
problems += _check_files(where, deck_dir, manifest)
problems += _check_references(where, manifest)
problems += _check_sockets_in_frame(where, manifest)
+ problems += _check_realtime(where, deck_dir, manifest)
return problems
@@ -309,6 +312,99 @@ def _check_sockets_in_frame(where: str, manifest: dict) -> list[str]:
return problems
+def image_size(path: Path) -> tuple[int, int, str]:
+ with Image.open(path) as image:
+ return image.width, image.height, image.mode
+
+
+def _check_realtime(where: str, deck_dir: Path, manifest: dict) -> list[str]:
+ """The eye-level export: every file it names, the glTF chunks, the budget."""
+ block = manifest.get("realtime")
+ folder = deck_dir / "realtime"
+ if block is None:
+ return [
+ f"{where}: realtime/ exists but the manifest has no realtime block"
+ ] * folder.is_dir()
+ problems: list[str] = []
+ expected: set[str] = set()
+ rooms = {room["id"] for room in manifest["rooms"]}
+ pages = block["lightmaps"]["pages"]
+ for index, page in enumerate(pages):
+ expected.add(Path(page["url"]).name)
+ path = deck_dir / page["url"]
+ if not path.is_file():
+ problems.append(f"{where}: missing {page['url']}")
+ continue
+ width, height, mode = image_size(path)
+ if (width, height) != (page["size"], page["size"]):
+ problems.append(
+ f"{where}: lightmap page {index} is {width}x{height}, not {page['size']}"
+ )
+ if mode != "RGBA":
+ problems.append(f"{where}: lightmap page {index} is {mode}, rgbm2 needs RGBA")
+ for probe in block["probes"]:
+ expected.add(Path(probe["url"]).name)
+ path = deck_dir / probe["url"]
+ if probe["room"] not in rooms:
+ problems.append(f"{where}: realtime probe for unknown room {probe['room']!r}")
+ if not path.is_file():
+ problems.append(f"{where}: missing {probe['url']}")
+ continue
+ width, height, mode = image_size(path)
+ if (width, height) != (probe["w"], probe["h"]) or mode != "RGBA":
+ problems.append(f"{where}: probe {probe['room']} is {width}x{height} {mode}")
+ scene = block["scene"]
+ expected.add(Path(scene["url"]).name)
+ path = deck_dir / scene["url"]
+ if not path.is_file():
+ problems.append(f"{where}: missing {scene['url']}")
+ else:
+ problems += _check_realtime_glb(where, path, block, rooms, len(pages))
+ if folder.is_dir():
+ extra = {p.name for p in folder.iterdir()} - expected
+ if extra:
+ problems.append(f"{where}: stray files in realtime/: {sorted(extra)}")
+ size = sum(p.stat().st_size for p in folder.rglob("*") if p.is_file())
+ if size != block["bytes"]:
+ problems.append(
+ f"{where}: realtime/ is {size} bytes, the manifest says {block['bytes']}"
+ )
+ if size > BUDGET_REALTIME:
+ budget = BUDGET_REALTIME // MB
+ problems.append(f"{where}: realtime/ is {size / MB:.2f} MB (budget {budget} MB)")
+ return problems
+
+
+def _check_realtime_glb(
+ where: str, path: Path, block: dict, rooms: set[str], pages: int
+) -> list[str]:
+ try:
+ gltf = glb_json(path)
+ except ValueError as error:
+ return [f"{where}: {error}"]
+ problems = []
+ required = set(gltf.get("extensionsRequired", []))
+ if required - {"EXT_meshopt_compression", "KHR_mesh_quantization"}:
+ problems.append(f"{where}: scene.glb requires unsupported extensions {sorted(required)}")
+ nodes = [node for node in gltf.get("nodes", []) if "mesh" in node]
+ chunks = block["scene"]["chunks"]
+ if len(nodes) != chunks:
+ problems.append(f"{where}: scene.glb has {len(nodes)} chunks, the manifest says {chunks}")
+ for node in nodes:
+ extras = node.get("extras") or {}
+ name = node.get("name", "?")
+ if extras.get("material") not in block["materials"]:
+ problems.append(
+ f"{where}: chunk {name} uses unknown material {extras.get('material')!r}"
+ )
+ if extras.get("room") not in rooms:
+ problems.append(f"{where}: chunk {name} names unknown room {extras.get('room')!r}")
+ page = extras.get("page")
+ if not isinstance(page, int) or not 0 <= page < pages:
+ problems.append(f"{where}: chunk {name} names lightmap page {page!r} of {pages}")
+ return problems
+
+
# ---------------------------------------------------------------- whole tree
diff --git a/tests/verse/test_verse_realtime.py b/tests/verse/test_verse_realtime.py
new file mode 100644
index 0000000000..5fb535667f
--- /dev/null
+++ b/tests/verse/test_verse_realtime.py
@@ -0,0 +1,260 @@
+"""Gate for the realtime (eye-level) export pieces that run without Blender:
+lightmap packing, gap filling, denoising, the rgbm2 encoding, the GLB writer
+and the validator's realtime checks (docs/verse/realtime.md)."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import shutil
+import struct
+import sys
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+TOOLS = REPO_ROOT / "scripts" / "verse"
+
+
+def _load(name: str, path: Path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+lightmap = _load("verse_lightmap_test", REPO_ROOT / "art" / "verse" / "lib" / "lightmap.py")
+package_realtime = _load("verse_package_realtime", TOOLS / "package_realtime.py")
+validate = _load("verse_validate_rt", TOOLS / "validate.py")
+
+REALTIME_DECKS = sorted(
+ p
+ for p in (validate.PUBLIC_VERSE / "decks").glob("*")
+ if (p / "manifest.json").is_file()
+ and "realtime" in json.loads((p / "manifest.json").read_text(encoding="utf-8"))
+)
+
+
+# ---------------------------------------------------------------- packing
+
+
+def test_packing_keeps_rectangles_apart_and_on_their_page() -> None:
+ rng = np.random.default_rng(3)
+ sizes = [(float(w), float(h)) for w, h in rng.integers(4, 300, size=(400, 2))]
+ groups = [int(g) for g in rng.integers(0, 4, size=400)]
+ pad = 7
+ placements = lightmap.pack_skyline(sizes, groups, 1024, pad)
+ boxes = {}
+ for (w, h), place in zip(sizes, placements, strict=True):
+ w, h = int(np.ceil(w * place.scale)), int(np.ceil(h * place.scale))
+ assert place.x >= pad and place.y >= pad
+ assert place.x + w <= 1024 - pad + 1 and place.y + h <= 1024 - pad + 1
+ boxes.setdefault(place.page, []).append(
+ (place.x - pad, place.y - pad, w + 2 * pad, h + 2 * pad)
+ )
+ for page in boxes.values():
+ for i, (ax, ay, aw, ah) in enumerate(page):
+ for bx, by, bw, bh in page[i + 1 :]:
+ assert ax + aw <= bx or bx + bw <= ax or ay + ah <= by or by + bh <= ay
+
+
+def test_packing_keeps_a_room_together() -> None:
+ sizes = [(100.0, 100.0)] * 6
+ placements = lightmap.pack_skyline(sizes, [0, 1, 0, 1, 0, 1], 512, 2)
+ rows = {}
+ for group, place in zip([0, 1, 0, 1, 0, 1], placements, strict=True):
+ rows.setdefault(group, []).append((place.page, place.y, place.x))
+ # Group 0 is placed before group 1 starts.
+ assert max(rows[0]) < min(rows[1])
+
+
+def test_oversized_rectangles_shrink_to_fit_a_page() -> None:
+ (place,) = lightmap.pack_skyline([(5000.0, 100.0)], [0], 1024, 4)
+ assert place.scale < 1 and 5000 * place.scale <= 1024 - 8 + 1
+
+
+def test_packing_fills_most_of_a_page_with_mixed_sizes() -> None:
+ # A few floors and walls a third of a page wide among hundreds of props.
+ rng = np.random.default_rng(5)
+ big = [(float(w), float(h)) for w, h in rng.integers(150, 450, size=(6, 2))]
+ small = [(float(w), float(h)) for w, h in rng.integers(4, 90, size=(300, 2))]
+ sizes = big + small
+ placements = lightmap.pack_skyline(sizes, [0] * len(sizes), 1024, 3)
+ assert max(p.page for p in placements) == 1
+ pairs = zip(sizes, placements, strict=True)
+ first = sum((w + 6) * (h + 6) for (w, h), p in pairs if p.page == 0)
+ assert first / (1024 * 1024) > 0.8 # the full first page (shelves: about half)
+
+
+# ---------------------------------------------------------------- filtering
+
+
+def test_fill_gaps_keeps_covered_texels_and_fills_the_rest() -> None:
+ image = np.zeros((32, 32, 3), np.float32)
+ covered = np.zeros((32, 32), bool)
+ image[4:10, 4:10] = (1.0, 2.0, 3.0)
+ covered[4:10, 4:10] = True
+ filled = lightmap.fill_gaps(image, covered)
+ assert np.allclose(filled[covered], image[covered])
+ assert np.isfinite(filled).all()
+ assert np.allclose(filled[20, 20], (1.0, 2.0, 3.0), atol=1e-4)
+
+
+def test_denoise_smooths_noise_but_not_across_a_corner() -> None:
+ rng = np.random.default_rng(1)
+ h, w = 64, 64
+ irradiance = np.ones((h, w, 3), np.float32)
+ irradiance[:, 32:] = 5.0
+ noisy = irradiance * (1 + 0.3 * rng.standard_normal((h, w, 1)).astype(np.float32))
+ normal = np.zeros((h, w, 3), np.float32)
+ normal[:, :32] = (0, 0, 1)
+ normal[:, 32:] = (1, 0, 0) # a corner between the two halves
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32) * 0.03
+ position = np.stack([xx, yy, np.zeros_like(xx)], axis=2)
+ covered = np.ones((h, w), bool)
+ out = lightmap.denoise(noisy, normal, position, covered, texel_m=0.03, passes=3)
+ assert np.std(out[:, 4:28]) < 0.5 * np.std(noisy[:, 4:28])
+ # No light bleeds over the corner: the dim side stays dim right next to it.
+ assert abs(float(out[:, 31].mean()) - 1.0) < 0.15
+ assert abs(float(out[:, 32].mean()) - 5.0) < 0.6
+
+
+# ---------------------------------------------------------------- rgbm2
+
+
[email protected]("value", [0.0005, 0.01, 0.3, 1.0, 7.5, 31.0])
+def test_rgbm2_round_trips_within_one_percent(value: float) -> None:
+ radiance = np.array([[[value, value * 0.5, value * 0.25]]], np.float32)
+ span = lightmap.rgbm_range(32.0)
+ back = lightmap.rgbm_decode(lightmap.rgbm_encode(radiance, span), span)
+ assert np.allclose(back[..., 0], value, rtol=0.012, atol=2e-6)
+ assert np.allclose(back[..., 2], value * 0.25, rtol=0.03, atol=2e-5)
+
+
+def test_rgbm2_range_is_a_power_of_two_capped_at_64() -> None:
+ assert lightmap.rgbm_range(0.3) == 1.0
+ assert lightmap.rgbm_range(24.0) == 32.0
+ assert lightmap.rgbm_range(500.0) == 64.0
+
+
+def test_rgbm2_webp_keeps_its_alpha_exactly(tmp_path: Path) -> None:
+ rng = np.random.default_rng(5)
+ radiance = (rng.random((64, 64, 3)) ** 4 * 20).astype(np.float32)
+ path = tmp_path / "page.webp"
+ package_realtime.write_rgbm_webp(radiance, path, 32.0, 90)
+ with Image.open(path) as image:
+ assert image.mode == "RGBA"
+ decoded = np.asarray(image)
+ assert np.array_equal(decoded[..., 3], lightmap.rgbm_encode(radiance, 32.0)[..., 3])
+
+
+# ---------------------------------------------------------------- glTF
+
+
+def _glb_parts(path: Path) -> tuple[dict, bytes]:
+ data = path.read_bytes()
+ magic, version, total = struct.unpack("<4sII", data[:12])
+ assert magic == b"glTF" and version == 2 and total == len(data)
+ length, kind = struct.unpack("<I4s", data[12:20])
+ assert kind == b"JSON"
+ gltf = json.loads(data[20 : 20 + length])
+ bin_length, bin_kind = struct.unpack("<I4s", data[20 + length : 28 + length])
+ assert bin_kind == b"BIN\0"
+ return gltf, data[28 + length : 28 + length + bin_length]
+
+
[email protected](shutil.which("node") is None, reason="node runs the meshopt encoder")
+def test_glb_writer_emits_quantised_meshopt_chunks(tmp_path: Path) -> None:
+ encoder = REPO_ROOT / "dodaios/ui/web/frontend/node_modules/meshoptimizer/meshopt_encoder.js"
+ if not encoder.is_file():
+ pytest.skip("frontend node_modules not installed")
+ pos = np.array([[0, 0, 0], [2, 0, 0], [2, 0, 3], [0, 0, 3]], np.float32)
+ arrays = {
+ "0_pos": pos,
+ "0_nrm": np.tile(np.array([[0, 1, 0]], np.float32), (4, 1)),
+ "0_uv": np.array([[0, 0], [1, 0], [1, 1], [0, 1]], np.float32),
+ "0_idx": np.array([0, 1, 2, 0, 2, 3], np.uint32),
+ }
+ chunks = [{"index": 0, "material": "M_Floor_GlossBlack", "room": "bridge", "page": 0}]
+ stats = package_realtime.write_glb(chunks, arrays, tmp_path / "scene.glb", tmp_path)
+ assert stats == {"vertices": 4, "triangles": 2, "chunks": 1}
+ gltf, _ = _glb_parts(tmp_path / "scene.glb")
+ assert set(gltf["extensionsRequired"]) == {"EXT_meshopt_compression", "KHR_mesh_quantization"}
+ (node,) = gltf["nodes"]
+ assert node["extras"] == {"material": "M_Floor_GlossBlack", "room": "bridge", "page": 0}
+ # Dequantised positions reproduce the chunk: translation + scale * q.
+ accessor = gltf["accessors"][gltf["meshes"][0]["primitives"][0]["attributes"]["POSITION"]]
+ lo = np.array(node["translation"]) + node["scale"][0] * np.array(accessor["min"])
+ hi = np.array(node["translation"]) + node["scale"][0] * np.array(accessor["max"])
+ assert np.allclose(lo, pos.min(axis=0), atol=1e-3)
+ assert np.allclose(hi, pos.max(axis=0), atol=1e-3)
+ for view in gltf["bufferViews"]:
+ assert view["extensions"]["EXT_meshopt_compression"]["buffer"] == 0
+
+
+# ---------------------------------------------------------------- validator
+
+
[email protected]("deck_dir", REALTIME_DECKS, ids=[p.name for p in REALTIME_DECKS])
+def test_realtime_export_fits_its_budget(deck_dir: Path) -> None:
+ manifest = json.loads((deck_dir / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["realtime"]["bytes"] <= validate.BUDGET_REALTIME
+
+
[email protected](not REALTIME_DECKS, reason="no deck has a realtime export yet")
+def test_validator_catches_broken_realtime_exports(tmp_path: Path) -> None:
+ source = REALTIME_DECKS[0]
+ deck = tmp_path / source.name
+ shutil.copytree(source, deck)
+ assert validate.validate_deck_dir(deck) == []
+ manifest_path = deck / "manifest.json"
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ manifest["realtime"]["probes"][0]["room"] = "nowhere"
+ manifest["realtime"]["scene"]["chunks"] += 1
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
+ (deck / "realtime" / "stray.bin").write_bytes(b"x")
+ (deck / manifest["realtime"]["lightmaps"]["pages"][0]["url"]).unlink()
+ problems = "\n".join(validate.validate_deck_dir(deck))
+ assert "unknown room 'nowhere'" in problems
+ assert "chunks, the manifest says" in problems
+ assert "stray files in realtime/" in problems
+ assert "missing realtime/lm_0.webp" in problems
+ del manifest["realtime"]
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
+ assert any("no realtime block" in p for p in validate.validate_deck_dir(deck))
+
+
+package = _load("verse_package_rt", TOOLS / "package.py")
+
+
+def test_a_plate_cook_keeps_the_realtime_export(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(package, "TILE_PX", 256)
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ np.save(raw / "plate_0.npy", np.zeros((320, 640, 3), np.uint8))
+ np.save(raw / "nav.npy", np.full((4, 4), 128, np.uint8))
+ (raw / "occluders.glb").write_bytes(b"glb")
+ (raw / "env.hdr").write_bytes(b"#?RADIANCE")
+ cook = {
+ "id": "deck", "name": "Deck", "floor": 1, "quality": "preview",
+ "camera": {"plate_w_px": 640, "plate_h_px": 320},
+ "plate_parts": [{"file": "plate_0.npy", "row0": 0, "row1": 320, "col0": 0, "col1": 640}],
+ "nav": {"w": 4, "h": 4}, "occluders": {"triangles": 1}, "env": {},
+ "probes": [], "rooms": [], "sockets": [], "stations": [], "stats": {},
+ } # fmt: skip
+ (raw / "cook.json").write_text(json.dumps(cook), encoding="utf-8")
+ out = tmp_path / "deck"
+ (out / "realtime").mkdir(parents=True)
+ (out / "realtime" / "scene.glb").write_bytes(b"scene")
+ block = {"version": 1, "bytes": 5}
+ (out / "manifest.json").write_text(json.dumps({"realtime": block}), encoding="utf-8")
+ manifest = package.package_deck(raw, out)
+ assert manifest["realtime"] == block
+ assert (out / "realtime" / "scene.glb").read_bytes() == b"scene"
+ assert json.loads((out / "manifest.json").read_text(encoding="utf-8"))["realtime"] == block