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
Layered architecture diagram of Play2Train's 67.9k-line ragdoll stack across 322 files. At the top, Robot Universe and MCP drive the RagdollSystem facade while Scene stays isolated via a generic pose override slot and teardown subscription. Layer 1 is Ragdoll Runtime (195 files, 40.1k lines, 59 percent of the codebase) containing the transactional Activation Pipeline, ActiveRagdollDriver, Recovery and Lifecycle controller with the 1e6 J/kg fail-safe, and PoseBridge. Layer 2 splits into Ragdoll Asset (73 files, 14.8k lines, 22 percent) for sidecar v2 parsing, validation, and QuickHull3D bone hull generation, alongside Ragdoll Components (9 files, 1.9k lines, 3 percent). Layer 3 is the Joint Solver (45 files, 11.1k lines, 16 percent) owning the single D6 JointConstraint, dense JointRegistry, 120 Hz soft SI rows, implicit drive rows, and post-substep NGS anchor pass. Arrows point strictly downward from Runtime to Asset to Solver.
Dependencies point strictly downward (runtime → asset → solver), keeping Scene unaware of ragdoll types while runtime policy accounts for 59% of the 67.9k-line stack.

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.

  • JointDefinition holds 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, and JointSolverConfig (ngsIterations = 30, ngsBeta = 0.8).
  • JointSolverState holds everything physics snapshots save and restore: warm-start impulse accumulators (lambdaPosition, lambdaAxis, lambdaDrive), NGS multipliers, linear and angular residuals, enabled/broken flags, and island assignment.
  • JointRegistry stores all constraints densely in flat arrays addressed by a strong JointId handle plus storage index. RagdollJointRuntime owns the registry and binds it into PhysicsSystem; any attempt to Add, RemoveByIds, Activate, or Deactivate while 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.

Pipeline diagram of one physics frame inside ConstraintSolverIslandExecution.h. A four-substep per-island loop runs five stages per substep: (1) JointSI_BeginSubstep and BeginPoseDriveSubstep rebuild Jacobians at the current pose and warm-start carried impulses; (2) unified velocity iterations solve Contact Manifolds, Pose Drive Rows, Joint Drive Rows, and Soft Anchor and Limit Rows in that exact order so limits always have the last word; (3) bodies integrate forward by h = dt/4; (4) a bias-free relax pass solves rows again with useBias=false to strip soft-bias velocity while keeping drive springs active; (5) contact geometry and joint Jacobians re-evaluate and contact NGS position iterations run. After all four substeps finish, a post-substep Joint NGS Linear Pass corrects anchor drift only (30 iterations, beta 0.8, LOD-scaled) and checks break thresholds, followed by the whole-ragdoll fail-safe invariant check before render publication. A bottom banner highlights the 120 Hz, damping ratio 2 soft-row invariant and the omitted workarounds: no impulse caps, no mass-ratio clamp, no projection pass, and no snapshot rollback.
Contacts, world-space pose drives, joint drives, and soft D6 rows converge together inside each velocity iteration, with limits always evaluated last.

The ordering inside each substep is deliberate:

  1. Warm start & row rebuild. JointSI_BeginSubstep and BeginPoseDriveSubstep rebuild every joint and drive Jacobian at the body's current pose and apply the warm-start impulses carried from the previous substep.
  2. 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.
  3. Body integration. Velocities integrate body positions and orientations forward by h = Δt / 4.
  4. Bias-free relax pass. RelaxJointVelocities runs one velocity iteration with useBias = false to 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.
  5. 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.
  6. 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% across Full, Reduced, Sparse, and Minimal).

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):

text
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 * accumulatedLambda

Setting 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:

  • ValidateRagdollAsset rejects any joint whose parent/child mass ratio exceeds defaults.maxJointMassRatio (default 17.0, sized to cover the anthropometric humanoid template's steepest ratio: spine:neck at 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):

text
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 * h

Each velocity iteration solves the exact same scalar impulse update as a soft joint row, clamped symmetrically to [-maxImpulse, +maxImpulse]:

text
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 unified Slerp mode) 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 optional rootBodyName (e.g., upper-body physical reaction while legs remain animated, or whole-body when empty).
  • Smooth stiffness transitions (TransitionToStiffnessProfile) interpolating over simulation time between named RagdollStiffnessProfile presets via LerpRagdollStiffnessProfile, 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 by motorWeakeningScale so 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.

