Architecture snapshot: November 2026. This article documents the animation authoring subsystem (src/engine/authoring/) and procedural quadruped generator (tools/quadruped-generator/) inside Gattic's closed-source C++23 Play2Train SDK, along with the in-game timeline HUD panel wired into Robot Universe. Interfaces and defaults continue to evolve as internal engine development progresses.
Most game animation pipelines treat authoring and runtime as two separate worlds. Poses are built in an external digital content creation (DCC) suite, exported to glTF or FBX, imported into the engine, bound to a blend tree, and inspected only after the round trip finishes. If an AI agent wants to author a walk cycle, adjust a paw placement, or prototype a creature emote, that gap becomes a wall: the agent cannot easily see the actual rendered character, cannot iterate pose by pose inside the engine's lighting and skinning path, and cannot hand off mid-edit to a human reviewing the same clip.
Play2Train takes a different approach by embedding an AI-drivable animation authoring server directly inside the engine. A Unix domain socket speaks newline-delimited JSON (NDJSON) with commands such as set_bone_rotation, set_ik_target, mirror, add_keyframe, preview_capture, undo, and export_clip. An agent can inspect a skeleton, pose limbs in character space or with analytic two-bone IK, capture a base64 PNG from its own preview camera, critique the frame, record scoped keyframes, and either bake clips directly into the runtime blend tree or splice them out as standalone glTF 2.0 .glb files — all serialized on the same game thread and timeline state as the human HUD panel.
Alongside that server sits a companion CLI tool, p2t-make-quadruped, that generates a complete, rigidly skinned 22-joint quadruped .glb directly from parametric body-plan dimensions — no external 3D editor required to stand up a rigged creature and start animating it.
Why build authoring inside the engine
Moving pose authoring into the runtime solves three problems that external scripting plugins struggle with:
- Ground-truth rendering. The preview frames an agent inspects come from the exact same GLB skinning palette, render normalization transform, and HDR lighting pipeline that the game uses — not a viewport approximation in another tool.
- A tight visual feedback loop. One socket line moves a limb; the next returns an ACES-tonemapped PNG inline as base64 JSON. The agent does not need screen-scraping, window focus, or temporary file juggling.
- Human and AI co-editing on one state. A human watching the viewport can hit play, toggle loop, or magnetically drag-scrub the
TimelinePanelHUD across keyframes that an agent just wrote, without fighting over camera control or corrupting pose history.
The subsystem lives cleanly inside Play2Train::Engine under src/engine/authoring/, keeping almost all math, protocol parsing, queuing, posing, IK, clip storage, baking, glTF splicing, and quadruped generation GL-free so they can be unit-tested deterministically without an OpenGL context. Only AuthoringBridge touches the live renderer and scene graph.
Architecture and threading model
The authoring bridge splits cleanly across two threads — a dedicated socket IO thread and the engine's main game thread — bridged by a synchronous FIFO command queue (AuthoringCommandQueue).
Here is how a frame flows when a host application starts the bridge (for example via --authoring-bridge [socket_path] --authoring-model <path> in Robot Universe's EngineApp):
- Socket ingress on the IO thread.
AuthoringSocketServeropens anAF_UNIX,SOCK_STREAMsocket — defaulting to$XDG_RUNTIME_DIR/play2train-authoring.sock(falling back to/tmp/play2train-authoring.sock). It unlinks any stale socket file on startup, caps each request line at 1 MiB (kMaxRequestBytes), strips optional\r, parses JSON viaParseCommandLine, and submits the typedAuthoringCommandintoAuthoringCommandQueue::SubmitAndWait. - Synchronous handoff without locking the render loop.
SubmitAndWaitpairs the command with astd::promise<AuthoringReply>and blocks the IO thread on the correspondingstd::future. The game thread never blocks waiting for network I/O; it only swaps out the pending deque under a short mutex lock. - Post-render drain on the game thread. Immediately after
Render()finishes each frame, the host callsAuthoringBridge::DrainAndExecute(dtSeconds). Because the OpenGL context is current and the frame has just been rendered, every queued command executes in strict FIFO order on the game thread, updatesGLBModelRenderer::SetAuthoringNodeStates, and fulfills its promise. - Shared playback and HUD serialization. Immediately after draining commands,
DrainAndExecuteadvancesAuthoringTimelinewhen playback is active and streams the sampled pose intoAuthoringPoseModel::LoadPose. Human HUD actions (UiPlay,UiPause,UiScrub,UiSetLoop) execute on that same game thread and call the exact same timeline and sampling helpers (UiScrubmirrors the socketset_timehandler). - Deadlock-free shutdown. On teardown,
AuthoringBridge::Shutdownexplicitly callsm_queue.Shutdown()beforem_server.Stop(). Failing any in-flight promises first guarantees the IO thread wakes fromfut.get()and exits cleanly beforem_server.Stop()joins it.
Sharing the timeline with the human HUD panel
In Robot Universe, TimelinePanel (src/ui/game/TimelinePanel.h) is a pure view/controller HUD strip (52 px tall, up to 640 px wide) layered over the live scene. Each frame it receives a read-only TimelineUiState snapshot from AuthoringBridge::GetTimelineUiState() containing the clip name, current playhead time, duration, play/loop booleans, and the deduplicated sorted union of bone and root keyframe times (CollectClipKeyTimes).
The panel renders golden keyframe ticks along the scrubber track, a play/pause button, a 0.00 / 0.00 s readout, and a loop toggle. Dragging the track automatically pauses playback (standard DCC behavior) and magnetically snaps to nearby keyframe ticks within 6 pixels (kSnapPx = 6.0f). It hides itself whenever no keyframes exist yet or a loading screen is active, and because LoadPose during scrubbing and playback deliberately skips pushing to the undo stack, dragging the timeline never wipes out the agent's or artist's pose undo history.
The closed-loop agent workflow
An agent interacting with the socket follows a tight five-stage loop: discover the rig, pose bones or limbs, inspect rendered frames from an independent camera, record explicitly scoped keyframes, and persist or export the result.
Wire protocol and command surface
Every request is a single compact JSON line with an optional numeric id, a required method, and an optional params object. Every reply is a single compact JSON line with id, boolean ok, and either result or error:
{"id": 1, "method": "get_skeleton"}
{"id": 1, "ok": true, "result": {"species": "quadruped", "ik_limbs": ["front_leg.L", "front_leg.R", "hind_leg.L", "hind_leg.R"], "bones": [...], "nodes": [...]}}AuthoringBridge implements 29 methods grouped into six functional areas:
| Group | Methods | Purpose |
|---|---|---|
| Rig inspection | get_status, get_bones, get_skeleton |
Query subject entity, raw node names, detected species (humanoid / quadruped / unknown), semantic bone slots, and verified ik_limbs |
| Posing & history | set_bone_rotation, set_root_transform, set_ik_target, mirror, reset_pose, undo, redo |
Pose individual bones (Euler degrees or quaternion, "character" or "local" frame), solve 2-bone IK limbs, move root, mirror bilaterally, and traverse 100-step pose history |
| Preview camera | orbit_subject, frame_bone, set_preview_camera, get_preview_camera, reset_preview_camera |
Aim the AI's isolated preview camera (m_previewCamera) around the subject or a specific posed joint without moving the human viewport camera |
| Frame capture | preview_capture, capture |
Render from the AI preview camera (preview_capture) or read back the main default framebuffer (capture), returning PNG bytes as png_base64 with width and height |
| Timeline & keys | new_clip, add_keyframe, delete_keyframe, list_keyframes, set_time, play, pause, get_timeline |
Manage clip channels, upsert/remove keys, inspect key times, scrub playhead, and control playback/looping |
| Persistence & export | save_clip, load_clip, list_clips, export_clip |
Save/load p2t-authoring-clip JSON under authored-clips/, or bake and splice the clip into a standalone glTF 2.0 .glb |
A concrete session transcript
Because the protocol is plain newline-delimited JSON over a Unix socket, any language — or a quick Python client inside a coding agent — can drive a complete animation pass:
{"id": 1, "method": "new_clip", "params": {"name": "dog_paw_lift"}}
{"id": 2, "method": "set_ik_target", "params": {"limb": "front_leg.L", "target": {"x": 0.15, "y": 0.24, "z": 0.62}, "space": "character", "orient": "keep"}}
{"id": 3, "method": "orbit_subject", "params": {"yaw_deg": 35, "pitch_deg": 12, "distance": 2.4}}
{"id": 4, "method": "preview_capture", "params": {"max_resolution": 512}}
{"id": 5, "method": "add_keyframe", "params": {"time": 0.4, "bones": ["front_upper.L", "front_lower.L", "front_paw.L"], "root": false}}
{"id": 6, "method": "mirror", "params": {"direction": "L2R"}}
{"id": 7, "method": "undo"}
{"id": 8, "method": "save_clip", "params": {"name": "dog_paw_lift"}}
{"id": 9, "method": "export_clip", "params": {"name": "dog_paw_lift"}}A few deliberate guardrails stand out in AuthoringProtocol.cpp and AuthoringBridge.cpp:
- Mutual exclusion on rotations.
set_bone_rotationrequires exactly one ofeuler_deg(3-element array, degrees) orquat({x, y, z, w}, normalized on ingress with a near-zero norm rejection< 1e-12). Providing both or neither fails cleanly. - Explicit keyframe scoping.
add_keyframerejects ambiguous "key everything" calls. The caller must specify either a single"bone"or an explicit"bones"array and an explicit boolean"root"flag. All requested bone names are validated before any channel is written so a typo fails atomically. - Zero-key safety. Until a clip has at least one bone or root key,
SampleAndPushAtis a no-op so scrubbing an empty clip never overwrites the live working pose with bind rest.
Coordinate frames, mirroring, and two-bone IK
Getting an AI agent to pose arbitrary glTF rigs reliably is notoriously fragile if the agent has to guess each rig's local bone axes. Different exporters orient shoulders, spines, and thighs along wildly different local axes. Play2Train isolates agents from those rig quirks with semantic bone maps, character-frame rotations, and a clean separation of three coordinate spaces.
Species detection and semantic bone maps
When a subject loads, SubjectRig runs both BuildHumanoidBoneMap (21 slots: 5 center-line + 8 bilateral pairs) and BuildQuadrupedBoneMap (22 slots: 8 center-line including tail_0..2 + 7 bilateral pairs) against the GLB's node names, then selects the winning species via DetectSubjectSpecies:
- Quadruped wins when at least 4 of its 6 per-side leg slots resolve on each side and its total resolved slot count exceeds the humanoid map's total.
- Humanoid wins next if it resolved any slots; otherwise a legless quadruped match still beats Unknown.
- Raw node names always work, even on
unknownspecies rigs, via exact and substring fallback.
Crucially, SubjectRig gates all slot lookups on the winning species. As the header notes, running the quadruped matcher on a humanoid rig would capture LeftForeArm/RightForeArm into the front-lower leg slot — so the non-winning map is never consulted after detection. get_skeleton also advertises only ik_limbs whose three-joint chains actually verify as contiguous parent-child triples (parents[mid] == root && parents[end] == mid).
Character-frame deltas and sagittal mirroring
By default, set_bone_rotation operates in frame: "character" (axes +X right, +Y up, +Z forward; Euler composition q = Rz(z) · Ry(y) · Rx(x)). CharacterFrameRotation converts a character-frame delta q_char into the node's parent-local quaternion against the rig's rest pose:
L_local = conj(P_rest) * q_char * P_rest * R_restwhere P_rest is the parent's rest world rotation and R_rest is the bone's rest local rotation. Because q_char is expressed in a fixed character basis independent of how the rig's joints were oriented in Blender or Mixamo, bilateral mirroring (mirror with "L2R", "R2L", or "swap") reduces to a single exact reflection across the sagittal plane (normal +X):
(x, y, z, w) -> (x, -y, -z, w)Left/right pairs copy or swap their reflected deltas, and center-line bones (hips/pelvis, spine, chest, neck, head, tail_0..2) reflect in place so an asymmetric lean mirrors cleanly. When an agent or solver needs exact rig-axis control, frame: "local" writes R_rest · q_local directly. If a clip channel already has keys in one frame and a new key arrives in the other (for example, an FK key at t = 0.0 followed by an IK key at t = 0.4), KeyframeScopedPose automatically converts the incoming delta via AuthoringPoseModel::ConvertDeltaFrame rather than flipping the channel's frame flag and corrupting earlier keys.
Stateless one-shot two-bone IK
set_ik_target supports four limb chains per species:
- Humanoid:
arm.L,arm.R,leg.L,leg.R(with aliaseshand.*andfoot.*). - Quadruped:
front_leg.L,front_leg.R,hind_leg.L,hind_leg.R(with aliasespaw.FL,paw.FR,paw.HL,paw.HR).
Rather than introducing a persistent runtime IK graph that fights manual FK edits, SolveLimbIk is one-shot and stateless:
- Space reconciliation. A target in
"character"space transforms byentityModel; a target in"world"space maps throughRenderedWorldToEntityWorld(entityModel, norm, target)so coordinates match the normalized mesh the human actually sees on screen. - Deterministic pole cascade. If the caller supplies an explicit
polevector, the solver uses it. Otherwise it derives the bend plane from the limb's current posed bend, falling back to the rest-pose bend, and finally to a deterministic perpendicular vector if the limb is collinear. - Analytic solve + end orientation.
SolveTwoBoneIKandApplySolvedTwoBoneChaincompute hierarchy-correct local rotations forrootNodeandmidNode. Whenorient: "keep"is requested,SolveLimbIkalso solves a compensating delta onendNodeso the hand or paw preserves its pre-solve world orientation. - Atomic undo batch. All 2 or 3 resulting local deltas are committed through
AuthoringPoseModel::SetBoneRotationsLocalBatchas a single undo entry — oneundoreverses the entire IK placement. The reply reportsreached(withinkIkReachEps = 1e-3f, 1 mm) andachievedcoordinates transformed back into the request's coordinate space.
Isolated preview camera and visual feedback
Letting an AI agent hijack the user's viewport camera while inspecting a shoulder joint would make co-editing unusable. AuthoringBridge therefore owns a completely separate Camera m_previewCamera initialized to a default standing-figure orbit (yaw = 0°, pitch = 10°, distance = 7.0 m aimed at the rendered subject torso center).
orbit_subjectplacesm_previewCameraat spherical(yaw_deg, pitch_deg, distance)around the subject's rendered center (tracking root-motion moves automatically).frame_boneevaluates forward kinematics (BonePosedWorldPosition) through the render normalization matrixNto locate any posed joint in rendered world space, then orbits the preview camera close to that joint (defaultdistance = 2.0 m,yaw = 20°,pitch = 10°).preview_captureinvokesGameEngine::RenderAuthoringPreviewusingm_previewCameraat the window's aspect ratio with the longest side capped atmin(max_resolution, 1024)(default512). The linear HDR float buffer is vertically flipped from OpenGL bottom-up to PNG top-left, passed throughTonemapLinearToSrgb8(Narkowicz ACES filmic approximation + exact sRGB transfer function on RGB, linear clamp on alpha), encoded in memory viastbi_write_png_to_mem, and returned inline aspng_base64.
When an agent wants the exact composited main viewport instead (including HUD overlays or the human's camera angle), capture reads back the default framebuffer with glReadPixels, downscales to the same resolution cap, and returns png_base64.
Keyframing, runtime baking, and glTF 2.0 export
Authored clips live in AuthoringClip as time-sorted BoneChannel delta quaternions (interpolated via SLERP, endpoint-clamped, with a 1e-4 s key-merge epsilon) plus an optional RootKey track (linear position interpolation + SLERP rotation). From that single representation, Play2Train supports two distinct delivery paths:
| Output path | Command / API | File produced | Best for |
|---|---|---|---|
| Portable clip JSON + runtime bake | save_clip → AuthoredClipLibrary::GetBaked |
authored-clips/<name>.json (p2t-authoring-clip v1) |
Fast edit-save-rebake loops directly inside Play2Train's BlendTree (AuthoredClipNode) |
| Self-contained glTF 2.0 GLB | export_clip → ExportAuthoredClipGlb |
authored-clips/<name>.glb |
External DCC inspection, engine-independent distribution, and standard glTF tooling |
Hot-rebaking straight into runtime blend trees
save_clip validates the clip name via SanitizeClipName (blocking path separators, .., and dotfiles) and writes compact JSON binding each channel by node_name (with a node_index fallback for portability across minor rig revisions).
At gameplay time, AuthoredClipLibrary::GetBaked(name, glb, err) loads the JSON, hashes its raw contents, and caches the baked result by (name, assetContentHash). Because the core authoring workflow is iterative editing, GetBaked re-reads the file and checks the content hash on each request so re-saving a clip triggers an automatic rebake instead of serving stale motion. BakeAuthoredClip converts every authored delta channel into absolute parent-local quaternions and fills unauthored skeleton nodes with constant rest keys so blending with other clips in BlendTree via AuthoredClipNode stays well-defined.
Safe, spec-compliant glTF 2.0 .glb export
export_clip does not require a prior save_clip. It reads the source model's .glb bytes, splits the container via SplitGlbContainer, bakes the authored clip, appends a new animation entry to the glTF JSON and binary buffer (reusing BuildGlbContainer with deterministic 4-byte 0x20 JSON / 0x00 BIN padding), and writes the result atomically via <name>.glb.tmp + std::rename.
Two subtle glTF-validation details handled by ExportAuthoredClipGlb are worth noting:
- Skeleton-subtree scoping and matrix-node hygiene. A loaded GLB's node list includes sibling mesh nodes and importer wrapper nodes above the skeleton, some of which carry
"matrix"transforms that the glTF 2.0 specification forbids animating.ExportAuthoredClipGlbscopes emission strictly to the rootmost skeleton subtree(s) of the authored channels. Unauthored nodes inside that subtree with a"matrix"transform are silently skipped rather than emitting illegal constant-rest channels, whereas an authored channel or root-motion node on a"matrix"transform fails closed with a clear error. - Root-motion parity. During live preview, root keys move the subject entity's
Transform. To match that motion identically in a standalone glTF animation without duplicating{node, "rotation"}targets,ExportAuthoredClipGlbfolds the root track into the resolved skeleton root node over the union of root and local key times:
t_node(t) = pos(t) + rootRot(t) * restT
q_node(t) = rootRot(t) * localRot(t)Companion tool: parametric rigged quadruped generator
Testing and demonstrating non-humanoid animation usually hits an immediate asset bottleneck: finding a cleanly named, permissively licensed, properly skinned quadruped .glb with consistent rest orientations. Play2Train removes that friction with QuadrupedGlbBuilder (src/engine/authoring/QuadrupedGlbBuilder.h) and its standalone CLI p2t-make-quadruped (tools/quadruped-generator/main.cpp).
Built internally as an explicit opt-in CMake target (add_subdirectory(tools/quadruped-generator EXCLUDE_FROM_ALL)), p2t-make-quadruped is completely GL-free and writes a ready-to-animate glTF 2.0 .glb in milliseconds:
cmake --build build --target p2t-make-quadruped --parallel 2
./build/tools/quadruped-generator/p2t-make-quadruped --species dog --out dog.glb
./build/tools/quadruped-generator/p2t-make-quadruped --species cat --out cat.glbExact rig and mesh geometry
Every generated .glb follows a strict, deterministic schema designed to pass both glTF validators and SubjectRig's quadruped auto-detection on first load:
- 24 nodes total:
Root(node 0, excluded fromskin.joints) + 22 canonical joints (nodes 1–22:Pelvis,Spine,Chest,Neck,Head,Tail_0..2,FrontScapula.L/R,FrontUpper/Lower/Paw.L/R,HindUpper/Lower/Paw.L/R) + 1 dedicated mesh node (node 23, identity transform, named afterplan.name, referencingmesh: 0andskin: 0). The scene lists[Root, meshNode]. - Closed-form rest pose and IBMs: 17 of the 22 joints are pure translation-only. Only 5 joints carry non-identity local rest rotations:
Neck(-45°pitch about+X, soHead's local(0, 0, neckLen)offset continues up and forward) and the four paws (FrontPaw.L/R,HindPaw.L/Rat-90°pitch about+X, redirecting local-Yonto world+Zso feet lie flat pointing forward instead of poking into the ground).Tail_0..2bake a-15°downward curve directly into their translation vectors. Inverse bind matrices are computed analytically asR(conj(q)) * T(-t). - Rigidly skinned articulated mesh: Each of the 22 joints gets one axis-aligned box spanning its segment vector padded by
±boneThickness / 2on every axis — 24 vertices (6 faces × 4 vertices with outward right-handed flat normals) and 12 triangles per joint, totaling 528 vertices and 264 triangles (792uint16indices). Every vertex is rigidly weighted1.0to its skin joint index (0..21), shaded with a single matte PBR material (metallicFactor: 0,roughnessFactor: 1).
Comparing the built-in dog and cat body plans
QuadrupedBodyPlan exposes 12 positive length/thickness dimensions (all validated before emission; non-positive values fail closed without touching the output buffer) plus an RGBA baseColor and asset name. The CLI ships two presets — a tan dog default and a compact cool-gray cat whose tail segments stay nearly as long as the dog's relative to its shorter torso:
Because the generated .glb uses the exact canonical joint names expected by QuadrupedBoneMap and reuses BuildGlbContainer from the glTF exporter, passing --authoring-model dog.glb immediately unlocks species: "quadruped", 7 bilateral mirror pairs, 8 center-line bones, all 4 front_leg.*/hind_leg.* IK chains, live preview_capture, and round-trip export_clip back into a playable animated .glb.
Verification boundaries and current limits
One of the deliberate design choices in src/engine/authoring/ is keeping the boundary between pure logic and OpenGL razor-thin:
- GL-free native unit tests. Over two dozen dedicated C++ test suites in the companion regression harness verify protocol parsing, Unix-socket framing, FIFO command queuing, character-frame quaternion math, undo/redo bounds, humanoid and quadruped bone mapping, species detection, two-bone IK accuracy and pole fallbacks, explicit keyframe scoping, SLERP clip sampling, clip baking,
AuthoredClipLibraryhot-rebake caching,AuthoredClipNodeblend-tree evaluation, glTF 2.0 container splicing,TimelineMathsnapping, andQuadrupedGlbBuilderoutput validation — all without initializing a GPU context. - Explicit operational boundaries.
AuthoringSocketServerserves one connected client at a time sequentially on its IO thread and enforces a 1 MiB per-line request cap; it is built for local single-agent or developer-session workflows overAF_UNIX, not public network exposure.- Mirroring applies exact sagittal reflection to
"character"-frame deltas; mirroring a"local"-frame delta is documented in source as best-effort because local bone axes are rig-dependent. QuadrupedGlbBuilderproduces rigidly skinned block-limb proxy geometry (one box per joint) for fast rigging, animation authoring, and IK testing — not organic smooth-skinned production meshes.AuthoredClipBakingbakes bone rotation channels intoBakedAuthoredClipfor in-placeBlendTreeplayback; full root-motion translation and rotation fold-in is preserved in the clip JSON and in standalone glTF.glbexports.
Sources and further reading
- Play2Train SDK (closed-source) — Gattic's internal C++23 engine containing
src/engine/authoring/(bridge, protocol, queue, pose model, IK, baking, glTF export, quadruped builder) andtools/quadruped-generator/(p2t-make-quadruped). - Robot Universe (closed-source, in development) — open-world cyberpunk action adventure set in Haven City, built on
Play2Train::Engineand hosting the--authoring-bridgeCLI entry point and the in-gameTimelinePanelHUD. - PloppyPals (closed-source, in development) — companion creature-care game built on the same
Play2Train::EngineSDK. - GatPi and GatPi-Harness guide — our open-source coding-agent runtime and operational harness used to drive local development tools and sockets.