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): duel bodies move like shooter fighters (#1042)

Ruben Lütke56eb2e4f41f1
diff --git a/art/verse/characters/README.md b/art/verse/characters/README.md
index fc75e84b26..602dd1b902 100644
--- a/art/verse/characters/README.md
+++ b/art/verse/characters/README.md
@@ -29,7 +29,7 @@ Builds are deterministic (no random numbers, fixed iteration order). Run
| `body.py`, `outfits.py`, `crew.py`, `drones.py` | geometry, skinning, vertex AO |
| `paint.py` | UV atlas, rasteriser, normal bake from the full-resolution garment, images, material wiring |
| `looks.py`, `looks_gear.py` | what the atlases show (faces, hair, tailoring, armour, drones) |
-| `anim.py`, `posing.py` | clips |
+| `anim.py`, `anim_combat.py`, `posing.py` | clips (crew, duel) |
| `qa.py`, `lookdev.py`, `check_glb.mjs` | checks and look-development renders |
| `sovereign.py`, `looks_sovereign.py`, `sovereign_qa.py` | the Sovereign skin, its atlas, its look-dev renders |
@@ -99,6 +99,29 @@ Only `Hips` has a translation track; every other bone is rotation only.
| `A_Stand_Up` | no | 1.27 s | Seated to standing (ends with the feet ~0.42 m in front of the root) |
| `A_Sleep` | yes | 6 s | Lying on the back, slow breathing |
+Duel clips (`anim_combat.py`; every one holds the blaster right-handed in a bladed
+stance; the runtime re-solves the arms onto the blaster, calibrated on `A_Combat_Idle`
+frame 0, where the barrel is level and straight ahead):
+
+| Clip | Loop | Length | Notes |
+|---|---|---|---|
+| `A_Combat_Idle` | yes | 2 s | Ready stance: knees soft, pelvis and chest turned right, head forward |
+| `A_Combat_Cover` | yes | 2 s | Crouched low behind cover, barrel down |
+| `A_Combat_Walk_F/L/B/R` | yes | 0.67 s | Combat walk at 2.4 m/s (back 1.87) along heading 0 / 90 / 180 / -90 deg |
+| `A_Combat_Run_F/L/B/R` | yes | 0.6 s | Run at 4.8 m/s (back 3.74); side runs cross over |
+| `A_Combat_Sprint` | yes | 0.53 s | 7 m/s, blaster low across the chest |
+| `A_Combat_Turn_L/R` | no | 0.6 s | Two steps turning 90 deg; turn the root by +-90 deg x smootherstep(t / 0.6) |
+| `A_Combat_Roll` | no | 0.6 s | Dive, tucked shoulder roll, landing; in place, face the root the roll's way |
+| `A_Combat_Hit_F/B/L/R` | no | 0.5 s | Additive flinch (frame 0 = idle frame 0), spine, head and shoulders only |
+| `A_Combat_Stagger` | no | 1 s | Additive reel |
+| `A_Combat_Death` | no | 1.4 s | Jolt, knees buckle, falls on the back towards -Z (behind the root) |
+| `A_Combat_GetUp` | no | 1.5 s | From the death's last pose to the idle |
+
+Locomotion clips share one phase (0 = left foot down, 0.5 = right); `characters.json`
+`clips` carries each one's `speed` (male skeleton, m/s) and `heading` (degrees, 90 =
+the body's left). `build.py --clips-only` rebakes only the clip files and the manifest.
+`skeletons.<v>.clipsBytes` versions the clip file's URL.
+
Placement conventions (all three.js axes, relative to the character root):
- **Seat**: the clip puts the buttocks on a seat surface `seatHeight` (0.46 m) above the
diff --git a/art/verse/characters/anim_combat.py b/art/verse/characters/anim_combat.py
new file mode 100644
index 0000000000..69d8ab73a2
--- /dev/null
+++ b/art/verse/characters/anim_combat.py
@@ -0,0 +1,807 @@
+"""Duel clips of the shared human skeleton: a rifle stance, directional locomotion,
+turn-in-place, the dodge roll, hit reactions, the knockout fall and the get-up.
+
+Same conventions as `anim.py` (Blender axes: X = character's left, -Y = forward,
+Z = up; 30 fps; in place). Every clip holds the blaster right-handed in a bladed
+stance (pelvis and chest turned right, head forward), so the left hand reaches the
+shroud. The runtime (`duel/figure.ts`) re-solves the arms onto the blaster every
+frame by two-bone IK and calibrates the hands against `A_Combat_Idle` frame 0, where
+the blaster points straight ahead, level, its grip `GRIP_FROM_WRIST` ahead of the
+right wrist.
+
+Locomotion clips share one phase convention: phase 0 is the left foot's contact,
+0.5 the right foot's, so the runtime blends any of them on one normalised phase. A
+clip moves its planted foot backwards at exactly its `LOCOMOTION` speed along its
+heading; the runtime advances the phase at (ground speed / blended stride), so the
+feet do not slide in any direction or blend.
+
+Hit and stagger clips are additive: frame 0 is the idle's frame 0 and only the
+spine, head and shoulders move.
+"""
+
+from __future__ import annotations
+
+import math
+
+from mathutils import Matrix, Vector
+
+from characters import common as C
+from characters.anim import TAU, Body, _lerp_spec, ease, frames, harm
+
+# Stance: pelvis and chest turned to the right (twist < 0), the head back to the front.
+BLADE = {"hips": -14.0, "Spine": -9.0, "Chest": -9.0, "Neck": 14.0, "Head": 18.0}
+
+# Gun geometry (metres along the barrel, Blender axes, scaled with the body).
+STOCK = 0.29 # stock butt behind the grip
+LEFT_HOLD = 0.22 # the left palm's hold ahead of the grip
+WRIST_BACK, WRIST_UP = 0.06, 0.03 # right wrist from the grip (behind, above)
+
+# heading in degrees: 0 = forward, 90 = to the character's left, 180 = back, -90 = right
+HEADINGS = {"F": 0.0, "L": 90.0, "B": 180.0, "R": -90.0}
+BACK_SPEED = 0.78 # straight back runs at 78% (combat tuning)
+
+GAITS = {
+ # frames per cycle (two steps), m/s forward, stance share, swing height, hip drop, forward lean
+ "Walk": {
+ "n": 20,
+ "speed": 2.4,
+ "duty": 0.52,
+ "lift": 0.075,
+ "drop": 0.075,
+ "lean": 5.0,
+ "bob": 0.014,
+ },
+ "Run": {
+ "n": 18,
+ "speed": 4.8,
+ "duty": 0.30,
+ "lift": 0.14,
+ "drop": 0.095,
+ "lean": 9.0,
+ "bob": 0.03,
+ },
+}
+SPRINT = {
+ "n": 16,
+ "speed": 7.0,
+ "duty": 0.24,
+ "lift": 0.18,
+ "drop": 0.10,
+ "lean": 15.0,
+ "bob": 0.035,
+}
+
+TURN_SECONDS = 0.6
+TURN_DEG = 90.0
+
+# Filled in by `combat_clips()`: per clip {"speed": m/s, "heading": deg} for the manifest.
+LOCOMOTION: dict[str, dict] = {}
+
+
+def _rz(deg: float) -> Matrix:
+ return Matrix.Rotation(math.radians(deg), 3, "Z")
+
+
+def _rx(deg: float) -> Matrix:
+ return Matrix.Rotation(math.radians(deg), 3, "X")
+
+
+def _dir(heading: float) -> Vector:
+ h = math.radians(heading)
+ return Vector((math.sin(h), -math.cos(h), 0.0))
+
+
+def smootherstep(x: float) -> float:
+ return ease(x)
+
+
+def _foot_rot(pitch: float, yaw: float) -> Matrix:
+ """Foot rotation: pitched (heel up > 0) about its own axis, then turned (left > 0)."""
+ return _rz(yaw) @ _rx(pitch)
+
+
+def _leg(b: Body, side: str, ankle: Vector, pitch: float, yaw: float, toe: float = 0.0, pole=None):
+ sg = 1.0 if side == "L" else -1.0
+ fv = _foot_rot(pitch, yaw) @ b.foot_vec
+ return {
+ "target": tuple(ankle),
+ "pole": pole if pole is not None else (sg * 0.12, -1.0, 0.1),
+ "foot_dir": tuple(fv.normalized()),
+ "foot_up": (0.0, 0.0, 1.0),
+ "toe": toe,
+ }
+
+
+def _planted(
+ b: Body, side: str, x: float, y: float, yaw: float, pitch: float = 0.0, lift: float = 0.0
+):
+ """Ankle over a floor point (x, y) for a flat foot, turned by `yaw` (left > 0)."""
+ return _leg(b, side, Vector((x, y, b.ankle.z + lift)), pitch, yaw)
+
+
+def _stance_feet(b: Body):
+ """Bladed stance: left foot ahead, right foot back and turned out (floor x, y, yaw per side)."""
+ s = b.scale
+ return {"L": (0.115 * s, -0.11 * s, -12.0), "R": (-0.155 * s, 0.13 * s, -38.0)}
+
+
+# ------------------------------------------------------------------------ the blaster
+
+
+def _shoulder_r(b: Body, p: dict) -> Vector:
+ M = b.rig.solve(p)
+ return M["UpperArm_R"].translation.copy(), M
+
+
+def hold_arms(b: Body, p: dict, pitch: float = 0.0, yaw: float = 0.0, tuck: float = 0.0):
+ """Both arms on the blaster: stock at the right shoulder pocket, barrel along (yaw, pitch)."""
+ sh, _M = _shoulder_r(b, p)
+ s = b.scale
+ fwd = _rz(yaw) @ (_rx(-pitch) @ Vector((0.0, -1.0, 0.0)))
+ right = _rz(yaw) @ Vector((-1.0, 0.0, 0.0))
+ up = right.cross(fwd).normalized()
+ pocket = sh + Vector((0.03, -0.07, -0.05)) * s
+ grip = pocket + fwd * (STOCK * s) - fwd * (tuck * 0.12) - up * (tuck * 0.10)
+ wrist_r = grip - fwd * (WRIST_BACK * s) + up * (WRIST_UP * s)
+ palm_l = grip + fwd * (LEFT_HOLD * s) - up * (0.03 * s)
+ wrist_l = palm_l - fwd * (0.05 * s) - up * (0.04 * s) - right * (0.03 * s)
+ return {
+ "arm_R": {
+ "target": tuple(wrist_r),
+ "pole": tuple((right * 1.0 - up * 1.0 + fwd * 0.3).normalized()),
+ "hand_dir": tuple((fwd * 0.7 - up * 0.7).normalized()),
+ "dorsal": tuple(right),
+ "fingers": 48.0,
+ "thumb": 26.0,
+ },
+ "arm_L": {
+ "target": tuple(wrist_l),
+ "pole": tuple((-right * 0.6 - up * 1.0).normalized()),
+ "hand_dir": tuple((fwd * 0.85 + right * 0.45 + up * 0.2).normalized()),
+ "dorsal": tuple((-up * 0.9 - right * 0.4).normalized()),
+ "fingers": 40.0,
+ "thumb": 20.0,
+ },
+ }
+
+
+def _with_hold(b: Body, p: dict, **kw) -> dict:
+ p.update(hold_arms(b, p, **kw))
+ return p
+
+
+def _spine(bend=0.0, twist=0.0, lean=0.0, extra=None):
+ sp = {
+ "Spine": (bend * 0.45, BLADE["Spine"] + twist * 0.5, lean * 0.5),
+ "Chest": (bend * 0.55, BLADE["Chest"] + twist * 0.5, lean * 0.5),
+ "Neck": (-bend * 0.3, BLADE["Neck"], -lean * 0.3),
+ "Head": (-bend * 0.4, BLADE["Head"], -lean * 0.4),
+ }
+ for k, v in (extra or {}).items():
+ a = sp[k]
+ sp[k] = (a[0] + v[0], a[1] + v[1], a[2] + v[2])
+ return sp
+
+
+# ------------------------------------------------------------------------- standing
+
+
+def combat_stand(
+ b: Body, t: float = 0.0, period: float = 2.0, crouch: float = 0.0, breathe: float = 1.0
+):
+ """The ready stance (no arms): knees soft, pelvis bladed, chest leaning in."""
+ w = harm(t, period, [(1, 1.0, 0.0)]) * breathe
+ br = harm(t, period, [(2, 1.0, 0.4)]) * breathe
+ s = b.scale
+ feet = _stance_feet(b)
+ hz = b.hips.z - (0.055 + 0.25 * crouch) * s - 0.004 * abs(w)
+ p = {
+ "hips": Vector((0.012 * w * s - 0.01 * s, 0.01 * s + 0.03 * crouch, hz)),
+ "hips_rot": (6.0 + 14.0 * crouch, BLADE["hips"], -1.2 * w),
+ "spine": _spine(bend=6.0 + 10.0 * crouch + 0.8 * br, lean=0.6 * w),
+ "shoulder_L": (0.6 * br, 4.0),
+ "shoulder_R": (0.6 * br, 0.0),
+ }
+ if crouch > 0:
+ wide = 1.0 + 0.25 * crouch
+ p["leg_L"] = _planted(
+ b, "L", feet["L"][0] * wide, feet["L"][1] * (1 + crouch), feet["L"][2]
+ )
+ p["leg_R"] = _planted(
+ b, "R", feet["R"][0] * wide, feet["R"][1] * (1 + crouch * 0.6), feet["R"][2]
+ )
+ else:
+ p["leg_L"] = _planted(b, "L", feet["L"][0], feet["L"][1], feet["L"][2])
+ p["leg_R"] = _planted(b, "R", feet["R"][0], feet["R"][1], feet["R"][2])
+ return p
+
+
+def clip_combat_idle(b: Body):
+ T = 2.0
+ out = []
+ for f in range(frames(T)):
+ t = f / C.FPS
+ p = combat_stand(b, t, T)
+ sway = harm(t, T, [(1, 1.2, 0.8)])
+ out.append(_with_hold(b, p, pitch=0.6 * sway if f else 0.0, yaw=0.0))
+ # Frame 0 is the calibration frame: the barrel level and straight ahead.
+ out[0] = _with_hold(b, combat_stand(b, 0.0, T), pitch=0.0, yaw=0.0)
+ out[-1] = out[0]
+ return out
+
+
+def clip_combat_cover(b: Body):
+ """Low behind cover: deep crouch, barrel down, head up and scanning."""
+ T = 2.0
+ out = []
+ for f in range(frames(T)):
+ t = f / C.FPS
+ p = combat_stand(b, t, T, crouch=1.0, breathe=1.3)
+ look = harm(t, T, [(1, 6.0, 0.3)])
+ sp = p["spine"]
+ sp["Head"] = (sp["Head"][0] - 6.0, sp["Head"][1] + look, sp["Head"][2])
+ out.append(_with_hold(b, p, pitch=-32.0, yaw=8.0, tuck=0.3))
+ return out
+
+
+# ---------------------------------------------------------------------- locomotion
+
+
+def _gait_foot(b: Body, ph: float, g: dict, heading: float, side: str):
+ """Ankle (in place), foot pitch and toe for one foot at phase `ph` (0 = its contact)."""
+ s = b.scale
+ n, d = g["n"], g["duty"]
+ speed = g["speed"] * (BACK_SPEED if abs(heading) > 135 else 1.0)
+ S = speed * n / C.FPS * (b.leg / 0.8426)
+ u = _dir(heading)
+ fwdness = math.cos(math.radians(heading))
+ lateral = abs(math.sin(math.radians(heading)))
+ sg = 1.0 if side == "L" else -1.0
+ width = (0.095 + 0.05 * lateral) * s
+ base = Vector((sg * width, 0.03 * s * max(0.0, fwdness), 0.0))
+ yaw = -6.0 * sg + 18.0 * math.sin(math.radians(heading)) * lateral
+ run = d < 0.4
+ strike = (0.0 if run else -14.0) if fwdness > 0.3 else (14.0 if fwdness < -0.3 else 0.0)
+ push = 34.0 if fwdness > -0.3 else 12.0
+ half = S * d * 0.5
+ if ph < d:
+ k = ph / d
+ along = half - S * ph
+ if k < 0.25:
+ pitch = C.lerp(strike, 0.0, ease(k / 0.25))
+ elif k > 0.55:
+ pitch = push * ((k - 0.55) / 0.45) ** 1.6
+ else:
+ pitch = 0.0
+ lift = 0.0
+ cross = 0.0
+ toe = pitch * 0.85 if pitch > 0 else 0.0
+ else:
+ k = (ph - d) / (1.0 - d)
+ m = -S * (1.0 - d)
+ h00 = 2 * k**3 - 3 * k**2 + 1
+ h10 = k**3 - 2 * k**2 + k
+ h01 = -2 * k**3 + 3 * k**2
+ h11 = k**3 - k**2
+ along = h00 * (-half) + h10 * m + h01 * half + h11 * m
+ lift = g["lift"] * s * math.sin(math.pi * k) ** 0.75
+ if k < 0.5:
+ pitch = C.lerp(push, -6.0, ease(k / 0.5))
+ else:
+ pitch = C.lerp(-6.0, strike, ease((k - 0.5) / 0.5))
+ toe = C.lerp(push * 0.85, 4.0, ease(min(1.0, k / 0.4)))
+ # Side steps cross over: the trailing foot passes in front, the leading one behind.
+ trailing = (sg > 0) != (u.x > 0)
+ cross = (-0.11 if trailing else 0.09) * s * lateral * math.sin(math.pi * k)
+ flat = base + u * along + Vector((0.0, cross, 0.0))
+ flat.z = b.ankle.z
+ R = _foot_rot(pitch, yaw)
+ if pitch > 0: # heel up: the ball stays where the flat foot's ball is
+ ankle = flat + _rz(yaw) @ b.foot_vec - R @ b.foot_vec
+ elif pitch < 0: # heel down: the heel stays
+ ankle = flat + _rz(yaw) @ b.heel_vec - R @ b.heel_vec
+ else:
+ ankle = flat.copy()
+ ankle.z += lift
+ return ankle, pitch, yaw, toe
+
+
+def _keep_reach(b: Body, legs: dict, hz: float, hx: float) -> float:
+ """Lower the hips just enough that both ankles stay inside the legs' reach."""
+ for s, (a, *_r) in legs.items():
+ hip = b.hip_l.copy()
+ hip.x = abs(hip.x) * (1 if s == "L" else -1) + hx
+ dx = a.x - hip.x
+ dy = a.y
+ reach = b.leg * 0.99
+ zmax = a.z + math.sqrt(max(0.0, reach**2 - dx * dx - dy * dy)) + (b.hips.z - b.hip_l.z)
+ if hz > zmax - 0.004:
+ hz = zmax - 0.004 - 0.004 * math.tanh((hz - zmax) / 0.004)
+ return hz
+
+
+def gait_clip(b: Body, g: dict, heading: float):
+ n = g["n"]
+ d = g["duty"]
+ s = b.scale
+ fwdness = math.cos(math.radians(heading))
+ side = math.sin(math.radians(heading))
+ run = d < 0.4
+ out = []
+ for f in range(n + 1):
+ ph = (f % n) / n
+ legs = {}
+ for sd, off in (("L", 0.0), ("R", 0.5)):
+ legs[sd] = _gait_foot(b, (ph + off) % 1.0, g, heading, sd)
+ bob_phase = math.cos(2 * TAU * (ph - d * 0.5))
+ bob = (-1.0 if run else 1.0) * g["bob"] * s * bob_phase
+ sway = math.cos(TAU * (ph - d * 0.5))
+ hx = 0.016 * s * sway * (0.5 if run else 1.0)
+ hz = b.hips.z - g["drop"] * s + bob
+ hz = _keep_reach(b, legs, hz, hx)
+ osc = math.cos(TAU * ph)
+ twist = -7.0 * osc * fwdness
+ lean = g["lean"] * (fwdness if fwdness > 0 else 0.35 * fwdness)
+ p = {
+ "hips": Vector((hx, 0.0, hz)),
+ "hips_rot": (lean, BLADE["hips"] * 0.6 + twist, 5.0 * side - 2.0 * sway),
+ "spine": _spine(
+ bend=4.0 + 0.4 * lean, twist=-twist * 0.8 + BLADE["hips"] * 0.4, lean=-3.0 * side
+ ),
+ "shoulder_L": (1.5 * bob_phase if run else 0.0, 4.0),
+ "shoulder_R": (1.5 * bob_phase if run else 0.0, 0.0),
+ }
+ for sd, (a, pitch, yaw, toe) in legs.items():
+ p[f"leg_{sd}"] = _leg(b, sd, a, pitch, yaw, toe)
+ out.append(_with_hold(b, p, pitch=0.0, yaw=0.0))
+ return out
+
+
+def sprint_clip(b: Body):
+ """Forward sprint, the blaster carried low across the chest."""
+ g = SPRINT
+ out = []
+ for p in gait_clip(b, g, 0.0):
+ p["spine"]["Chest"] = (
+ p["spine"]["Chest"][0] + 4.0,
+ p["spine"]["Chest"][1] + 6.0,
+ p["spine"]["Chest"][2],
+ )
+ out.append(_with_hold(b, p, pitch=-35.0, yaw=35.0, tuck=0.6))
+ return out
+
+
+# ---------------------------------------------------------------------- turn in place
+
+
+def turn_clip(b: Body, sign: float):
+ """Two steps turning the body by TURN_DEG (sign +1 = left). The runtime turns the
+ root by sign * TURN_DEG * smootherstep(t / TURN_SECONDS); the feet are posed in the
+ world and counter-rotated into the turning root, so they stay planted."""
+ T = TURN_SECONDS
+ feet = _stance_feet(b)
+ first, second = ("L", "R") if sign > 0 else ("R", "L")
+ windows = {first: (0.03, 0.33), second: (0.26, 0.57)}
+ out = []
+ for f in range(frames(T)):
+ t = f / C.FPS
+ r = sign * TURN_DEG * smootherstep(t / T)
+ p = combat_stand(b, 0.0, 2.0, breathe=0.0)
+ dip = math.sin(math.pi * C.clamp(t / T, 0.0, 1.0))
+ p["hips"] = p["hips"] + Vector((0.0, 0.0, -0.02 * b.scale * dip))
+ hr = p["hips_rot"]
+ p["hips_rot"] = (hr[0], hr[1] + sign * 8.0 * dip, hr[2])
+ for sd in ("L", "R"):
+ x, y, yaw0 = feet[sd]
+ w0, w1 = windows[sd]
+ k = ease(C.clamp((t - w0) / (w1 - w0), 0.0, 1.0))
+ start = Vector((x, y, 0.0))
+ end = _rz(sign * TURN_DEG) @ start
+ world = start.lerp(end, k)
+ yaw_world = yaw0 + sign * TURN_DEG * k
+ lift = 0.06 * b.scale * math.sin(math.pi * k)
+ local = _rz(-r) @ world
+ p[f"leg_{sd}"] = _planted(
+ b,
+ sd,
+ local.x,
+ local.y,
+ yaw_world - r,
+ pitch=-4.0 * math.sin(math.pi * k),
+ lift=lift,
+ )
+ out.append(_with_hold(b, p))
+ return out
+
+
+# --------------------------------------------------------------------------- the roll
+
+
+def roll_clip(b: Body):
+ """Dodge roll in place (the runtime carries the root along the roll and faces it the
+ roll's way): dive, tucked shoulder roll through 360 degrees, crouched landing, up."""
+ T = 0.6
+ s = b.scale
+ out = []
+ stand = combat_stand(b, 0.0, 2.0, breathe=0.0)
+ feet = _stance_feet(b)
+ for f in range(frames(T)):
+ t = f / C.FPS
+ a = 360.0 * smootherstep((t - 0.05) / 0.33)
+ tuck = smootherstep((t - 0.03) / 0.08) * (1.0 - smootherstep((t - 0.33) / 0.09))
+ crouch = smootherstep(t / 0.07) * (1.0 - smootherstep((t - 0.40) / 0.2))
+ Ra = _rx(a)
+ centre = Vector((0.0, 0.0, 0.43 * s))
+ stand_hips = Vector(stand["hips"]) + Vector((0.0, -0.05 * crouch, -0.30 * s * crouch))
+ tucked_hips = centre + Ra @ Vector((0.0, 0.06 * s, -0.04 * s))
+ hips = stand_hips.lerp(tucked_hips, tuck)
+ # Past half way the untucked pelvis angle counts from a full turn, so it never spins back.
+ base = stand["hips_rot"][0] + 22.0 * crouch + (360.0 if a > 180.0 else 0.0)
+ p = {
+ "hips": hips,
+ "hips_rot": (C.lerp(base, a, tuck), -4.0 * tuck, 14.0 * tuck),
+ "spine": _spine(
+ bend=10.0 * crouch + 70.0 * tuck,
+ extra={"Neck": (48.0 * tuck, 0, 0), "Head": (50.0 * tuck, 0, 0)},
+ ),
+ "shoulder_L": (6.0 * tuck, 10.0 * tuck),
+ "shoulder_R": (6.0 * tuck, 10.0 * tuck),
+ }
+ for sd in ("L", "R"):
+ sg = 1.0 if sd == "L" else -1.0
+ x, y, yaw = feet[sd]
+ floor = _planted(b, sd, x * (1 + 0.3 * crouch), y * (1 - 0.6 * crouch), yaw)
+ fl = Vector(floor["target"])
+ tl = hips + Ra @ Vector((sg * 0.13 * s, -0.02 * s, -0.30 * s))
+ target = fl.lerp(tl, tuck)
+ pole = Vector((sg * 0.12, -1.0, 0.1)).lerp(Ra @ Vector((sg * 0.1, -1.0, 0.4)), tuck)
+ fdir = (
+ Vector(floor["foot_dir"]).lerp(Ra @ Vector((0.0, -0.3, -0.95)), tuck).normalized()
+ )
+ fup = Vector((0, 0, 1)).lerp(Ra @ Vector((0.0, -1.0, 0.2)), tuck).normalized()
+ p[f"leg_{sd}"] = {
+ "target": tuple(target),
+ "pole": tuple(pole),
+ "foot_dir": tuple(fdir),
+ "foot_up": tuple(fup),
+ "toe": 10.0 * tuck,
+ }
+ out.append(_chest_hold(b, p, tuck=0.6 * tuck + 0.3 * crouch))
+ return out
+
+
+_HOLD_CACHE: dict[int, tuple] = {}
+
+
+def _chest_local_hold(b: Body):
+ """The idle's frame-0 hands in the chest's own frame (so the blaster can follow a
+ rolling or falling chest)."""
+ key = id(b)
+ if key not in _HOLD_CACHE:
+ p = clip_combat_idle(b)[0]
+ M = b.rig.solve(p)
+ inv = M["Chest"].inverted()
+ rot = inv.to_3x3()
+ arms = {}
+ for sd in ("L", "R"):
+ spec = dict(p[f"arm_{sd}"])
+ spec["target"] = tuple((inv @ Vector((*spec["target"], 1.0))).xyz)
+ for k in ("pole", "hand_dir", "dorsal"):
+ spec[k] = tuple(rot @ Vector(spec[k]))
+ arms[sd] = spec
+ _HOLD_CACHE[key] = arms
+ return _HOLD_CACHE[key]
+
+
+def _chest_hold(b: Body, p: dict, tuck: float = 0.0) -> dict:
+ """Arms holding the blaster where the idle holds it, relative to the chest."""
+ M = b.rig.solve(p)
+ ch = M["Chest"]
+ rot = ch.to_3x3()
+ local = _chest_local_hold(b)
+ for sd in ("L", "R"):
+ spec = dict(local[sd])
+ tgt = Vector(spec["target"])
+ # Tucked: the hands come in towards the sternum and down.
+ tgt = tgt.lerp(Vector((tgt.x * 0.6, tgt.y - 0.08, tgt.z * 0.55)), tuck)
+ spec["target"] = tuple((ch @ Vector((*tgt, 1.0))).xyz)
+ for k in ("pole", "hand_dir", "dorsal"):
+ spec[k] = tuple(rot @ Vector(spec[k]))
+ p[f"arm_{sd}"] = spec
+ return p
+
+
+# -------------------------------------------------------------------- additive hits
+
+
+def _additive(b: Body, T: float, deltas):
+ """Clip whose every frame is the idle's frame 0 plus spine/shoulder deltas(t)."""
+ base = clip_combat_idle(b)[0]
+ out = []
+ for f in range(frames(T)):
+ t = f / C.FPS
+ p = dict(base)
+ sp = dict(base["spine"])
+ d = deltas(t)
+ for k, v in d.get("spine", {}).items():
+ a = sp[k]
+ sp[k] = (a[0] + v[0], a[1] + v[1], a[2] + v[2])
+ p["spine"] = sp
+ for k in ("shoulder_L", "shoulder_R"):
+ if k in d:
+ a = base[k]
+ p[k] = (a[0] + d[k][0], a[1] + d[k][1])
+ out.append(p)
+ out[0] = base
+ return out
+
+
+def _flinch_env(t: float) -> float:
+ if t < 0.05:
+ return ease(t / 0.05)
+ x = t - 0.05
+ return math.exp(-x / 0.1) * math.cos(x * 9.0) * (1.0 - ease((t - 0.36) / 0.12))
+
+
+def hit_clip(b: Body, side: str):
+ """Additive flinch from a bolt arriving from `side` (F, B, L, R)."""
+
+ def deltas(t):
+ e = _flinch_env(t)
+ if side == "F":
+ sp = {
+ "Spine": (-6 * e, 0, 0),
+ "Chest": (-9 * e, 0, 0),
+ "Neck": (-4 * e, 0, 0),
+ "Head": (-12 * e, 0, 0),
+ }
+ sh = (5 * e, -4 * e)
+ elif side == "B":
+ sp = {
+ "Spine": (7 * e, 0, 0),
+ "Chest": (9 * e, 0, 0),
+ "Neck": (5 * e, 0, 0),
+ "Head": (10 * e, 0, 0),
+ }
+ sh = (3 * e, 4 * e)
+ else:
+ sg = 1.0 if side == "L" else -1.0
+ sp = {
+ "Spine": (-2 * e, 5 * sg * e, -5 * sg * e),
+ "Chest": (-3 * e, 8 * sg * e, -7 * sg * e),
+ "Head": (-4 * e, 6 * sg * e, -10 * sg * e),
+ }
+ sh = (4 * e, -3 * e)
+ return {"spine": sp, "shoulder_L": sh, "shoulder_R": sh}
+
+ return _additive(b, 0.5, deltas)
+
+
+def stagger_clip(b: Body):
+ """Additive reel after eating one's own reflected bolt: thrown back, wobbling, recovering."""
+
+ def deltas(t):
+ hit = ease(t / 0.1) * (1.0 - ease((t - 0.25) / 0.6))
+ wob = math.sin(t * 15.0) * math.exp(-t / 0.35) * (1.0 - ease((t - 0.7) / 0.3))
+ sp = {
+ "Spine": (-10 * hit, 4 * wob, 3 * wob),
+ "Chest": (-16 * hit, 7 * wob, 5 * wob),
+ "Neck": (-6 * hit, 0, 0),
+ "Head": (-18 * hit + 8 * wob * 0.5, -6 * wob, -8 * wob),
+ }
+ return {
+ "spine": sp,
+ "shoulder_L": (12 * hit, -10 * hit),
+ "shoulder_R": (12 * hit, -6 * hit),
+ }
+
+ return _additive(b, 1.0, deltas)
+
+
+# ---------------------------------------------------------------- knockout and get-up
+
+
+def _lying(b: Body):
+ """On the back on the floor, root at the feet's end: the body lies towards +Y."""
+ s = b.scale
+ p = {
+ "hips": Vector((0.02 * s, 0.62 * s, 0.11 * s)),
+ "hips_rot": (-90.0, -10.0, 4.0),
+ "spine": {
+ "Spine": (-2.0, 3.0, 0.0),
+ "Chest": (2.0, 4.0, 0.0),
+ "Neck": (8.0, 10.0, 0.0),
+ "Head": (6.0, 26.0, 0.0),
+ },
+ "shoulder_L": (0.0, 0.0),
+ "shoulder_R": (0.0, 0.0),
+ "leg_L": {
+ "target": (0.17 * s, 0.62 * s - b.leg * 0.97, b.ankle.z * 0.6 + 0.02),
+ "pole": (0.35, 0.0, 1.0),
+ "foot_dir": tuple(Vector((0.35, -0.6, 0.75)).normalized()),
+ "foot_up": (0.0, 1.0, 0.0),
+ "toe": 0.0,
+ },
+ "leg_R": {
+ "target": (-0.10 * s, 0.62 * s - 0.48 * s, b.ankle.z),
+ "pole": (-0.25, -0.35, 1.0),
+ "foot_dir": tuple(Vector((-0.1, -0.85, -0.45)).normalized()),
+ "foot_up": (0.0, 0.0, 1.0),
+ "toe": 0.0,
+ },
+ "arm_R": {
+ "target": (-0.46 * s, 0.78 * s, 0.07 * s),
+ "pole": (-0.3, 0.2, -1.0),
+ "hand_dir": (-0.5, -0.8, -0.1),
+ "dorsal": (0.0, 0.0, 1.0),
+ "fingers": 30.0,
+ "thumb": 15.0,
+ },
+ "arm_L": {
+ "target": (0.40 * s, 0.86 * s, 0.06 * s),
+ "pole": (0.3, 0.2, -1.0),
+ "hand_dir": (0.6, 0.7, -0.1),
+ "dorsal": (0.0, 0.0, 1.0),
+ "fingers": 20.0,
+ "thumb": 10.0,
+ },
+ }
+ return p
+
+
+def _abs_hold(b: Body, p: dict, tuck: float = 0.0) -> dict:
+ return _chest_hold(b, p, tuck=tuck)
+
+
+def _keyed(keys, t: float):
+ """Pose at time t between timed key poses (eased per segment)."""
+ if t <= keys[0][0]:
+ return keys[0][1]
+ for (t0, p0), (t1, p1) in zip(keys, keys[1:], strict=False):
+ if t <= t1:
+ return _lerp_spec(p0, p1, ease((t - t0) / (t1 - t0)))
+ return keys[-1][1]
+
+
+def _norm(p: dict) -> dict:
+ """Arm and leg vectors as tuples, hips as a Vector (so key poses blend)."""
+ q = dict(p)
+ q["hips"] = Vector(p["hips"])
+ for k in ("arm_L", "arm_R", "leg_L", "leg_R"):
+ q[k] = {
+ kk: (tuple(v) if isinstance(v, (Vector, tuple, list)) else v) for kk, v in p[k].items()
+ }
+ q["spine"] = {k: tuple(v) for k, v in p["spine"].items()}
+ return q
+
+
+def death_clip(b: Body):
+ """Knocked out: jolted back, knees buckle, falls on the back, a small bounce, still."""
+ s = b.scale
+ k0 = _norm(clip_combat_idle(b)[0])
+ jolt = combat_stand(b, 0.0, 2.0, breathe=0.0)
+ jolt["hips"] = Vector(jolt["hips"]) + Vector((0.0, 0.05 * s, -0.02 * s))
+ jolt["hips_rot"] = (-6.0, BLADE["hips"] - 6.0, 3.0)
+ jolt["spine"] = _spine(bend=-14.0, extra={"Head": (-18.0, 0, 0)})
+ jolt = _norm(_abs_hold(b, jolt))
+ jolt["arm_L"] = dict(
+ jolt["arm_L"],
+ target=tuple(Vector(jolt["arm_L"]["target"]) + Vector((0.16, 0.10, 0.12)) * s),
+ )
+ buckle = combat_stand(b, 0.0, 2.0, breathe=0.0)
+ buckle["hips"] = Vector((0.0, 0.16 * s, 0.60 * s))
+ buckle["hips_rot"] = (-18.0, BLADE["hips"] - 14.0, 6.0)
+ buckle["spine"] = _spine(bend=-8.0, extra={"Head": (16.0, 8.0, 0.0)})
+ buckle = _norm(_abs_hold(b, buckle, tuck=0.4))
+ buckle["arm_L"] = dict(
+ buckle["arm_L"],
+ target=tuple(Vector(buckle["arm_L"]["target"]) + Vector((0.25, 0.05, -0.10)) * s),
+ )
+ rest = _norm(_lying(b))
+ land = _norm(_lying(b))
+ land["hips"] = Vector((0.0, 0.44 * s, 0.22 * s))
+ land["hips_rot"] = (-66.0, -14.0, 5.0)
+ land["spine"] = {
+ "Spine": (12.0, 0, 0),
+ "Chest": (8.0, 2.0, 0.0),
+ "Neck": (12.0, 4.0, 0.0),
+ "Head": (18.0, 10.0, 0.0),
+ }
+ land["leg_L"] = dict(rest["leg_L"], target=(0.16 * s, 0.05 * s, b.ankle.z + 0.06 * s))
+ land["leg_R"] = dict(rest["leg_R"], target=(-0.12 * s, 0.10 * s, b.ankle.z + 0.03 * s))
+ impact = _norm(_lying(b))
+ impact["hips"] = Vector((0.01 * s, 0.58 * s, 0.10 * s))
+ impact["spine"] = dict(impact["spine"], Head=(-6.0, 14.0, 0.0), Neck=(-4.0, 6.0, 0.0))
+ bounce = _norm(_lying(b))
+ bounce["hips"] = Vector((0.02 * s, 0.61 * s, 0.13 * s))
+ bounce["spine"] = dict(bounce["spine"], Chest=(6.0, 4.0, 0.0), Head=(12.0, 22.0, 0.0))
+ keys = [
+ (0.0, k0),
+ (0.1, jolt),
+ (0.42, buckle),
+ (0.68, land),
+ (0.82, impact),
+ (0.96, bounce),
+ (1.3, rest),
+ ]
+ return [_keyed(keys, f / C.FPS) for f in range(frames(1.4))]
+
+
+def getup_clip(b: Body):
+ """From the knockout pose back to the ready stance (round reset): sit up, a knee, up."""
+ s = b.scale
+ rest = _norm(_lying(b))
+ sit = _norm(_lying(b))
+ sit["hips"] = Vector((0.0, 0.56 * s, 0.12 * s))
+ sit["hips_rot"] = (-28.0, -6.0, 0.0)
+ sit["spine"] = {
+ "Spine": (18.0, 0, 0),
+ "Chest": (10.0, 0.0, 0.0),
+ "Neck": (0.0, 0.0, 0.0),
+ "Head": (4.0, 0.0, 0.0),
+ }
+ sit["leg_L"] = dict(
+ rest["leg_L"],
+ target=(0.16 * s, 0.12 * s, b.ankle.z),
+ foot_dir=tuple(Vector((0.1, -0.85, -0.45)).normalized()),
+ foot_up=(0, 0, 1),
+ pole=(0.3, -0.3, 1.0),
+ )
+ sit["leg_R"] = dict(
+ rest["leg_R"],
+ target=(-0.13 * s, 0.22 * s, b.ankle.z),
+ foot_dir=tuple(Vector((-0.1, -0.85, -0.45)).normalized()),
+ foot_up=(0, 0, 1),
+ pole=(-0.3, -0.3, 1.0),
+ )
+ sit["arm_R"] = dict(rest["arm_R"], target=(-0.26 * s, 0.82 * s, 0.10 * s))
+ sit["arm_L"] = dict(rest["arm_L"], target=(0.26 * s, 0.82 * s, 0.10 * s))
+ kneel = combat_stand(b, 0.0, 2.0, breathe=0.0)
+ kneel["hips"] = Vector((0.0, 0.30 * s, 0.52 * s))
+ kneel["hips_rot"] = (14.0, -10.0, 0.0)
+ kneel["spine"] = _spine(bend=12.0)
+ kneel["leg_L"] = _planted(b, "L", 0.14 * s, -0.02 * s, -8.0)
+ kneel["leg_R"] = {
+ "target": (-0.13 * s, 0.66 * s, 0.13 * s),
+ "pole": (-0.05, -1.0, -0.6),
+ "foot_dir": tuple(Vector((0.0, 0.35, -0.94)).normalized()),
+ "foot_up": (0.0, 1.0, 0.0),
+ "toe": 30.0,
+ }
+ kneel = _norm(_abs_hold(b, kneel, tuck=0.3))
+ rise = combat_stand(b, 0.0, 2.0, crouch=0.6, breathe=0.0)
+ rise["hips"] = Vector((0.0, 0.12 * s, 0.74 * s))
+ rise = _norm(_abs_hold(b, rise, tuck=0.15))
+ end = _norm(clip_combat_idle(b)[0])
+ sit = _norm(sit)
+ keys = [(0.0, rest), (0.32, sit), (0.72, kneel), (1.08, rise), (1.45, end)]
+ return [_keyed(keys, f / C.FPS) for f in range(frames(1.5))]
+
+
+# ------------------------------------------------------------------------- registry
+
+
+def combat_clips():
+ """{name: (fn, loop)} of every duel clip; fills LOCOMOTION."""
+ clips = {
+ "A_Combat_Idle": (clip_combat_idle, True),
+ "A_Combat_Cover": (clip_combat_cover, True),
+ }
+ LOCOMOTION.clear()
+ for gname, g in GAITS.items():
+ for dname, heading in HEADINGS.items():
+ name = f"A_Combat_{gname}_{dname}"
+ clips[name] = ((lambda b, g=g, h=heading: gait_clip(b, g, h)), True)
+ speed = round(g["speed"] * (BACK_SPEED if dname == "B" else 1.0), 4)
+ LOCOMOTION[name] = {"speed": speed, "heading": heading}
+ clips["A_Combat_Sprint"] = (sprint_clip, True)
+ LOCOMOTION["A_Combat_Sprint"] = {"speed": SPRINT["speed"], "heading": 0.0}
+ clips["A_Combat_Turn_L"] = ((lambda b: turn_clip(b, 1.0)), False)
+ clips["A_Combat_Turn_R"] = ((lambda b: turn_clip(b, -1.0)), False)
+ clips["A_Combat_Roll"] = (roll_clip, False)
+ for sd in ("F", "B", "L", "R"):
+ clips[f"A_Combat_Hit_{sd}"] = ((lambda b, sd=sd: hit_clip(b, sd)), False)
+ clips["A_Combat_Stagger"] = (stagger_clip, False)
+ clips["A_Combat_Death"] = (death_clip, False)
+ clips["A_Combat_GetUp"] = (getup_clip, False)
+ return clips
diff --git a/art/verse/characters/build.py b/art/verse/characters/build.py
index f253c7d247..45f84f607e 100644
--- a/art/verse/characters/build.py
+++ b/art/verse/characters/build.py
@@ -21,6 +21,7 @@ import bpy
from mathutils import Vector
from characters import anim as A
+from characters import anim_combat as AC
from characters import common as C
from characters import crew
from characters import looks as LK
@@ -193,6 +194,11 @@ def main(argv):
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="")
ap.add_argument("--no-clips", action="store_true")
+ ap.add_argument(
+ "--clips-only",
+ action="store_true",
+ help="rebuild A_Human_<variant>.glb and the manifest's clips, leave the bodies",
+ )
ap.add_argument("--qa", action="store_true")
ap.add_argument("--qa-contact", action="store_true", help="QA contact sheets only")
args = ap.parse_args(argv)
@@ -200,6 +206,11 @@ def main(argv):
O.make_materials()
out = C.ensure_dir(C.OUT_DIR)
only = [s for s in args.only.split(",") if s] or list(CHARACTERS)
+ if args.clips_only:
+ ctxs = {v: O.Ctx(v) for v in sorted(C.VARIANTS)}
+ clip_info = export_clips(out, ctxs)
+ write_manifest(out, [], clip_info, ctxs)
+ return {}
ctxs: dict[str, O.Ctx] = {}
built = {}
entries = []
@@ -253,26 +264,7 @@ def main(argv):
for o in objs:
o.name = f"{cid}:{o.name}"
o.data.name = o.name
- clip_info = {}
- if not args.no_clips:
- for variant, ctx in sorted(ctxs.items()):
- body = A.Body(ctx.rig)
- acts = []
- for name, (fn, loop) in A.CLIPS.items():
- poses = fn(body)
- acts.append(P.write_action(ctx.rig, name, poses))
- clip_info[name] = {"loop": loop, "seconds": round((len(poses) - 1) / C.FPS, 4)}
- P.stash_actions(ctx.arm, acts)
- size = export_glb(out / f"A_Human_{variant}.glb", [ctx.arm], animations=True)
- print(f"[characters] A_Human_{variant}: {size} bytes")
- ctx.walk_speed = A.walk_stride(body) / (A.WALK_FRAMES / C.FPS)
- ctx.arm.animation_data.action = None
- for tr in list(ctx.arm.animation_data.nla_tracks):
- ctx.arm.animation_data.nla_tracks.remove(tr)
- # The exporter's ACTIONS mode takes every compatible action in the file:
- # drop this variant's clips before the next variant is exported.
- for act, _slot in acts:
- bpy.data.actions.remove(act)
+ clip_info = {} if args.no_clips else export_clips(out, ctxs)
write_manifest(out, entries, clip_info, ctxs)
if args.qa or args.qa_contact:
from characters import qa
@@ -281,6 +273,40 @@ def main(argv):
return built
+def all_clips():
+ """Every clip of the shared human skeleton: the crew's and the duel's."""
+ return {**A.CLIPS, **AC.combat_clips()}
+
+
+def export_clips(out: Path, ctxs) -> dict:
+ """Bake every clip per variant into A_Human_<variant>.glb; returns the manifest's clips."""
+ clip_info = {}
+ clips = all_clips()
+ for variant, ctx in sorted(ctxs.items()):
+ body = A.Body(ctx.rig)
+ acts = []
+ for name, (fn, loop) in clips.items():
+ poses = fn(body)
+ acts.append(P.write_action(ctx.rig, name, poses))
+ clip_info[name] = {"loop": loop, "seconds": round((len(poses) - 1) / C.FPS, 4)}
+ if name in AC.LOCOMOTION:
+ # Ground speed (male skeleton, m/s) and heading (degrees, 90 = the body's left).
+ clip_info[name].update(AC.LOCOMOTION[name])
+ P.stash_actions(ctx.arm, acts)
+ size = export_glb(out / f"A_Human_{variant}.glb", [ctx.arm], animations=True)
+ print(f"[characters] A_Human_{variant}: {size} bytes")
+ ctx.clips_bytes = size
+ ctx.walk_speed = A.walk_stride(body) / (A.WALK_FRAMES / C.FPS)
+ ctx.arm.animation_data.action = None
+ for tr in list(ctx.arm.animation_data.nla_tracks):
+ ctx.arm.animation_data.nla_tracks.remove(tr)
+ # The exporter's ACTIONS mode takes every compatible action in the file:
+ # drop this variant's clips before the next variant is exported.
+ for act, _slot in acts:
+ bpy.data.actions.remove(act)
+ return clip_info
+
+
def write_manifest(out: Path, entries, clip_info, ctxs):
path = out / "characters.json"
old = {}
@@ -305,6 +331,9 @@ def write_manifest(out: Path, entries, clip_info, ctxs):
"walkSpeed": round(getattr(ctx, "walk_speed", 0.0), 4)
or skeletons.get(v, {}).get("walkSpeed"),
"bones": ctx.bones,
+ # Versions the clips file's URL (the runtime appends it), so new clips are never stale.
+ "clipsBytes": getattr(ctx, "clips_bytes", None)
+ or skeletons.get(v, {}).get("clipsBytes"),
}
manifest = {
"version": 1,
diff --git a/art/verse/characters/check_glb.mjs b/art/verse/characters/check_glb.mjs
index 1a17f8885d..8c6f2c964a 100644
--- a/art/verse/characters/check_glb.mjs
+++ b/art/verse/characters/check_glb.mjs
@@ -187,6 +187,45 @@ for (const m of manifest.models) {
root.updateMatrixWorld(true);
const hips = root.getObjectByName("Hips").getWorldPosition(new THREE.Vector3());
console.log(` A_Sit_Type: hips at y ${hips.y.toFixed(3)} (seat ${manifest.seatHeight})`);
+ // Duel locomotion: each clip's planted feet hold still while the root moves at its
+ // manifest speed along its heading (male skeleton; the female stride is shorter).
+ if (m.skeleton === "M") {
+ for (const [name, info] of Object.entries(manifest.clips ?? {})) {
+ if (typeof info.speed !== "number") continue;
+ const clip = clips.find((c) => c.name === name);
+ if (!clip) { fail(`${name} missing from A_Human_M`); continue; }
+ mixer.stopAllAction();
+ mixer.clipAction(clip).play();
+ const h = (info.heading * Math.PI) / 180;
+ let worst = 0;
+ for (const side of ["L", "R"]) {
+ const foot = root.getObjectByName(`Foot_${side}`);
+ const toe = root.getObjectByName(`Toe_${side}`);
+ const pts = [];
+ const steps = 48;
+ for (let i = 0; i <= steps; i += 1) {
+ const t = (clip.duration * i) / steps;
+ mixer.setTime(t);
+ root.position.set(Math.sin(h) * info.speed * t, 0, Math.cos(h) * info.speed * t);
+ root.updateMatrixWorld(true);
+ const p = foot.getWorldPosition(new THREE.Vector3());
+ const q = toe.getWorldPosition(new THREE.Vector3());
+ if (p.y < 0.085 && q.y < 0.04) pts.push({ i, p });
+ }
+ // Longest run of consecutive planted samples belongs to one contact.
+ for (let k = 1; k < pts.length; k += 1) {
+ if (pts[k].i !== pts[k - 1].i + 1) continue;
+ const a = pts[k].p;
+ const b = pts[k - 1].p;
+ const d = Math.hypot(a.x - b.x, a.z - b.z);
+ if (d < 0.25) worst = Math.max(worst, d * (steps / clip.duration) / 30);
+ }
+ }
+ console.log(` ${name} @ ${info.speed} m/s: planted-foot drift ${(worst * 100).toFixed(1)} cm/frame`);
+ if (!(worst < 0.04)) fail(`${m.id} feet slide in ${name} (${worst.toFixed(3)} m per frame)`);
+ }
+ root.position.set(0, 0, 0);
+ }
}
}
console.log(failures ? `${failures} failure(s)` : "all checks passed");
diff --git a/docs/verse/combat.md b/docs/verse/combat.md
index b35f9e57d7..1d0adea556 100644
--- a/docs/verse/combat.md
+++ b/docs/verse/combat.md
@@ -791,13 +791,32 @@ is set.
- **Figures** (`figure.ts`): the commander's own officer body and look for the
person, the trooper body in gunmetal armour with red accents and a red visor
- for the bot. The legs walk the way the body moves (the walk plays backwards
- when it backs off, the hips turn at most 80 deg off the aim), spine and chest
- twist and bend toward the aim, the head follows it, and both arms reach the
- blaster by two-bone IK (`solveElbow`): right hand on the grip, left on the
- shroud, or palm forward behind a raised shield. Sprinting carries the
- blaster low, venting tips it up. A dodge is a tucked roll along the move
- direction; a knocked-out body falls backwards.
+ for the bot. The duel clip set `A_Combat_*` (authored in the character
+ pipeline, `art/verse/characters/anim_combat.py`, original work, no
+ third-party motion) drives the body through `FighterAnimator`
+ (`fighterAnim.ts`, pure, tested): a bladed rifle stance; eight-way
+ locomotion from a combat walk and a run in four headings each plus the
+ sprint, the legs facing the aim, the headings and gaits blended so the
+ blended stride points where the body moves, and one shared phase advanced
+ at ground speed over that stride (planted feet hold still at any speed and
+ angle; `check_glb.mjs` measures it per clip); step-turns of 90 deg when the
+ aim swings more than 70 deg round a standing body; the dodge roll (the body
+ faces the roll's way, a tucked shoulder roll, the recovery runs 0.2 s past
+ the sim's roll as the blaster comes back); additive directional flinches
+ (headshots harder) and a stagger when a bolt the fighter fired is parried
+ back into them; the knockout fall (the body turns to the shooter and falls
+ back, away) and a get-up at the next round. On top: lean into acceleration,
+ the aim offset over spine and chest, the head on the aim (the bot's on the
+ person), the blaster's stock in the right shoulder pocket read from the
+ chest bone, raised to the eye in the sights, low across the chest
+ sprinting, by the hip behind the shield, tipped and racked by the left hand
+ while venting, low behind cover, and a recoil kick per shot; both hands on
+ it by two-bone IK (`solveElbow`) calibrated against `A_Combat_Idle` frame 0.
+ The shield raises the left forearm in front of the chest and shoves on a
+ perfect parry. The bot's body shows its tactics (`BotBrain.presentation()`,
+ read by nothing in the match): low behind cover while it hides, leaning out
+ toward the peek side while it peeks. QA: `window.__verseDuelBodies()` gives
+ each body's animation frame, blaster direction and grip.
- **Blaster** (`blaster.ts`): procedural, graphite and brushed gold, energy
cells along the receiver (amber for the person, red for the bot), heat vents
on the shroud glowing blue to amber to red with the heat and pulsing while
@@ -863,8 +882,9 @@ CPU 1.5..3.8 ms per frame.
### Open
-- The bodies have no aiming, firing, hit-reaction or roll clips; the upper
- body and the roll are procedural. Proper clips would look better.
+- The duel clips are keyframed by pose functions, not captured motion; a
+ crouch in cover is presentation only (the hit capsule stays standing, the
+ bot only hides behind cover taller than it).
- Pointer lock in the desktop app's WebView is untested here (headless runs
aim through the QA hook).
- No settings for the duel's volume or a separate mouse sensitivity (it uses
diff --git a/dodaios/ui/web/frontend/public/verse/characters/A_Human_F.glb b/dodaios/ui/web/frontend/public/verse/characters/A_Human_F.glb
index 8e9a676d6f..827ea11a1a 100644
Binary files a/dodaios/ui/web/frontend/public/verse/characters/A_Human_F.glb and b/dodaios/ui/web/frontend/public/verse/characters/A_Human_F.glb differ
diff --git a/dodaios/ui/web/frontend/public/verse/characters/A_Human_M.glb b/dodaios/ui/web/frontend/public/verse/characters/A_Human_M.glb
index 11aeb12709..6f92a56d8e 100644
Binary files a/dodaios/ui/web/frontend/public/verse/characters/A_Human_M.glb and b/dodaios/ui/web/frontend/public/verse/characters/A_Human_M.glb differ
diff --git a/dodaios/ui/web/frontend/public/verse/characters/characters.json b/dodaios/ui/web/frontend/public/verse/characters/characters.json
index 5f05ef8431..bb9e8964d2 100644
--- a/dodaios/ui/web/frontend/public/verse/characters/characters.json
+++ b/dodaios/ui/web/frontend/public/verse/characters/characters.json
@@ -65,6 +65,108 @@
"A_Sleep": {
"loop": true,
"seconds": 6.0
+ },
+ "A_Combat_Idle": {
+ "loop": true,
+ "seconds": 2.0
+ },
+ "A_Combat_Cover": {
+ "loop": true,
+ "seconds": 2.0
+ },
+ "A_Combat_Walk_F": {
+ "loop": true,
+ "seconds": 0.6667,
+ "speed": 2.4,
+ "heading": 0.0
+ },
+ "A_Combat_Walk_L": {
+ "loop": true,
+ "seconds": 0.6667,
+ "speed": 2.4,
+ "heading": 90.0
+ },
+ "A_Combat_Walk_B": {
+ "loop": true,
+ "seconds": 0.6667,
+ "speed": 1.872,
+ "heading": 180.0
+ },
+ "A_Combat_Walk_R": {
+ "loop": true,
+ "seconds": 0.6667,
+ "speed": 2.4,
+ "heading": -90.0
+ },
+ "A_Combat_Run_F": {
+ "loop": true,
+ "seconds": 0.6,
+ "speed": 4.8,
+ "heading": 0.0
+ },
+ "A_Combat_Run_L": {
+ "loop": true,
+ "seconds": 0.6,
+ "speed": 4.8,
+ "heading": 90.0
+ },
+ "A_Combat_Run_B": {
+ "loop": true,
+ "seconds": 0.6,
+ "speed": 3.744,
+ "heading": 180.0
+ },
+ "A_Combat_Run_R": {
+ "loop": true,
+ "seconds": 0.6,
+ "speed": 4.8,
+ "heading": -90.0
+ },
+ "A_Combat_Sprint": {
+ "loop": true,
+ "seconds": 0.5333,
+ "speed": 7.0,
+ "heading": 0.0
+ },
+ "A_Combat_Turn_L": {
+ "loop": false,
+ "seconds": 0.6
+ },
+ "A_Combat_Turn_R": {
+ "loop": false,
+ "seconds": 0.6
+ },
+ "A_Combat_Roll": {
+ "loop": false,
+ "seconds": 0.6
+ },
+ "A_Combat_Hit_F": {
+ "loop": false,
+ "seconds": 0.5
+ },
+ "A_Combat_Hit_B": {
+ "loop": false,
+ "seconds": 0.5
+ },
+ "A_Combat_Hit_L": {
+ "loop": false,
+ "seconds": 0.5
+ },
+ "A_Combat_Hit_R": {
+ "loop": false,
+ "seconds": 0.5
+ },
+ "A_Combat_Stagger": {
+ "loop": false,
+ "seconds": 1.0
+ },
+ "A_Combat_Death": {
+ "loop": false,
+ "seconds": 1.4
+ },
+ "A_Combat_GetUp": {
+ "loop": false,
+ "seconds": 1.5
}
},
"skeletons": {
@@ -98,7 +200,8 @@
"LowerLeg_R",
"Foot_R",
"Toe_R"
- ]
+ ],
+ "clipsBytes": 999236
},
"F": {
"height": 1.68,
@@ -130,7 +233,8 @@
"LowerLeg_R",
"Foot_R",
"Toe_R"
- ]
+ ],
+ "clipsBytes": 1000668
}
},
"tiers": {
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/actors/characters.ts b/dodaios/ui/web/frontend/src/components/society/verse/actors/characters.ts
index f3723415f7..3debd4e91b 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/actors/characters.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/actors/characters.ts
@@ -43,6 +43,16 @@ export interface SkeletonEntry {
height: number;
clips: string;
walkSpeed: number | null;
+ /** Size of the clips file; versions its URL like a model's `bytes`. */
+ clipsBytes?: number;
+}
+
+/** The manifest's clip table: loop and length, and for locomotion clips their ground speed (m/s) and heading (degrees). */
+export interface ClipInfo {
+ loop?: boolean;
+ seconds?: number;
+ speed?: number;
+ heading?: number;
}
export interface TierColours {
@@ -63,6 +73,7 @@ export interface CharacterContract {
skeletons: Record<string, SkeletonEntry>;
tiers: Record<Tier, TierColours>;
models: ModelEntry[];
+ clips?: Record<string, ClipInfo>;
}
/** Walking pace when the contract does not say (m/s); a calm shipboard walk. */
@@ -137,7 +148,8 @@ export class CharacterLibrary {
private gltf(url: string): Promise<GLTF> {
let pending = this.gltfs.get(url);
if (!pending) {
- const size = this.contract.models.find((m) => m.url === url)?.bytes;
+ const size = this.contract.models.find((m) => m.url === url)?.bytes
+ ?? Object.values(this.contract.skeletons).find((s) => s.clips === url)?.clipsBytes;
pending = this.loader.loadAsync(versionedUrl(assetUrl(url), size));
this.gltfs.set(url, pending);
pending.catch(() => this.gltfs.delete(url));
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts
index 3b25e7e83f..9a5a2c9857 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/bot/brain.ts
@@ -63,6 +63,14 @@ const ms = (v: number) => Math.round((v * TICK_RATE) / 1000);
/** Radial pull toward a distant target when there is no reason to close in (the strafe is 1). */
const APPROACH_DRIFT = 0.2;
+/** What the bot's body shows (see `BotBrain.presentation`). */
+export interface BotPresentation {
+ action: BotAction;
+ cover: "hide" | "peek" | null;
+ spot: { x: number; z: number } | null;
+ peek: { x: number; z: number } | null;
+}
+
export class BotBrain {
readonly slot: number;
private readonly rng: Rng;
@@ -126,6 +134,22 @@ export class BotBrain {
this.aim = new AimController(params, this.rng.fork(1));
}
+ /**
+ * Presentation only (the bot's body in the 3D view; nothing in the match
+ * reads it): the current tactic and, in cover, whether it hides or peeks and
+ * where its cover spot and peek point are.
+ */
+ presentation(): BotPresentation {
+ const c = this.cover;
+ const inCover = c !== null && c.state !== "go" && (this.action === "cover" || this.action === "retreat" || this.action === "camp");
+ return {
+ action: this.action,
+ cover: inCover ? c.state as "hide" | "peek" : null,
+ spot: inCover ? { x: c.spot.x, z: c.spot.z } : null,
+ peek: inCover && c.peek ? { x: c.peek.x, z: c.peek.z } : null,
+ };
+ }
+
// ------------------------------------------------------------ perception
private sampleReaction(scale = 1): number {
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts b/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts
index 9aadb76c6d..ad0d976d16 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/combat/session.ts
@@ -16,7 +16,7 @@
*/
import { buildArena, type Arena, type ArenaDef } from "./arena";
import { REACTOR_ARENA } from "./arenaReactor";
-import { BotBrain } from "./bot/brain";
+import { BotBrain, type BotPresentation } from "./bot/brain";
import { botParams, type BotParams, type BotTier } from "./bot/tiers";
import { MatchClient } from "./client";
import { idleControl, type ControlState } from "./input";
@@ -67,6 +67,8 @@ export interface LocalDuel {
forfeit(): void;
readonly result: DuelResult | null;
readonly finished: boolean;
+ /** Presentation only: what the bot's body should show (cover, peeking); null before the bot has thought. */
+ botPresentation?(): BotPresentation | null;
dispose(): void;
}
@@ -139,6 +141,7 @@ export function createLocalDuel(o: LocalDuelOptions = {}): LocalDuel {
get result() { return resultOf(); },
// Over once the person's client has the end (so the last events reached the view).
get finished() { return person.status === "ended" || person.status === "closed" || person.status === "rejected"; },
+ botPresentation: () => brain.current?.presentation() ?? null,
dispose() {
disposed = true;
if (!server.finished) server.cancel();
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 2978aded5f..6e9217db3a 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
@@ -26,7 +26,7 @@ import type { CombatEvent } from "../combat/types";
import { BOLT_COLOURS } from "./blaster";
import type { DuelController } from "./duelController";
import { BoltPool, Flashes, radialTexture, Scorches, Sparks, Steam } from "./effects";
-import { DuelFigure, type FigureLook } from "./figure";
+import { botCues, DuelFigure, routeFigureEvent, type FigureCues, type FigureLook } from "./figure";
import { ShieldMesh } from "./shield";
import { HIDE_BODY_FIRST_SHARE } from "../viewmodel/motion";
@@ -95,12 +95,12 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
if (!alive) { for (const i of [a, b]) if (i) disposeInstance(i); return; }
if (a) {
applyLook(a, library.contract, commanderLook);
- const f = new DuelFigure(a, { accent: OWN_ACCENT }, shadow);
+ const f = new DuelFigure(a, { accent: OWN_ACCENT }, shadow, library.contract.clips);
figures.current.own = f;
fx.group.add(f.group);
}
if (b) {
- const f = new DuelFigure(b, OPPONENT_LOOK, shadow);
+ const f = new DuelFigure(b, OPPONENT_LOOK, shadow, library.contract.clips);
figures.current.foe = f;
fx.group.add(f.group);
}
@@ -125,7 +125,7 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
}), [controller, runtime, fx]);
useEffect(() => () => { runtime.cameraOverride = null; }, [runtime]);
- const scratch = useMemo(() => ({ v: new Vector3(), time: 0, steamAcc: [0, 0] }), []);
+ const scratch = useMemo(() => ({ v: new Vector3(), time: 0, steamAcc: [0, 0], parried: new Set<number>(), cues: {} as FigureCues }), []);
const override = useMemo(() => ({ position: { x: 0, y: 0, z: 0 }, target: { x: 0, y: 0, z: 0 }, fovDeg: CAMERA_RIGS.hip.fovDeg }), []);
useFrame((_, dt) => {
@@ -155,7 +155,12 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
const bySlot = (slot: number) => (slot === mySlot ? figures.current.own : figures.current.foe);
for (const p of view.players) {
const f = bySlot(p.slot);
- f?.update(step, p, floorY, deck, scratch.time);
+ if (f) {
+ f.slot = p.slot;
+ // The bot's body shows its cover and looks at the person; the person's own body follows their aim.
+ const cues = p.slot === mySlot ? undefined : botCues(controller.botPresentation(), p, view.players.find((q) => q.slot === mySlot), floorY, scratch.cues);
+ f.update(step, p, floorY, deck, scratch.time, cues);
+ }
fx.shields[p.slot === mySlot ? 0 : 1].update(step, p, floorY);
// A venting blaster steams.
const k = p.slot === mySlot ? 0 : 1;
@@ -168,7 +173,10 @@ export function DuelLayer({ runtime, controller, deck, library, commanderId, com
fx.bolts.update(view.bolts, mySlot, floorY);
const events = controller.visualEvents;
- for (const e of events) play(e);
+ for (const e of events) {
+ routeFigureEvent(e, view.players, bySlot, scratch.parried);
+ play(e);
+ }
events.length = 0;
fx.sparks.update(step, floorY);
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 8a729e09bf..b198ef651e 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
@@ -21,6 +21,7 @@
*/
import { resolveAim } from "../combat/camera";
import { idleControl, type ControlState } from "../combat/input";
+import type { BotPresentation } from "../combat/bot/brain";
import type { BotTier } from "../combat/bot/tiers";
import { createLocalDuel, type DuelResult, type LocalDuel, type LocalDuelOptions } from "../combat/session";
import type { CombatEvent } from "../combat/types";
@@ -195,6 +196,11 @@ export class DuelController {
this.forcedPress[name] = true;
}
+ /** Presentation only: what the bot's body should show (cover, peeking), or null. */
+ botPresentation(): BotPresentation | null {
+ return this.duel?.botPresentation?.() ?? null;
+ }
+
/** The camera pose of the last frame (world coordinates), for the renderer. */
get pose(): DuelCameraPose {
return this.camera.pose;
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/fighterAnim.test.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/fighterAnim.test.ts
new file mode 100644
index 0000000000..56c75c7bd0
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/fighterAnim.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_LOCO, DUEL_CLIPS, FighterAnimator, flinchSide, headingWeights, locoClips, locomotionBlend, TIMING,
+ type FighterFrame, type FighterInput,
+} from "./fighterAnim";
+
+const DEG = Math.PI / 180;
+const run = DEFAULT_LOCO.filter((c) => c.gait === "run");
+
+function strideDir(weights: Map<string, number>): number {
+ let f = 0;
+ let l = 0;
+ for (const c of DEFAULT_LOCO) {
+ const w = weights.get(c.name) ?? 0;
+ f += Math.cos(c.heading) * c.speed * c.seconds * w;
+ l += Math.sin(c.heading) * c.speed * c.seconds * w;
+ }
+ return Math.atan2(l, f);
+}
+
+function sum(m: Map<string, number>): number {
+ let s = 0;
+ for (const w of m.values()) s += w;
+ return s;
+}
+
+function input(over: Partial<FighterInput> = {}): FighterInput {
+ return {
+ x: 0, z: 0, vx: 0, vz: 0, aimYaw: 0, aimPitch: 0, alive: true, dodging: false, dodgeProgress: 0,
+ sprinting: false, shieldUp: false, ads: 0, venting: false, ...over,
+ };
+}
+
+function baseSum(f: FighterFrame): number {
+ return f.base.reduce((s, c) => s + c.weight, 0);
+}
+
+function weightOf(f: FighterFrame, name: string): number {
+ return f.base.filter((c) => c.name === name).reduce((s, c) => s + c.weight, 0);
+}
+
+describe("heading weights", () => {
+ it("plays the one clip whose heading the motion matches", () => {
+ expect(headingWeights(0, run).get("A_Combat_Run_F")).toBeCloseTo(1);
+ expect(headingWeights(90 * DEG, run).get("A_Combat_Run_L")).toBeCloseTo(1);
+ expect(headingWeights(-90 * DEG, run).get("A_Combat_Run_R")).toBeCloseTo(1);
+ expect(headingWeights(180 * DEG, run).get("A_Combat_Run_B")).toBeCloseTo(1);
+ });
+
+ it("blends the two neighbours so the blended stride points where the body moves", () => {
+ for (let a = -179; a <= 180; a += 7) {
+ const w = headingWeights(a * DEG, run);
+ expect(sum(w)).toBeCloseTo(1, 6);
+ expect(w.size).toBeLessThanOrEqual(2);
+ const err = Math.atan2(Math.sin(strideDir(w) - a * DEG), Math.cos(strideDir(w) - a * DEG));
+ expect(Math.abs(err)).toBeLessThan(1e-6);
+ }
+ });
+
+ it("weights a diagonal toward the shorter stride (backpedal is slower)", () => {
+ const w = headingWeights(135 * DEG, run);
+ expect(w.get("A_Combat_Run_B")!).toBeGreaterThan(w.get("A_Combat_Run_L")!);
+ });
+});
+
+describe("locomotion blend", () => {
+ it("walks slowly, runs at full speed and mixes the gaits in between", () => {
+ const slow = locomotionBlend(DEFAULT_LOCO, 0, 2, 0);
+ expect(slow.weights.get("A_Combat_Walk_F")).toBeCloseTo(1);
+ const fast = locomotionBlend(DEFAULT_LOCO, 0, 4.8, 0);
+ expect(fast.weights.get("A_Combat_Run_F")).toBeCloseTo(1);
+ const mid = locomotionBlend(DEFAULT_LOCO, 0, 3.2, 0);
+ expect(mid.weights.get("A_Combat_Walk_F")! > 0 && mid.weights.get("A_Combat_Run_F")! > 0).toBe(true);
+ for (const b of [slow, fast, mid]) expect(sum(b.weights)).toBeCloseTo(1, 6);
+ });
+
+ it("hands the body to the sprint by its share", () => {
+ const b = locomotionBlend(DEFAULT_LOCO, 0, 7, 1);
+ expect(b.weights.get(DUEL_CLIPS.sprint)).toBeCloseTo(1);
+ expect(b.stride).toBeCloseTo(7 * (16 / 30), 6);
+ });
+
+ it("strides as far as the blended clips travel per cycle", () => {
+ const b = locomotionBlend(DEFAULT_LOCO, 0, 4.8, 0);
+ expect(b.stride).toBeCloseTo(4.8 * (18 / 30), 6);
+ });
+
+ it("reads speeds and headings from the manifest and scales them with the body", () => {
+ const table = { A_Combat_Run_F: { speed: 5, heading: 0, seconds: 0.6 }, A_Combat_Run_L: { speed: 5, heading: 90 } };
+ const clips = locoClips(table, new Set(["A_Combat_Run_F", "A_Combat_Run_L"]), 0.5);
+ expect(clips.map((c) => c.name)).toEqual(["A_Combat_Run_F", "A_Combat_Run_L"]);
+ expect(clips[0].speed).toBeCloseTo(2.5);
+ expect(clips[1].heading).toBeCloseTo(Math.PI / 2);
+ });
+});
+
+describe("flinch side", () => {
+ it("names the side a bolt arrives from, relative to the body's facing", () => {
+ expect(flinchSide(0, 0, 0, 0, 5)).toBe("F");
+ expect(flinchSide(0, 0, 0, 0, -5)).toBe("B");
+ expect(flinchSide(0, 0, 0, 5, 0)).toBe("L");
+ expect(flinchSide(0, 0, 0, -5, 0)).toBe("R");
+ expect(flinchSide(0, 0, Math.PI / 2, 5, 0)).toBe("F");
+ });
+});
+
+describe("fighter animator", () => {
+ const dt = 1 / 60;
+
+ it("advances the gait phase at ground speed over the stride, so feet do not slide", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ let f = a.update(dt, input());
+ for (let i = 0; i < 120; i += 1) f = a.update(dt, input({ vz: 4.8 }));
+ const before = f.phase;
+ f = a.update(0.05, input({ vz: 4.8 }));
+ const advanced = (f.phase - before + 1) % 1;
+ expect(advanced).toBeCloseTo((0.05 * 4.8) / (4.8 * (18 / 30)), 6);
+ expect(weightOf(f, "A_Combat_Run_F")).toBeGreaterThan(0.95);
+ });
+
+ it("strafes and backpedals with the legs still facing the aim", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ let f = a.update(dt, input());
+ for (let i = 0; i < 90; i += 1) f = a.update(dt, input({ vx: 4.8 }));
+ expect(f.legsYaw).toBeCloseTo(0, 3);
+ expect(weightOf(f, "A_Combat_Run_L")).toBeGreaterThan(0.95);
+ for (let i = 0; i < 90; i += 1) f = a.update(dt, input({ vz: -3.7 }));
+ expect(weightOf(f, "A_Combat_Run_B") + weightOf(f, "A_Combat_Walk_B")).toBeGreaterThan(0.95);
+ });
+
+ it("keeps the base layer's weights summing to one through every state", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ const script: Array<[number, Partial<FighterInput>]> = [
+ [30, {}], [40, { vz: 4.8 }], [20, { vx: -4.8, aimYaw: 0.4 }], [12, { dodging: true, vx: 10 }],
+ [30, {}], [40, { aimYaw: 2 }], [20, { alive: false }], [90, { alive: false }], [120, {}],
+ [20, { vz: 7, sprinting: true }], [10, { shieldUp: true }],
+ ];
+ let t = 0;
+ for (const [n, over] of script) {
+ for (let i = 0; i < n; i += 1) {
+ t += dt;
+ const p = input({ ...over, dodgeProgress: over.dodging ? Math.min(1, (i * dt) / TIMING.rollSim) : 0 });
+ const f = a.update(dt, p);
+ expect(baseSum(f)).toBeCloseTo(1, 5);
+ for (const c of f.base) expect(c.weight).toBeGreaterThanOrEqual(0);
+ }
+ }
+ expect(t).toBeGreaterThan(5);
+ });
+
+ it("step-turns a standing body when the aim swings far, and the legs end on the aim", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ a.update(dt, input());
+ let f = a.update(dt, input({ aimYaw: Math.PI / 2 }));
+ expect(f.base.some((c) => c.name === DUEL_CLIPS.turnL)).toBe(true);
+ for (let i = 0; i < 60; i += 1) f = a.update(dt, input({ aimYaw: Math.PI / 2 }));
+ expect(f.legsYaw).toBeCloseTo(Math.PI / 2, 3);
+ expect(f.base.some((c) => c.name === DUEL_CLIPS.turnL && c.weight > 0.01)).toBe(false);
+ // A small swing is the spine's job, not the legs'.
+ f = a.update(dt, input({ aimYaw: Math.PI / 2 + 0.5 }));
+ expect(f.base.some((c) => c.name === DUEL_CLIPS.turnL || c.name === DUEL_CLIPS.turnR)).toBe(false);
+ expect(f.twist).toBeCloseTo(0.5, 3);
+ });
+
+ it("rolls the roll's way, lets go of the blaster, and takes it back after the recovery", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ a.update(dt, input());
+ let f = a.update(dt, input({ dodging: true, vx: 10, dodgeProgress: 0.05 }));
+ for (let i = 1; i < 24; i += 1) f = a.update(dt, input({ dodging: true, vx: 10, dodgeProgress: (i * dt) / TIMING.rollSim }));
+ expect(f.legsYaw).toBeCloseTo(Math.PI / 2, 2);
+ expect(weightOf(f, DUEL_CLIPS.roll)).toBeGreaterThan(0.95);
+ expect(f.ik).toBe(0);
+ for (let i = 0; i < 30; i += 1) f = a.update(dt, input());
+ expect(weightOf(f, DUEL_CLIPS.roll)).toBe(0);
+ expect(f.ik).toBe(1);
+ });
+
+ it("falls away from the shooter, stays down, and gets up when revived", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ a.update(dt, input());
+ a.knockedOut(0, 0, 0, -10);
+ let f = a.update(dt, input({ alive: false }));
+ for (let i = 0; i < 200; i += 1) f = a.update(dt, input({ alive: false }));
+ expect(Math.abs(f.legsYaw)).toBeCloseTo(Math.PI, 2);
+ const death = f.base.find((c) => c.name === DUEL_CLIPS.death);
+ expect(death?.weight).toBeCloseTo(1);
+ expect(death?.time).toBeCloseTo(TIMING.death);
+ expect(f.ik).toBe(0);
+ f = a.update(dt, input({ alive: true }));
+ expect(weightOf(f, DUEL_CLIPS.getUp)).toBeGreaterThan(0.9);
+ for (let i = 0; i < 120; i += 1) f = a.update(dt, input());
+ expect(weightOf(f, DUEL_CLIPS.getUp)).toBe(0);
+ expect(weightOf(f, DUEL_CLIPS.idle)).toBeCloseTo(1);
+ });
+
+ it("flinches additively toward the hit and staggers on its own reflected bolt", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ a.update(dt, input());
+ a.hit(0, 0, -5, 0, false, false);
+ let f = a.update(dt, input());
+ expect(f.additive.map((c) => c.name)).toEqual([DUEL_CLIPS.hitR]);
+ a.hit(0, 0, 0, 5, true, true);
+ f = a.update(dt, input());
+ expect(f.additive.map((c) => c.name).sort()).toEqual([DUEL_CLIPS.hitF, DUEL_CLIPS.hitR, DUEL_CLIPS.stagger].sort());
+ for (let i = 0; i < 70; i += 1) f = a.update(dt, input());
+ expect(f.additive).toEqual([]);
+ });
+
+ it("kicks on a shot and settles again", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ a.update(dt, input());
+ a.shot(false);
+ let peak = 0;
+ let f = a.update(dt, input());
+ for (let i = 0; i < 60; i += 1) { f = a.update(dt, input()); peak = Math.max(peak, f.recoil); }
+ expect(peak).toBeGreaterThan(0.1);
+ expect(Math.abs(f.recoil)).toBeLessThan(0.01);
+ });
+
+ it("shows the bot low behind cover and leans it out to peek", () => {
+ const a = new FighterAnimator(DEFAULT_LOCO);
+ let f = a.update(dt, input());
+ for (let i = 0; i < 90; i += 1) f = a.update(dt, input({ cover: "hide" }));
+ expect(weightOf(f, DUEL_CLIPS.cover)).toBeGreaterThan(0.9);
+ for (let i = 0; i < 90; i += 1) f = a.update(dt, input({ cover: "peek", peekSide: -1 }));
+ expect(weightOf(f, DUEL_CLIPS.cover)).toBeLessThan(0.1);
+ expect(f.peek).toBeLessThan(-0.9);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/fighterAnim.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/fighterAnim.ts
new file mode 100644
index 0000000000..7328766524
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/fighterAnim.ts
@@ -0,0 +1,490 @@
+/**
+ * What a duellist's body plays, frame by frame: the animation state of one
+ * fighter, pure and three.js-free (the figure applies it to the skeleton).
+ *
+ * Layers, in the order the figure applies them:
+ *
+ * - **Base** (weights sum to 1): the ready stance (or the low cover stance),
+ * a step-turn when the aim swings far round a standing body, eight-way
+ * locomotion from two gaits (combat walk and run, four headings each) plus
+ * the sprint, and the one-shots that own the whole body: the dodge roll,
+ * the knockout fall and the get-up. Locomotion clips share one normalised
+ * phase (0 = left foot down) that advances at ground speed over the blended
+ * stride, so the planted feet hold still at any speed and heading.
+ * - **Additive**: directional flinches and the stagger after eating one's own
+ * reflected bolt.
+ * - **Procedural** (the figure): the aim offset over spine, chest and head,
+ * the blaster in both hands by IK (ready, sights, sprint carry, lowered
+ * behind the shield, tipped while venting, low behind cover), recoil kicks,
+ * the shield arm, a lean into acceleration and a peek lean out of cover.
+ *
+ * The clips come from the character pipeline (`art/verse/characters/anim_combat.py`).
+ */
+import { clamp, wrapAngle } from "../combat/math";
+
+/** Clip names of the duel set (the character contract owns them). */
+export const DUEL_CLIPS = {
+ idle: "A_Combat_Idle",
+ cover: "A_Combat_Cover",
+ sprint: "A_Combat_Sprint",
+ turnL: "A_Combat_Turn_L",
+ turnR: "A_Combat_Turn_R",
+ roll: "A_Combat_Roll",
+ death: "A_Combat_Death",
+ getUp: "A_Combat_GetUp",
+ stagger: "A_Combat_Stagger",
+ hitF: "A_Combat_Hit_F",
+ hitB: "A_Combat_Hit_B",
+ hitL: "A_Combat_Hit_L",
+ hitR: "A_Combat_Hit_R",
+} as const;
+
+export const ADDITIVE_CLIPS: readonly string[] = [DUEL_CLIPS.stagger, DUEL_CLIPS.hitF, DUEL_CLIPS.hitB, DUEL_CLIPS.hitL, DUEL_CLIPS.hitR];
+
+/** Clip lengths and timings (seconds), as authored. */
+export const TIMING = {
+ turn: 0.6,
+ /** A step-turn turns the body this far (radians). */
+ turnAngle: Math.PI / 2,
+ roll: 0.6,
+ /** The sim's roll lasts this long; the clip's recovery runs on after it. */
+ rollSim: 0.4,
+ death: 1.4,
+ getUp: 1.5,
+ hit: 0.5,
+ stagger: 1.0,
+} as const;
+
+/** One locomotion clip: its ground speed (m/s), heading (radians, 0 = forward, + = the body's left), cycle length. */
+export interface LocoClip {
+ name: string;
+ gait: "walk" | "run" | "sprint";
+ speed: number;
+ heading: number;
+ seconds: number;
+}
+
+const DEG = Math.PI / 180;
+const HEADINGS: ReadonlyArray<readonly ["F" | "L" | "B" | "R", number]> = [["F", 0], ["L", 90], ["B", 180], ["R", -90]];
+
+/** The authored set, for a manifest without speeds. */
+export const DEFAULT_LOCO: readonly LocoClip[] = [
+ ...HEADINGS.map(([d, h]) => ({ name: `A_Combat_Walk_${d}`, gait: "walk" as const, speed: d === "B" ? 1.872 : 2.4, heading: h * DEG, seconds: 20 / 30 })),
+ ...HEADINGS.map(([d, h]) => ({ name: `A_Combat_Run_${d}`, gait: "run" as const, speed: d === "B" ? 3.744 : 4.8, heading: h * DEG, seconds: 18 / 30 })),
+ { name: DUEL_CLIPS.sprint, gait: "sprint", speed: 7.0, heading: 0, seconds: 16 / 30 },
+];
+
+/** The manifest's clip table (`characters.json` `clips`): loop, seconds and, for locomotion, speed and heading in degrees. */
+export type ClipTable = Readonly<Record<string, { loop?: boolean; seconds?: number; speed?: number; heading?: number }>>;
+
+/** The locomotion clips a body can play: the manifest's numbers where it has them, the authored ones otherwise. */
+export function locoClips(table: ClipTable | undefined, available: ReadonlySet<string>, scale = 1): LocoClip[] {
+ return DEFAULT_LOCO.filter((c) => available.has(c.name)).map((c) => {
+ const info = table?.[c.name];
+ return {
+ ...c,
+ speed: (typeof info?.speed === "number" ? info.speed : c.speed) * scale,
+ heading: typeof info?.heading === "number" ? info.heading * DEG : c.heading,
+ seconds: typeof info?.seconds === "number" && info.seconds > 0 ? info.seconds : c.seconds,
+ };
+ });
+}
+
+export function smootherstep(x: number): number {
+ const t = clamp(x, 0, 1);
+ return t * t * t * (t * (6 * t - 15) + 10);
+}
+
+function smoothstep(x: number): number {
+ const t = clamp(x, 0, 1);
+ return t * t * (3 - 2 * t);
+}
+
+/** Exponential approach of `cur` to `want` at `rate` per second. */
+function approach(cur: number, want: number, rate: number, dt: number): number {
+ return cur + (want - cur) * (1 - Math.exp(-rate * dt));
+}
+
+/**
+ * Weights of one gait's headings so that the blended stride points along
+ * `angle` (radians, 0 = forward, + = left): the two neighbouring headings,
+ * weighted by the angle and their strides. Pure; sums to 1.
+ */
+export function headingWeights(angle: number, clips: readonly LocoClip[]): Map<string, number> {
+ const out = new Map<string, number>();
+ if (!clips.length) return out;
+ const a = wrapAngle(angle);
+ // The two clips whose headings bracket the angle.
+ let lo: LocoClip | null = null;
+ let hi: LocoClip | null = null;
+ let loGap = Infinity;
+ let hiGap = Infinity;
+ for (const c of clips) {
+ const d = wrapAngle(a - c.heading);
+ if (d >= 0 && d < loGap) { loGap = d; lo = c; }
+ if (d <= 0 && -d < hiGap) { hiGap = -d; hi = c; }
+ }
+ if (!lo || !hi || lo === hi || loGap + hiGap < 1e-6) {
+ const only = lo ?? hi ?? clips[0];
+ out.set(only.name, 1);
+ return out;
+ }
+ // Solve w_lo * S_lo * u_lo + w_hi * S_hi * u_hi parallel to u(a).
+ const span = loGap + hiGap;
+ const sLo = lo.speed * lo.seconds;
+ const sHi = hi.speed * hi.seconds;
+ const wLo = Math.sin(hiGap) / Math.max(1e-6, sLo);
+ const wHi = Math.sin(loGap) / Math.max(1e-6, sHi);
+ const sum = wLo + wHi;
+ if (sum < 1e-9 || span > Math.PI - 1e-6) {
+ out.set(loGap <= hiGap ? lo.name : hi.name, 1);
+ return out;
+ }
+ out.set(lo.name, wLo / sum);
+ out.set(hi.name, (out.get(hi.name) ?? 0) + wHi / sum);
+ return out;
+}
+
+export interface LocoBlend {
+ /** Clip name -> weight within locomotion (sums to 1). */
+ weights: Map<string, number>;
+ /** Ground distance one full cycle covers along the move direction (metres). */
+ stride: number;
+}
+
+/**
+ * The locomotion mix for moving at `speed` (m/s) towards `angle` (body-relative
+ * radians): the combat walk below about 2.5 m/s, the run above 3.9, both in
+ * between; the sprint (forward only) by `sprint` (0..1). Pure.
+ */
+export function locomotionBlend(clips: readonly LocoClip[], angle: number, speed: number, sprint: number): LocoBlend {
+ const walk = clips.filter((c) => c.gait === "walk");
+ const run = clips.filter((c) => c.gait === "run");
+ const sprintClip = clips.find((c) => c.gait === "sprint");
+ const runShare = walk.length && run.length ? smoothstep((speed - 2.5) / 1.4) : run.length ? 1 : 0;
+ const sprintShare = sprintClip ? clamp(sprint, 0, 1) : 0;
+ const weights = new Map<string, number>();
+ const add = (m: Map<string, number>, k: number) => { for (const [n, w] of m) if (w * k > 0) weights.set(n, (weights.get(n) ?? 0) + w * k); };
+ const rest = 1 - sprintShare;
+ if (walk.length) add(headingWeights(angle, walk), rest * (1 - runShare));
+ if (run.length) add(headingWeights(angle, run), rest * runShare);
+ if (sprintClip && sprintShare > 0) weights.set(sprintClip.name, sprintShare);
+ // The blended stride: the weighted sum of the clips' per-cycle ground travel vectors.
+ let f = 0;
+ let l = 0;
+ for (const c of clips) {
+ const w = weights.get(c.name);
+ if (!w) continue;
+ const s = c.speed * c.seconds * w;
+ f += Math.cos(c.heading) * s;
+ l += Math.sin(c.heading) * s;
+ }
+ return { weights, stride: Math.hypot(f, l) };
+}
+
+export type Flinch = "F" | "B" | "L" | "R";
+
+/** Which side a bolt from (fromX, fromZ) hits a body at (x, z) facing `yaw`. Pure. */
+export function flinchSide(x: number, z: number, yaw: number, fromX: number, fromZ: number): Flinch {
+ const dx = fromX - x;
+ const dz = fromZ - z;
+ const fwd = dx * Math.sin(yaw) + dz * Math.cos(yaw);
+ const left = dx * Math.cos(yaw) - dz * Math.sin(yaw);
+ if (Math.abs(fwd) >= Math.abs(left)) return fwd >= 0 ? "F" : "B";
+ return left >= 0 ? "L" : "R";
+}
+
+/** What the figure knows about its fighter this frame. */
+export interface FighterInput {
+ x: number;
+ z: number;
+ vx: number;
+ vz: number;
+ aimYaw: number;
+ aimPitch: number;
+ alive: boolean;
+ dodging: boolean;
+ /** 0..1 through the sim's roll. */
+ dodgeProgress: number;
+ sprinting: boolean;
+ shieldUp: boolean;
+ /** 0..1 into the sights. */
+ ads: number;
+ venting: boolean;
+ /** Bot presentation: hiding low behind cover, or peeking out of it to this side (+1 left, -1 right). */
+ cover?: "hide" | "peek" | null;
+ peekSide?: number;
+}
+
+export interface ClipWeight {
+ name: string;
+ weight: number;
+ /** Seconds into the clip. */
+ time: number;
+}
+
+export interface FighterFrame {
+ /** The root's facing (the legs' way), radians. */
+ legsYaw: number;
+ base: ClipWeight[];
+ additive: ClipWeight[];
+ /** 0..1: the arms hold the blaster by IK (0 while a one-shot owns the body). */
+ ik: number;
+ /** Aim relative to the legs (radians) for the spine and head. */
+ twist: number;
+ pitch: number;
+ /** Lean into acceleration (radians; forward, to the left). */
+ leanFwd: number;
+ leanSide: number;
+ /** Blaster carries, 0..1 each. */
+ ads: number;
+ sprint: number;
+ shield: number;
+ vent: number;
+ cover: number;
+ /** 0..1 through the vent's hand motion (reach, pull, back). */
+ ventPull: number;
+ /** Recoil kick, about 0..1. */
+ recoil: number;
+ /** The shield arm's shove of a perfect parry, 0..1. */
+ parryPush: number;
+ /** Lean out of cover (-1 right .. +1 left). */
+ peek: number;
+ /** Locomotion share of the base layer and its phase (0..1). */
+ moving: number;
+ phase: number;
+}
+
+interface OneShot { t: number; weight: number }
+
+/** Seconds from a shot to the recoil's peak. */
+const RECOIL_TAU = 0.045;
+
+/**
+ * The animation state of one fighter. Feed it every rendered frame
+ * (`update`) and the frame's combat events (`shot`, `hit`, ...).
+ */
+export class FighterAnimator {
+ private legsYaw = 0;
+ private primed = false;
+ private clock = 0;
+ private phase = 0;
+ private moveW = 0;
+ private sprintW = 0;
+ private shieldW = 0;
+ private ventW = 0;
+ private coverW = 0;
+ private peekW = 0;
+ private ventT = 0;
+ private wasVenting = false;
+ private turn: { t: number; sign: number; from: number } | null = null;
+ private turnW = 0;
+ private roll: { t: number; yaw: number } | null = null;
+ private rollW = 0;
+ private death: { t: number; yaw: number } | null = null;
+ private getUp: { t: number } | null = null;
+ private wasAlive = true;
+ private readonly hits = new Map<string, OneShot>();
+ /** Shots still kicking: age (s) and size. */
+ private readonly kicks: { age: number; size: number }[] = [];
+ private parryT = 1;
+ private accF = 0;
+ private accL = 0;
+ private prevVx = 0;
+ private prevVz = 0;
+ private readonly frame: FighterFrame = {
+ legsYaw: 0, base: [], additive: [], ik: 1, twist: 0, pitch: 0, leanFwd: 0, leanSide: 0,
+ ads: 0, sprint: 0, shield: 0, vent: 0, cover: 0, ventPull: 0, recoil: 0, parryPush: 0, peek: 0, moving: 0, phase: 0,
+ };
+
+ constructor(private readonly loco: readonly LocoClip[], private readonly has: (name: string) => boolean = () => true) {}
+
+ /** A shot left this fighter's blaster. */
+ shot(ads: boolean): void {
+ this.kicks.push({ age: 0, size: ads ? 0.65 : 1 });
+ }
+
+ /** A bolt hit this fighter from (fromX, fromZ); `stagger` when it was their own bolt parried back at them. */
+ hit(x: number, z: number, fromX: number, fromZ: number, headshot: boolean, stagger: boolean): void {
+ if (!this.wasAlive) return;
+ const side = flinchSide(x, z, this.legsYaw, fromX, fromZ);
+ const name = { F: DUEL_CLIPS.hitF, B: DUEL_CLIPS.hitB, L: DUEL_CLIPS.hitL, R: DUEL_CLIPS.hitR }[side];
+ this.hits.set(name, { t: 0, weight: headshot ? 1.35 : 1 });
+ if (stagger) this.hits.set(DUEL_CLIPS.stagger, { t: 0, weight: 1 });
+ }
+
+ /** This fighter parried a bolt (the shield arm shoves). */
+ parried(): void {
+ this.parryT = 0;
+ }
+
+ /** Knocked out by a shooter standing at (fromX, fromZ): the body turns to face them and falls back, away. */
+ knockedOut(x: number, z: number, fromX: number, fromZ: number): void {
+ if (this.death) return;
+ const yaw = Math.hypot(fromX - x, fromZ - z) > 0.05 ? Math.atan2(fromX - x, fromZ - z) : this.legsYaw;
+ this.death = { t: 0, yaw };
+ }
+
+ /** Advance by `dt` seconds with this frame's fighter state. */
+ update(dtS: number, p: FighterInput): FighterFrame {
+ const dt = clamp(dtS, 0, 0.1);
+ const f = this.frame;
+ this.clock += dt;
+ if (!this.primed) { this.legsYaw = p.aimYaw; this.primed = true; this.wasAlive = p.alive; }
+
+ // Life: a knockout without its event still falls; a revived body gets up.
+ if (!p.alive && !this.death) this.death = { t: 0, yaw: this.legsYaw };
+ if (p.alive && !this.wasAlive) {
+ this.death = null;
+ this.getUp = { t: 0 };
+ this.legsYaw = p.aimYaw;
+ this.turn = null;
+ this.roll = null;
+ this.hits.clear();
+ }
+ this.wasAlive = p.alive;
+ if (this.death) this.death.t = Math.min(TIMING.death, this.death.t + dt);
+ if (this.getUp) { this.getUp.t += dt; if (this.getUp.t >= TIMING.getUp) this.getUp = null; }
+
+ // Ground motion, relative to the legs, and a smoothed acceleration for the lean.
+ const speed = Math.hypot(p.vx, p.vz);
+ if (dt > 0) {
+ const ax = (p.vx - this.prevVx) / dt;
+ const az = (p.vz - this.prevVz) / dt;
+ const s = Math.sin(this.legsYaw);
+ const c = Math.cos(this.legsYaw);
+ this.accF = approach(this.accF, clamp(ax * s + az * c, -60, 60), 10, dt);
+ this.accL = approach(this.accL, clamp(ax * c - az * s, -60, 60), 10, dt);
+ }
+ this.prevVx = p.vx;
+ this.prevVz = p.vz;
+
+ // The roll: faces the roll's way, its recovery runs on after the sim's roll.
+ if (p.alive && p.dodging) {
+ const yaw = speed > 0.5 ? Math.atan2(p.vx, p.vz) : this.roll?.yaw ?? p.aimYaw + Math.PI;
+ if (!this.roll || this.roll.t > TIMING.rollSim + 0.05) this.roll = { t: 0, yaw };
+ this.roll.t = Math.max(this.roll.t, clamp(p.dodgeProgress, 0, 1) * TIMING.rollSim);
+ this.roll.yaw = yaw;
+ this.turn = null;
+ } else if (this.roll) {
+ this.roll.t += dt;
+ if (this.roll.t >= TIMING.roll || !p.alive) this.roll = null;
+ }
+ // In fast, out over the clip's last 0.16 s.
+ this.rollW = this.roll
+ ? Math.min(1 - smoothstep((this.roll.t - (TIMING.roll - 0.16)) / 0.16), approach(this.rollW, 1, 40, dt))
+ : 0;
+
+ // Legs: face the aim while moving (strafe and backpedal clips carry the direction); standing, step-turn when the aim swings far.
+ const moving = p.alive && !p.dodging && speed > 0.3;
+ const sprinting = p.alive && p.sprinting && speed > 4.5;
+ if (this.death) {
+ this.legsYaw += wrapAngle(this.death.yaw - this.legsYaw) * Math.min(1, dt * 25);
+ } else if (this.roll) {
+ this.legsYaw += wrapAngle(this.roll.yaw - this.legsYaw) * (p.dodging ? Math.min(1, dt * 30) : Math.min(1, dt * 12));
+ } else if (moving) {
+ this.turn = null;
+ const want = sprinting ? Math.atan2(p.vx, p.vz) : p.aimYaw;
+ this.legsYaw += wrapAngle(want - this.legsYaw) * Math.min(1, dt * 10);
+ } else if (this.turn) {
+ this.turn.t += dt;
+ const k = smootherstep(this.turn.t / TIMING.turn);
+ this.legsYaw = this.turn.from + this.turn.sign * TIMING.turnAngle * k;
+ if (this.turn.t >= TIMING.turn) this.turn = null;
+ } else if (p.alive && !this.getUp) {
+ const off = wrapAngle(p.aimYaw - this.legsYaw);
+ if (Math.abs(off) > 70 * DEG && this.has(off > 0 ? DUEL_CLIPS.turnL : DUEL_CLIPS.turnR)) {
+ this.turn = { t: 0, sign: Math.sign(off), from: this.legsYaw };
+ } else if (Math.abs(off) > 70 * DEG) {
+ this.legsYaw += off * Math.min(1, dt * 6);
+ }
+ }
+ this.legsYaw = wrapAngle(this.legsYaw);
+ this.turnW = approach(this.turnW, this.turn ? 1 : 0, this.turn ? 25 : 12, dt);
+
+ // Locomotion phase: ground speed over the blended stride, so planted feet hold still.
+ this.sprintW = approach(this.sprintW, sprinting ? 1 : 0, 8, dt);
+ const angle = wrapAngle(Math.atan2(p.vx, p.vz) - this.legsYaw);
+ const blend = locomotionBlend(this.loco, angle, speed, this.sprintW);
+ if (blend.stride > 1e-3) this.phase = (this.phase + (dt * speed) / blend.stride) % 1;
+ this.moveW = approach(this.moveW, moving ? clamp(speed / 0.9, 0, 1) : 0, moving ? 14 : 10, dt);
+
+ // Carries.
+ this.shieldW = approach(this.shieldW, p.alive && p.shieldUp ? 1 : 0, p.shieldUp ? 22 : 12, dt);
+ this.ventW = approach(this.ventW, p.alive && p.venting ? 1 : 0, p.venting ? 16 : 10, dt);
+ if (p.venting && !this.wasVenting) this.ventT = 0;
+ this.wasVenting = p.venting;
+ this.ventT += dt;
+ const hiding = p.cover === "hide" && speed < 0.8;
+ this.coverW = approach(this.coverW, p.alive && hiding ? 1 : 0, 6, dt);
+ const peek = p.cover === "peek" ? clamp(p.peekSide ?? 0, -1, 1) : 0;
+ this.peekW = approach(this.peekW, peek, 7, dt);
+ // Recoil: each shot kicks along t/tau * e^(1 - t/tau) (peak 1 at tau), the kicks add up.
+ let recoil = 0;
+ for (let i = this.kicks.length - 1; i >= 0; i -= 1) {
+ const k = this.kicks[i];
+ k.age += dt;
+ if (k.age > 0.5) { this.kicks.splice(i, 1); continue; }
+ const u = k.age / RECOIL_TAU;
+ recoil += k.size * u * Math.exp(1 - u);
+ }
+ this.parryT = Math.min(1, this.parryT + dt / 0.28);
+ for (const [name, h] of this.hits) {
+ h.t += dt;
+ const len = name === DUEL_CLIPS.stagger ? TIMING.stagger : TIMING.hit;
+ if (h.t >= len) this.hits.delete(name);
+ }
+
+ // Base layer.
+ const base = f.base;
+ base.length = 0;
+ const deathW = this.death ? smoothstep(this.death.t / 0.08) : 0;
+ const getUpW = this.getUp ? 1 - smoothstep((this.getUp.t - (TIMING.getUp - 0.3)) / 0.3) : 0;
+ const rollW = p.alive ? this.rollW : 0;
+ const special = Math.min(1, deathW + getUpW + rollW);
+ if (this.death && deathW > 0) base.push({ name: DUEL_CLIPS.death, weight: deathW, time: this.death.t });
+ if (this.getUp && getUpW > 0 && !this.death) base.push({ name: DUEL_CLIPS.getUp, weight: getUpW * (1 - deathW), time: this.getUp.t });
+ if (this.roll && rollW > 0 && !this.death) base.push({ name: DUEL_CLIPS.roll, weight: rollW, time: this.roll.t });
+ const rest = 1 - special;
+ const move = rest * this.moveW;
+ const stand = rest - move;
+ if (move > 0) {
+ for (const c of this.loco) {
+ const w = blend.weights.get(c.name);
+ if (w) base.push({ name: c.name, weight: move * w, time: this.phase * c.seconds });
+ }
+ }
+ if (stand > 0) {
+ const turnShare = this.turn ? this.turnW : 0;
+ if (turnShare > 0 && this.turn) {
+ base.push({ name: this.turn.sign > 0 ? DUEL_CLIPS.turnL : DUEL_CLIPS.turnR, weight: stand * turnShare, time: Math.min(this.turn.t, TIMING.turn) });
+ }
+ const still = stand * (1 - turnShare);
+ if (this.coverW > 0.001) base.push({ name: DUEL_CLIPS.cover, weight: still * this.coverW, time: this.clock % 2 });
+ base.push({ name: DUEL_CLIPS.idle, weight: still * (1 - this.coverW), time: this.clock % 2 });
+ }
+
+ const additive = f.additive;
+ additive.length = 0;
+ if (p.alive) for (const [name, h] of this.hits) additive.push({ name, weight: h.weight, time: h.t });
+
+ f.legsYaw = this.legsYaw;
+ f.ik = p.alive ? clamp(1 - special * 1.15, 0, 1) : 0;
+ f.twist = clamp(wrapAngle(p.aimYaw - this.legsYaw), -100 * DEG, 100 * DEG) * (1 - special);
+ f.pitch = p.aimPitch * (1 - special);
+ f.leanFwd = clamp(this.accF * 0.006, -0.16, 0.16) * (1 - special);
+ f.leanSide = clamp(this.accL * 0.005, -0.14, 0.14) * (1 - special);
+ f.ads = p.alive ? clamp(p.ads, 0, 1) : 0;
+ f.sprint = this.sprintW;
+ f.shield = this.shieldW;
+ f.vent = this.ventW;
+ f.cover = this.coverW * (1 - this.moveW);
+ f.ventPull = p.venting ? clamp(this.ventT / 0.55, 0, 1) : 1;
+ f.recoil = clamp(recoil, 0, 1.6);
+ f.parryPush = this.parryT < 1 ? Math.sin(Math.PI * this.parryT) : 0;
+ f.peek = this.peekW;
+ f.moving = move;
+ f.phase = this.phase;
+ return f;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts b/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts
index 723b3b9cc1..e671ec8f72 100644
--- a/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts
+++ b/dodaios/ui/web/frontend/src/components/society/verse/duel/figure.ts
@@ -1,30 +1,46 @@
/**
- * A duellist's body: a character from the library (the commander's officer
- * body for the person, the trooper for the bot) with the blaster in its
- * hands, posed every frame from the combat view.
+ * A duellist's body: a character from the library (the commander's skin for
+ * the person, the trooper for the bot) with the blaster in its hands, posed
+ * every frame from the combat view.
*
- * The clip set has walk and idle but no aiming, so the upper body is posed
- * procedurally on top of the clips: the legs walk the way the body moves
- * (backwards when it backs off), the spine and chest twist and bend toward
- * the aim, the head follows it, and both arms reach the blaster by two-bone
- * IK (right hand on the grip, left hand on the shroud). Sprinting carries
- * the blaster low, the raised shield lowers it and puts the left palm
- * forward, venting tips it up. A dodge is a tucked roll along the move
- * direction; a knocked-out body falls backwards.
+ * The duel clip set (`A_Combat_*`, authored in the character pipeline) drives
+ * the body through `FighterAnimator`: a bladed rifle stance, eight-way
+ * locomotion with planted feet, step-turns, the dodge roll, flinches, the
+ * stagger, the knockout fall and the get-up. On top of the clips, every frame:
+ *
+ * - the aim offset turns spine and chest toward the aim (pitch and yaw), the
+ * head follows the aim or, for the bot, the opponent;
+ * - the blaster sits with its stock in the right shoulder pocket (read from
+ * the chest bone, so it moves with every flinch and lean) along the aim:
+ * raised to the eye in the sights, carried low across the chest sprinting,
+ * lowered by the hip behind the shield, tipped while venting, low behind
+ * cover, kicked back by a recoil spring per shot;
+ * - both hands go to it by two-bone IK, calibrated against `A_Combat_Idle`
+ * frame 0 (where the blaster is level and straight ahead), so the grip and
+ * the hand rotations match the authored hold; the shield raises the left
+ * forearm with its emitter in front of the chest and shoves on a parry; a
+ * vent racks the receiver with the left hand;
+ * - while a one-shot owns the body (roll, fall, get-up) the blaster rides in
+ * the right hand instead.
*/
import {
- AnimationMixer, Color, Group, LoopRepeat, Matrix4, Mesh, MeshBasicMaterial, PlaneGeometry, Quaternion, Vector3,
+ AdditiveAnimationBlendMode, AnimationClip, AnimationMixer, AnimationUtils, Color, Group, LoopRepeat, Matrix4, Mesh,
+ MeshBasicMaterial, PlaneGeometry, Quaternion, Vector3,
type AnimationAction, type Bone, type Material, type MeshStandardMaterial, type Object3D, type Texture,
} from "three";
import type { Deck } from "../content/deck";
import { disposeInstance, type CharacterInstance } from "../actors/characters";
-import { clipFor } from "../actors/clips";
import { RoomLight } from "../actors/roomLight";
import { CloakRig } from "../actors/cloak";
+import type { BotPresentation } from "../combat/bot/brain";
+import type { CombatEvent } from "../combat/types";
import type { PlayerView } from "../combat/view";
import { buildBlaster, type Blaster } from "./blaster";
+import { ADDITIVE_CLIPS, DUEL_CLIPS, FighterAnimator, locoClips, type ClipTable, type FighterFrame } from "./fighterAnim";
const UP = new Vector3(0, 1, 0);
+/** Stock butt to grip along the barrel, metres (the blaster's stock, for a 1.78 m body). */
+const STOCK = 0.29;
function wrap(a: number): number {
return Math.atan2(Math.sin(a), Math.cos(a));
@@ -77,16 +93,51 @@ export function aimBone(bone: Object3D, child: Object3D, target: Vector3): void
}
/** Rotate a bone about a world axis by `angle` (its parent must be up to date). */
-function turnBone(bone: Object3D, axis: Vector3, angle: number): void {
- if (Math.abs(angle) < 1e-5) return;
+function turnBone(bone: Object3D | undefined, axis: Vector3, angle: number): void {
+ if (!bone || Math.abs(angle) < 1e-5) return;
const parentInv = bone.parent ? bone.parent.getWorldQuaternion(tmpP).invert() : tmpP.identity();
const local = tmpA.copy(axis).applyQuaternion(parentInv).normalize();
bone.quaternion.premultiply(tmpQ.setFromAxisAngle(local, angle));
bone.updateMatrixWorld(true);
}
+/** Give `bone` this world rotation (its parent must be up to date). */
+function setWorldQuat(bone: Object3D, q: Quaternion): void {
+ const parentInv = bone.parent ? bone.parent.getWorldQuaternion(tmpP).invert() : tmpP.identity();
+ bone.quaternion.copy(parentInv.multiply(q));
+ bone.updateMatrixWorld(true);
+}
+
+/** Additive copies of the flinch clips, one per source clip (the library shares clips between bodies). */
+const additiveCache = new WeakMap<AnimationClip, AnimationClip>();
+function additiveOf(clip: AnimationClip): AnimationClip {
+ let out = additiveCache.get(clip);
+ if (!out) {
+ out = AnimationUtils.makeClipAdditive(clip.clone(), 0);
+ out.blendMode = AdditiveAnimationBlendMode;
+ additiveCache.set(clip, out);
+ }
+ return out;
+}
+
interface Arm { upper: Bone; fore: Bone; hand: Bone; a: number; b: number }
+/** The duellists on stage; `window.__verseDuelBodies()` reads them (QA hook, every build, like `__verseDuel`). */
+const LIVE_BODIES = new Set<DuelFigure>();
+if (typeof window !== "undefined") {
+ Object.assign(window, { __verseDuelBodies: () => [...LIVE_BODIES].map((b) => b.qa()) });
+}
+
+/** Where the hands hold the blaster, in the blaster's frame (grip at the origin, +Z the barrel). */
+interface Hold {
+ wristR: Vector3;
+ wristL: Vector3;
+ handR: Quaternion;
+ handL: Quaternion;
+ /** The stock's shoulder pocket in the chest bone's frame. */
+ pocket: Vector3;
+}
+
export interface FigureLook {
/** Recolour these material names (the trooper's armour and accents). */
tint?: Readonly<Record<string, string>>;
@@ -96,48 +147,128 @@ export interface FigureLook {
accent: Color;
}
+/** What the figure is told besides the fighter's own state. */
+export interface FigureCues {
+ /** Look here (the opponent's head), world. */
+ lookAt?: Vector3 | null;
+ /** Bot presentation: hiding low behind cover, or peeking out of it toward `peekSide` (+1 left, -1 right). */
+ cover?: "hide" | "peek" | null;
+ peekSide?: number;
+}
+
+/**
+ * Hand a frame's combat event to the bodies it moves: recoil on a shot, a
+ * flinch on a hit (a stagger when the bolt was one parried back at its
+ * shooter), the shield shove on a parry, the fall on a knockout. `parried`
+ * remembers reflected bolts across frames.
+ */
+export function routeFigureEvent(
+ e: CombatEvent, players: readonly PlayerView[], figureFor: (slot: number) => DuelFigure | null, parried: Set<number>,
+): void {
+ const at = (slot: number) => players.find((p) => p.slot === slot);
+ switch (e.type) {
+ case "shot":
+ figureFor(e.player)?.anim.shot(e.ads);
+ break;
+ case "parry":
+ parried.add(e.bolt);
+ if (parried.size > 64) parried.delete(parried.values().next().value as number);
+ figureFor(e.player)?.anim.parried();
+ break;
+ case "hit": {
+ const p = at(e.target);
+ if (p) figureFor(e.target)?.anim.hit(p.x, p.z, e.fromX, e.fromZ, e.headshot, parried.has(e.bolt));
+ break;
+ }
+ case "death": {
+ const p = at(e.player);
+ const k = at(e.killer);
+ if (p) figureFor(e.player)?.anim.knockedOut(p.x, p.z, k?.x ?? p.x, k?.z ?? p.z);
+ break;
+ }
+ case "round_start":
+ parried.clear();
+ break;
+ default:
+ break;
+ }
+}
+
+/**
+ * The bot body's cues from its presentation: hiding or peeking, the peek's
+ * side relative to its aim (+1 left), and the opponent's head to look at.
+ */
+export function botCues(pres: BotPresentation | null, bot: PlayerView, foe: PlayerView | undefined, floorY: number, out: FigureCues): FigureCues {
+ out.cover = pres?.cover ?? null;
+ out.peekSide = 0;
+ if (pres?.cover === "peek" && pres.spot && pres.peek) {
+ const left = (pres.peek.x - pres.spot.x) * Math.cos(bot.aimYaw) - (pres.peek.z - pres.spot.z) * Math.sin(bot.aimYaw);
+ out.peekSide = Math.abs(left) > 0.05 ? Math.sign(left) : 0;
+ }
+ if (foe && foe.alive) {
+ out.lookAt = (out.lookAt ?? new Vector3()).set(foe.x, floorY + 1.6, foe.z);
+ } else {
+ out.lookAt = null;
+ }
+ return out;
+}
+
export class DuelFigure {
readonly group = new Group();
readonly blaster: Blaster;
+ readonly anim: FighterAnimator;
+ /** The combat slot this body shows (set by the layer). */
+ slot = -1;
+ /** The last frame's animation state (QA: `window.__verseDuelBodies`). */
+ lastFrame: FighterFrame | null = null;
private readonly mixer: AnimationMixer;
+ private readonly actions = new Map<string, AnimationAction>();
/** The skin's cloak, when it has one. */
private readonly cloak: CloakRig | null;
private readonly light = new RoomLight();
- private idle: AnimationAction | null = null;
- private walk: AnimationAction | null = null;
private readonly bones: Record<string, Bone | undefined> = {};
private right: Arm | null = null;
private left: Arm | null = null;
- private legsYaw = 0;
- private walkWeight = 0;
- private deathT = 0;
- private primed = false;
+ private hold: Hold | null = null;
+ private readonly scale: number;
private readonly shadow: Mesh<PlaneGeometry, MeshBasicMaterial>;
- private readonly walkSpeed: number;
// Scratch, reused every frame.
private readonly grip = new Vector3();
- private readonly fore = new Vector3();
+ private readonly dir = new Vector3();
+ private readonly fwd = new Vector3();
+ private readonly lft = new Vector3();
+ private readonly up = new Vector3();
+ private readonly pocket = new Vector3();
private readonly elbow = new Vector3();
private readonly pole = new Vector3();
- private readonly aim = new Vector3();
- private readonly side = new Vector3();
- private readonly qRoll = new Quaternion();
- private readonly qYaw = new Quaternion();
+ private readonly target = new Vector3();
+ private readonly qB = new Quaternion();
+ private readonly qHand = new Quaternion();
+ private readonly qAttach = new Quaternion();
+ private readonly pAttach = new Vector3();
private readonly m4 = new Matrix4();
+ private readonly saved: Quaternion[] = Array.from({ length: 6 }, () => new Quaternion());
- constructor(readonly instance: CharacterInstance, look: FigureLook, shadow: Texture) {
+ constructor(readonly instance: CharacterInstance, look: FigureLook, shadow: Texture, clipTable?: ClipTable) {
this.mixer = new AnimationMixer(instance.root);
this.cloak = CloakRig.find(instance.root);
- this.walkSpeed = instance.walkSpeed || 1.4;
+ this.scale = (instance.model.height || 1.78) / 1.78;
for (const name of ["Hips", "Spine", "Chest", "Neck", "Head", "UpperArm_R", "ForeArm_R", "Hand_R", "UpperArm_L", "ForeArm_L", "Hand_L"]) {
const o = instance.root.getObjectByName(name) as Bone | undefined;
if (o) this.bones[name] = o;
}
const names = new Set(instance.clips.keys());
- const idleName = clipFor("idle", names);
- const walkName = clipFor("walk", names);
- if (idleName) { this.idle = this.mixer.clipAction(instance.clips.get(idleName)!); this.idle.setLoop(LoopRepeat, Infinity).play(); }
- if (walkName) { this.walk = this.mixer.clipAction(instance.clips.get(walkName)!); this.walk.setLoop(LoopRepeat, Infinity).play(); this.walk.weight = 0; }
+ this.anim = new FighterAnimator(locoClips(clipTable, names), (n) => names.has(n));
+ for (const [name, clip] of instance.clips) {
+ if (!name.startsWith("A_Combat_")) continue;
+ const additive = ADDITIVE_CLIPS.includes(name);
+ const action = this.mixer.clipAction(additive ? additiveOf(clip) : clip);
+ action.setLoop(LoopRepeat, Infinity);
+ action.setEffectiveTimeScale(0);
+ action.setEffectiveWeight(0);
+ action.play();
+ this.actions.set(name, action);
+ }
for (const [name, colour] of Object.entries(look.tint ?? {})) {
for (const m of instance.materials.get(name) ?? []) (m as MeshStandardMaterial).color?.set(colour);
}
@@ -155,18 +286,30 @@ export class DuelFigure {
this.shadow.rotation.x = -Math.PI / 2;
this.group.add(this.shadow);
for (const mesh of instance.meshes) mesh.frustumCulled = false;
- this.setupArms();
+ this.calibrate();
+ LIVE_BODIES.add(this);
+ }
+
+ /** QA: where the blaster points and what the body plays. */
+ qa(): { slot: number; frame: FighterFrame | null; blasterDir: number[]; grip: number[]; root: number[] } {
+ const d = new Vector3(0, 0, 1).applyQuaternion(this.blaster.group.quaternion);
+ const g = this.blaster.group.position;
+ const r = this.instance.root.position;
+ return { slot: this.slot, frame: this.lastFrame, blasterDir: [d.x, d.y, d.z], grip: [g.x, g.y, g.z], root: [r.x, r.y, r.z] };
}
get materials(): Material[] {
return [...[...this.instance.materials.values()].flat(), ...this.blaster.materials];
}
- private setupArms(): void {
+ /** The arms, and the authored hold of the idle's frame 0 (blaster level, straight ahead along +Z). */
+ private calibrate(): void {
const b = this.bones;
const root = this.instance.root;
root.position.set(0, 0, 0);
- root.rotation.set(0, 0, 0);
+ root.quaternion.identity();
+ const idle = this.actions.get(DUEL_CLIPS.idle);
+ if (idle) { idle.time = 0; idle.setEffectiveWeight(1); this.mixer.update(0); idle.setEffectiveWeight(0); }
root.updateMatrixWorld(true);
const arm = (u?: Bone, f?: Bone, h?: Bone): Arm | null => {
if (!u || !f || !h) return null;
@@ -174,150 +317,196 @@ export class DuelFigure {
const c = f.getWorldPosition(new Vector3()).distanceTo(h.getWorldPosition(new Vector3()));
return a > 0.05 && c > 0.05 ? { upper: u, fore: f, hand: h, a, b: c } : null;
};
- let right = arm(b.UpperArm_R, b.ForeArm_R, b.Hand_R);
- let left = arm(b.UpperArm_L, b.ForeArm_L, b.Hand_L);
- // A body facing +Z has its right side toward -X; if the rig's "_R" sits on +X the sides are named the other way.
- if (right && left && right.upper.getWorldPosition(new Vector3()).x > left.upper.getWorldPosition(new Vector3()).x) [right, left] = [left, right];
- this.right = right;
- this.left = left;
+ this.right = arm(b.UpperArm_R, b.ForeArm_R, b.Hand_R);
+ this.left = arm(b.UpperArm_L, b.ForeArm_L, b.Hand_L);
+ if (!idle || !b.Hand_R || !b.Hand_L || !b.Chest) return;
+ const s = this.scale;
+ const wristR = b.Hand_R.getWorldPosition(new Vector3());
+ const wristL = b.Hand_L.getWorldPosition(new Vector3());
+ // The grip is ahead of and below the right wrist (anim_combat.py: WRIST_BACK, WRIST_UP).
+ const grip = wristR.clone().add(new Vector3(0, -0.03 * s, 0.06 * s));
+ const pocketWorld = grip.clone().add(new Vector3(0, 0, -STOCK * s));
+ this.hold = {
+ wristR: wristR.clone().sub(grip),
+ wristL: wristL.clone().sub(grip),
+ handR: b.Hand_R.getWorldQuaternion(new Quaternion()),
+ handL: b.Hand_L.getWorldQuaternion(new Quaternion()),
+ pocket: pocketWorld.applyMatrix4(b.Chest.matrixWorld.clone().invert()),
+ };
+ }
+
+ private applyClips(f: FighterFrame): void {
+ for (const a of this.actions.values()) a.setEffectiveWeight(0);
+ for (const layer of [f.base, f.additive]) {
+ for (const c of layer) {
+ const a = this.actions.get(c.name);
+ if (!a) continue;
+ a.time = Math.min(c.time, a.getClip().duration);
+ a.setEffectiveWeight(c.weight);
+ }
+ }
+ this.mixer.update(0);
}
/**
* Pose the body for one frame. `floorY` is the deck floor under the arena;
* `deck` lights the body from the room's probe.
*/
- update(dtS: number, p: PlayerView, floorY: number, deck: Deck | null, timeS: number): void {
+ update(dtS: number, p: PlayerView, floorY: number, deck: Deck | null, timeS: number, cues: FigureCues = {}): void {
const dt = Math.min(0.1, Math.max(0, dtS));
const root = this.instance.root;
- const aimYaw = p.aimYaw;
- const aimPitch = p.aimPitch;
-
- // Legs: walk the way the body moves; backing off plays the walk backwards.
- const moving = p.speed > 0.35 && p.alive && !p.dodging;
- let reverse = false;
- if (moving) {
- const moveYaw = Math.atan2(p.vx, p.vz);
- let want = moveYaw;
- if (Math.abs(wrap(moveYaw - aimYaw)) > (100 * Math.PI) / 180) { want = moveYaw + Math.PI; reverse = true; }
- // Never twist further than the spine can carry.
- const lim = (80 * Math.PI) / 180;
- const off = wrap(want - aimYaw);
- if (Math.abs(off) > lim) want = aimYaw + Math.sign(off) * lim;
- this.legsYaw = this.primed ? this.legsYaw + wrap(want - this.legsYaw) * Math.min(1, dt * 12) : want;
- } else {
- this.legsYaw = this.primed ? this.legsYaw + wrap(aimYaw - this.legsYaw) * Math.min(1, dt * 8) : aimYaw;
- }
- this.primed = true;
- this.walkWeight += ((moving ? 1 : 0) - this.walkWeight) * Math.min(1, dt * 10);
- if (this.walk && this.idle) {
- this.walk.weight = this.walkWeight;
- this.idle.weight = 1 - this.walkWeight;
- const rate = Math.min(3.2, Math.max(0.6, (p.speed / this.walkSpeed) * 0.72));
- this.walk.timeScale = reverse ? -rate : rate;
- }
- this.mixer.update(dt);
-
- // Root: on the floor at the player's position, facing the legs' way; a roll or a fall turns it on top.
- const x = p.x;
- const z = p.z;
- this.qYaw.setFromAxisAngle(UP, this.legsYaw);
- root.position.set(x, floorY, z);
- root.quaternion.copy(this.qYaw);
- if (p.dodging) {
- const sp = Math.hypot(p.vx, p.vz);
- const dx = sp > 0.1 ? p.vx / sp : Math.sin(aimYaw);
- const dz = sp > 0.1 ? p.vz / sp : Math.cos(aimYaw);
- const t = p.dodgeProgress;
- const e = t * t * (3 - 2 * t);
- const axis = this.side.set(dz, 0, -dx).normalize();
- this.qRoll.setFromAxisAngle(axis, e * Math.PI * 2);
- const pivotY = 0.5;
- const tuck = Math.sin(t * Math.PI) * 0.18;
- const off = tmpA.set(0, -pivotY, 0).applyQuaternion(this.qRoll);
- root.position.set(x + off.x, floorY + pivotY - tuck * 0.5 + off.y, z + off.z);
- root.quaternion.copy(this.qRoll).multiply(this.qYaw);
- }
- if (!p.alive) {
- this.deathT = Math.min(1, this.deathT + dt / 0.6);
- const e = 1 - (1 - this.deathT) * (1 - this.deathT);
- const axis = this.side.set(-Math.cos(aimYaw), 0, Math.sin(aimYaw));
- this.qRoll.setFromAxisAngle(axis, e * (Math.PI / 2) * 0.96);
- root.quaternion.copy(this.qRoll).multiply(this.qYaw);
- root.position.y = floorY + e * 0.12;
- } else {
- this.deathT = 0;
- }
+ const f = this.lastFrame = this.anim.update(dt, {
+ x: p.x, z: p.z, vx: p.vx, vz: p.vz, aimYaw: p.aimYaw, aimPitch: p.aimPitch, alive: p.alive,
+ dodging: p.dodging, dodgeProgress: p.dodgeProgress, sprinting: p.sprinting, shieldUp: p.shieldUp, ads: p.ads,
+ venting: p.venting, cover: cues.cover ?? null, peekSide: cues.peekSide ?? 0,
+ });
+ root.position.set(p.x, floorY, p.z);
+ root.quaternion.setFromAxisAngle(UP, f.legsYaw);
+ root.updateMatrixWorld(true);
+ this.applyClips(f);
root.updateMatrixWorld(true);
const b = this.bones;
- const posing = p.alive && !p.dodging;
- if (posing) {
- // Upper body toward the aim: twist over spine and chest, bend with the pitch.
- const twist = wrap(aimYaw - this.legsYaw);
- if (b.Spine) turnBone(b.Spine, UP, twist * 0.45);
- if (b.Chest) turnBone(b.Chest, UP, twist * 0.55);
- const rightAxis = this.side.set(-Math.cos(aimYaw), 0, Math.sin(aimYaw));
- const bend = p.sprinting ? 0.12 : -aimPitch * 0.5;
- if (b.Chest) turnBone(b.Chest, rightAxis, -bend * 0.6);
- if (b.Spine) turnBone(b.Spine, rightAxis, -bend * 0.4);
- if (b.Head) turnBone(b.Head, rightAxis, aimPitch * 0.35);
- }
+ const s = this.scale;
+ const aimYaw = p.aimYaw;
+ // Body axes along the aim.
+ this.fwd.set(Math.sin(aimYaw), 0, Math.cos(aimYaw));
+ this.lft.set(Math.cos(aimYaw), 0, -Math.sin(aimYaw));
+ const legsLeft = tmpB.set(Math.cos(f.legsYaw), 0, -Math.sin(f.legsYaw));
+ const legsFwd = this.up.set(Math.sin(f.legsYaw), 0, Math.cos(f.legsYaw));
- // The blaster: held at the shoulder along the aim; low while sprinting, lowered behind a raised shield, tipped up venting.
+ // Lean into acceleration and out of cover, then the aim offset over spine and chest; the recoil rocks the chest.
+ turnBone(b.Spine, legsLeft, f.leanFwd);
+ turnBone(b.Spine, legsFwd, -f.leanSide - f.peek * 0.14);
+ turnBone(b.Chest, legsFwd, -f.peek * 0.12);
+ turnBone(b.Spine, UP, f.twist * 0.35);
+ turnBone(b.Chest, UP, f.twist * 0.45);
+ turnBone(b.Spine, this.lft, -f.pitch * 0.25);
+ turnBone(b.Chest, this.lft, -f.pitch * 0.35 - f.recoil * 0.05);
+
+ // The blaster.
const bl = this.blaster.group;
- bl.visible = p.alive;
+ bl.visible = p.alive || f.ik < 1;
+ const hold = this.hold;
let yaw = aimYaw;
- let pitch = aimPitch;
+ let pitch = p.aimPitch;
let roll = 0;
- let reach = 0.3;
- if (p.sprinting) { pitch = -0.55; yaw = aimYaw - 0.5; reach = 0.16; roll = 0.4; }
- else if (p.shieldUp) { pitch = -0.75; yaw = aimYaw - 0.35; reach = 0.16; roll = 0.2; }
- else if (p.venting) { pitch = 0.55; yaw = aimYaw - 0.25; roll = -0.7; reach = 0.22; }
- const dir = this.aim.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch));
- const rx = -Math.cos(aimYaw);
- const rz = Math.sin(aimYaw);
- const shoulderY = floorY + (p.sprinting ? 1.2 : 1.3) + (p.ads > 0.5 ? 0.06 : 0);
- this.grip.set(x + rx * 0.27 + dir.x * reach, shoulderY - 0.06 + dir.y * reach, z + rz * 0.27 + dir.z * reach);
- if (posing) {
- bl.position.copy(this.grip);
- this.m4.lookAt(tmpA.set(0, 0, 0), tmpB.copy(dir).negate(), UP);
- bl.quaternion.setFromRotationMatrix(this.m4);
- if (roll) bl.quaternion.multiply(tmpQ.setFromAxisAngle(tmpA.set(0, 0, 1), roll));
- bl.updateMatrixWorld(true);
- this.fore.copy(this.blaster.fore).applyMatrix4(bl.matrixWorld);
- // Right hand on the grip, elbow out and down; left hand on the shroud (on the shield's face while it is up).
+ const blendTo = (w: number, y: number, pi: number, r: number) => {
+ if (w <= 0) return;
+ yaw += wrap(y - yaw) * w;
+ pitch += (pi - pitch) * w;
+ roll += (r - roll) * w;
+ };
+ blendTo(f.cover, aimYaw + 0.25, -0.55, 0.1);
+ blendTo(f.sprint, f.legsYaw + 0.7, -0.6, 0.45);
+ blendTo(f.shield, aimYaw - 0.35, -0.85, 0.2);
+ blendTo(f.vent * (1 - f.shield), aimYaw + 0.3, 0.5, -0.75);
+ pitch += 0.09 * f.recoil * (1 - f.shield);
+ this.dir.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch));
+ if (hold && b.Chest) {
+ this.pocket.copy(hold.pocket).applyMatrix4(b.Chest.matrixWorld);
+ } else {
+ this.pocket.set(p.x - this.lft.x * 0.15, floorY + 1.36 * s, p.z - this.lft.z * 0.15);
+ }
+ // Sights: up to the eye and in toward the centre line; sprint: low across the chest; shield: down by the hip.
+ const inward = f.ads * 0.06 + f.sprint * 0.1 - f.shield * 0.04;
+ this.pocket.addScaledVector(this.lft, inward * s);
+ this.pocket.y += (f.ads * 0.07 - f.sprint * 0.12 - f.shield * 0.2 - f.cover * 0.08 - f.vent * 0.03) * s;
+ this.pocket.y += Math.sin(f.phase * Math.PI * 4) * 0.02 * f.sprint;
+ this.pocket.addScaledVector(this.dir, -0.05 * f.recoil * (1 - 0.4 * f.ads));
+ this.grip.copy(this.pocket).addScaledVector(this.dir, STOCK * s);
+ this.m4.lookAt(tmpA.set(0, 0, 0), this.target.copy(this.dir).negate(), UP);
+ this.qB.setFromRotationMatrix(this.m4);
+ if (roll) this.qB.multiply(tmpQ.setFromAxisAngle(tmpA.set(0, 0, 1), roll));
+ // While a one-shot owns the body the blaster rides in the right hand.
+ if (hold && b.Hand_R && f.ik < 1) {
+ b.Hand_R.getWorldQuaternion(this.qAttach).multiply(tmpQ.copy(hold.handR).invert());
+ b.Hand_R.getWorldPosition(this.pAttach).sub(tmpA.copy(hold.wristR).applyQuaternion(this.qAttach));
+ this.grip.lerpVectors(this.pAttach, this.grip, f.ik);
+ this.qB.slerpQuaternions(this.qAttach, this.qB, f.ik);
+ }
+ bl.position.copy(this.grip);
+ bl.quaternion.copy(this.qB);
+ bl.updateMatrixWorld(true);
+
+ // Hands on it.
+ if (hold && f.ik > 0) {
const r = this.right;
if (r) {
- const s = r.upper.getWorldPosition(new Vector3());
- this.pole.set(rx * 0.7, -1, rz * 0.7).addScaledVector(dir, -0.2).normalize();
- solveElbow(s, this.grip, r.a, r.b, this.pole, this.elbow);
- aimBone(r.upper, r.fore, this.elbow);
- aimBone(r.fore, r.hand, this.grip);
+ this.target.copy(hold.wristR).applyQuaternion(this.qB).add(this.grip);
+ this.pole.set(-this.lft.x * 0.8, -1, -this.lft.z * 0.8).addScaledVector(this.dir, -0.25).normalize();
+ this.reach(r, this.target, this.pole, this.qHand.copy(this.qB).multiply(hold.handR), f.ik);
}
const l = this.left;
if (l) {
- const target = p.shieldUp
- ? tmpB.set(x + Math.sin(aimYaw) * 0.42 - rx * 0.05, floorY + 1.3, z + Math.cos(aimYaw) * 0.42 - rz * 0.05)
- : this.fore;
- const s = l.upper.getWorldPosition(new Vector3());
- this.pole.set(-rx * 0.6, -1, -rz * 0.6).normalize();
- const t = target.clone();
- solveElbow(s, t, l.a, l.b, this.pole, this.elbow);
- aimBone(l.upper, l.fore, this.elbow);
- aimBone(l.fore, l.hand, t);
+ if (f.shield > 0.01) {
+ // The shield arm: forearm up in front of the chest, palm out, the emitter facing the aim.
+ const chest = b.Chest ? b.Chest.getWorldPosition(tmpA) : tmpA.set(p.x, floorY + 1.25 * s, p.z);
+ const shieldAt = this.elbow.copy(chest).addScaledVector(this.fwd, (0.34 + 0.13 * f.parryPush) * s)
+ .addScaledVector(this.lft, 0.06 * s).addScaledVector(UP, 0.12 * s);
+ const onGun = tmpB.copy(hold.wristL).applyQuaternion(this.qB).add(this.grip);
+ this.target.lerpVectors(onGun, shieldAt, f.shield);
+ tmpQ2.setFromAxisAngle(UP, aimYaw).multiply(tmpQ.setFromAxisAngle(tmpA.set(1, 0, 0), -Math.PI / 2))
+ .multiply(tmpP.setFromAxisAngle(tmpB.set(0, 0, 1), Math.PI));
+ this.qHand.copy(this.qB).multiply(hold.handL).slerp(tmpQ2.multiply(hold.handL), f.shield);
+ } else {
+ // A vent racks the receiver: reach to its left side, pull back, return.
+ const v = f.vent;
+ const k = f.ventPull;
+ const reach = Math.min(1, k / 0.3);
+ const pull = k < 0.3 ? 0 : k < 0.7 ? (k - 0.3) / 0.4 : 1 - (k - 0.7) / 0.3;
+ const side = tmpB.set(0.07 * s, 0.03 * s, (0.1 - 0.07 * pull) * s);
+ this.target.copy(hold.wristL).lerp(side, v * reach).applyQuaternion(this.qB).add(this.grip);
+ this.qHand.copy(this.qB).multiply(hold.handL);
+ }
+ this.pole.set(this.lft.x * 0.6, -1, this.lft.z * 0.6).normalize();
+ this.reach(l, this.target, this.pole, this.qHand, f.ik);
+ }
+ }
+
+ // Head: toward what it looks at (the opponent, else the aim); in the sights it settles on the stock.
+ if (f.ik > 0 && b.Head) {
+ const head = b.Head.getWorldPosition(tmpA);
+ let lookYaw = aimYaw;
+ let lookPitch = p.aimPitch;
+ if (cues.lookAt) {
+ const dx = cues.lookAt.x - head.x;
+ const dz = cues.lookAt.z - head.z;
+ lookYaw = Math.atan2(dx, dz);
+ lookPitch = Math.atan2(cues.lookAt.y - head.y, Math.hypot(dx, dz) || 1);
}
- } else if (p.alive && b.Hand_R) {
- // Rolling: the blaster stays in the right hand.
- b.Hand_R.getWorldPosition(bl.position);
- bl.quaternion.copy(root.quaternion);
- bl.updateMatrixWorld(true);
+ const yawRem = Math.max(-1.1, Math.min(1.1, wrap(lookYaw - f.legsYaw - f.twist * 0.8))) * f.ik;
+ const pitchRem = Math.max(-0.7, Math.min(0.7, lookPitch - f.pitch * 0.6)) * f.ik;
+ turnBone(b.Neck, UP, yawRem * 0.4);
+ turnBone(b.Head, UP, yawRem * 0.6);
+ const headLeft = tmpB.set(Math.cos(lookYaw), 0, -Math.sin(lookYaw));
+ turnBone(b.Neck, headLeft, -pitchRem * 0.35);
+ turnBone(b.Head, headLeft, -pitchRem * 0.65 + f.ads * 0.08);
+ turnBone(b.Head, this.fwd, f.ads * 0.16);
}
this.blaster.setHeat(p.heat, p.venting, p.overheated, timeS);
- if (!p.dodging && p.alive) this.cloak?.update(dt, x, z, this.legsYaw);
- this.shadow.position.set(x, floorY + 0.008, z);
+ if (p.alive && f.ik > 0.5) this.cloak?.update(dt, p.x, p.z, f.legsYaw);
+ this.shadow.position.set(p.x, floorY + 0.008, p.z);
this.shadow.scale.setScalar(p.alive ? 0.95 : 1.6);
- if (deck) this.light.update(deck, x, floorY, z, dt);
+ if (deck) this.light.update(deck, p.x, floorY, p.z, dt);
+ }
+
+ /** Two-bone IK of one arm to a wrist target with a hand rotation, blended with the clip's pose by `w`. */
+ private reach(arm: Arm, target: Vector3, pole: Vector3, handQ: Quaternion, w: number): void {
+ const saved = this.saved;
+ if (w < 1) { saved[0].copy(arm.upper.quaternion); saved[1].copy(arm.fore.quaternion); saved[2].copy(arm.hand.quaternion); }
+ const s = arm.upper.getWorldPosition(new Vector3());
+ solveElbow(s, target, arm.a, arm.b, pole, this.elbow);
+ aimBone(arm.upper, arm.fore, this.elbow);
+ aimBone(arm.fore, arm.hand, target);
+ setWorldQuat(arm.hand, handQ);
+ if (w < 1) {
+ arm.upper.quaternion.slerpQuaternions(saved[0], arm.upper.quaternion, w);
+ arm.fore.quaternion.slerpQuaternions(saved[1], arm.fore.quaternion, w);
+ arm.hand.quaternion.slerpQuaternions(saved[2], arm.hand.quaternion, w);
+ arm.upper.updateMatrixWorld(true);
+ }
}
/** Where the blaster's muzzle is in the world (for the flash). */
@@ -326,6 +515,7 @@ export class DuelFigure {
}
dispose(): void {
+ LIVE_BODIES.delete(this);
this.mixer.stopAllAction();
this.mixer.uncacheRoot(this.instance.root);
this.blaster.dispose();