Architecture snapshot: November 2026. This article documents the consolidated ragdoll and joint subsystem (src/engine/physics/solver/, src/engine/physics/ragdoll/, src/engine/runtime/, and src/engine/components/, summarized in docs/ragdoll-joints-architecture.md) inside Gattic's closed-source C++23 Play2Train SDK, as exercised by Robot Universe and its headless MCP runtime. PloppyPals uses its own lightweight PalRagdoll and does not depend on this stack.
Most game ragdoll systems accumulate layers of defensive hacks over time. Someone adds a second hinge solver for elbows, caps joint impulses to stop limbs exploding when a character clips a wall, adds a post-frame teleport projection pass to hide anchor separation, and wires up a per-joint divergence detector that quietly turns off misbehaving constraints. Each workaround masks a symptom while breaking conservation of momentum and turning physical animation into a fragile pile of special cases.
Play2Train takes the opposite bet. Across roughly 68,000 lines of C++23, the engine runs one six-degree-of-freedom (D6) joint type with unified mass- and timestep-independent soft rows, solves active-ragdoll drives as implicit spring-dampers inside the exact same velocity loop as contacts, and enforces a strict solver discipline: no impulse caps, no mass-ratio clamp, no projection pass, no snapshot rollback, and no per-joint divergence handling. When a character is knocked down, recovery advances through a deterministic, forward-only five-stage state machine (Settle → Stagger → Brace → GetUp → Standing) with per-stage timeout budgets. Per-bone collision hulls are built automatically from each bone's skin-weighted visual mesh vertices, and a single whole-ragdoll fail-safe watches body invariants and freezes the entire articulation if specific kinetic energy ever crosses 1e6 J/kg.
Layered layout and the 68k-line footprint
The subsystem is organized into four layers with strictly downward dependencies: runtime → asset → solver. Crucially, Scene includes no ragdoll header at all — per-scene ragdoll worlds plug into the scene's generic character-pose override slot and receive teardown notifications through a lifecycle subscription.
| Layer | Directory | Files / lines | Responsibility |
|---|---|---|---|
| Joint solver | src/engine/physics/solver |
45 / 11.1k | D6 JointConstraint, dense JointRegistry, soft SI rows, implicit drive rows, post-substep NGS linear pass |
| Ragdoll asset | src/engine/physics/ragdoll |
73 / 14.8k | Sidecar v2 schema, loader, immutable RagdollDefinition, validator, defaults table, humanoid authoring generator, bone hull builder |
| Ragdoll runtime | src/engine/runtime (*Ragdoll*, recovery/) |
195 / 40.1k | Per-scene RagdollWorld, transactional activation, PoseBridge, ActiveRagdollDriver, staged recovery, corpse lifecycle, fail-safe, diagnostics |
| Ragdoll components | src/engine/components (*Ragdoll*) |
9 / 1.9k | Per-entity RagdollInstanceComponent, snapshots, pose drives, pose override contract |
Why does a clean single-joint design still span ~67.8k production lines (versus the original consolidation plan's 25–30k rough estimate)? Because the solver itself is only 16% of the stack (11.1k lines, including contact-path orchestration). Nearly 60% lives in production runtime policy: transactional activation with full rollback of bodies, joints, and self-collision exclusions; render-pose publication across full, partial, and distance-LOD ragdolls; physical-animation stiffness transitions and hit weakening; staged get-up recovery and corpse budgeting; and structured diagnostics wired into RagdollDiagnosticSchema.h.
One D6 joint type and soft rows without magic crutches
Every joint in Play2Train — spine, neck, shoulder, elbow, hip, knee, ankle, wrist, toe — is an instance of one type: JointConstraint. There is no inheritance hierarchy and no per-kind switch table inside the inner loop.
JointDefinitionholds the authored D6 configuration: body pair, explicit parent and child constraint frames (JointConstraintFrames), per-axis motion (Locked | Limited | Free) across 3 linear and 3 angular axes, limit bounds (plus optional restitution and axis friction), linear and angular drive profiles and targets, break thresholds, andJointSolverConfig(ngsIterations = 30,ngsBeta = 0.8).JointSolverStateholds everything physics snapshots save and restore: warm-start impulse accumulators (lambdaPosition,lambdaAxis,lambdaDrive), NGS multipliers, linear and angular residuals,enabled/brokenflags, and island assignment.JointRegistrystores all constraints densely in flat arrays addressed by a strongJointIdhandle plus storage index.RagdollJointRuntimeowns the registry and binds it intoPhysicsSystem; any attempt toAdd,RemoveByIds,Activate, orDeactivatewhile the physics step is active (ScopedPhysicsStep) is rejected deterministically.
Inside one substepped physics frame
Substepping belongs to the world, not individual joints (EngineConfig::physics.solverSubsteps, default 4, yielding a h = 1/240 s substep at 60 fps). Independent solver islands touch disjoint bodies, contact pairs, and joints, so ExecuteIslandVelocityPhases runs multi-island scenes in parallel while keeping single-island scenes inline with zero scheduling overhead.
The ordering inside each substep is deliberate:
- Warm start & row rebuild.
JointSI_BeginSubstepandBeginPoseDriveSubsteprebuild every joint and drive Jacobian at the body's current pose and apply the warm-start impulses carried from the previous substep. - Unified velocity iterations. Contacts, world-space pose-drive rows, joint drive rows, and soft D6 anchor/limit rows solve inside the same Sequential Impulses (SI) loop. Drives always run before anchor and limit rows so an aggressive muscle target can never overpower a bone limit or pull an elbow backwards.
- Body integration. Velocities integrate body positions and orientations forward by
h = Δt / 4. - Bias-free relax pass.
RelaxJointVelocitiesruns one velocity iteration withuseBias = falseto bleed off the artificial kinetic energy injected by positional bias during the substep. Drive rows are physical springs rather than position-error bias terms, so they execute unchanged. - Re-evaluation & contact positions. Between substeps, contact geometry and joint Jacobians re-evaluate against the newly integrated poses, and contact NGS position iterations resolve residual overlap.
- Post-substep joint NGS linear pass. Once all four substeps finish, a single nonlinear Gauss-Seidel linear pass corrects anchor drift only (
ngsIterations = 30,ngsBeta = 0.8). During the consolidation effort, dropping this pass allowed high-energy impact transients to exceed the 1 cm anchor gate, so it was explicitly retained while distance LOD (MakeJointSolverLodConfig) scales only its iteration count (100% / 75% / 50% / 35%acrossFull,Reduced,Sparse, andMinimal).
Mass- and timestep-independent soft rows
Instead of tuning ad-hoc Baumgarte factors per body mass, every anchor, locked axis, and angular limit shares one Box2D-style soft-step formulation (MakeJointSoftness in JointCommon.h):
omega = 2 * pi * hertz // hertz = 120 Hz (Nyquist of 240 Hz substep)
a1 = 2 * dampingRatio + h * omega // dampingRatio = 2.0 (overdamped)
a2 = h * omega * a1
a3 = 1 / (1 + a2)
biasRate = omega / a1
massScale = a2 * a3
impulseScale = a3
deltaLambda = -effectiveMass * massScale * (Cdot + biasRate * C)
- impulseScale * accumulatedLambdaSetting kJointSoftnessHertz = 120.0f pins joint stiffness directly to the Nyquist frequency of the default 240 Hz substep (h · ω = π), and kJointSoftnessDampingRatio = 2.0f keeps the response cleanly overdamped so position error decays without ringing. Separated limits act speculatively (bias = C / h) so fast-swinging limbs catch on the limit wall within the substep instead of tunneling past it, and angular rows evaluate exact swing-twist Jacobians rather than small-angle Euler approximations.
Because the soft-step equations are unconditionally well-conditioned for valid rigs, Play2Train strips out the usual solver crutches: no impulse caps on joint rows, no runtime mass-ratio clamp, no teleport projection pass, no snapshot rollback, and no per-joint divergence disabling. Bad rigs are caught before spawning rather than patched inside the solver:
ValidateRagdollAssetrejects any joint whose parent/child mass ratio exceedsdefaults.maxJointMassRatio(default 17.0, sized to cover the anthropometric humanoid template's steepest ratio:spine:neckat 16.8).- Activation validates authored rest-pose anchor alignment and rejects any joint whose parent and child anchors start more than 0.05 m apart before a single physics body is created.
Active ragdolls: implicit spring-damper drives in the contact loop
Active ragdolls — characters that try to hold an animated pose, stagger under an impact, or brace with their arms — fail violently when implemented as explicit forces (F = k·e + c·v) injected before the physics step. At high stiffness, an explicit spring overshoots within one frame and pumps energy into the articulation faster than contact friction can dissipate it.
Play2Train eliminates explicit spring instability by solving every drive as an implicit Euler spring-damper row (JointDriveRow) inside the same velocity loop as contacts and joints (ConfigureJointDriveRow in JointCommon.h):
springDamper = damping + h * stiffness
a = h * springDamper * (accelerationDrive ? 1.0 : invEffectiveMass)
effectiveMass = 1.0 / invEffectiveMass
targetVelocity = (stiffness * error + damping * targetCdot) / springDamper
massScale = a / (1.0 + a)
impulseScale = 1.0 / (1.0 + a)
maxImpulse = maxForce * hEach velocity iteration solves the exact same scalar impulse update as a soft joint row, clamped symmetrically to [-maxImpulse, +maxImpulse]:
delta = effectiveMass * massScale * (targetVelocity - Cdot) - impulseScale * lambda
lambda_next = clamp(lambda + delta, -maxImpulse, +maxImpulse)Because the spring-damper force is evaluated implicitly at the end of the substep, arbitrarily stiff gains stay bounded and warm-started across substeps, while maxForce · h (or maxTorque · h) gives designers a physical strength limit so muscles yield naturally when hit by a heavy object.
The solver exposes two complementary drive surfaces that share this exact kernel:
- Joint drives (
JointConstraintSISolveDrive.h). Linear and angular drives (Twist,Swing1,Swing2, or unifiedSlerpmode) acting along the parent constraint frame's basis between connected bodies. - World-space pose drives (
ConstraintSolverPoseDriveRows.h). Six implicit rows per driven body (3 linear at the body transform origin + 3 angular) pulling a body toward a world-space animated target. Play2Train deliberately keeps pose drives as world-space body rows rather than collapsing them into joint drives: a joint-local motor cannot express a world-space position target or apply any drive to the root pelvis body, and both capabilities are required for upright active ragdolls.
Physical-animation profiles, stiffness blending, and hit weakening
Gameplay code never manipulates drive rows directly. Each frame, ActiveRagdollDriver::UpdateAnimationTargets samples the character's animation into per-body RagdollPoseDrive entries, and ActiveRagdollController (RagdollSystem::ActiveRagdoll()) exposes the single public control surface:
- Subtree physical-animation profiles (
ApplyPhysicalAnimationProfile,DisablePhysicalAnimation) scoped by an optionalrootBodyName(e.g., upper-body physical reaction while legs remain animated, or whole-body when empty). - Smooth stiffness transitions (
TransitionToStiffnessProfile) interpolating over simulation time between namedRagdollStiffnessProfilepresets viaLerpRagdollStiffnessProfile, taking the sorted union of per-body overrides:
| Preset | Global stiffness | Global damping | Per-body overrides |
|---|---|---|---|
Alert |
1.0× |
1.0× |
None — full baseline muscle tone |
Floppy |
0.05× |
0.5× |
None — near-passive slump with moderate damping |
Twitchy |
3.0× |
0.3× |
head (1.5× stiffness, 0.7× damping), spine_03 (0.8× stiffness, 1.2× damping) |
- Production hit weakening (
ApplyHitImpulse), which activates an inactive ragdoll if allowed, applies the impact impulse at the hit point, weakens the physical-animation profile bymotorWeakeningScaleso the character visibly gives way under the blow, and arms recovery.
Staged get-up recovery (Settle → Stagger → Brace → GetUp → Standing)
Getting a physics-driven character back onto its feet without sliding, snapping, or getting permanently stuck upside down on stairs requires decoupling what stage recovery is in from the physics scene itself.
Play2Train models this as a two-level state machine. At the outer level, RagdollStateEnum tracks Inactive (0), Simulating (1), Recovering (2), Sleeping (3), and Frozen (4). While the outer state is Recovering, RecoveryStateMachine (src/engine/runtime/recovery/RecoveryStateMachine.h/.cpp) runs a pure-logic, forward-only substate machine with zero access to Scene, PhysicsBody, or GLBData.
Every tick, the lifecycle controller passes a plain RecoveryStageSignals snapshot (maxBodyLinearSpeed, maxBodyAngularSpeed, staggerOverlayReady, braceContactsValid, getUpClipFinished, and optional request*Now jumps) plus dt, and receives RecoveryStageEvent notifications (Entered, Exited, Timeout).
| Stage | Default budget | Natural early-exit condition | Fallback on timeout |
|---|---|---|---|
Settle |
1.5 s |
maxBodyLinearSpeed < 0.1 m/s and maxBodyAngularSpeed < 0.3 rad/s continuously for 0.25 s |
Emit Timeout → advance to Stagger |
Stagger |
2.0 s |
staggerOverlayReady == true (procedural balance overlay engaged) |
Emit Timeout → advance to Brace |
Brace |
1.0 s |
braceContactsValid == true (procedural arms-down catch established) |
Emit Timeout → advance to GetUp |
GetUp |
3.0 s |
getUpClipFinished == true (face-up / face-down animation clip complete) |
Emit Timeout → advance to Standing |
Standing |
0.0 s (terminal) |
Lifecycle controller reconciles root transform and deactivates ragdoll | Terminal — outer state exits Recovering |
Four small implementation details in RecoveryStateMachine.cpp and RagdollLifecycleRecoverySupport.cpp prevent common recovery bugs:
- Strict forward-only allow-list.
IsValidStageTransitionpermits onlySettle → Stagger → Brace → GetUp → Standing, same-stage refresh, and one explicit shortcut:Settle → GetUp(requestGetUpNow) when a severe knockdown makes procedural stagger/brace pointless. Reverse requests (such asBrace → Stagger) are rejected outright, eliminating state-chatter loops. - Bounce-proof Settle hysteresis. The
settleHoldAccumulator_only increments while both linear (< 0.1 m/s) and angular (< 0.3 rad/s) speeds stay under threshold; any single-frame bounce resets the hold timer to0.0 sso a ragdoll settling on soft geometry or a slope does not prematurely start standing mid-rebound. Non-finite velocity norms return+inf, never masquerading as rest. - Guaranteed termination. Every non-terminal stage has a positive timeout budget (totaling
7.5 sunder defaults, and overridable per authored asset viaMakeBudgetsFromLifecyclePolicy). Even if a gameplay system has not wired realbraceContactsValidsignals yet — or a hand gets snagged on world debris — the budget expires, emitsTimeout, and advances cleanly. - Clip-aligned controller root reconciliation. When
GetUpfinishes and transitions toStanding,TryResolveClipAlignedRecoveryRootaligns the entity's ground-projected yaw (outRotation = ragdollYaw * conj(clipYaw)) and solves the entity root position (pelvisPos - outRotation * clipPelvisPos) from the selected face-up or face-down get-up clip (DetectOrientation) through the renderer's normalization transform, handing control back to the animation state machine with zero teleport pop.
Dead characters follow the sibling corpse path instead: Simulating → Sleeping once aggregate body velocity and joint error stay below rest thresholds (0.05 m/s, 0.30 rad/s, 0.03 m for 60 frames), then Sleeping → Frozen after sleepToFreezeDelay (flipping colliders static to eliminate solver cost), with frozen corpses trimmed only under scene budget pressure.
Automatic collision hulls from skin-weighted vertices
Capsules and spheres work well for soft organic limbs, but hard-surface robots, armored characters, and stylized silhouettes collide awkwardly when wrapped in oversized generic primitives. Hand-authoring custom convex hulls for 14–18 bones per character does not scale either.
Play2Train solves this in RagdollBoneHullBuilder (src/engine/physics/ragdoll/RagdollBoneHullBuilder.h/.cpp) with the ConvexHullFromBone shape type, which builds each bone's convex hull automatically from the visual GLB mesh's skin-weighted vertices.
BuildBoneLocalHull runs four deterministic stages per bone:
- Dominant-weight partitioning. It locates the bone's
(skinIndex, jointSlot)inGLBData, restricts scanning to meshes referencing that skin (plus an optionalhullMeshFilterto exclude loose capes or accessories), and checks each vertex's 4WEIGHTS_0/JOINTS_0influences. A vertex joins the bone's cluster only when that bone is its dominant influence and its weight meetshullWeightThreshold(default0.4, clamped to[0.25, 0.75]for hard-surface humanoid robot hints). - Exact renderer-to-body-local projection. Every accepted vertex is transformed into visual world space using the exact composite matrix the skinning renderer uses (
M_full = entityModel × jointWorldMat × IBM), then inverse-transformed into the rigid body's unit-scale local frame (p_local = R_body⁻¹ · (p_world - t_body)). BecausePhysicsBodytransforms always carry unit scale (scale = 1), baking the scale and normalization transform directly into body-local meters removes every source of unit mismatch between visual mesh and narrowphase collider. - Exporter-resilient cluster validation. Real-world glTF exporters occasionally write raw node indices instead of skin slot indices into
JOINTS_0.ChooseHullClusterbuilds the spec-compliantslotcluster first and falls back to thenodecluster only if the slot cluster fails sanity checks: at least 50 vertices (kMinHullClusterVertexCount), maximum axis spread ≤ 1.0 m (kMaxHullClusterSpread), and origin-to-AABB distance ≤ 0.05 m (kMaxHullOriginOffset). - Bounded QuickHull3D & sidecar cooking. If a dense mesh yields more than
kMaxHullInputPoints = 512points for a bone, the builder applies a deterministic uniform stride downsample before callingPhysicsCache::QuickHull3D. The resulting vertices are serialized into the sidecar'scookedPhysicsblock (RagdollCookedConvexHull). At runtime activation,BuildSpawnBodyColliderSetupnever rebuilds hulls on the hot path — it validates that cooked hull data exists with at least 4 vertices, derives the body's AABB half-extents directly from the hull, and fails closed if a production asset is missing cooked geometry.
Whole-ragdoll fail-safe (1e6 J/kg) and automated gates
Because the solver refuses to hide bugs behind impulse caps or silent per-joint disabling, Play2Train places one explicit, observable circuit breaker at the boundary between physics stepping and render-pose publication: RagdollLifecycleController::EnforceBodyInvariants (src/engine/runtime/detail/RagdollFailSafe.h/.cpp and RagdollLifecycleController_FailSafe.cpp).
Every frame, for every Simulating and Recovering ragdoll, CheckRagdollBodyInvariants walks all spawned bodies and checks two invariants:
- Finite body state (
NonFiniteBodyState). Position, rotation quaternion, linear velocity, and angular velocity must all be finite across every body. - Bounded specific kinetic energy (
EnergyExplosion). The checker sumsbody->ComputeKineticEnergy()across all dynamic bodies, divides by their total dynamic mass (specificKineticEnergy = kineticEnergy / dynamicMass), and tests!(specificKineticEnergy <= 1.0e6f)— an inverted comparison that deliberately catchesNaNoverflow alongside extreme finite energy.
// Kinetic energy per kilogram of ragdoll mass above which motion is a
// numerical explosion, not gameplay. 1e6 J/kg is an RMS body speed of about
// 1.4 km/s; the most energetic measured scenario, a synthetic far-off-centre
// strike, peaks at 3.0e4 J/kg.
inline constexpr float kRagdollExplosionSpecificKineticEnergy = 1.0e6f;An aggregate specific kinetic energy of 1e6 J/kg corresponds to an RMS body velocity of sqrt(2 × 10⁶) ≈ 1.41 km/s — over Mach 4 across the entire character. By contrast, Play2Train's most violent benchmarked gameplay input (a synthetic far-off-center strike) peaks at 3.0e4 J/kg, leaving a 33× safety margin so legitimate high-energy impacts never false-trigger while true numerical explosions are caught on the very first frame.
When either invariant trips, TripFailSafe executes a clean four-step containment sequence before RagdollPublishedPoses::PublishScene publishes the frame:
- Log loudly at
ERROR(event=ragdoll_fail_safe_trip) with entity ID, collision group, model path, trigger label (non_finite_body_stateorenergy_explosion), offending body index, measured specific kinetic energy, and previous state. - Restore the last valid body pose (
RestoreLastValidBodyPose), rewinding body transforms to the last clean frame recorded byRecordLastValidBodyPose(seeded at activation commit). Because publication has not run yet, the static colliders and the visible rendered skeleton remain in exact agreement. - Freeze the entire ragdoll (
ForceSleepingCorpse → ApplyFreezeBodiesAction → EnterFrozenCorpse) rather than disabling a single joint. - Record a
FailSafeTrippedsession event and enqueue the entity as a frozen corpse for budget management — ensuring both live telemetry and automated CI gates treat any trip as a hard failure.
Structural and behavioral release gates
Shipping without solver workarounds only holds if regressions are caught mechanically. Play2Train and Robot Universe enforce three complementary gates:
- Joint-correctness & hero-ragdoll gates (
p2t-ragdoll-runtime-tests joint-correctness+ bench gates): limit violation p99 ≤ 2° and max ≤ 5°; anchor separation ≤ 1 cm; relative momentum drift ≤ 1e-4; zero non-finite states and zero fail-safe trips across shipped scenarios; hero-ragdoll frame budget 2000 µs median / 2500 µs p95. - Golden trajectories & render-bridge goldens tracked in
wiki/subsystem-plans/2026-07-30-ragdoll-test-manifest.json, verifying end-to-end physics and skinning output stability. - Structural quality gates (
scripts/structural-quality-gates.shin Robot Universe) that fail CI if any retired solver, activation, diagnostic, asset, or state identifier reappears, pin theRagdollSystem::Implmodule set and canonicalRagdollDiagnosticSchema.hwire names, and generate per-layer line-count reports (ragdoll-structural-report.py).
Explicit design boundaries and trade-offs
Several architectural decisions documented in docs/ragdoll-joints-architecture.md deliberately trade theoretical minimalism for operational clarity:
- No runtime auto-generation on activation.
BuildAutoGeneratedHumanoidRagdoll(driven by the 18-partHumanoidIdentityTable.hcovering pelvis through hands and toes) is strictly an authoring tool that emits<model>.ragdoll.jsonsidecars. CallingRagdollSystem::Activateon a model without a sidecar returnsMissingSidecarrather than guessing bone limits at runtime. - Joint NGS linear pass stays, projection passes do not. Pure velocity-level soft rows held angular limits well, but high-impulse strikes briefly pulled anchors beyond the 1 cm gate. Keeping a single anchor-only NGS linear pass (
ngsIterations = 30,ngsBeta = 0.8) solved impact separation without reintroducing full rigid-body projection hacks. - Entity-component instance storage.
RagdollInstanceComponentstays on the entity rather than moving intoRagdollWorldtables so the renderer, game systems, and MCP inspection tools can query per-entity state without coupling to aRagdollSystemhandle or leaking ragdoll headers intoScene. - Single-source observability. All wire metrics come from
RagdollDiagnosticSchema.h, anomalies log through centralGLoggerwith repeat budgets, verbose traces sit behindP2T_LOG_VERBOSEchannels (Ragdoll,Physics), and no subsystem source reads environment variables directly or maintainsthread_localstate.
Sources and further reading
- Play2Train SDK (closed-source) — Gattic's internal C++23 engine containing
docs/ragdoll-joints-architecture.md,src/engine/physics/solver/(JointCommon.h,ConstraintSolverIslandExecution.h,JointConstraintSISolveDrive.h,ConstraintSolverPoseDriveRows.h),src/engine/physics/ragdoll/(RagdollBoneHullBuilder.h/.cpp,RagdollDefaultValues.h,RagdollStiffnessProfile.h/.cpp), andsrc/engine/runtime/(recovery/RecoveryStage.h,recovery/RecoveryStateMachine.h/.cpp,detail/RagdollFailSafe.h/.cpp). - AI-Drivable Animation Authoring in Play2Train — companion architecture deep dive covering Play2Train's embedded Unix-socket posing server, two-bone IK, timeline HUD, and procedural quadruped generator.
- Robot Universe (closed-source, in development) — open-world cyberpunk action adventure set in Haven City, consuming
RagdollSystem, MCP ragdoll telemetry (get_ragdoll_metrics), and structural quality gates. - PloppyPals (closed-source, in development) — companion creature-care game built on
Play2Train::Engine.