State machine and timeline diagram of Play2Train's staged get-up recovery. The top strip shows the outer RagdollStateEnum lifecycle: Inactive to Simulating to Recovering, plus a dashed corpse path from Simulating to Sleeping to Frozen (or directly to Frozen on a fail-safe trip). Below, Recovering expands into the pure-logic forward-only RecoveryStateMachine with five stages: Settle (1.5 s budget, exits early when linear speed is under 0.1 m/s and angular speed is under 0.3 rad/s continuously for 0.25 s, with bounces resetting the window), Stagger (2.0 s budget, awaits staggerOverlayReady), Brace (1.0 s budget, awaits braceContactsValid), GetUp (3.0 s budget, awaits getUpClipFinished), and terminal Standing (0 s budget, triggers root reconciliation and deactivation). A dashed top arc allows a direct Settle to GetUp jump via requestGetUpNow for severe knockdowns. At the bottom, a proportional 7.5-second timeline bar displays the worst-case timeout budget across Settle, Stagger, Brace, and GetUp.
Forward-only transitions prevent stage oscillation; per-stage timeout budgets guarantee a character can never wedge indefinitely inside recovery.

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:

  1. Strict forward-only allow-list. IsValidStageTransition permits only Settle → 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 as Brace → Stagger) are rejected outright, eliminating state-chatter loops.
  2. 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 to 0.0 s so 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.
  3. Guaranteed termination. Every non-terminal stage has a positive timeout budget (totaling 7.5 s under defaults, and overridable per authored asset via MakeBudgetsFromLifecyclePolicy). Even if a gameplay system has not wired real braceContactsValid signals yet — or a hand gets snagged on world debris — the budget expires, emits Timeout, and advances cleanly.
  4. Clip-aligned controller root reconciliation. When GetUp finishes and transitions to Standing, TryResolveClipAlignedRecoveryRoot aligns 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.

Diagram of Play2Train's skin-weighted bone convex hull pipeline in RagdollBoneHullBuilder. On the left, a visual limb mesh is partitioned around its bone frame: vertices whose dominant skinning weight is at least 0.4 are marked solid dark green and wrapped in a tight QuickHull3D polygon, while lower-weight blend-zone vertices are excluded. Below the illustration, exact transform formulas show M_full = entityModel times jointWorld times IBM, followed by p_local = R_body inverse times (M_full times p minus t_body). On the right, four sequential pipeline stages run: (1) partition skin-bound meshes by dominant weight (with optional meshFilter), (2) validate glTF slot vs node JOINTS_0 clusters requiring at least 50 vertices, spread at most 1.0 m, and origin offset at most 0.05 m, (3) stride-downsample to at most 512 points and compute QuickHull3D, and (4) cook into the sidecar cookedPhysics payload where spawn validates at least 4 vertices and loads unit-scale hulls.
Transforming dominant-weight vertices through the exact renderer skinning matrix into unit-scale body-local meters guarantees 1:1 alignment between visual geometry and physics narrowphase.

