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): first-person viewmodel with the commander's arms and the duel blaster (#913)

Ruben Lütke64665ddc37a7
diff --git a/docs/verse/combat.md b/docs/verse/combat.md
index 574876c222..5ea5a2adfc 100644
--- a/docs/verse/combat.md
+++ b/docs/verse/combat.md
@@ -744,6 +744,7 @@ stands in the line of fire.
| Q | energy shield (hold) |
| Space | dodge roll in the move direction |
| R | vent; again inside the gold window: perfect vent |
+| 2 / 3, V | fight over the shoulder / through the eyes (V toggles); the bird's-eye view waits for the match's end |
| Esc | pause; again: leave |
Presses are latched until the next frame reads them. Keys the duel uses never
@@ -755,8 +756,17 @@ again (*Click to aim* shows under the crosshair).
`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
+is fought in the person the deck was seen in: over the shoulder from third
+person (or the bird's-eye view), through the eyes from first person; 2, 3
+and V switch mid-match and the camera blends over about a fifth of a second.
+Through the eyes (`firstPerson`) the camera sits at the duellist's eyes
+(1.65 m, 0.1 m ahead of the body's axis, kept 0.12 m short of a wall in
+front), dips through a dodge roll and falls with a knocked-out body; its field
+of view is the person's first-person setting on the frame's aspect, narrowed
+in the sights and widened in a sprint by the same ratios as the rigs
+(`firstFov`); recoil and shake apply as over the shoulder. The person's own
+body is hidden and the first-person viewmodel (realtime.md, "First-person
+viewmodel") holds the blaster. Over the shoulder 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
(50 deg hip, about 80 deg across a 16:9 frame, the angle the bot's perception
diff --git a/docs/verse/realtime.md b/docs/verse/realtime.md
index a4c4265afd..9c0203e57c 100644
--- a/docs/verse/realtime.md
+++ b/docs/verse/realtime.md
@@ -170,6 +170,9 @@ Code: `src/components/society/verse/engine/realtime/`.
| `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 first-person viewmodel (the commander's own arms and, in a duel, the
+blaster) lives in `src/components/society/verse/viewmodel/` (below).
+
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,
@@ -252,12 +255,53 @@ mid-thigh up, the room at eye level in depth.
| 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 |
+| 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, where the viewmodel's arms take over |
| 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 |
+### First-person viewmodel
+
+In first person the commander sees their own arms: gloved hands at the
+bottom of the frame on the deck, and in a duel fought through the eyes the
+blaster in the right hand with the left supporting it. Code:
+`src/components/society/verse/viewmodel/`.
+
+| File | Role |
+|---|---|
+| `motion.ts` | Pure: who is drawn (`viewmodelVisibility`: arms in exactly where the third-person body goes out, past 30 % of the blend; the body also goes when a wall pushes the shoulder camera within 0.55 m), the walk bob (a dip per footfall, a sway per stride, scaled by ground speed / walk speed up to 1.7), idle breathing, look lag (the arms trail a turn by up to 0.07 rad and settle in ~0.1 s) and the recoil spring (a shot kicks the blaster back ~2 cm and the muzzle up ~2.5°, settling in ~0.25 s). prefers-reduced-motion drops bob, sway and lag and halves the recoil. |
+| `arms.ts` | The arms, procedural: sleeves in the commander's uniform colour (the rank tier's `M_Uniform`), a gauntleted glove (rounded palm, armoured knuckle plate, a panel in the uniform's trim, two-segment lathe-turned fingers and thumb that curl by a parameter), two-bone IK from shoulder to wrist (`solveElbow`), the forearm turned so its back follows the back of the hand. The left forearm carries the shield emitter. |
+| `viewmodel.ts` | The rig, its own scene and camera, posed every frame in the camera's space; the layout (`VIEWMODEL`: poses, holds, shoulders, field of view, light). |
+| `viewmodelPass.ts` | The draw: a pass in the eye view's post chain after the deck's render pass, into the same multisampled HDR target with depth cleared first (so the arms get the deck's anti-aliasing, bloom and AgX and never meet a wall); on the low tier the same draw straight to the screen. No full-screen pass of its own. |
+| `ViewmodelLayer.tsx` | Mounts the viewmodel on a stage with an eye-level view (`runtime.viewmodel`) and tells it each frame what to show: the deck's hands, the duel's blaster, or nothing. |
+
+The viewmodel camera takes the eye camera's orientation but sits at the
+origin with its own near plane (1 cm) and a fixed horizontal field of view
+(88°, 76° in the sights), so the arms keep their shape whatever the person's
+field-of-view setting. Because the rig is turned with the view, the room's
+SH probe (`RoomLight`) and the deck's environment light it as they light the
+deck; a soft key light over the shoulder (divided by the deck's exposure, so
+it reads the same on every deck) keeps dark uniforms and gloves legible.
+
+In a duel the blaster is the duel's own model (`buildBlaster`, chamfered
+edges for the close view, the stock left out so it never hides the right
+hand, the sight's glowing pane swapped for a see-through reticle). Poses,
+blended over ~0.1 s: hip (bottom right, canted in), sights (`ads` moves the
+sight's window onto the view axis 0.3 m ahead; the field of view narrows),
+sprint (carried low and turned in), shield (Q: the blaster drops, the left
+forearm comes up before the face, palm forward, its emitter lit with the
+shield's energy and flaring on a parry), vent (R: the blaster tips up and the
+left hand slaps the receiver's side), knocked out (the arms drop away). A
+dodge dips the arms. Each shot kicks the recoil spring and flashes at the
+muzzle (a sprite and a short light on the hands); the world's own muzzle
+flash and vent steam for the person are skipped in first person. About
+6,500 triangles and ~65 small draws in a duel (fewer on the deck); the world pass is unchanged.
+
+Development handle (dev builds only): `window.__verseViewmodel = { layout,
+arm, motion, retune(), viewmodel }` tunes the layout live: change `layout`
+(or `arm`), then `retune()`.
+
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
@@ -334,8 +378,8 @@ packing rebuild the bridge's pages held 3-15 %. The bridge numbers in
## 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.
+- The viewmodel's arms are procedural (no skinned mesh): the fingers curl as
+ one per hand, there is no reload or inspect animation beyond the vent slap.
- There are no strafe or backwards clips: strafing leans the walk up to 45°,
backwards plays the walk in reverse.
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 4c94244c4a..964297d037 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/VerseStage.tsx
@@ -77,6 +77,7 @@ import { REACTOR_ARENA } from "./combat/arenaReactor";
import { DuelController, type DuelDifficulty } from "./duel/duelController";
import { attachDuelInput } from "./duel/duelInput";
import { DuelLayer } from "./duel/DuelLayer";
+import { ViewmodelLayer } from "./viewmodel/ViewmodelLayer";
import { DuelHud } from "./hud/DuelHud";
import { DuelPanel } from "./hud/DuelPanel";
import "./verse.css";
@@ -268,7 +269,10 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
duel.camera.sensitivity = sensitivity;
duel.camera.invertY = invertY;
duel.camera.hfovSetting = fovThird;
+ duel.camera.hfovFirst = fovFirst;
}, [runtime, duel, sensitivity, invertY, fovThird, fovFirst]);
+ // A duel is fought in the person the deck was seen in: through the eyes in first person, else over the shoulder.
+ useEffect(() => { duel.camera.firstPerson = view === "first"; }, [duel, view]);
// The doors open once the car has arrived and the new deck is on screen (or after a moment, whatever happens).
useEffect(() => {
@@ -507,6 +511,14 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
},
relock: () => duelActions.current.lockAim(),
live: () => duel.live,
+ // 2 and 3 (and V) switch between the shoulder and the eyes mid-match; the bird's-eye view waits for the end.
+ view: (code) => {
+ const direct = viewForKey(code);
+ const next = code === "KeyV" ? (viewRef.current === "first" ? "third" : "first") : direct;
+ if (!next || next === "overview") return false;
+ keyActions.current.showView(next);
+ return true;
+ },
});
}
// Third and first person: shooter mouse look (a click takes the mouse), the wheel zooms and hands over between them.
@@ -868,6 +880,9 @@ export function VerseStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenG
{deck && !problem && eyeCapable && dueling && (
<DuelLayer runtime={runtime} controller={duel} deck={deck} library={library} commanderId={COMMANDER_ID} commanderLook={commanderLook} />
)}
+ {deck && !problem && eyeCapable && (
+ <ViewmodelLayer runtime={runtime} duel={duel} deck={deck} library={library} commanderId={COMMANDER_ID} commanderLook={commanderLook} />
+ )}
{deck && !problem && (
<DeckBackdrop runtime={runtime} deck={deck} debug={debug} awake={awake} active={!eyeOn} onReady={onPlateReady} onError={onFailure}>
<DeckEnvironment url={deck.envUrl} />
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
index 5e742dc716..5b00790830 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/duel/DuelLayer.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/DuelLayer.tsx
@@ -6,6 +6,10 @@
* flashes, impact sparks and scorches, hit sparks, block ripples, parry
* bursts, overheat steam).
*
+ * In first person the person's own body is not drawn (the viewmodel's arms
+ * and blaster stand in for it, `viewmodel/`), and their muzzle flashes and
+ * vent steam come from the viewmodel's blaster instead.
+ *
* Mounted inside the stage's Canvas while a duel is on; everything it adds
* to the scene goes again when it unmounts.
*/
@@ -24,6 +28,7 @@ import type { DuelController } from "./duelController";
import { BoltPool, Flashes, radialTexture, Scorches, Sparks, Steam } from "./effects";
import { DuelFigure, type FigureLook } from "./figure";
import { ShieldMesh } from "./shield";
+import { HIDE_BODY_FIRST_SHARE } from "../viewmodel/motion";
interface Props {
runtime: StageRuntime;
@@ -41,7 +46,8 @@ export const OPPONENT_LOOK: FigureLook = {
accent: new Color(1, 0.16, 0.08),
};
-const OWN_ACCENT = new Color(1, 0.6, 0.15);
+/** The person's blaster cells (amber). */
+export 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);
@@ -129,6 +135,8 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
}
fx.group.visible = true;
const floorY = controller.floorY;
+ const eyeCamera = runtime.eye?.camera;
+ if (eyeCamera) controller.camera.aspect = eyeCamera.aspect;
controller.frame(Math.min(dt, 0.25) * 1000, runtime.eye?.test ?? null);
const view = controller.view;
if (!view) return;
@@ -141,6 +149,9 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
const step = controller.phase === "paused" ? 0 : Math.min(dt, 0.1);
scratch.time += step;
const mySlot = view.slot;
+ // Through the eyes the person's own body is hidden; the viewmodel draws their arms and blaster.
+ const ownHidden = controller.camera.firstShare > HIDE_BODY_FIRST_SHARE;
+ if (figures.current.own) figures.current.own.group.visible = !ownHidden;
const bySlot = (slot: number) => (slot === mySlot ? figures.current.own : figures.current.foe);
for (const p of view.players) {
const f = bySlot(p.slot);
@@ -148,7 +159,7 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
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)) {
+ if (f && p.alive && (p.venting || p.heat > 0.85) && !(k === 0 && ownHidden)) {
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); }
@@ -170,6 +181,7 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
switch (e.type) {
case "shot": {
const own = e.player === mySlot;
+ if (own && ownHidden) break;
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);
@@ -211,6 +223,7 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
fx.shields[e.player === mySlot ? 0 : 1].shatter();
break;
case "overheat": {
+ if (e.player === mySlot && ownHidden) break;
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;
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
index 6507898305..ec0d6dfae9 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/duel/blaster.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/blaster.ts
@@ -12,12 +12,19 @@
import {
BoxGeometry, Color, CylinderGeometry, Group, Mesh, MeshStandardMaterial, TorusGeometry, Vector3, type BufferGeometry, type Material,
} from "three";
+import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";
export interface Blaster {
group: Group;
/** Muzzle point and the left hand's hold point, local. */
muzzle: Vector3;
fore: Vector3;
+ /** The centre of the holographic sight's window, local (aiming down the sights puts it on the eye line). */
+ sight: Vector3;
+ /** The sight's glowing pane (the first-person view swaps it for a see-through reticle). */
+ sightGlass: Mesh;
+ /** The stock's parts (the first-person view leaves them out: they would hide the right hand). */
+ stock: Mesh[];
materials: Material[];
/** Heat 0..1; `venting` pulses the vents; `overheated` turns them red. */
setHeat(heat: number, venting: boolean, overheated: boolean, timeS: number): void;
@@ -36,7 +43,15 @@ 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 {
+export interface BlasterOptions {
+ /**
+ * Chamfer the boxes' edges so they catch the light (the first-person view, a hand's breadth from the eye).
+ * The duellists' blasters, seen from metres away, keep plain boxes.
+ */
+ bevel?: boolean;
+}
+
+export function buildBlaster(accent: Color, options: BlasterOptions = {}): Blaster {
const group = new Group();
group.name = "DuelBlaster";
// Built at true size, drawn a little larger so it reads at shoulder-camera distance.
@@ -62,32 +77,40 @@ export function buildBlaster(accent: Color): Blaster {
parts.add(m);
return m;
};
+ const box = (w: number, h: number, d: number): BufferGeometry =>
+ options.bevel ? new RoundedBoxGeometry(w, h, d, 1, Math.min(w, h, d) * 0.22) : new BoxGeometry(w, h, d);
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);
+ add(box(0.056, 0.078, 0.32), graphite, 0, 0.012, 0.06);
+ add(box(0.06, 0.03, 0.2), steel, 0, -0.03, 0.03);
+ add(box(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);
+ add(box(0.004, 0.016, 0.17), cells, 0.0295, 0.016, 0.07);
+ add(box(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);
+ for (let i = 0; i < 3; i++) add(box(0.03, 0.006, 0.022), vents, 0, 0.04, 0.25 + i * 0.045);
+ add(box(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);
+ add(box(0.028, 0.012, 0.08), steel, 0, 0.058, 0.0);
+ // The sight's frame is open (four bars), so the first-person view can look through it.
+ add(box(0.03, 0.004, 0.006), gold, 0, 0.091, 0.035);
+ add(box(0.03, 0.004, 0.006), gold, 0, 0.066, 0.035);
+ add(box(0.004, 0.03, 0.006), gold, 0.013, 0.0785, 0.035);
+ add(box(0.004, 0.03, 0.006), gold, -0.013, 0.0785, 0.035);
+ const sightGlass = add(new BoxGeometry(0.022, 0.021, 0.002), emitter, 0, 0.0785, 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);
+ add(box(0.034, 0.105, 0.042), grip, 0, -0.06, -0.01, -0.28);
+ add(box(0.008, 0.008, 0.07), steel, 0, -0.06, 0.04);
+ const stock = [
+ add(box(0.04, 0.06, 0.13), graphite, 0, -0.005, -0.15, 0.12),
+ add(box(0.044, 0.07, 0.014), gold, 0, -0.01, -0.22, 0.12),
+ ];
const base = { cells: accent.clone() };
const tmp = new Color();
@@ -95,6 +118,9 @@ export function buildBlaster(accent: Color): Blaster {
group,
muzzle: new Vector3(0, 0.012, 0.49).multiplyScalar(BLASTER_SCALE),
fore: new Vector3(0, -0.02, 0.29).multiplyScalar(BLASTER_SCALE),
+ sight: new Vector3(0, 0.0785, 0.034).multiplyScalar(BLASTER_SCALE),
+ sightGlass,
+ stock,
materials,
setHeat(heat, venting, overheated, timeS) {
const h = Math.max(0, Math.min(1, heat));
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
index d307521c8f..e45d731977 100644
--- 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
@@ -9,7 +9,8 @@ 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, duelFov } from "./duelCamera";
+import { SHOULDER } from "../engine/realtime/shoulderRig";
+import { DuelCamera, DUEL_CAMERA, duelFov, firstFov } from "./duelCamera";
import { DuelController, type DuelExit } from "./duelController";
import { buildHudModel, DuelHudFeed, HUD_TIMES } from "./duelHud";
import { DuelInput, isDuelKey } from "./duelInput";
@@ -175,6 +176,65 @@ describe("duel camera", () => {
expect(pose.dir.y).toBeGreaterThan(0.015);
expect(pose.aimDir.y).toBeCloseTo(0, 6);
});
+
+ it("fights through the eyes in first person, with the first-person field of view", () => {
+ const cam = new DuelCamera();
+ cam.firstPerson = true;
+ cam.face(0);
+ const p = player();
+ const pose = cam.update(1 / 60, p, 0);
+ expect(cam.firstShare).toBe(1);
+ // At eye height, a little ahead of the body's axis along the view (+Z), not beside the head.
+ expect(pose.position.y).toBeCloseTo(DUEL_CAMERA.eyeHeight, 6);
+ expect(pose.position.x).toBeCloseTo(p.x, 6);
+ expect(pose.position.z).toBeCloseTo(p.z + DUEL_CAMERA.eyeForward, 6);
+ expect(pose.fovDeg).toBeCloseTo(firstFov(50, SHOULDER.firstHfovDeg, 16 / 9), 3);
+ // The sights narrow it.
+ const hipFov = pose.fovDeg;
+ let ads = hipFov;
+ for (let i = 0; i < 60; i++) ads = cam.update(1 / 60, player({ ads: 1 }), 0).fovDeg;
+ expect(ads).toBeLessThan(hipFov);
+ // A wider first-person setting widens it.
+ expect(firstFov(50, 100)).toBeGreaterThan(firstFov(50, 85));
+ });
+
+ it("blends between the shoulder and the eyes when the person changes mid-match", () => {
+ const cam = new DuelCamera();
+ cam.face(0);
+ const third = cam.update(1 / 60, player(), 0).position.y;
+ cam.firstPerson = true;
+ cam.update(1 / 60, player(), 0);
+ expect(cam.firstShare).toBeGreaterThan(0);
+ expect(cam.firstShare).toBeLessThan(1);
+ for (let i = 0; i < 60; i++) cam.update(1 / 60, player(), 0);
+ expect(cam.firstShare).toBe(1);
+ cam.firstPerson = false;
+ for (let i = 0; i < 60; i++) cam.update(1 / 60, player(), 0);
+ expect(cam.firstShare).toBe(0);
+ expect(cam.pose.position.y).toBeCloseTo(third, 3);
+ });
+
+ it("dips the eyes through a dodge roll, drops them when knocked out, keeps them off a wall ahead", () => {
+ const cam = new DuelCamera();
+ cam.firstPerson = true;
+ cam.face(0);
+ const rolling = cam.update(1 / 60, player({ dodging: true, dodgeProgress: 0.5 }), 0).position.y;
+ expect(rolling).toBeLessThan(DUEL_CAMERA.eyeHeight - 0.4);
+ let down = 0;
+ for (let i = 0; i < 60; i++) down = cam.update(1 / 60, player({ alive: false }), 0).position.y;
+ expect(down).toBeLessThan(0.5);
+ // A wall 5 cm ahead of the body's axis: the eyes stay behind it.
+ const p = player();
+ const wall = p.z + 0.05;
+ const test = (from: { z: number }, to: { z: number }) => {
+ if ((from.z - wall) * (to.z - wall) >= 0) return null;
+ return (wall - from.z) / (to.z - from.z);
+ };
+ const near = new DuelCamera();
+ near.firstPerson = true;
+ near.face(0);
+ expect(near.update(1 / 60, p, 0, test).position.z).toBeLessThanOrEqual(wall);
+ });
});
function viewOf(over: { phase?: ViewState["match"]["phase"]; countdown?: number; round?: number; me?: Partial<PlayerView> } = {}): ViewState {
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
index 5b22ba4dc6..847b9d716f 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelCamera.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelCamera.ts
@@ -10,15 +10,23 @@
* 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.
*
+ * First person (the deck's first-person view carried into the match): the
+ * camera sits at the duellist's eyes, 1.65 m up and a little ahead of the
+ * body's axis, kept short of a wall in front, dipping with a dodge roll and
+ * falling with a knocked-out body; its field of view is the person's
+ * first-person setting, narrowed in the sights and widened in a sprint by
+ * the same ratios as the shoulder rigs. Switching person blends over about a
+ * fifth of a second. The blaster and arms are the viewmodel's (`viewmodel/`).
+ *
* 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 { CAMERA_RIGS, 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 { SHOULDER, clampHfov, type SegmentTest, type Vec3 } from "../engine/realtime/shoulderRig";
+import { SHOULDER, clampHfov, verticalFov, type SegmentTest, type 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. */
@@ -39,6 +47,15 @@ export const DUEL_CAMERA = {
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,
+ /** First person: eye height, how far ahead of the body's axis the eyes are, the gap kept to a wall in front (metres). */
+ eyeHeight: SHOULDER.eyeHeight,
+ eyeForward: SHOULDER.eyeForward,
+ eyeClearance: SHOULDER.eyeClearance,
+ /** How far a dodge roll dips the eyes at its middle, and a knocked-out body drops them, metres. */
+ dodgeDip: 0.55,
+ downDrop: 1.3,
+ /** Time constant of the third ↔ first person blend, seconds. */
+ personS: SHOULDER.personS,
} as const;
export interface DuelCameraPose {
@@ -79,6 +96,17 @@ function dirOf(yaw: number, pitch: number, out: Vec3): Vec3 {
return out;
}
+/**
+ * The first-person vertical field of view (degrees) for a rig: the person's
+ * first-person horizontal setting on this frame, zoomed by the rig's ratio to
+ * the hip rig (the sights narrow it, a sprint widens it). Pure.
+ */
+export function firstFov(rigFovDeg: number, hfovFirstDeg: number = SHOULDER.firstHfovDeg, aspect = 16 / 9): number {
+ const base = verticalFov(aspect, clampHfov(hfovFirstDeg, SHOULDER.firstHfovDeg));
+ const zoom = Math.tan((rigFovDeg * DEG) / 2) / Math.tan((CAMERA_RIGS.hip.fovDeg * DEG) / 2);
+ return (2 * Math.atan(Math.tan((base * DEG) / 2) * zoom)) / DEG;
+}
+
export class DuelCamera {
/** The aim, radians (yaw 0 faces +Z, pitch positive up). */
yaw = 0;
@@ -87,6 +115,15 @@ export class DuelCamera {
invertY = false;
/** The person's third-person horizontal field of view (view settings), degrees. */
hfovSetting: number = SHOULDER.hfovDeg;
+ /** Fight through the eyes (the person's first-person view) instead of over the shoulder. */
+ firstPerson = false;
+ /** The person's first-person horizontal field of view, degrees, and the frame's width / height. */
+ hfovFirst: number = SHOULDER.firstHfovDeg;
+ aspect = 16 / 9;
+ /** How far the camera has blended into first person (0 shoulder .. 1 eyes, eased), after `update`. */
+ firstShare = 0;
+ private blend = 0;
+ private downT = 0;
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: duelFov(cameraRigFor({ sprinting: false, shieldUp: false, ads: 0 } as PlayerView).fovDeg),
};
@@ -99,6 +136,7 @@ export class DuelCamera {
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 };
+ private readonly eye: 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 {
@@ -113,6 +151,7 @@ export class DuelCamera {
this.yaw = wrap(yaw);
this.pitch = clamp(pitch, DUEL_CAMERA.minPitch, DUEL_CAMERA.maxPitch);
this.primed = false;
+ this.downT = 0;
}
/** A short shake (a shot, a hit taken); strength in degrees. */
@@ -177,17 +216,50 @@ export class DuelCamera {
const hit = test(pivot, far);
if (hit !== null) reach = Math.max(0.2, hit * r.back - DUEL_CAMERA.clearance);
}
+ const wasPrimed = this.primed;
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 = duelFov(r.fovDeg, this.hfovSetting);
+ const tx = pivot.x - dir.x * this.back;
+ const ty = pivot.y - dir.y * this.back;
+ const tz = pivot.z - dir.z * this.back;
+
+ // First person: the eyes, ahead of the body's axis along the view, dipping with a roll, falling when knocked out.
+ const wantFirst = this.firstPerson ? 1 : 0;
+ this.blend = wasPrimed ? this.blend + (wantFirst - this.blend) * (1 - Math.exp(-dt / DUEL_CAMERA.personS)) : wantFirst;
+ if (Math.abs(wantFirst - this.blend) < 1e-3) this.blend = wantFirst;
+ const s = this.blend * this.blend * (3 - 2 * this.blend);
+ this.firstShare = s;
+ this.downT = me.alive ? 0 : Math.min(1, this.downT + dt / 0.6);
+ const fall = 1 - (1 - this.downT) * (1 - this.downT);
+ const fx = Math.sin(viewYaw);
+ const fz = Math.cos(viewYaw);
+ const eye = this.eye;
+ eye.y = floorY + DUEL_CAMERA.eyeHeight - (me.dodging ? Math.sin(me.dodgeProgress * Math.PI) * DUEL_CAMERA.dodgeDip : 0) - fall * DUEL_CAMERA.downDrop;
+ let ahead: number = DUEL_CAMERA.eyeForward;
+ if (test && s > 0) {
+ // Never past a wall the face is against: the eyes stay a little short of it.
+ const probe = DUEL_CAMERA.eyeForward + DUEL_CAMERA.eyeClearance;
+ head.y = eye.y;
+ const far = this.far;
+ far.x = me.x + fx * probe;
+ far.y = eye.y;
+ far.z = me.z + fz * probe;
+ const hit = test(head, far);
+ if (hit !== null) ahead = Math.max(0, hit * probe - DUEL_CAMERA.eyeClearance);
+ }
+ eye.x = me.x + fx * ahead;
+ eye.z = me.z + fz * ahead;
+
+ pose.position.x = tx + (eye.x - tx) * s;
+ pose.position.y = ty + (eye.y - ty) * s;
+ pose.position.z = tz + (eye.z - tz) * s;
+ pose.target.x = pose.position.x + dir.x * 20;
+ pose.target.y = pose.position.y + dir.y * 20;
+ pose.target.z = pose.position.z + dir.z * 20;
+ const third = duelFov(r.fovDeg, this.hfovSetting);
+ pose.fovDeg = s > 0 ? third + (firstFov(r.fovDeg, this.hfovFirst, this.aspect) - third) * s : third;
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
index 8c8043dff5..9cb3c6a7d6 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelController.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelController.ts
@@ -67,6 +67,9 @@ export class DuelController {
aimTarget: "player" | "world" | "none" = "none";
/** QA: held controls forced on top of the person's (`window.__verseDuel.hold`). */
forced: Partial<ControlState> = {};
+ /** Shots the person has fired this match, and whether the last one was in the sights (the viewmodel kicks on each). */
+ ownShots = 0;
+ lastShotAds = false;
private duel: LocalDuel | null = null;
private readonly control: ControlState = idleControl();
private readonly listeners = new Set<() => void>();
@@ -120,6 +123,7 @@ export class DuelController {
this.forced = {};
this.forcedPress = {};
this.hadLock = false;
+ this.ownShots = 0;
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);
@@ -238,7 +242,11 @@ export class DuelController {
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 === "shot" && e.player === view.slot) {
+ this.camera.kick(e.ads ? 0.35 : 0.6);
+ this.ownShots++;
+ this.lastShotAds = !!e.ads;
+ }
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);
}
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
index c223920ab3..5472f62b38 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/duel/duelInput.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/duelInput.ts
@@ -12,6 +12,7 @@
* | Q (hold) | energy shield |
* | Space | dodge roll (in the move direction) |
* | R | vent; again inside the window: perfect |
+ * | 2, 3, V | over the shoulder / through the eyes |
* | Esc | pause (pointer released); again: leave |
*
* Presses (dodge, vent) are latched until the next `control()` call reads
@@ -137,6 +138,8 @@ export interface DuelInputCallbacks {
relock: () => void;
/** The duel takes input now (running, not paused or over). */
live: () => boolean;
+ /** A key that may switch the view (third / first person); returns whether it did. */
+ view?: (code: string) => boolean;
}
/**
@@ -160,6 +163,11 @@ export function attachDuelInput(el: HTMLElement, input: DuelInput, cb: DuelInput
}
if (!cb.live()) return;
if (e.ctrlKey || e.metaKey || e.altKey) return;
+ if (!e.repeat && cb.view?.(e.code)) {
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ return;
+ }
if (input.keyDown(e.code, e.repeat)) {
e.preventDefault();
e.stopImmediatePropagation();
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
index 2effdf5580..7613c344a7 100644
--- 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
@@ -4,7 +4,9 @@
* 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`).
+ * camera for the HUD and the pointer (`runtime.eye`). In first person the
+ * commander's own arms (`runtime.viewmodel`) are drawn last, into the same
+ * target with depth cleared.
*
* 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,
@@ -17,7 +19,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useFrame, useThree } from "@react-three/fiber";
import {
- AgXToneMapping, Color, DoubleSide, HalfFloatType, PerspectiveCamera, Ray, Vector2, Vector3, WebGLRenderTarget,
+ AgXToneMapping, Color, DoubleSide, HalfFloatType, PerspectiveCamera, Ray, Vector2, Vector3, WebGLRenderTarget, type Texture,
} from "three";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
@@ -31,6 +33,8 @@ import { loadRealtimeScene, type RealtimeScene } from "./realtimeScene";
import { DECK_SHARED } from "./deckMaterial";
import { verticalFov, type SegmentTest } from "./shoulderRig";
import type { QualityChoice } from "./viewSettings";
+import { viewmodelVisibility } from "../../viewmodel/motion";
+import { drawViewmodel, ViewmodelPass } from "../../viewmodel/viewmodelPass";
interface Props {
runtime: StageRuntime;
@@ -56,10 +60,6 @@ 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;
@@ -147,14 +147,17 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
return c;
}, []);
- const { composer, bloom } = useMemo(() => {
+ const { composer, bloom, viewmodelPass } = useMemo(() => {
const target = new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples: 4 });
const c = new EffectComposer(gl, target);
c.addPass(new RenderPass(scene, camera));
+ // First person: the commander's arms over the deck, before bloom and tone mapping like everything else.
+ const vm = new ViewmodelPass();
+ c.addPass(vm);
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 };
+ return { composer: c, bloom: pass, viewmodelPass: vm };
}, [gl, scene, camera]);
useEffect(() => () => composer.dispose(), [composer]);
@@ -233,13 +236,17 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
rig.update(dt, body, test);
}
if (!override) {
- runtime.commanderHidden = rig.actual < HIDE_COMMANDER_BELOW_M || rig.firstShare > HIDE_COMMANDER_FIRST_SHARE;
+ // Close behind the head or inside it (first person) the commander's own body is not drawn.
+ runtime.commanderHidden = viewmodelVisibility({ eyeOn: true, firstShare: rig.firstShare, thirdDistance: rig.actual, duelFirstShare: null }).hideOwnBody;
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();
+ const vm = runtime.viewmodel;
+ vm?.prepare(camera, dt, scene.environment as Texture | null);
+ viewmodelPass.draw = vm;
gl.info.reset();
const tune = tuning();
if (tune || tuned.current) applyTuning(loaded, bloom, tune);
@@ -256,6 +263,7 @@ export function RealtimeBackdrop({ runtime, deck, active, commanderId, quality =
} else {
gl.setRenderTarget(null);
gl.render(scene, camera);
+ if (vm?.visible) drawViewmodel(gl, vm, null);
}
gl.setClearColor(clearColour, clearAlpha);
const s = runtime.stats;
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 0b03196b60..24dbf7c225 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/runtime.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/runtime.ts
@@ -9,7 +9,7 @@
* 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 { DoubleSide, Ray, Raycaster, Vector2, Vector3, type PerspectiveCamera, type Scene, type Texture } from "three";
import type { MeshBVH } from "three-mesh-bvh";
import type { Deck } from "./content/deck";
import { worldToPlate } from "./engine/plateMath";
@@ -62,6 +62,18 @@ export interface CameraOverride {
fovDeg: number;
}
+/**
+ * The first-person viewmodel (`viewmodel/`): a scene and camera of its own,
+ * drawn over the eye view with depth cleared. The eye view calls `prepare`
+ * once its camera is placed for the frame, then draws it while `visible`.
+ */
+export interface ViewmodelDraw {
+ scene: Scene;
+ camera: PerspectiveCamera;
+ visible: boolean;
+ prepare(eye: PerspectiveCamera, dtS: number, environment: Texture | null): void;
+}
+
/** A screen point (CSS px). */
export interface ScreenPoint { x: number; y: number }
@@ -84,6 +96,8 @@ export class StageRuntime {
commanderHidden = false;
/** While set, the eye-level view renders from this camera instead of the shoulder rig (a duel). */
cameraOverride: CameraOverride | null = null;
+ /** The first-person arms (and blaster), drawn over the eye view while set and visible. */
+ viewmodel: ViewmodelDraw | 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). */
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx
new file mode 100644
index 0000000000..45d2893d5b
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/ViewmodelLayer.tsx
@@ -0,0 +1,110 @@
+/**
+ * Mounts the first-person viewmodel on a stage with an eye-level view: makes
+ * the arms in the commander's uniform, hands them to the eye view
+ * (`runtime.viewmodel`), and every frame tells them what to show: the deck's
+ * empty hands while the commander walks in first person, the blaster while a
+ * duel is fought through the eyes, nothing in third person or bird's-eye.
+ */
+import { useEffect, useMemo, useRef } from "react";
+import { useFrame } from "@react-three/fiber";
+import type { Deck } from "../content/deck";
+import type { StageRuntime } from "../runtime";
+import type { CharacterLibrary } from "../actors/characters";
+import type { Look } from "../actors/look";
+import type { DuelController } from "../duel/duelController";
+import { OWN_ACCENT } from "../duel/DuelLayer";
+import { ARM } from "./arms";
+import { MOTION, viewmodelVisibility } from "./motion";
+import { Viewmodel, VIEWMODEL, type ArmColours, type ViewmodelFrame } from "./viewmodel";
+
+interface Props {
+ runtime: StageRuntime;
+ duel: DuelController;
+ deck: Deck;
+ library: CharacterLibrary | null;
+ commanderId: string;
+ commanderLook: Look;
+}
+
+/** The uniform tiers' colours when the character contract has not loaded yet. */
+const FALLBACK: ArmColours = { uniform: "#3b3f47", trim: "#5a5f68" };
+/** A walking officer's speed (the bob is measured against it) when the library has none. */
+const WALK_SPEED = 1.4;
+
+export function armColours(library: CharacterLibrary | null, look: Look): ArmColours {
+ const tier = library?.contract.tiers[look.tier];
+ return tier ? { uniform: tier.M_Uniform, trim: tier.M_Trim } : FALLBACK;
+}
+
+export function ViewmodelLayer({ runtime, duel, deck, library, commanderId, commanderLook }: Props) {
+ const { uniform, trim } = armColours(library, commanderLook);
+ const vmRef = useRef<Viewmodel | null>(null);
+ useEffect(() => {
+ const vm = new Viewmodel(FALLBACK, OWN_ACCENT);
+ vmRef.current = vm;
+ runtime.viewmodel = vm;
+ // Development handle: tune the layout live (edit `layout`, then `retune()`).
+ if (import.meta.env.DEV) Object.assign(window, { __verseViewmodel: { layout: VIEWMODEL, arm: ARM, motion: MOTION, retune: () => vm.retune(), viewmodel: vm } });
+ return () => {
+ if (runtime.viewmodel === vm) runtime.viewmodel = null;
+ if (vmRef.current === vm) vmRef.current = null;
+ vm.dispose();
+ };
+ }, [runtime]);
+ // The sleeves wear the commander's uniform (a promotion repaints them).
+ useEffect(() => { vmRef.current?.setColours({ uniform, trim }); }, [runtime, uniform, trim]);
+
+ const frame = useMemo<ViewmodelFrame>(() => ({
+ visibility: { arms: false, mode: "deck", hideOwnBody: false, raise: 0 },
+ player: null, speed: 0, walkSpeed: WALK_SPEED, x: 0, y: 0, z: 0, deck: null, reduced: false, frozen: false,
+ }), []);
+ const last = useRef({ x: 0, z: 0, primed: false });
+
+ // Before the eye view renders (priority 1) and after the duel's frame: what the arms show this frame.
+ useFrame((_, dt) => {
+ const vm = vmRef.current;
+ if (!vm) return;
+ const eyeOn = !!runtime.eye;
+ const step = Math.min(0.25, Math.max(1e-4, dt));
+ const view = duel.active ? duel.view : null;
+ const me = view ? view.players[view.slot] ?? null : null;
+ frame.visibility = viewmodelVisibility({
+ eyeOn,
+ firstShare: runtime.shoulder.firstShare,
+ thirdDistance: runtime.shoulder.actual,
+ duelFirstShare: duel.active ? duel.camera.firstShare : null,
+ });
+ frame.deck = deck;
+ frame.reduced = runtime.view.reduced;
+ frame.player = me;
+ frame.frozen = duel.active && duel.phase !== "running";
+ if (me) {
+ frame.speed = me.speed;
+ frame.x = me.x;
+ frame.y = duel.floorY;
+ frame.z = me.z;
+ vm.shot(duel.ownShots, duel.lastShotAds);
+ last.current.primed = false;
+ } else {
+ const pose = runtime.poses.get(commanderId);
+ if (pose) {
+ const l = last.current;
+ const moved = l.primed ? Math.hypot(pose.x - l.x, pose.z - l.z) : 0;
+ // A jump (a lift ride, a duel's end) is not a walk.
+ const speed = moved > 1 ? 0 : moved / step;
+ frame.speed += (speed - frame.speed) * Math.min(1, step / 0.08);
+ l.x = pose.x;
+ l.z = pose.z;
+ l.primed = true;
+ frame.x = pose.x;
+ frame.y = pose.y;
+ frame.z = pose.z;
+ } else {
+ frame.speed = 0;
+ }
+ }
+ vm.set(frame);
+ }, 0);
+
+ return null;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts
new file mode 100644
index 0000000000..09f757ea04
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/arms.ts
@@ -0,0 +1,245 @@
+/**
+ * The commander's own arms for the first-person viewmodel, built
+ * procedurally (a few hundred triangles each): an upper arm and a tapered
+ * forearm in the uniform's cloth, a cuff in the uniform's trim, and a gloved
+ * hand (palm, knuckle roll, four two-segment fingers and a thumb) whose
+ * fingers curl by a parameter, so one hand closes around a grip, cradles a
+ * shroud or hangs loose. The left forearm carries the shield emitter.
+ *
+ * Hand frame (the `hand` group, origin at the wrist): +Z runs to the
+ * knuckles, +Y is the back of the hand, +X the thumb's side for the right
+ * hand; the left hand is the same hand mirrored (thumb on −X). Fingers curl
+ * toward −Y (the palm).
+ *
+ * `pose` places the arm for a frame: shoulder, wrist and the hand's frame
+ * given, the elbow is solved by two-bone IK toward a pole (it hangs down and
+ * out, as an arm does), and the forearm turns about its axis so its back (and
+ * the emitter) faces the way the back of the hand does.
+ */
+import {
+ BoxGeometry, CapsuleGeometry, CylinderGeometry, Group, LatheGeometry, Matrix4, Mesh, SphereGeometry, TorusGeometry, Vector2, Vector3,
+ type BufferGeometry, type Material, type Quaternion,
+} from "three";
+import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";
+import { solveElbow } from "../duel/figure";
+
+export interface ArmMaterials {
+ /** The uniform's cloth (sleeves). */
+ sleeve: Material;
+ /** The uniform's trim (the sleeve's cuff band, the glove's seam). */
+ trim: Material;
+ /** Glove leather. */
+ glove: Material;
+ /** The shield emitter's housing and its glowing strip (left forearm only). */
+ housing: Material;
+ emitter: Material;
+}
+
+export const ARM = {
+ /** Upper arm and forearm lengths, metres (the upper arm is never in view; it is long enough that the hands reach the blaster). */
+ upper: 0.36,
+ fore: 0.3,
+ /** Sleeve radii: shoulder, elbow, wrist. */
+ rShoulder: 0.05,
+ rElbow: 0.043,
+ rWrist: 0.035,
+ /** Finger capsule radius and segment lengths. */
+ finger: 0.0092,
+ seg1: 0.042,
+ seg2: 0.036,
+ /** The forearm's sleeve stops this far short of the wrist, inside the glove's gauntlet. */
+ sleeveShort: 0.06,
+};
+
+const SCRATCH_X = new Vector3();
+const SCRATCH_Y = new Vector3();
+const SCRATCH_Z = new Vector3();
+const SCRATCH_M = new Matrix4();
+
+/**
+ * A finger segment along +Z from the origin: a tube tapering from radius `r0`
+ * to `r1` over `length`, both ends rounded (a lathe-turned profile). Pure.
+ */
+export function fingerSegment(r0: number, r1: number, length: number, radial = 7): LatheGeometry {
+ const profile = [
+ new Vector2(0, 0), new Vector2(r0 * 0.75, r0 * 0.33), new Vector2(r0, r0),
+ new Vector2(r1, length - r1), new Vector2(r1 * 0.75, length - r1 * 0.33), new Vector2(0, length),
+ ];
+ return new LatheGeometry(profile, radial).rotateX(Math.PI / 2);
+}
+
+/** Position a cuff part along the forearm (y) and squash it to the forearm's oval (x across, z front to back). */
+function placed(mesh: Mesh, y: number, sx: number, sz: number): Mesh {
+ mesh.position.set(0, y, 0);
+ mesh.scale.set(sx, 1, sz);
+ return mesh;
+}
+
+/** A finger: two segments in a chain, the second hinged at the end of the first. */
+interface Finger { base: Group; joint: Group }
+
+export class ViewArm {
+ readonly group = new Group();
+ /** The hand: place it with `pose`; its children are in the hand frame. */
+ readonly hand = new Group();
+ /** The bones (unscaled, turned along shoulder → elbow and elbow → wrist). */
+ readonly upper = new Group();
+ readonly fore = new Group();
+ /** The glove's gauntlet, on the forearm at the wrist. */
+ private readonly cuff = new Group();
+ /** The left forearm's emitter strip (null on the right arm). */
+ readonly emitterStrip: Mesh | null = null;
+ private readonly upperSleeve: Mesh;
+ private readonly foreSleeve: Mesh;
+ private readonly housing: Mesh | null = null;
+ private readonly fingers: Finger[] = [];
+ private readonly thumb: Finger;
+ private readonly geometries: BufferGeometry[] = [];
+ private readonly elbow = new Vector3();
+ private readonly axis = new Vector3();
+ private readonly back = new Vector3();
+ private readonly across = new Vector3();
+ private readonly m4 = new Matrix4();
+
+ constructor(readonly side: "left" | "right", mats: ArmMaterials) {
+ this.group.name = `ViewArm_${side}`;
+ const g = <T extends BufferGeometry>(geo: T): T => { this.geometries.push(geo); return geo; };
+ // Sleeves: unit-height cylinders along +Y from the joint, scaled to the bone's length by `pose`.
+ this.upperSleeve = new Mesh(g(new CylinderGeometry(ARM.rElbow, ARM.rShoulder, 1, 12, 1, true).translate(0, 0.5, 0)), mats.sleeve);
+ this.foreSleeve = new Mesh(g(new CylinderGeometry(ARM.rWrist, ARM.rElbow, 1, 12, 1, true).translate(0, 0.5, 0)), mats.sleeve);
+ this.upper.add(this.upperSleeve);
+ this.fore.add(this.foreSleeve);
+ // An elbow cap closes the joint between the two sleeves (at the forearm's start).
+ const elbowCap = new Mesh(g(new CapsuleGeometry(ARM.rElbow * 0.98, 0.001, 3, 10)), mats.sleeve);
+ this.fore.add(elbowCap);
+ this.group.add(this.upper, this.fore, this.hand);
+
+ // The glove's gauntlet rides on the forearm (it follows the arm, not the bent wrist): it flares over the sleeve's
+ // end (the sleeve stops inside it) with a rolled rim and a strap. `pose` puts `cuff` at the wrist.
+ this.cuff.add(
+ placed(new Mesh(g(new CylinderGeometry(0.036, 0.0415, 0.08, 18, 1, true).translate(0, -0.04, 0)), mats.glove), 0, 1.08, 0.9),
+ placed(new Mesh(g(new TorusGeometry(0.0415, 0.0042, 6, 18).rotateX(Math.PI / 2)), mats.glove), -0.08, 1.08, 0.9),
+ placed(new Mesh(g(new CylinderGeometry(0.0408, 0.0418, 0.012, 18, 1, true)), mats.housing), -0.058, 1.1, 0.92),
+ );
+ this.fore.add(this.cuff);
+ // The wrist: a rounded joint between the gauntlet and the palm.
+ const wristBall = new Mesh(g(new SphereGeometry(0.031, 10, 7)), mats.glove);
+ wristBall.position.set(0, -0.002, 0.006);
+ wristBall.scale.set(1.12, 0.82, 1);
+ // Palm: a rounded slab; an armoured plate over the knuckles and a panel on the back of the hand.
+ const palm = new Mesh(g(new RoundedBoxGeometry(0.08, 0.03, 0.084, 2, 0.013)), mats.glove);
+ palm.position.set(0, 0, 0.05);
+ const plate = new Mesh(g(new RoundedBoxGeometry(0.07, 0.01, 0.026, 2, 0.0045)), mats.housing);
+ plate.position.set(0, 0.0145, 0.08);
+ plate.rotation.set(0.12, 0, 0);
+ const panel = new Mesh(g(new RoundedBoxGeometry(0.052, 0.006, 0.038, 2, 0.0028)), mats.trim);
+ panel.position.set(0, 0.0138, 0.042);
+ this.hand.add(wristBall, palm, plate, panel);
+
+ // Fingers: two tapered, round-ended segments each; index on the thumb's side (+X), little finger outside.
+ const seg1 = g(fingerSegment(0.0098, 0.009, ARM.seg1));
+ const seg2 = g(fingerSegment(0.009, 0.0078, ARM.seg2));
+ const lengths = [1, 1.08, 1.02, 0.84];
+ const xs = [0.0265, 0.0088, -0.0088, -0.0262];
+ for (let i = 0; i < 4; i++) {
+ const base = new Group();
+ base.position.set(xs[i], -0.001, 0.086);
+ const s1 = new Mesh(seg1, mats.glove);
+ s1.scale.set(1, 1, lengths[i]);
+ const joint = new Group();
+ joint.position.set(0, 0, ARM.seg1 * lengths[i] - 0.008);
+ const s2 = new Mesh(seg2, mats.glove);
+ s2.scale.set(1, 1, lengths[i]);
+ joint.add(s2);
+ base.add(s1, joint);
+ this.hand.add(base);
+ this.fingers.push({ base, joint });
+ }
+ // Thumb: from the heel of the palm on the thumb's side, angled forward and in.
+ const tb = new Group();
+ tb.position.set(0.034, -0.007, 0.028);
+ const t1 = new Mesh(g(fingerSegment(0.0118, 0.0105, 0.042)), mats.glove);
+ const tj = new Group();
+ tj.position.set(0, 0, 0.034);
+ const t2 = new Mesh(g(fingerSegment(0.0105, 0.009, 0.036)), mats.glove);
+ tj.add(t2);
+ tb.add(t1, tj);
+ this.hand.add(tb);
+ this.thumb = { base: tb, joint: tj };
+
+ if (side === "left") {
+ // The shield emitter: a flat housing along the back of the forearm with a glowing strip and a lens.
+ const housing = new Mesh(g(new BoxGeometry(0.052, 0.13, 0.02)), mats.housing);
+ const strip = new Mesh(g(new BoxGeometry(0.012, 0.1, 0.004)), mats.emitter);
+ strip.position.set(0, -0.005, 0.011);
+ const lens = new Mesh(g(new CylinderGeometry(0.011, 0.013, 0.006, 12).rotateX(Math.PI / 2)), mats.emitter);
+ lens.position.set(0, 0.05, 0.012);
+ housing.add(strip, lens);
+ this.fore.add(housing);
+ this.housing = housing;
+ this.emitterStrip = strip;
+ this.hand.scale.x = -1;
+ }
+ this.group.traverse((o) => { o.frustumCulled = false; });
+ this.curl(1.2, 1.1, 0.4);
+ }
+
+ /** Curl the fingers: first and second joints (radians toward the palm), and the thumb's bend (0 open .. 1 closed). */
+ curl(c1: number, c2: number, thumb: number): void {
+ for (let i = 0; i < this.fingers.length; i++) {
+ const f = this.fingers[i];
+ // The little finger curls a touch more, as a real grip does.
+ const extra = i * 0.05;
+ f.base.rotation.set(c1 + extra, 0, 0);
+ f.joint.rotation.set(c2 + extra, 0, 0);
+ }
+ this.thumb.base.rotation.set(0.35 + thumb * 0.5, -0.55 - thumb * 0.25, 0);
+ this.thumb.joint.rotation.set(thumb * 0.6, -0.2, 0);
+ }
+
+ /**
+ * Place the arm (all in the parent's space): `shoulder`, the hand at
+ * `wrist` turned by `handQuat` (the hand frame), the elbow bending toward
+ * `pole` (unit). The forearm's back follows the back of the hand.
+ */
+ pose(shoulder: Vector3, wrist: Vector3, handQuat: Quaternion, pole: Vector3): void {
+ this.hand.position.copy(wrist);
+ this.hand.quaternion.copy(handQuat);
+ const elbow = solveElbow(shoulder, wrist, ARM.upper, ARM.fore, pole, this.elbow);
+ this.place(this.upper, this.upperSleeve, shoulder, elbow, pole);
+ this.back.set(0, 1, 0).applyQuaternion(handQuat);
+ const length = this.place(this.fore, this.foreSleeve, elbow, wrist, this.back, ARM.sleeveShort);
+ // The emitter lies along the forearm's back, a hand's width short of the wrist.
+ this.cuff.position.set(0, length, 0);
+ if (this.housing) this.housing.position.set(0, Math.max(0, length - 0.15), ARM.rWrist + 0.008);
+ }
+
+ /** Turn `bone` along `a` → `b` (its +Y) with its +Z toward `up`; the sleeve scales to the length. Returns the length. */
+ private place(bone: Group, sleeve: Mesh, a: Vector3, b: Vector3, up: Vector3, short = 0): number {
+ const axis = this.axis.subVectors(b, a);
+ const length = axis.length();
+ if (length < 1e-5) return 0;
+ axis.multiplyScalar(1 / length);
+ const z = this.across.copy(up).addScaledVector(axis, -up.dot(axis));
+ if (z.lengthSq() < 1e-8) z.set(0, 0, 1).addScaledVector(axis, -axis.z);
+ z.normalize();
+ const x = SCRATCH_X.crossVectors(axis, z);
+ this.m4.makeBasis(x, axis, z);
+ bone.quaternion.setFromRotationMatrix(this.m4);
+ bone.position.copy(a);
+ sleeve.scale.set(1, Math.max(0.01, length - short), 1);
+ return length;
+ }
+
+ /** The hand's frame from its knuckle direction and the back of the hand (any lengths). Written into `out`. */
+ static handFrame(knuckles: Vector3, backOfHand: Vector3, out: Quaternion): Quaternion {
+ const z = SCRATCH_Z.copy(knuckles).normalize();
+ const y = SCRATCH_Y.copy(backOfHand).addScaledVector(z, -backOfHand.dot(z)).normalize();
+ const x = SCRATCH_X.crossVectors(y, z);
+ return out.setFromRotationMatrix(SCRATCH_M.makeBasis(x, y, z));
+ }
+
+ dispose(): void {
+ for (const geo of this.geometries) geo.dispose();
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/motion.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/motion.ts
new file mode 100644
index 0000000000..a59667a647
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/motion.ts
@@ -0,0 +1,271 @@
+/**
+ * The first-person viewmodel's motion and visibility rules (docs/verse/realtime.md,
+ * "First-person viewmodel"). Pure state and maths, no three.js:
+ *
+ * - who is drawn: the commander's own arms in first person, their
+ * third-person body hidden once the camera is close to (or inside) the head;
+ * - walk bob: a step dip and a sideways sway per stride, scaled by the ground speed;
+ * - idle sway: a slow breathing drift while standing;
+ * - look lag: the arms trail a turn of the view a little and settle back;
+ * - recoil: a damped spring kicked by every shot (the blaster jumps back and up).
+ *
+ * prefers-reduced-motion drops the bob, the idle sway and the look lag and
+ * halves the recoil. Every offset is in the viewmodel camera's space: x right,
+ * y up, z toward the viewer (metres), and pitch (muzzle up), yaw (muzzle left),
+ * roll (top to the left) in radians.
+ */
+
+/** Below this share of the third ↔ first person blend the third-person body is drawn. */
+export const HIDE_BODY_FIRST_SHARE = 0.3;
+/** Closer than this behind the pivot (a wall pushed the third-person camera in), the body is hidden too, metres. */
+export const HIDE_BODY_BELOW_M = 0.55;
+
+export interface VisibilityInput {
+ /** The eye-level view is on screen. */
+ eyeOn: boolean;
+ /** How far the deck camera has blended into first person (0 third .. 1 first). */
+ firstShare: number;
+ /** The deck camera's distance behind the commander in third person, metres. */
+ thirdDistance: number;
+ /** A duel is on: its camera's share of first person (0..1), else null. */
+ duelFirstShare: number | null;
+}
+
+export interface Visibility {
+ /** Draw the viewmodel arms. */
+ arms: boolean;
+ /** Which arms: the deck's empty hands or the duel's blaster grip. */
+ mode: "deck" | "duel";
+ /** Hide the commander's (or the duellist's) own third-person body from the eye camera. */
+ hideOwnBody: boolean;
+ /** 0..1: how far the arms have come up into view (they rise as the camera blends into the head). */
+ raise: number;
+}
+
+function clamp01(v: number): number {
+ return v <= 0 ? 0 : v >= 1 ? 1 : v;
+}
+
+function smoothstep(a: number, b: number, v: number): number {
+ const t = clamp01((v - a) / (b - a));
+ return t * t * (3 - 2 * t);
+}
+
+/**
+ * Who is drawn this frame. The arms come in once the third-person body is
+ * hidden (past HIDE_BODY_FIRST_SHARE of the blend), rising into view as the
+ * blend completes, so there is never a frame with both or neither. Pure.
+ */
+export function viewmodelVisibility(v: VisibilityInput): Visibility {
+ if (v.duelFirstShare !== null) {
+ const s = clamp01(v.duelFirstShare);
+ const hide = s > HIDE_BODY_FIRST_SHARE;
+ return { arms: v.eyeOn && hide, mode: "duel", hideOwnBody: hide, raise: smoothstep(HIDE_BODY_FIRST_SHARE, 1, s) };
+ }
+ const s = clamp01(v.firstShare);
+ const first = s > HIDE_BODY_FIRST_SHARE;
+ return {
+ arms: v.eyeOn && first,
+ mode: "deck",
+ hideOwnBody: v.eyeOn && (first || v.thirdDistance < HIDE_BODY_BELOW_M),
+ raise: smoothstep(HIDE_BODY_FIRST_SHARE, 1, s),
+ };
+}
+
+export const MOTION = {
+ /** Metres walked per step: the bob dips once per step and sways once per stride (two steps). */
+ stepM: 0.75,
+ /** Bob at walking speed: vertical dip, sideways sway (metres) and roll (radians). */
+ bobY: 0.011,
+ bobX: 0.008,
+ bobRoll: 0.018,
+ /** The bob grows with speed up to this multiple of a walk (a run). */
+ bobMax: 1.7,
+ /** Time constant of the bob's fade in and out, seconds. */
+ bobEaseS: 0.12,
+ /** Idle breathing: vertical and sideways drift (metres), periods (seconds). */
+ idleY: 0.0022,
+ idleX: 0.0016,
+ idlePeriodY: 3.9,
+ idlePeriodX: 6.3,
+ /** Look lag: share of a turn the arms trail (radians per radian), its limit and settle time. */
+ lagGain: 0.55,
+ lagMax: 0.07,
+ lagS: 0.09,
+ /** Sideways and vertical shift per radian of lag, metres. */
+ lagShift: 0.22,
+ /** Recoil spring: stiffness and damping (per second²/per second); a shot's kick (velocity). */
+ recoilK: 380,
+ recoilC: 30,
+ recoilKick: 6.5,
+ /** Recoil per unit of spring displacement: back (metres), muzzle up (radians). */
+ recoilBack: 0.2,
+ recoilPitch: 0.4,
+ recoilUp: 0.04,
+ /** Aiming down the sights: share of bob, sway and recoil that is left. */
+ adsCalm: 0.25,
+ adsRecoil: 0.5,
+ /** Reduced motion: share of the recoil that is left. */
+ reducedRecoil: 0.5,
+} as const;
+
+export interface Offsets {
+ x: number;
+ y: number;
+ z: number;
+ pitch: number;
+ yaw: number;
+ roll: number;
+}
+
+export function zeroOffsets(out?: Offsets): Offsets {
+ const o = out ?? { x: 0, y: 0, z: 0, pitch: 0, yaw: 0, roll: 0 };
+ o.x = 0; o.y = 0; o.z = 0; o.pitch = 0; o.yaw = 0; o.roll = 0;
+ return o;
+}
+
+/**
+ * The walk bob at stride `phase` (radians; π per step) and `amount` (1 at a
+ * walk): the arms dip at every footfall and sway toward the planted foot once
+ * per stride. Added into `out`. Pure.
+ */
+export function walkBob(phase: number, amount: number, out: Offsets): Offsets {
+ const s = Math.sin(phase);
+ const c = Math.cos(phase);
+ out.y -= MOTION.bobY * amount * s * s;
+ out.x += MOTION.bobX * amount * c;
+ out.roll += MOTION.bobRoll * amount * c;
+ return out;
+}
+
+/** The idle breathing drift at time `t` seconds, scaled by `amount` (0..1). Added into `out`. Pure. */
+export function idleSway(t: number, amount: number, out: Offsets): Offsets {
+ out.y += MOTION.idleY * amount * Math.sin((t * 2 * Math.PI) / MOTION.idlePeriodY);
+ out.x += MOTION.idleX * amount * Math.sin((t * 2 * Math.PI) / MOTION.idlePeriodX + 0.7);
+ out.roll += 0.004 * amount * Math.sin((t * 2 * Math.PI) / MOTION.idlePeriodX);
+ return out;
+}
+
+/**
+ * One step of a damped spring pulled to 0 (semi-implicit Euler in sub-steps
+ * of at most 1/120 s, so a slow frame never blows it up). Pure; returns the
+ * new [position, velocity].
+ */
+export function springStep(x: number, v: number, dt: number, k: number, c: number): [number, number] {
+ let left = Math.max(0, dt);
+ while (left > 1e-9) {
+ const h = Math.min(left, 1 / 120);
+ v += (-k * x - c * v) * h;
+ x += v * h;
+ left -= h;
+ }
+ return [x, v];
+}
+
+export interface MotionInput {
+ /** Seconds since the last frame. */
+ dt: number;
+ /** Ground speed, metres per second. */
+ speed: number;
+ /** The body's walking speed (the bob is 1 at it). */
+ walkSpeed: number;
+ /** How far the view turned this frame, radians: yaw positive to the right, pitch positive up. */
+ turnYaw: number;
+ turnPitch: number;
+ /** Aiming down the sights, 0..1. */
+ ads: number;
+ /** prefers-reduced-motion. */
+ reduced: boolean;
+}
+
+/**
+ * The viewmodel's own motion over time: stride phase, eased bob amount, look
+ * lag and the recoil spring. `step` once per frame, `fire` per shot; read
+ * `offsets` after a step.
+ */
+export class ViewmodelMotion {
+ readonly offsets: Offsets = zeroOffsets();
+ /** Stride phase, radians (π per step). */
+ phase = 0;
+ /** The bob's eased amount (0 standing .. bobMax running). */
+ bob = 0;
+ /** Look lag, radians (yaw positive right, pitch positive up). */
+ lagYaw = 0;
+ lagPitch = 0;
+ /** Recoil spring displacement and velocity. */
+ recoil = 0;
+ recoilV = 0;
+ /** Seconds of motion so far (the idle breathing's clock). */
+ time = 0;
+
+ /** A shot: kick the recoil spring (`strength` 1 at the hip). */
+ fire(strength = 1): void {
+ this.recoilV += MOTION.recoilKick * strength;
+ }
+
+ step(m: MotionInput): Offsets {
+ const dt = Math.min(0.1, Math.max(0, m.dt));
+ this.time += dt;
+ const calm = 1 - (1 - MOTION.adsCalm) * clamp01(m.ads);
+ // Bob: the phase walks with the ground covered; the amount eases toward the speed's share of a walk.
+ const speed = Number.isFinite(m.speed) ? Math.max(0, m.speed) : 0;
+ this.phase = (this.phase + (speed * dt * Math.PI) / MOTION.stepM) % (Math.PI * 2);
+ const wantBob = m.reduced ? 0 : Math.min(MOTION.bobMax, speed / Math.max(0.1, m.walkSpeed));
+ this.bob += (wantBob - this.bob) * (1 - Math.exp(-dt / MOTION.bobEaseS));
+ // Look lag: the turn piles up and decays; the arms trail it (a turn of the view leaves them behind).
+ const k = Math.exp(-dt / MOTION.lagS);
+ if (m.reduced) {
+ this.lagYaw = 0;
+ this.lagPitch = 0;
+ } else {
+ const ty = Number.isFinite(m.turnYaw) ? m.turnYaw : 0;
+ const tp = Number.isFinite(m.turnPitch) ? m.turnPitch : 0;
+ this.lagYaw = clampAbs((this.lagYaw + ty * MOTION.lagGain) * k, MOTION.lagMax);
+ this.lagPitch = clampAbs((this.lagPitch + tp * MOTION.lagGain) * k, MOTION.lagMax);
+ }
+ [this.recoil, this.recoilV] = springStep(this.recoil, this.recoilV, dt, MOTION.recoilK, MOTION.recoilC);
+
+ const o = zeroOffsets(this.offsets);
+ walkBob(this.phase, this.bob * calm, o);
+ if (!m.reduced) idleSway(this.time, calm, o);
+ // Turning right leaves the arms to the left and turned right-to-left; looking up leaves them low.
+ o.x -= this.lagYaw * MOTION.lagShift * calm;
+ o.y -= this.lagPitch * MOTION.lagShift * calm;
+ o.yaw += this.lagYaw * 0.6 * calm;
+ o.pitch -= this.lagPitch * 0.4 * calm;
+ o.roll -= this.lagYaw * 0.5 * calm;
+ const kick = this.recoil * (m.reduced ? MOTION.reducedRecoil : 1) * (1 - (1 - MOTION.adsRecoil) * clamp01(m.ads));
+ o.z += kick * MOTION.recoilBack;
+ o.pitch += kick * MOTION.recoilPitch;
+ o.y += kick * MOTION.recoilUp;
+ return o;
+ }
+
+ /** Back to rest (a new match, the view changed person). */
+ reset(): void {
+ this.phase = 0;
+ this.bob = 0;
+ this.lagYaw = 0;
+ this.lagPitch = 0;
+ this.recoil = 0;
+ this.recoilV = 0;
+ zeroOffsets(this.offsets);
+ }
+}
+
+function clampAbs(v: number, max: number): number {
+ return v > max ? max : v < -max ? -max : v;
+}
+
+/**
+ * The view's turn between two frames from its directions (yaw about +Y with 0
+ * facing +Z, pitch positive up): yaw positive for a turn to the right. A jump
+ * larger than `maxJump` (a respawn, a cut) counts as no turn. Pure.
+ */
+export function turnBetween(prevYaw: number, prevPitch: number, yaw: number, pitch: number, maxJump = 0.6): { yaw: number; pitch: number } {
+ // The deck's yaw grows to the left (toward +X when facing +Z), so a right turn lowers it.
+ const dy = -Math.atan2(Math.sin(yaw - prevYaw), Math.cos(yaw - prevYaw));
+ const dp = pitch - prevPitch;
+ if (Math.abs(dy) > maxJump || Math.abs(dp) > maxJump) return { yaw: 0, pitch: 0 };
+ return { yaw: dy, pitch: dp };
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts
new file mode 100644
index 0000000000..d6e50d2235
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.test.ts
@@ -0,0 +1,316 @@
+/**
+ * The first-person viewmodel: who is drawn (arms in, own body out), the walk
+ * bob, idle sway, look lag and recoil maths, the arm's IK and hand frames,
+ * and the rig posed in the viewmodel camera's frustum on the deck and in a
+ * duel (hip, sights, shield, a shot).
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { Box3, Color, Frustum, Matrix4, MeshStandardMaterial, PerspectiveCamera, Quaternion, Vector3 } from "three";
+import type { PlayerView } from "../combat/view";
+import { ARM, fingerSegment, ViewArm } from "./arms";
+import {
+ HIDE_BODY_BELOW_M, HIDE_BODY_FIRST_SHARE, idleSway, MOTION, springStep, turnBetween, ViewmodelMotion, viewmodelVisibility,
+ walkBob, zeroOffsets, type MotionInput,
+} from "./motion";
+import { Viewmodel, VIEWMODEL, type ViewmodelFrame } from "./viewmodel";
+
+const still: MotionInput = { dt: 1 / 60, speed: 0, walkSpeed: 1.4, turnYaw: 0, turnPitch: 0, ads: 0, reduced: false };
+
+describe("viewmodel visibility", () => {
+ it("shows the arms only in first person at eye level, once the body is hidden", () => {
+ const third = viewmodelVisibility({ eyeOn: true, firstShare: 0, thirdDistance: 2.4, duelFirstShare: null });
+ expect(third).toMatchObject({ arms: false, hideOwnBody: false, mode: "deck" });
+ const blending = viewmodelVisibility({ eyeOn: true, firstShare: HIDE_BODY_FIRST_SHARE + 0.01, thirdDistance: 1.2, duelFirstShare: null });
+ expect(blending.arms).toBe(true);
+ expect(blending.hideOwnBody).toBe(true);
+ expect(blending.raise).toBeGreaterThan(0);
+ expect(blending.raise).toBeLessThan(0.1);
+ const first = viewmodelVisibility({ eyeOn: true, firstShare: 1, thirdDistance: 1.2, duelFirstShare: null });
+ expect(first).toMatchObject({ arms: true, hideOwnBody: true, raise: 1 });
+ // Never both bodies, never neither: the arms come in exactly where the body goes.
+ for (let s = 0; s <= 1; s += 0.05) {
+ const v = viewmodelVisibility({ eyeOn: true, firstShare: s, thirdDistance: 2, duelFirstShare: null });
+ expect(v.arms).toBe(v.hideOwnBody);
+ }
+ });
+
+ it("hides the body when a wall pushes the shoulder camera into it, without arms", () => {
+ const v = viewmodelVisibility({ eyeOn: true, firstShare: 0, thirdDistance: HIDE_BODY_BELOW_M - 0.1, duelFirstShare: null });
+ expect(v).toMatchObject({ arms: false, hideOwnBody: true });
+ });
+
+ it("draws nothing of its own without the eye-level view", () => {
+ const v = viewmodelVisibility({ eyeOn: false, firstShare: 1, thirdDistance: 0.2, duelFirstShare: null });
+ expect(v).toMatchObject({ arms: false, hideOwnBody: false });
+ });
+
+ it("follows the duel camera's person during a duel", () => {
+ expect(viewmodelVisibility({ eyeOn: true, firstShare: 1, thirdDistance: 1.2, duelFirstShare: 0 })).toMatchObject({ arms: false, hideOwnBody: false, mode: "duel" });
+ expect(viewmodelVisibility({ eyeOn: true, firstShare: 0, thirdDistance: 2.4, duelFirstShare: 1 })).toMatchObject({ arms: true, hideOwnBody: true, mode: "duel" });
+ });
+});
+
+describe("viewmodel motion", () => {
+ it("bobs with the stride: a dip at every footfall, a sway once per stride, nothing standing", () => {
+ const none = walkBob(1.3, 0, zeroOffsets());
+ expect(Math.abs(none.x) + Math.abs(none.y) + Math.abs(none.roll)).toBe(0);
+ const mid = walkBob(Math.PI / 2, 1, zeroOffsets());
+ expect(mid.y).toBeCloseTo(-MOTION.bobY, 9);
+ const plant = walkBob(0, 1, zeroOffsets());
+ expect(plant.y).toBeCloseTo(0, 9);
+ expect(plant.x).toBeCloseTo(MOTION.bobX, 9);
+ expect(walkBob(Math.PI, 1, zeroOffsets()).x).toBeCloseTo(-MOTION.bobX, 9);
+ // Twice the speed, twice the bob.
+ expect(walkBob(Math.PI / 2, 2, zeroOffsets()).y).toBeCloseTo(2 * mid.y, 9);
+ });
+
+ it("breathes a few millimetres while standing", () => {
+ for (let t = 0; t < 12; t += 0.37) {
+ const o = idleSway(t, 1, zeroOffsets());
+ expect(Math.abs(o.y)).toBeLessThanOrEqual(MOTION.idleY + 1e-12);
+ expect(Math.abs(o.x)).toBeLessThanOrEqual(MOTION.idleX + 1e-12);
+ }
+ });
+
+ it("walks the stride phase with the ground covered and eases the bob in", () => {
+ const m = new ViewmodelMotion();
+ for (let i = 0; i < 60; i++) m.step({ ...still, speed: 1.4 });
+ // One second at 1.4 m/s: 1.4 / stepM steps, π per step.
+ expect(m.bob).toBeGreaterThan(0.95);
+ const standing = new ViewmodelMotion();
+ for (let i = 0; i < 60; i++) standing.step(still);
+ expect(standing.bob).toBe(0);
+ const running = new ViewmodelMotion();
+ for (let i = 0; i < 120; i++) running.step({ ...still, speed: 6 });
+ expect(running.bob).toBeLessThanOrEqual(MOTION.bobMax + 1e-9);
+ });
+
+ it("settles a damped spring and survives a long frame", () => {
+ let [x, v] = [0, 10];
+ for (let i = 0; i < 120; i++) [x, v] = springStep(x, v, 1 / 60, MOTION.recoilK, MOTION.recoilC);
+ expect(Math.abs(x)).toBeLessThan(1e-3);
+ [x, v] = springStep(0, 10, 0.5, MOTION.recoilK, MOTION.recoilC);
+ expect(Number.isFinite(x) && Math.abs(x) < 1).toBe(true);
+ });
+
+ it("kicks back and up on a shot and comes back to rest", () => {
+ const m = new ViewmodelMotion();
+ m.fire(1);
+ let peakZ = 0;
+ let peakPitch = 0;
+ for (let i = 0; i < 6; i++) {
+ const o = m.step(still);
+ peakZ = Math.max(peakZ, o.z);
+ peakPitch = Math.max(peakPitch, o.pitch);
+ }
+ // Toward the eye (+z) and muzzle up, by a centimetre or more.
+ expect(peakZ).toBeGreaterThan(0.01);
+ expect(peakPitch).toBeGreaterThan(0.02);
+ for (let i = 0; i < 90; i++) m.step(still);
+ expect(Math.abs(m.offsets.z)).toBeLessThan(1e-3);
+ // The sights steady it.
+ const ads = new ViewmodelMotion();
+ ads.fire(1);
+ let adsPeak = 0;
+ for (let i = 0; i < 6; i++) adsPeak = Math.max(adsPeak, ads.step({ ...still, ads: 1 }).z);
+ expect(adsPeak).toBeLessThan(peakZ);
+ });
+
+ it("trails a turn of the view and lets it go", () => {
+ const m = new ViewmodelMotion();
+ const o = m.step({ ...still, turnYaw: 0.05 });
+ // Turned right: the arms are left behind (to the left), muzzle still pointing back left.
+ expect(o.x).toBeLessThan(0);
+ expect(o.yaw).toBeGreaterThan(0);
+ const up = new ViewmodelMotion().step({ ...still, turnPitch: 0.05 });
+ expect(up.y).toBeLessThan(0);
+ for (let i = 0; i < 60; i++) m.step(still);
+ expect(Math.abs(m.lagYaw)).toBeLessThan(1e-4);
+ // A flick never throws the arms out of frame.
+ const flick = new ViewmodelMotion();
+ flick.step({ ...still, turnYaw: 3 });
+ expect(Math.abs(flick.lagYaw)).toBeLessThanOrEqual(MOTION.lagMax);
+ });
+
+ it("drops bob, sway and lag and softens the recoil for reduced motion", () => {
+ const m = new ViewmodelMotion();
+ for (let i = 0; i < 60; i++) m.step({ ...still, speed: 1.4, turnYaw: 0.02, reduced: true });
+ expect(m.bob).toBe(0);
+ expect(m.lagYaw).toBe(0);
+ expect(m.offsets.x).toBe(0);
+ expect(m.offsets.y).toBe(0);
+ const full = new ViewmodelMotion();
+ const calm = new ViewmodelMotion();
+ full.fire(1);
+ calm.fire(1);
+ const a = full.step(still).z;
+ const b = calm.step({ ...still, reduced: true }).z;
+ expect(b).toBeCloseTo(a * MOTION.reducedRecoil, 9);
+ });
+
+ it("measures the view's turn between frames, right positive, ignoring cuts", () => {
+ // The deck's yaw grows to the left, so a right turn lowers it.
+ expect(turnBetween(0.5, 0, 0.45, 0).yaw).toBeCloseTo(0.05, 9);
+ expect(turnBetween(0, 0, 0, 0.1).pitch).toBeCloseTo(0.1, 9);
+ // Across ±π.
+ expect(turnBetween(Math.PI - 0.01, 0, -Math.PI + 0.01, 0).yaw).toBeCloseTo(-0.02, 9);
+ expect(turnBetween(0, 0, 2, 0)).toEqual({ yaw: 0, pitch: 0 });
+ });
+});
+
+describe("viewmodel arms", () => {
+ it("turns finger segments along +Z, round at both ends", () => {
+ const geo = fingerSegment(0.01, 0.008, 0.04);
+ geo.computeBoundingBox();
+ const box = geo.boundingBox as Box3;
+ expect(box.min.z).toBeCloseTo(0, 6);
+ expect(box.max.z).toBeCloseTo(0.04, 6);
+ expect(box.max.x).toBeCloseTo(0.01, 3);
+ geo.dispose();
+ });
+
+ it("reaches the wrist with a two-bone arm whose elbow bends toward the pole", () => {
+ const mats = { sleeve: new MeshMat(), trim: new MeshMat(), glove: new MeshMat(), housing: new MeshMat(), emitter: new MeshMat() };
+ const arm = new ViewArm("right", mats);
+ const shoulder = new Vector3(0.2, -0.38, 0);
+ const wrist = new Vector3(0.12, -0.12, -0.4);
+ const q = ViewArm.handFrame(new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Quaternion());
+ arm.pose(shoulder, wrist, q, new Vector3(1, -0.6, 0).normalize());
+ arm.group.updateMatrixWorld(true);
+ expect(arm.hand.position.distanceTo(wrist)).toBeLessThan(1e-9);
+ const elbow = arm.fore.position;
+ expect(elbow.distanceTo(shoulder)).toBeCloseTo(ARM.upper, 6);
+ expect(elbow.distanceTo(wrist)).toBeCloseTo(ARM.fore, 6);
+ // The elbow hangs out and down, as an arm does.
+ expect(elbow.x).toBeGreaterThan((shoulder.x + wrist.x) / 2);
+ // The hand frame: knuckles ahead (−Z), back of the hand up.
+ const knuckles = new Vector3(0, 0, 1).applyQuaternion(q);
+ expect(knuckles.z).toBeCloseTo(-1, 6);
+ arm.dispose();
+ });
+});
+
+const MeshMat = MeshStandardMaterial;
+
+function player(over: Partial<PlayerView> = {}): PlayerView {
+ return {
+ slot: 0, id: "a", local: true, side: 0, x: 0, z: 0, 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("viewmodel rig", () => {
+ // jsdom has no 2D canvas: the reticle and flash textures stay blank.
+ let spy: ReturnType<typeof vi.spyOn> | null = null;
+ beforeAll(() => { spy = vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null); });
+ afterAll(() => { spy?.mockRestore(); });
+
+ function frameFor(over: Partial<ViewmodelFrame> = {}): ViewmodelFrame {
+ return {
+ visibility: { arms: true, mode: "deck", hideOwnBody: true, raise: 1 },
+ player: null, speed: 0, walkSpeed: 1.4, x: 0, y: 0, z: 0, deck: null, reduced: false, frozen: false, ...over,
+ };
+ }
+
+ function eye(): PerspectiveCamera {
+ const c = new PerspectiveCamera(60, 16 / 9, 0.05, 500);
+ c.position.set(3, 1.65, -2);
+ c.lookAt(3, 1.65, -10);
+ c.updateMatrixWorld();
+ return c;
+ }
+
+ /** Whether a world point of the rig is in the viewmodel camera's view. */
+ function inView(vm: Viewmodel, p: Vector3): boolean {
+ const cam = vm.camera;
+ cam.updateMatrixWorld();
+ const f = new Frustum().setFromProjectionMatrix(new Matrix4().multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse));
+ return f.containsPoint(p);
+ }
+
+ function world(o: { getWorldPosition(v: Vector3): Vector3 }): Vector3 {
+ return o.getWorldPosition(new Vector3());
+ }
+
+ it("draws nothing until first person asks for the arms", () => {
+ const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ vm.prepare(eye(), 1 / 60, null);
+ expect(vm.visible).toBe(false);
+ vm.set(frameFor({ visibility: { arms: false, mode: "deck", hideOwnBody: false, raise: 0 } }));
+ vm.prepare(eye(), 1 / 60, null);
+ expect(vm.visible).toBe(false);
+ vm.dispose();
+ });
+
+ it("puts both hands in the lower corners on the deck, the blaster away", () => {
+ const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ vm.set(frameFor());
+ vm.prepare(eye(), 1 / 60, null);
+ expect(vm.visible).toBe(true);
+ const parts = vm as unknown as { right: ViewArm; left: ViewArm; gun: { visible: boolean } };
+ expect(parts.gun.visible).toBe(false);
+ vm.scene.updateMatrixWorld(true);
+ // The knuckles are in view; the right hand right of centre, the left hand left of it, both below the eye line.
+ const r = world(parts.right.hand.children[2]);
+ const l = world(parts.left.hand.children[2]);
+ expect(inView(vm, r)).toBe(true);
+ expect(inView(vm, l)).toBe(true);
+ const toCam = (p: Vector3) => p.clone().applyMatrix4(vm.camera.matrixWorldInverse);
+ expect(toCam(r).x).toBeGreaterThan(0.05);
+ expect(toCam(l).x).toBeLessThan(-0.05);
+ expect(toCam(r).y).toBeLessThan(0);
+ vm.dispose();
+ });
+
+ it("holds the blaster in a duel: muzzle and both hands in view at the hip; the sight on the eye line in the sights", () => {
+ const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ const parts = vm as unknown as { right: ViewArm; left: ViewArm; blaster: { group: { localToWorld(v: Vector3): Vector3 }; muzzle: Vector3; sight: Vector3 } };
+ const duelFrame = (p: PlayerView) => frameFor({ visibility: { arms: true, mode: "duel", hideOwnBody: true, raise: 1 }, player: p });
+ const cam = eye();
+ vm.set(duelFrame(player()));
+ for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
+ vm.scene.updateMatrixWorld(true);
+ const muzzle = parts.blaster.group.localToWorld(parts.blaster.muzzle.clone());
+ expect(inView(vm, muzzle)).toBe(true);
+ expect(inView(vm, world(parts.left.hand))).toBe(true);
+ // The right hand sits on the grip at the bottom right.
+ const right = world(parts.right.hand).applyMatrix4(vm.camera.matrixWorldInverse);
+ expect(right.x).toBeGreaterThan(0.08);
+ expect(right.y).toBeLessThan(-0.1);
+ // Aiming down the sights: the sight's window on the view axis at adsDistance.
+ vm.set(duelFrame(player({ ads: 1 })));
+ for (let i = 0; i < 60; i++) vm.prepare(cam, 1 / 60, null);
+ vm.scene.updateMatrixWorld(true);
+ const sight = parts.blaster.group.localToWorld(parts.blaster.sight.clone()).applyMatrix4(vm.camera.matrixWorldInverse);
+ expect(Math.abs(sight.x)).toBeLessThan(0.004);
+ expect(Math.abs(sight.y)).toBeLessThan(0.004);
+ expect(-sight.z).toBeCloseTo(VIEWMODEL.adsDistance, 2);
+ vm.dispose();
+ });
+
+ it("raises the left forearm with the shield up and kicks with a shot", () => {
+ const vm = new Viewmodel({ uniform: "#3b3f47", trim: "#5a5f68" }, new Color(1, 0.6, 0.15));
+ const parts = vm as unknown as { left: ViewArm; gun: { position: Vector3 } };
+ const cam = eye();
+ const duelFrame = (p: PlayerView) => frameFor({ visibility: { arms: true, mode: "duel", hideOwnBody: true, raise: 1 }, player: p });
+ vm.set(duelFrame(player()));
+ for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
+ vm.scene.updateMatrixWorld(true);
+ const restY = world(parts.left.hand).applyMatrix4(vm.camera.matrixWorldInverse).y;
+ const restZ = parts.gun.position.z;
+ vm.set(duelFrame(player({ shieldUp: true })));
+ for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
+ vm.scene.updateMatrixWorld(true);
+ expect(world(parts.left.hand).applyMatrix4(vm.camera.matrixWorldInverse).y).toBeGreaterThan(restY + 0.03);
+ // The emitter's strip lights.
+ expect((parts.left.emitterStrip?.material as unknown as { emissiveIntensity: number }).emissiveIntensity).toBeGreaterThan(3);
+ vm.set(duelFrame(player()));
+ for (let i = 0; i < 30; i++) vm.prepare(cam, 1 / 60, null);
+ vm.shot(1, false);
+ let back = -Infinity;
+ for (let i = 0; i < 5; i++) { vm.prepare(cam, 1 / 60, null); back = Math.max(back, parts.gun.position.z); }
+ expect(back).toBeGreaterThan(restZ + 0.01);
+ vm.dispose();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts
new file mode 100644
index 0000000000..18dc755f34
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodel.ts
@@ -0,0 +1,481 @@
+/**
+ * The first-person viewmodel (docs/verse/realtime.md, "First-person
+ * viewmodel"): the commander's own arms, and in a duel the blaster in their
+ * hands, drawn in a pass of their own after the deck.
+ *
+ * It is a tiny scene with its own camera: the camera takes the eye camera's
+ * orientation (so the room's light and reflections fall on the arms the way
+ * they fall on the deck) but sits at the origin with its own near plane and
+ * field of view, and the pass clears depth before it draws, so the arms never
+ * sink into a wall and never stretch with a wide field-of-view setting.
+ *
+ * The rig is posed in the camera's space every frame (x right, y up, −z ahead):
+ * on the deck both hands hang loose low in the frame and swing with the walk;
+ * in a duel the right hand holds the blaster's grip and the left its shroud,
+ * blended between hip, sights (the sight's window moves onto the eye line),
+ * sprint (carried low), shield (the left forearm comes up with its emitter
+ * lit, the blaster lowered) and vent (the blaster tips up, the left hand
+ * slaps the receiver). Walk bob, idle sway, look lag and recoil
+ * (`motion.ts`) ride on top; a shot also flashes at the muzzle and lights
+ * the hands. The frame path allocates nothing.
+ */
+import {
+ AdditiveBlending, CanvasTexture, Color, DirectionalLight, DoubleSide, Euler, Group, MeshBasicMaterial, MeshStandardMaterial,
+ PerspectiveCamera, PointLight, Quaternion, Scene, Sprite, SpriteMaterial, Vector3, type Texture,
+} from "three";
+import type { Deck } from "../content/deck";
+import { RoomLight } from "../actors/roomLight";
+import type { PlayerView } from "../combat/view";
+import { buildBlaster, type Blaster } from "../duel/blaster";
+import { radialTexture } from "../duel/effects";
+import { verticalFov } from "../engine/realtime/shoulderRig";
+import { ViewArm, type ArmMaterials } from "./arms";
+import { turnBetween, ViewmodelMotion, type Visibility } from "./motion";
+
+/** A pose of the blaster (its grip, the right hand's hold) in the camera's space. */
+export interface GunPose { x: number; y: number; z: number; pitch: number; yaw: number; roll: number }
+
+/**
+ * The viewmodel's layout. Plain mutable data so a QA run can tune it live
+ * (`window.__verseViewmodel` in development builds, then `retune()`).
+ */
+export const VIEWMODEL = {
+ /** Horizontal field of view of the viewmodel camera, degrees (fixed: the arms keep their shape whatever the person's setting). */
+ hfovDeg: 88,
+ /** ... and while aiming down the sights (the sight comes a little closer). */
+ adsHfovDeg: 76,
+ near: 0.01,
+ far: 4,
+ /** The blaster's size in the hands, relative to the duel's model. */
+ gunScale: 0.65,
+ /** Distance from the eye to the sight's window when aiming down the sights, metres. */
+ adsDistance: 0.3,
+ /** Time constant of the pose blends (sprint, shield, vent), seconds. */
+ blendS: 0.075,
+ /** How long a muzzle flash shows, seconds. */
+ flashS: 0.07,
+ /** Reflection strength of the deck's environment on the arms and blaster, and the share of the blaster's glow kept. */
+ envGain: 0.6,
+ glowGain: 0.08,
+ /**
+ * A soft key light over the shoulder (in the view's frame, so the arms always read): divided by the deck's
+ * exposure, it lights the arms the same on every deck.
+ */
+ fill: 1.2,
+ /** The blaster at the hip, carried low in a sprint, lowered behind the shield, rolled over to vent, dropped when knocked out. */
+ hip: { x: 0.14, y: -0.09, z: -0.33, pitch: 0.05, yaw: 0.06, roll: 0.22 } as GunPose,
+ sprint: { x: 0.17, y: -0.16, z: -0.31, pitch: -0.3, yaw: 0.45, roll: 0.45 } as GunPose,
+ shield: { x: 0.2, y: -0.22, z: -0.32, pitch: -0.45, yaw: 0.3, roll: 0.35 } as GunPose,
+ vent: { x: 0.11, y: -0.11, z: -0.33, pitch: 0.25, yaw: 0.2, roll: -0.4 } as GunPose,
+ down: { x: 0.16, y: -0.7, z: -0.25, pitch: -0.9, yaw: 0.3, roll: 0.3 } as GunPose,
+ /** The left wrist with the shield up, camera space. */
+ shieldWrist: { x: -0.13, y: -0.07, z: -0.42 },
+ /** The wrists on the deck (the left mirrors x), camera space. */
+ deckWrist: { x: 0.2, y: -0.2, z: -0.42 },
+ /** Shoulders, below and behind the eyes, and the elbows' pull (down and out); the support arm reaches in from further out. */
+ shoulderR: new Vector3(0.22, -0.38, -0.02),
+ shoulderL: new Vector3(-0.3, -0.38, -0.02),
+ poleR: new Vector3(1, -0.6, 0.1),
+ poleL: new Vector3(-1, -0.6, 0.1),
+ /**
+ * The hands: the right hand's hold on the grip (along the grip, along the knuckles, out to the side), the left's
+ * beside the shroud (out to its left, up, ahead), hand frames as knuckle and back-of-hand directions, finger curls (two joints and
+ * the thumb).
+ */
+ hands: {
+ grip: [0.012, -0.06, 0.036],
+ gripCurl: [1.45, 1.35, 0.7],
+ fore: [0.042, 0.012, -0.06],
+ foreKnuckles: [-0.15, 0.25, 1],
+ foreBack: [1, -0.15, 0],
+ foreCurl: [1.25, 1.0, 0.5],
+ ventKnuckles: [0, 0.35, 1],
+ ventBack: [1, 0.1, 0],
+ deckKnuckles: [-0.35, 0.25, -1],
+ deckBack: [0.35, 1, 0.1],
+ deckCurl: [1.3, 1.15, 0.6],
+ shieldKnuckles: [0.15, 1, -0.2],
+ shieldBack: [0.2, 0.15, 1],
+ },
+};
+
+const SHOULDER_R = new Vector3();
+const SHOULDER_L = new Vector3();
+const POLE_R = new Vector3();
+const POLE_L = new Vector3();
+
+/** The person's colours for the arms: the uniform's cloth and trim (CSS colours). */
+export interface ArmColours {
+ uniform: string;
+ trim: string;
+}
+
+export interface ViewmodelFrame {
+ visibility: Visibility;
+ /** The duel's local player, or null on the deck. */
+ player: PlayerView | null;
+ /** Ground speed, metres per second, and the walk speed the bob is measured against. */
+ speed: number;
+ walkSpeed: number;
+ /** Where the body stands (for the room's light), world metres. */
+ x: number;
+ y: number;
+ z: number;
+ /** The deck on screen (its room probes light the arms). */
+ deck: Deck | null;
+ reduced: boolean;
+ /** The duel's clock is stopped (paused): the arms hold still. */
+ frozen: boolean;
+}
+
+function lerpPose(out: GunPose, to: GunPose, t: number): void {
+ if (t <= 0) return;
+ out.x += (to.x - out.x) * t;
+ out.y += (to.y - out.y) * t;
+ out.z += (to.z - out.z) * t;
+ out.pitch += (to.pitch - out.pitch) * t;
+ out.yaw += (to.yaw - out.yaw) * t;
+ out.roll += (to.roll - out.roll) * t;
+}
+
+function reticleTexture(): Texture {
+ const size = 64;
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = size;
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ ctx.strokeStyle = "rgba(255,255,255,0.85)";
+ ctx.lineWidth = 3;
+ ctx.beginPath();
+ ctx.arc(size / 2, size / 2, size * 0.3, 0, Math.PI * 2);
+ ctx.stroke();
+ ctx.fillStyle = "rgba(255,255,255,1)";
+ ctx.beginPath();
+ ctx.arc(size / 2, size / 2, size * 0.055, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ return new CanvasTexture(canvas);
+}
+
+export class Viewmodel {
+ readonly scene = new Scene();
+ readonly camera: PerspectiveCamera;
+ /** Draw the pass this frame (set by `prepare`). */
+ visible = false;
+ private readonly rig = new Group();
+ private readonly right: ViewArm;
+ private readonly left: ViewArm;
+ private readonly blaster: Blaster;
+ private readonly gun = new Group();
+ private readonly mats: ArmMaterials & { sleeve: MeshStandardMaterial; trim: MeshStandardMaterial; emitter: MeshStandardMaterial };
+ private readonly reticle: MeshBasicMaterial;
+ private readonly flash: Sprite;
+ private readonly flashLight = new PointLight(0xffa040, 0, 1.2, 2);
+ private readonly key = new DirectionalLight(0xfff2e0, 0);
+ private readonly light = new RoomLight();
+ private readonly motion = new ViewmodelMotion();
+ private readonly textures: Texture[] = [];
+ /** The lit materials (the room's reflections are scaled on them) and the blaster's glowing ones. */
+ private readonly lit: MeshStandardMaterial[];
+ private readonly glowing: MeshStandardMaterial[];
+ private frame: ViewmodelFrame | null = null;
+ private shots = 0;
+ private flashT = 0;
+ private time = 0;
+ private ventT = 0;
+ private readonly w = { sprint: 0, shield: 0, vent: 0, down: 0 };
+ private primed = false;
+ private prevYaw = 0;
+ private prevPitch = 0;
+ // Scratch, reused every frame.
+ private readonly pose: GunPose = { ...VIEWMODEL.hip };
+ private readonly ads: GunPose = { ...VIEWMODEL.hip };
+ private readonly euler = new Euler(0, 0, 0, "YXZ");
+ private readonly qGun = new Quaternion();
+ private readonly qTmp = new Quaternion();
+ private readonly qBase = new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.PI);
+ private readonly qHandR = new Quaternion();
+ private readonly qHandL = new Quaternion();
+ private readonly qDeckR = new Quaternion();
+ private readonly qDeckL = new Quaternion();
+ private readonly qShieldL = new Quaternion();
+ private readonly wristR = new Vector3();
+ private readonly wristL = new Vector3();
+ private readonly v = new Vector3();
+ private readonly dir = new Vector3();
+ /** The hands' holds in the blaster's frame: wrist points and hand frames. */
+ private readonly holdR = { at: new Vector3(), q: new Quaternion() };
+ private readonly holdL = { at: new Vector3(), q: new Quaternion() };
+ private readonly ventL = { at: new Vector3(), q: new Quaternion() };
+
+ constructor(colours: ArmColours, accent: Color) {
+ this.camera = new PerspectiveCamera(60, 1, VIEWMODEL.near, VIEWMODEL.far);
+ this.scene.name = "Viewmodel";
+ const sleeve = new MeshStandardMaterial({ name: "M_View_Sleeve", color: colours.uniform, roughness: 0.78, metalness: 0, side: DoubleSide });
+ const trim = new MeshStandardMaterial({ name: "M_View_Trim", color: colours.trim, roughness: 0.55, metalness: 0.2 });
+ const glove = new MeshStandardMaterial({ name: "M_View_Glove", color: 0x2b2c31, roughness: 0.46, metalness: 0.05, side: DoubleSide });
+ const housing = new MeshStandardMaterial({ name: "M_View_Emitter_Housing", color: 0x2a2e34, roughness: 0.35, metalness: 0.85 });
+ const emitter = new MeshStandardMaterial({ name: "M_View_Emitter", color: 0x050505, emissive: new Color(0.35, 0.75, 1.6), emissiveIntensity: 0.6, roughness: 0.4 });
+ this.mats = { sleeve, trim, glove, housing, emitter };
+ this.right = new ViewArm("right", this.mats);
+ this.left = new ViewArm("left", this.mats);
+ this.blaster = buildBlaster(accent, { bevel: true });
+ // The sight's pane becomes a see-through reticle.
+ const reticleMap = reticleTexture();
+ this.textures.push(reticleMap);
+ this.reticle = new MeshBasicMaterial({
+ map: reticleMap, color: new Color(1.6, 0.85, 0.25), transparent: true, blending: AdditiveBlending, depthWrite: false,
+ });
+ this.blaster.sightGlass.material = this.reticle;
+ for (const m of this.blaster.stock) m.visible = false;
+ this.gun.add(this.blaster.group);
+ // The muzzle flash: a short additive burst at the muzzle, and the light it throws on the hands.
+ const flashMap = radialTexture([[0, "rgba(255,255,255,1)"], [0.25, "rgba(255,190,90,0.9)"], [1, "rgba(255,120,30,0)"]]);
+ this.textures.push(flashMap);
+ this.flash = new Sprite(new SpriteMaterial({ map: flashMap, color: new Color(2.4, 1.5, 0.6), blending: AdditiveBlending, depthWrite: false, transparent: true }));
+ this.flash.scale.setScalar(0.11);
+ this.flash.visible = false;
+ this.blaster.group.add(this.flash);
+ this.flash.position.copy(this.blaster.muzzle).setZ(this.blaster.muzzle.z + 0.04);
+ this.blaster.group.add(this.flashLight);
+ this.flashLight.position.copy(this.blaster.muzzle);
+
+ this.rig.add(this.right.group, this.left.group, this.gun, this.key, this.key.target);
+ this.key.position.set(-0.4, 1, 0.5);
+ this.scene.add(this.rig);
+ this.rig.traverse((o) => { o.frustumCulled = false; });
+ this.lit = [sleeve, trim, glove, housing, ...this.blaster.materials].filter((m): m is MeshStandardMaterial => (m as MeshStandardMaterial).isMeshStandardMaterial === true);
+ this.glowing = this.lit.filter((m) => /Cells|Vents|Emitter$/.test(m.name) && m.name.startsWith("M_Blaster"));
+ this.light.attach(this.lit);
+ this.retune();
+ }
+
+ /** The person's colours changed (a promotion): repaint the sleeves. */
+ setColours(colours: ArmColours): void {
+ this.mats.sleeve.color.set(colours.uniform);
+ this.mats.trim.color.set(colours.trim);
+ }
+
+ /** This frame's state (the layer fills it before the eye view renders). */
+ set(frame: ViewmodelFrame): void {
+ this.frame = frame;
+ }
+
+ /** A shot left the blaster (the duel counts them): kick and flash. */
+ shot(count: number, ads: boolean): void {
+ if (count === this.shots) return;
+ const fresh = count > this.shots && this.primed;
+ this.shots = count;
+ if (!fresh) return;
+ this.motion.fire(ads ? 0.75 : 1);
+ this.flashT = VIEWMODEL.flashS;
+ this.flash.material.rotation = Math.random() * Math.PI * 2;
+ }
+
+ /** Apply VIEWMODEL's layout: the blaster's size, the shoulders, the hands' holds on the blaster (in its frame). */
+ retune(): void {
+ const s = VIEWMODEL.gunScale;
+ this.blaster.group.scale.setScalar(s);
+ SHOULDER_R.copy(VIEWMODEL.shoulderR);
+ SHOULDER_L.copy(VIEWMODEL.shoulderL);
+ POLE_R.copy(VIEWMODEL.poleR).normalize();
+ POLE_L.copy(VIEWMODEL.poleL).normalize();
+ // Right hand: the grip's axis runs up and back (the grip rakes 0.28 rad); the back of the hand faces the
+ // blaster's right (−X), the knuckles wrap the grip's front and the fingers curl round to its left side.
+ const up = new Vector3(0, Math.cos(0.28), -Math.sin(0.28));
+ const backR = new Vector3(-1, 0, 0);
+ const knR = new Vector3().crossVectors(up, backR);
+ const h = VIEWMODEL.hands;
+ const vec = (a: readonly number[]) => new Vector3(a[0], a[1], a[2]);
+ const grip = new Vector3(0, -0.06, -0.01).multiplyScalar(1.3 * s);
+ this.holdR.at.copy(grip).addScaledVector(up, h.grip[0]).addScaledVector(knR, h.grip[1]).addScaledVector(backR, h.grip[2]);
+ ViewArm.handFrame(knR, backR, this.holdR.q);
+ // Left hand: a clamp on the shroud from its left, the thumb over the top, the knuckles along the barrel, the back
+ // of the hand outward; the fingers curl in under the shroud.
+ const fore = this.blaster.fore.clone().multiplyScalar(s);
+ const knL = vec(h.foreKnuckles).normalize();
+ const backL = vec(h.foreBack).normalize();
+ this.holdL.at.set(fore.x + h.fore[0], fore.y + h.fore[1], fore.z + h.fore[2]).addScaledVector(knL, -0.05);
+ ViewArm.handFrame(knL, backL, this.holdL.q);
+ // Venting: the left hand leaves the shroud and slaps the receiver's side, palm flat against it.
+ const vents = new Vector3(0.05, 0.02, 0.12).multiplyScalar(1.3 * s);
+ const knV = vec(h.ventKnuckles).normalize();
+ const backV = vec(h.ventBack).normalize();
+ this.ventL.at.copy(vents).addScaledVector(backV, 0.018).addScaledVector(knV, -0.05);
+ ViewArm.handFrame(knV, backV, this.ventL.q);
+ // On the deck: relaxed hands, knuckles ahead, the backs of the hands up and out (the left mirrors the right).
+ const dk = vec(h.deckKnuckles);
+ const db = vec(h.deckBack);
+ ViewArm.handFrame(dk, db, this.qDeckR);
+ ViewArm.handFrame(dk.setX(-dk.x), db.setX(-db.x), this.qDeckL);
+ // Shield up: the left forearm vertical before the face's left, the palm forward, the back of the hand (and the
+ // emitter on the forearm's back) toward the eyes.
+ ViewArm.handFrame(vec(h.shieldKnuckles), vec(h.shieldBack), this.qShieldL);
+ // The aiming pose: the sight's window on the eye line at adsDistance.
+ const sight = this.blaster.sight.clone().multiplyScalar(s).applyQuaternion(this.qBase);
+ this.ads.x = -sight.x;
+ this.ads.y = -sight.y;
+ this.ads.z = -VIEWMODEL.adsDistance - sight.z;
+ this.ads.pitch = 0;
+ this.ads.yaw = 0;
+ this.ads.roll = 0;
+ }
+
+ /**
+ * Called by the eye view once its camera is placed for the frame: follow
+ * its orientation, step the motion, pose the rig. `dt` in seconds.
+ */
+ prepare(eye: PerspectiveCamera, dt: number, environment: Texture | null): void {
+ const f = this.frame;
+ this.visible = !!f && f.visibility.arms;
+ // The view's turn since the last frame (for the look lag), from the eye camera's direction.
+ eye.getWorldDirection(this.dir);
+ const yaw = Math.atan2(this.dir.x, this.dir.z);
+ const pitch = Math.asin(Math.max(-1, Math.min(1, this.dir.y)));
+ const turn = this.primed ? turnBetween(this.prevYaw, this.prevPitch, yaw, pitch) : { yaw: 0, pitch: 0 };
+ this.prevYaw = yaw;
+ this.prevPitch = pitch;
+ if (!f || !this.visible) {
+ this.primed = false;
+ this.motion.reset();
+ return;
+ }
+ this.primed = true;
+ const step = f.frozen ? 0 : Math.min(0.1, Math.max(0, dt));
+ this.time += step;
+ this.scene.environment = environment;
+ this.camera.quaternion.copy(eye.quaternion);
+ this.camera.position.set(0, 0, 0);
+ const aspect = eye.aspect || 1;
+ const p = f.player;
+ const ads = p ? p.ads : 0;
+ const hfov = VIEWMODEL.hfovDeg + (VIEWMODEL.adsHfovDeg - VIEWMODEL.hfovDeg) * ads;
+ const fov = verticalFov(aspect, hfov, 30);
+ if (Math.abs(this.camera.aspect - aspect) > 1e-4 || Math.abs(this.camera.fov - fov) > 1e-3) {
+ this.camera.aspect = aspect;
+ this.camera.fov = fov;
+ this.camera.updateProjectionMatrix();
+ }
+ this.camera.updateMatrixWorld();
+ this.rig.quaternion.copy(eye.quaternion);
+ this.rig.updateMatrixWorld();
+
+ const o = this.motion.step({
+ dt: step, speed: f.speed, walkSpeed: f.walkSpeed, turnYaw: step ? turn.yaw : 0, turnPitch: step ? turn.pitch : 0, ads, reduced: f.reduced,
+ });
+ // Pose weights ease in and out.
+ const w = this.w;
+ const k = step ? 1 - Math.exp(-step / VIEWMODEL.blendS) : 0;
+ const duel = f.visibility.mode === "duel" && !!p;
+ w.sprint += ((p?.sprinting ? 1 : 0) - w.sprint) * k;
+ w.shield += ((p?.shieldUp && p.alive ? 1 : 0) - w.shield) * k;
+ w.vent += ((p?.venting && p.alive ? 1 : 0) - w.vent) * k;
+ w.down += ((p && !p.alive ? 1 : 0) - w.down) * k;
+ this.ventT = p?.venting ? this.ventT + step : 0;
+ // The arms rise into view as the camera blends into the head; a dodge dips them.
+ const raise = f.visibility.raise;
+ // The deck's exposure scales everything drawn; the viewmodel's own lights are divided by it.
+ const exposure = Math.pow(2, f.deck?.exposure ?? 0);
+ const dip = (1 - raise) * 0.35 + (p?.dodging ? Math.sin(p.dodgeProgress * Math.PI) * 0.12 : 0);
+
+ this.gun.visible = duel;
+ if (duel && p) this.poseDuel(p, o, dip);
+ else this.poseDeck(o, dip);
+
+ // Muzzle flash and its light.
+ this.flashT = Math.max(0, this.flashT - step);
+ const fl = this.flashT / VIEWMODEL.flashS;
+ this.flash.visible = duel && fl > 0;
+ this.flash.scale.setScalar(0.1 + 0.14 * fl);
+ this.flashLight.intensity = duel ? (fl * 1.6) / exposure : 0;
+ this.key.intensity = VIEWMODEL.fill / exposure;
+ // The left forearm's emitter: dim at rest, bright while the shield is up.
+ const e = this.mats.emitter;
+ e.emissiveIntensity = 0.5 + w.shield * (4 + (p ? p.shieldEnergy * 4 : 0)) + (p?.parrying ? 6 : 0);
+ if (duel && p) {
+ this.blaster.setHeat(p.heat, p.venting, p.overheated, this.time);
+ // A hand's breadth from the eye the duel model's glow (tuned to read at shoulder distance) would flood the bloom.
+ for (const m of this.glowing) m.emissiveIntensity *= VIEWMODEL.glowGain;
+ }
+ // The room's reflections: the deck's environment is captured in the open room, the hands are in the body's shade.
+ for (const m of this.lit) m.envMapIntensity = VIEWMODEL.envGain;
+ if (f.deck) this.light.update(f.deck, f.x, f.y, f.z, step);
+ }
+
+ private poseDuel(p: PlayerView, o: { x: number; y: number; z: number; pitch: number; yaw: number; roll: number }, dip: number): void {
+ const w = this.w;
+ const pose = this.pose;
+ Object.assign(pose, VIEWMODEL.hip);
+ lerpPose(pose, this.ads, p.ads);
+ lerpPose(pose, VIEWMODEL.sprint, w.sprint);
+ lerpPose(pose, VIEWMODEL.shield, w.shield);
+ // Venting tips the blaster up; knocked out, it drops away.
+ lerpPose(pose, VIEWMODEL.vent, w.vent);
+ lerpPose(pose, VIEWMODEL.down, w.down);
+ pose.x += o.x;
+ pose.y += o.y - dip;
+ pose.z += o.z;
+ this.euler.set(pose.pitch + o.pitch, pose.yaw + o.yaw, pose.roll + o.roll, "YXZ");
+ this.qGun.setFromEuler(this.euler).multiply(this.qBase);
+ this.gun.position.set(pose.x, pose.y, pose.z);
+ this.gun.quaternion.copy(this.qGun);
+ this.gun.updateMatrixWorld();
+
+ // Right hand on the grip.
+ this.wristR.copy(this.holdR.at).applyQuaternion(this.qGun).add(this.gun.position);
+ this.qHandR.copy(this.qGun).multiply(this.holdR.q);
+ const h = VIEWMODEL.hands;
+ this.right.curl(h.gripCurl[0], h.gripCurl[1], h.gripCurl[2]);
+ this.right.pose(SHOULDER_R, this.wristR, this.qHandR, POLE_R);
+
+ // Left hand: on the shroud, against the receiver while venting, up before the face behind the shield.
+ this.wristL.copy(this.holdL.at).applyQuaternion(this.qGun).add(this.gun.position);
+ this.qHandL.copy(this.qGun).multiply(this.holdL.q);
+ let c1 = h.foreCurl[0];
+ let c2 = h.foreCurl[1];
+ if (w.vent > 1e-3) {
+ // A slap: the hand swings out and in against the receiver in the first quarter second, then rests there.
+ const t = Math.min(1, this.ventT / 0.2);
+ const swing = Math.sin(t * Math.PI) * 0.06;
+ this.v.copy(this.ventL.at).setX(this.ventL.at.x + swing).applyQuaternion(this.qGun).add(this.gun.position);
+ this.wristL.lerp(this.v, w.vent);
+ this.qTmp.copy(this.qGun).multiply(this.ventL.q);
+ this.qHandL.slerp(this.qTmp, w.vent);
+ c1 += (0.35 - c1) * w.vent;
+ c2 += (0.3 - c2) * w.vent;
+ }
+ if (w.shield > 1e-3) {
+ const sw = VIEWMODEL.shieldWrist;
+ this.v.set(sw.x + o.x, sw.y + o.y - dip, sw.z + o.z);
+ this.wristL.lerp(this.v, w.shield);
+ this.qHandL.slerp(this.qShieldL, w.shield);
+ c1 += (0.15 - c1) * w.shield;
+ c2 += (0.1 - c2) * w.shield;
+ }
+ if (w.down > 1e-3) this.wristL.y -= w.down * 0.5;
+ this.left.curl(c1, c2, h.foreCurl[2]);
+ this.left.pose(SHOULDER_L, this.wristL, this.qHandL, POLE_L);
+ }
+
+ private poseDeck(o: { x: number; y: number; z: number; pitch: number; yaw: number; roll: number }, dip: number): void {
+ // Loose hands low in the frame; while walking they swing against each other with the stride.
+ const swing = Math.sin(this.motion.phase) * 0.05 * Math.min(1, this.motion.bob);
+ const c = VIEWMODEL.hands.deckCurl;
+ this.right.curl(c[0], c[1], c[2]);
+ this.left.curl(c[0], c[1], c[2]);
+ const d = VIEWMODEL.deckWrist;
+ this.wristR.set(d.x + o.x, d.y + o.y - dip + Math.abs(swing) * 0.2, d.z + o.z - swing);
+ this.wristL.set(-d.x + o.x, d.y + o.y - dip + Math.abs(swing) * 0.2, d.z + o.z + swing);
+ this.right.pose(SHOULDER_R, this.wristR, this.qDeckR, POLE_R);
+ this.left.pose(SHOULDER_L, this.wristL, this.qDeckL, POLE_L);
+ }
+
+ dispose(): void {
+ this.right.dispose();
+ this.left.dispose();
+ this.blaster.dispose();
+ for (const m of [this.mats.sleeve, this.mats.trim, this.mats.glove, this.mats.housing, this.mats.emitter, this.reticle, this.flash.material]) m.dispose();
+ for (const t of this.textures) t.dispose();
+ }
+}
+
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodelPass.ts b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodelPass.ts
new file mode 100644
index 0000000000..b253e0a4bd
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/viewmodel/viewmodelPass.ts
@@ -0,0 +1,36 @@
+/**
+ * The viewmodel's draw in the eye view's post chain: after the deck's render
+ * pass, into the same (multisampled HDR) target, depth cleared first, so the
+ * arms get the deck's anti-aliasing, bloom and tone mapping and never meet
+ * its walls. No full-screen pass of its own; with nothing to draw it skips.
+ */
+import type { WebGLRenderer, WebGLRenderTarget } from "three";
+import { Pass } from "three/examples/jsm/postprocessing/Pass.js";
+import type { ViewmodelDraw } from "../runtime";
+
+export class ViewmodelPass extends Pass {
+ /** What to draw this frame (null or invisible: nothing). */
+ draw: ViewmodelDraw | null = null;
+
+ constructor() {
+ super();
+ this.needsSwap = false;
+ this.clear = false;
+ }
+
+ override render(renderer: WebGLRenderer, _writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget): void {
+ const vm = this.draw;
+ if (!vm?.visible) return;
+ drawViewmodel(renderer, vm, this.renderToScreen ? null : readBuffer);
+ }
+}
+
+/** Clear depth on `target` (null: the screen) and draw the viewmodel over what is there. */
+export function drawViewmodel(renderer: WebGLRenderer, vm: ViewmodelDraw, target: WebGLRenderTarget | null): void {
+ const autoClear = renderer.autoClear;
+ renderer.setRenderTarget(target);
+ renderer.autoClear = false;
+ renderer.clearDepth();
+ renderer.render(vm.scene, vm.camera);
+ renderer.autoClear = autoClear;
+}