BuildBoneLocalHull runs four deterministic stages per bone:

  1. Dominant-weight partitioning. It locates the bone's (skinIndex, jointSlot) in GLBData, restricts scanning to meshes referencing that skin (plus an optional hullMeshFilter to exclude loose capes or accessories), and checks each vertex's 4 WEIGHTS_0 / JOINTS_0 influences. A vertex joins the bone's cluster only when that bone is its dominant influence and its weight meets hullWeightThreshold (default 0.4, clamped to [0.25, 0.75] for hard-surface humanoid robot hints).
  2. 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)). Because PhysicsBody transforms 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.
  3. Exporter-resilient cluster validation. Real-world glTF exporters occasionally write raw node indices instead of skin slot indices into JOINTS_0. ChooseHullCluster builds the spec-compliant slot cluster first and falls back to the node cluster 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).
  4. Bounded QuickHull3D & sidecar cooking. If a dense mesh yields more than kMaxHullInputPoints = 512 points for a bone, the builder applies a deterministic uniform stride downsample before calling PhysicsCache::QuickHull3D. The resulting vertices are serialized into the sidecar's cookedPhysics block (RagdollCookedConvexHull). At runtime activation, BuildSpawnBodyColliderSetup never 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:

  1. Finite body state (NonFiniteBodyState). Position, rotation quaternion, linear velocity, and angular velocity must all be finite across every body.
  2. Bounded specific kinetic energy (EnergyExplosion). The checker sums body->ComputeKineticEnergy() across all dynamic bodies, divides by their total dynamic mass (specificKineticEnergy = kineticEnergy / dynamicMass), and tests !(specificKineticEnergy <= 1.0e6f) — an inverted comparison that deliberately catches NaN overflow alongside extreme finite energy.
cpp
// 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.

Two-part engineering chart. The top panel plots specific kinetic energy on a base-10 logarithmic axis from 10^-3 to 10^7 J/kg, placing four reference regimes: the Settle speed gate at 5e-3 J/kg (0.1 m/s), typical ragdoll falls around 20 to 50 J/kg (6 to 10 m/s impacts), the peak measured synthetic far-off-center strike at 3.0e4 J/kg, and the whole-ragdoll fail-safe trip wall at 1.0e6 J/kg (approximately 1.4 km/s RMS), highlighting the 33x safety margin between peak gameplay energy and the freeze threshold. The bottom panel displays five KPI cards for Play2Train's automated behavior and performance release gates: limit violation p99 at most 2 degrees and max at most 5 degrees, anchor gap at most 1.0 cm (with 0.05 m spawn validation), relative momentum drift at most 1e-4, zero fail-safe trips or non-finite states across shipped scenarios, and a hero-ragdoll performance budget of 2000 microseconds median and 2500 microseconds p95.
The 1e6 J/kg ceiling sits 33× above the most violent measured strike; five automated behavior and performance gates keep the solver inside spec without runtime crutches.

When either invariant trips, TripFailSafe executes a clean four-step containment sequence before RagdollPublishedPoses::PublishScene publishes the frame:

  1. Log loudly at ERROR (event=ragdoll_fail_safe_trip) with entity ID, collision group, model path, trigger label (non_finite_body_state or energy_explosion), offending body index, measured specific kinetic energy, and previous state.
  2. Restore the last valid body pose (RestoreLastValidBodyPose), rewinding body transforms to the last clean frame recorded by RecordLastValidBodyPose (seeded at activation commit). Because publication has not run yet, the static colliders and the visible rendered skeleton remain in exact agreement.
  3. Freeze the entire ragdoll (ForceSleepingCorpse → ApplyFreezeBodiesAction → EnterFrozenCorpse) rather than disabling a single joint.
  4. Record a FailSafeTripped session 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.sh in Robot Universe) that fail CI if any retired solver, activation, diagnostic, asset, or state identifier reappears, pin the RagdollSystem::Impl module set and canonical RagdollDiagnosticSchema.h wire 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-part HumanoidIdentityTable.h covering pelvis through hands and toes) is strictly an authoring tool that emits <model>.ragdoll.json sidecars. Calling RagdollSystem::Activate on a model without a sidecar returns MissingSidecar rather 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. RagdollInstanceComponent stays on the entity rather than moving into RagdollWorld tables so the renderer, game systems, and MCP inspection tools can query per-entity state without coupling to a RagdollSystem handle or leaking ragdoll headers into Scene.
  • Single-source observability. All wire metrics come from RagdollDiagnosticSchema.h, anomalies log through central GLogger with repeat budgets, verbose traces sit behind P2T_LOG_VERBOSE channels (Ragdoll, Physics), and no subsystem source reads environment variables directly or maintains thread_local state.

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), and src/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.