#!/usr/bin/env bun /** * rig-pose — puts motion from a body-18 pose sequence onto a rig rig-c built. * * The command line is the interface for an agent that cannot see the rig: every * refusal names the rule, the object, the value found and the value required, * and the exit code says which kind of outcome it was. */ import { figureScaleLines } from './src/figurescale.ts'; import { accessSync, constants, lstatSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { createHash } from 'node:crypto'; import { FIGURE_SCALE_SPEC, figureScalePath, writeFigureScaleRecord } from './src/figurescalerecord.ts'; import pkg from './package.json' with { type: 'json' }; import { clean, cleanLine, holdRegions, unheldText, untestedText, HOLD_BLEND, HOLD_MIN_SECONDS, HOLD_REACH, HOLD_SPEED, HOLD_SPEED_WINDOW, LEGS, OCCLUSION_SCORE, OCCLUSION_WINDOW, SPIKE_TRUNKS, SPIKE_WINDOW, windowProblem } from './src/clean.ts'; import { convertCoco17, DEPTH_GAITS, readPoseSequence, writePoseSequence, type DepthGait } from './src/pose.ts'; import { FLAT_BAND, SIDE_ON } from './src/depth.ts'; import { runCloth, type ClothArgs } from './src/cloth.ts'; import { parseWindows } from './src/compare.ts'; import { lineOf, Problems, Refusal } from './src/problems.ts'; import { makeOutDirs, planOutDirs } from './src/outdir.ts'; import { runCompare, type CompareArgs } from './src/runcompare.ts'; import { PELVIS_MODES, runPelvis, type PelvisMode } from './src/pelvis.ts'; import { PROVENANCE_FILE } from './src/provenance.ts'; import { runRetarget, type RetargetArgs } from './src/run.ts'; import { runExtract } from './src/runextract.ts'; const HELP = `rig-pose ${pkg.version} — motion from a pose sequence onto a rig-c rig Usage: rig-pose extract --model --map --animation --fps --out [--loop] rig-pose pelvis --pose --out (--frames [--mode silhouette|waistband|below-cover] | --pelvis-keys ) [--person ] rig-pose clean --pose --out [--loop] [--legs 5] [--rest 7] [--hold off] [--depth walk|run] [--coco] [--person ] rig-pose retarget --rig --map --sequence --out [--animation dance] [flags] rig-pose convert --coco --out rig-pose compare --reference --render --map [flags] rig-pose cloth (--rig --map --skirt-slots [--animation dance] [--fps 24] | --frames --pose [--person ] [--alpha-min 16]) [--windows ] --out rig-pose --version | --help extract (compiled source landmarks; clean the output before retarget) --model compiled skeleton.model.json; raw Spine is refused with the rigc ingest/build remedy --map rig-pose-extract-map/1: sidedness and explicit joint/bone/origin-or-tip rows --animation one source animation, or all in source order (numbered files under --out) --fps required positive frame rate; nonloop ends on the first sample at/after duration --out pose sequence and .extract.json provenance; a directory for all --loop one fixed-rate cycle, endpoint excluded; source duration must agree with N/fps pelvis (before clean; rig-c/pose#288) --pose rig-pose-sequence/1 as a scan wrote it, before clean (a cleaned one is refused, PELVIS_AFTER_CLEAN: clean must smooth the track this writes) --out the same sequence with the pelvis track: "pelvisTilt" on every frame and "pelvisSource", written as rig-pose-sequence/1.1. pelvisTilt is Spine degrees (counter-clockwise, y up) of the direction from the figure's right hip to its left — the angle retarget reads off r_hip → l_hip, about 0 facing the camera — or null on a frame the reading declined --frames the picture: one PNG per sequence frame, in file-name order, the sequence's size (no video; extract the frames first). The hip keypoints place the reading; their angle is not read --mode silhouette|waistband|below-cover silhouette (default): the straightest edge of the drawn figure across the hip span (between the two hip keypoints), within 40° of level and one hip width of the hips' height — a drawn pelvis line or the edge of a drawn hip. waistband: the top edge of a garment covering the hips (skirt, shorts) — the colour at the hips' midpoint, its first row in each column of the span. below-cover: for a garment whose top is hidden under another (a sweater's hem over a skirt) — the bottomwear's lower hem across the span, where each thigh leaves it, and the band's top only where nothing covers it; the mean of those cues, declined when they differ by more than 8° (a CUES line per frame; the hip keypoints are printed there, not fitted). Forearms (elbow → wrist) and hands are masked. A frame either cannot read (the pelvis blank, no garment, no straight edge over 60% of the span) is declined, named on a DECLINED line, and written null: marked, not guessed --pelvis-keys the hand override, instead of --frames: rig-pose-pelvis-keys/1, { "spec": "rig-pose-pelvis-keys/1", "keys": [{ "frame", "deg" }], "note"? } — the tilt in pelvisTilt's sense at frames, linear between keys (the short way round) and held outside them; pelvisSource "keys". A frame may be fractional (a drawn key between scan frames, rig-c/pose#294); frames strictly increase within [0, last frame], one outside is refused --person the person to read when the sequence holds more than one; only that person is written clean then smooths pelvisTilt as its own track (the legs' window, wrapped with --loop), and retarget keys the map's pelvis chain (one bone, joints r_hip → l_hip) from it, printing PELVIS: from , swing N°. clean (required before retarget; rig-c/pose#67) --pose rig-pose-sequence/1 as a scan wrote it, or COCO-17 with --coco --out the cleaned rig-pose-sequence/1, carrying the record of what was done ("cleaned"); also writes .figure-scale.json, an external measured input-scale diagnostic --coco read --pose as coco17-sequence/1 and convert it first (neck = the shoulders' midpoint) --person the person to clean when the sequence holds more than one; only that person is written --loop the sequence is one cycle (a gait's strike to strike): every window wraps, last frame to first, and the floor is re-pinned; the sequence is written with "travel": "in-place" (rig-c/pose#92) --legs Savitzky–Golay window over the legs — both hips, knees and ankles (default: 5) --rest Savitzky–Golay window over every other joint (default: 7) n is 1 (none), or odd and ≥ 5: a quadratic through 3 points passes through all three --hips-inferred declare the hips inferred (rig-c/pose#63): r_hip and l_hip are marked "inferred" — a position the detector supplied but did not see — on every frame where they have one, and the record says so (hipsInferred: { by: "declared" }). Positions are unchanged, so retarget's keys are too; its POSTURE line does not read the hip tilt ("hip tilt not read: hips inferred") --hold off turn the stillness hold off (rig-c/pose#91); recorded as hold: "off" --hold-speed the hold's speed limit, trunk lengths per frame (default: 0.015) --hold-reach how far a held joint may lie from its span median, trunk lengths (default: 0.03) --depth walk|run derive each limb segment's depth on every frame (rig-c/pose#281; off by default, and without it the output is unchanged): "depth": { "": { ratio, sign, source: "derived" } }, written as rig-pose-sequence/1.2. ratio = drawn length ÷ rest length (the larger side's 95th-percentile length over the clip); sign +1 when the segment's far end is nearer the camera, -1 farther, 0 flat (ratio within 0.95–1.05, or above it) or undecided (the trunk side-on). Which way a foreshortened segment leans comes from the body, with "forward" the trunk's facing: thigh and forearm forward (a hip flexes forward, an elbow bends back); an upper arm with the opposite leg (forward when the other thigh is the more foreshortened); a shin back (a knee folds it back) — the same in a walk and a run, after the owner's two statements (rig-c/pose#336): a walk's lifted foot is behind the supporting leg, a run's lifted leg is in front, its knee protruding. The gait is this flag's value and decides the joint --draw-order depth reads. tools/skeleton.ts colours the segments by it, and retarget --report orders the limbs front to back by it (layers) In order, each step printed with its figures: (1) spikes — a joint more than 0.2 trunk lengths (neck → mid_hip, the median over the clip) from its 5-frame median takes the median, each listed by frame and joint; without --loop the first and last two frames, whose window a clip end cuts, are not tested and are listed as untested; (2) occlusion — a joint not "observed", or scored under 0.3, takes its 3-frame median; (3) a quadratic Savitzky–Golay per joint, the window cut at the ends (wrapped with --loop); (4) with --loop, the figure moved in y so the lowest ankle over the cycle is where it was before smoothing. A median is per coordinate over the window's frames where the joint has a position. A joint with no position on a frame is left without one (retarget holds it). States and scores are written as read. Jitter: the mean |second difference| of y over every joint, px/f², before and after. (5) the stillness hold (rig-c/pose#91), per joint, on the cleaned positions: a span of ≥ 0.5 s where the joint's 5-frame median speed (its movement from the frame before, in trunk lengths) is under --hold-speed and it stays within --hold-reach of its own span median is written as that median, blended in linearly over the 6 frames before and out over the 6 after (two holds of a joint back to back, or under 6 frames apart, cross-fade over the 6 frames plus the gap, centred on it, SEAM); each hold is printed (HOLD) and recorded with its jitter before and after, and the joints not held where others are are named with the test each fails (UNHELD). retarget --rig the rig spec rigc builds from: a rig.json, or a directory holding one (with its motion.json beside it — @rig-c/parts writes the pair to /rig/); naming the rig.json reads no motion spec, so a rig that needs its motion is given as the directory --map rig-pose-map/1: which bones carry which joints --sequence rig-pose-sequence/1 (body-18 per frame) that rig-pose clean wrote; a sequence without its "cleaned" record is refused (POSE_NOT_CLEANED), naming the clean command to run --pose the same flag under this command's first name (rig-c/pose#243); --sequence is the name rig-c/exam's grader uses. Both given, they must name the same file --out where the motion spec goes: the rig's own animations plus the new one, ready for \`rigc build --rig --motion \`; a directory it names that is not there yet is made once the run is green, and a "made directory" line says so --animation the new animation's name (default: dance); refused if the rig has one by that name --name the same flag under this command's first name (rig-c/pose#243); --animation is the name rigc render uses. Both given, they must be the same name --coco read --sequence as coco17-sequence/1: refused (POSE_NOT_CLEANED) — clean it with rig-pose clean --coco, then retarget the cleaned file --person the person to follow when the sequence holds more than one --base-motion the rig's motion spec, when it is not motion.json beside rig.json --images passed to rigc build: where the rig spec's images are, when its own "images" path does not reach them (a rig.json copied away from its images) --shoulder-lift read supplied calibrated shoulder elevation relative to arms-down rest; unknown refuses --min-score a joint scored below s is not good on that frame and holds its last good value (default: 0.3); a joint with no score is good --smooth an alias kept since rig-c/pose#67: the smoothing is clean's (--legs, --rest); retarget prints "--smooth is carried by clean; ignored" and smooths nothing --flip |off a segment that turns more than degrees in one frame of the pose is spread over the frames around the jump, centred on it, and listed as FLIP (default: off, every turn kept as the pose gives it; 90 is the measured setting) --short |off a segment whose picture length on a frame is under of its median length (seen end-on, or collapsed by blur) has its angle there interpolated from the frames either side, before the flip guard, and listed as SHORT; a run under lasting ≥ 0.15 s is also listed as END-ON (default: off; 0.35 is the measured setting, f in (0, 1)) --bends refuse|clamp a hinge (elbow, knee: any joint inside a chain) bent the wrong way refuses the run (default), or is straightened on that frame and listed --bend-tolerance degrees past straight a hinge may bend the wrong way before it counts (default: 0) --leg-scale |off each leg segment (two of one side's hip, knee, ankle) is scaled along its own x axis (a scalex key) by its picture length over its straight length — the 95th percentile of its picture length, in px — clamped to [min, max], listed as LEG-SCALE with the frames clamped, the limits in px, and on a free leg how far the clamps moved its ankle from the picture's; min and max are shares of that segment's own straight length, not of FEET's leg length (the median hip → ankle --stance is in). FEET prints every segment's picture length ÷ straight (min · median · max) with or without this flag: read the minimum before choosing min. A bone under a scaled one is keyed through its parent's scale (default: off; 0.8,1.05 is the card's range, rig-c/pose#47, read off a dance whose leg picture length ran 0.86–1.18 of its median — not a walk's) --depth-scale foot-only perspective from clean --depth walk|run (+ toward camera); 0 < min <= 1 <= max. Walk uses ankle depth, run knee depth; affine clip extrema per side (zero span: 1). Requires a foot bone at each ankle; scales x/y about its ankle, the sole follows. Keeps the anatomical ankle. DEPTH-SCALE reports per-side min/median/max and clamped frames (default: off). --depth-shade leg slot RGB shade from clean --depth walk|run; k in [0,1], off unless given. --depth-shade-chains with --depth-shade: comma-separated mapped arm/leg chain names; default legs. Mapped arm/leg chain slots only; behind-plane depth normalized per limb over the clip, holds recorded signs and uses the recorded clean SG windows. Preserves alpha and setup RGB; k=1 is an identity. Bone --reduce leaves these dense RGB tracks intact. No far depth: no RGB track. --plant-feet the hip is placed so the supporting foot stays where it took support: the lower ankle in the picture, changing after the other has been 0.02 leg lengths lower for 0.1 s, blended over 3 frames; a jump (both ankles and mid_hip 0.05 leg lengths above their rolling floor — the 95th-percentile y over ±1 s — for ≥ 2 frames) follows the pose's travel and re-plants on landing; a supporting ankle moving > 0.03 leg lengths a frame releases its plant to the other foot, or to the pose's travel, until it is still (< 0.01 for 2 frames) (FEET lines). Every support span is planted on one floor: its supporting ankle moved in y onto the median of the spans' planted heights (world y on the rig, posed by rig-c), the hip and everything above with it; FEET lists each span's shift. On the 3 blend frames the supporting leg's scalex is stretched (k within [0.92, 1.08], past it listed) so its ankle stays on the floor (rig-c/pose#85). On a sequence with "travel": "in-place" (rig-c/pose#92) each supporting foot follows its own ankle's picture x, scaled, instead of being held, no step releases it, and the hip's x drift from the first frame to the last is spread back over the frames, closing the loop --floor with --plant-feet: the floor's world y (rig units, y up) instead of the median --stance with --plant-feet: on a frame outside the jumps, a free ankle within this many leg lengths of the supporting one in the picture, above or below, is planted. The unit is FEET's leg length — each side's median picture length hip → ankle, in px on the FEET line — not LEG-SCALE's straight length (a 95th percentile); STANCE prints the tolerance in px and as a share of the straight leg. Keep it below the lifted-foot threshold the material is graded at: a lifted foot under it is planted too — its leg's scalex keys stretched by k = (root y − floor y) / (root y − ankle y) until the foot reaches the floor, raised or lowered, k within [min(0.92, the leg's own fold on the frame), 1.08] (#95; past it, reported, not forced); above the tolerance the foot is lifted and keeps the pose's height; below it, it is reported (past the tolerance below, #114) and not planted; "the pose's height kept" is printed only on frames no --leg-scale clamp moved the free ankle (STANCE lines; default: off; 0.07 is the card's, rig-c/pose#60, measured on a dance's flat-footed span — not a walk's) --raised-by-head while a set whose arm is drawn raised shows (its "drawn" upper arm within 30° of straight up), that arm's wrist goes where the reference's is against the head, in eye distances: rig head centre + (reference wrist − reference head centre) × rig eye distance ÷ the reference's, per frame; each eye distance is its median over the span. The head centre is the eyes' midpoint; the rig's eyes are the two points the head chain's "a>b" aim names (refused without one, RAISED_HEAD), posed from the targets of the bones above. A target out of the arm's reach, too far or too near, goes to the reach limit on the ray from the head centre toward it and is graded at that placed distance (REACH lines, in eye distances). A two-bone solve on the rig's own lengths keeps the pose's elbow side; when the set's "turn" holds the upper arm the forearm is re-aimed at the wrist. ART-RANGE: a forearm still past its turn, or a held arm leaving the wrist > 0.01 eye distances short of its placed point (the shortfall listed). RAISED lines (default: off; rig-c/pose#62) --draw-order depth key the legs' draw order from the sequence's depth (clean --depth; rig-c/pose#304): on each frame the leg whose depth reads farther from the camera is drawn behind the other, a tie (equal depths) holding the order before, in rig-c's drawOrder timeline. The depth is read at the joint the gait names (rig-c/pose#336): a walk (clean --depth walk) by the ankle, the lifted foot behind; a run by the knee, the lifted leg in front. The legs' slots must fill one unbroken run of the setup draw order (else the pair is not keyed and the line names the slot between); a set's slot goes with the leg it depicts. Refused on a sequence without depth (DRAWORDER_NO_DEPTH), and on a walk cleaned before rig-c/pose#336 (a shin leaning forward: DEPTH_RECLEAN; clean it again). With a layout.json (rig-parts-layout/1) beside the rig and the map's "layout" binding each group to r_forearm | l_forearm against "trunk" (rig-c/pose#346), each forearm is also drawn in front of its target where its depth leans toward the camera by the tie, behind it otherwise; a placement with no binding is refused by name (LAYOUT_UNBOUND), and so is a layout bound to other rig bytes (LAYOUT_RIG_SHA). DRAWORDER lines (default: off) --contact-keys which foot supports, by hand (rig-c/pose#303): rig-pose-contact-keys/1, { "spec": "rig-pose-contact-keys/1", "keys": [{ "frame", "side" }], "note"? }, side l | r | both | none; frames the sequence's, fractional allowed, strictly increasing in [0, N − 1]. A key holds until the next one (contact is a state, not interpolated); before the first key the support is read as without it. On every frame they cover the keys decide, over the vertical speed (#280) and ankle height: none is flight; both, the foot that landed. Malformed keys are refused by name (CONTACT_KEYS). FEET support and stride lines (default: off) --cloth-track fit the skirt's physics constraints to a reference cloth track (rig-c-cloth-track/0, rig-c/pose#34): steps the compiled animations at the track's fps through rig-c's core poser (poseRawAnimationEach with physicsClockStep) over the rig's own values plus SKIRT_PHYSICS_GRID, drops any candidate whose skirt mesh folds on any stepped frame of any animation in motion.json (refusing CLOTH_FIT_FOLDS if all fold), scores lag, swing ratio and overshoot on the retargeted animation against #34's bands, and emits t=0 physics timeline tracks (inertia, strength, damping, mass, mix) onto every animation in motion.json so switching animations keeps the fitted physics. Prints CLOTH lines and records clothFit in --report (default: off) --cloth-windows with --cloth-track: windows in seconds (t0-t1[,t0-t1...]) over which lag, swing ratio and overshoot are scored (default: the reference track's skirtSwing windows; refused as CLOTH_FIT_WINDOWS when none are given or recorded, when a window is ≤ 12 frames, or when a window has no reference hip stroke) --skirt-slots with --cloth-track: comma-separated slot names whose mesh attachments form the skirt (default: discovered from mesh slots matching /skirt|bottomwear|dress|hem|kilt|gown/i; refused as CLOTH_FIT_SLOTS when none match, when a named slot is missing, or when a named slot has no mesh attachment) --idle the rig's animation read as its idle (default: idle). Every idle track the new animation does not key, on any channel, is listed as IDLE-DROPPED (a blink, a breath); one it keys is IDLE-KEPT-OUT, naming the track that keys it, and so is a rotate, scale or shear of a bone above a mapped bone (a translate of one is carried) --carry-idle loop the IDLE-DROPPED tracks into the new animation: the idle's keys repeated every idle duration and cut at the new animation's end, with the value interpolated there (default: off — a blink keyed over a set's art is the author's call) --merge merge rig-pose-tracks/1 into the new animation: { "spec": "rig-pose-tracks/1", "tracks": [ … ] } at absolute times from its start (blinks read off the video); a track on a target and property it already keys is refused (MERGE_CONFLICT), and so is a key past its duration (MERGE_TIME) --reduce thin each mapped bone's rotate keys to few keys with curves (linear, or one raw Bezier per span with handles at its thirds), on the pose's own frame times, so every bone's world aim stays within deg of the dense keys on every frame; fitted top-down, each bone against its parent's reduced error, so errors do not pile up down a chain. Kept regardless: the first and last frame, the frames either side of a switch boundary on the chains it changes, and the edges of every FLIP spread, SHORT span and RANGE run (REDUCE lines; default: off). It runs last, on the final keys: with --leg-scale, --plant-feet and --stance, a scaled bone's scalex is thinned within 5e-5 of its setup length, a bone under one is re-solved through its parent as reduced, and each ankle is held to what the reduced bones above it may move it by (rig-c/pose#94), printed at the end as "ankle drift allowed" in units and leg lengths (rig-c/pose#240). --reduce ,=,… gives a map chain its own tolerance, the first item every other chain's (rig-c/pose#283): legs held tight against slide while the trunk is smoothed, e.g. --reduce 3,leg_r=0.2,leg_l=0.2; each LAND line and ankle allowance follows its chain's tolerance, and the run line, the REDUCE lines and the report name them --reduce-hip with --reduce, thin the hip's translate keys too, its world origin within units of the dense keys (default: the hip stays dense) --reduce-keep-planted with --reduce and --plant-feet, keep every frame of each support span on the supporting leg (each mapped bone from the hip down to its ankle) at its dense key, so the planted ankle lands as dense on its support frames: its landing tolerance there is the plant's plus the hip's --reduce-hip, off them --reduce's allowance (rig-c/pose#251) --switch-tolerance a set of alternate drawings (the map's "alternates") may show on a frame where every segment of its chains is within d degrees of its key skeleton (default: 25), and only where every bone it shows by its "drawn" angle unaided (no "turn", the set not re-solved) is within d degrees of it; a set whose key and drawn angle disagree by more than d on such a bone is refused (SET_KEY_DRAWN, rig-c/pose#355) --switch-min a run of one set shorter than s seconds is dropped (default: 0.25) --switch-at first|peak where a switch is keyed: first (default) keeps the frame the selection gave it; peak moves each boundary to the frame within ±switch-min/2 where the chains it changes turn fastest, among those that newly show a set only on frames within 2 × the switch tolerance of its key skeleton (it stays when none qualifies) --profile spine|rig-play rigc's gate profile (default: spine, rigc's own default; spine-html is a deprecated alias for rig-play through 1.x) --build keep the gated build (skeleton.json, .atlas, .model.json) here, with the record of what made it beside it: retarget.json (rig-pose-retarget/1 — both versions, each input as given with its sha256, the sequence's source, every option as resolved; rig-c/pose#270) --reference with --build: written into retarget.json as "reference", exactly as given — the video or file the motion was made to match. Echoed, never read: the path is not checked to exist. Without it the record has no "reference" (compare's --reference is another flag) --render keep rigc's render of the animation (frames, contact.png, folds.json) here --parts @rig-c/parts' parts.json, or the directory holding it (its build's --out, beside rig/): the neighbour pairs the seam reading reads — each limb's consecutive segments. Each pair is read by rigc render --seam over the new animation and every span of a gap or a ghost thicker than one cell prints a SEAM line and a report seams row; a reading, never a gate. Without it no pair is declared (a rig spec carries none): seams: [] --report write the run's measurements (holds, short, endOn, flips, bends, landings, folds, seams, switches, uncovered, turns, range, artRange, raised, byHip, idleDropped, idleKeptOut, merged, reduce) as JSON (default: .report.json beside the motion, a trailing .json of --out replaced); its wrote line names the mtime of a report it replaced --verbose print every line in full (rig-c/pose#238): the CLEAN line with the stillness hold's per-joint record, one BEND line per frame under --bends clamp, and before a collapsed POSE_BEND_ONE_WAY refusal the per-frame refusals it stands for. Without it, the CLEAN line counts the holds (the record: --report's cleaned.holds, cleaned.unheld, cleaned.seams) and each hinge's wrong-way frames are one line: count, frame range, worst angle --summary print only the run line, one line per measure — GATE, FEET (the posed build), LIFT (the STANCE runs), JITTER (the worst ratio), LAND (each kind's worst) — and the wrote lines: the lines two runs are compared on. Refusals print as without it --camera write the sequence's camera track (rig-pose-camera/1: continuous figure scale s, raw standing height ratio, pan tx/ty, and composite videoS) as a sidecar JSON file without changing motion.json (rig-c/pose#161) It writes nothing until rigc's gate is green with the animation in, every mapped bone lands on the angle the pose asks for (posed by rig-c's own poser), and no hinge bends the wrong way. \`rigc render --folds\` is a reading: the run lists every mesh that folds, and still writes. With "alternates" in the map, it keys attachment switches beside the bone keys (SWITCH lines) and lists every fold no switch covers (UNCOVERED lines). A chain's "range" clamps a rotate key outside the spans of a set depicting it (RANGE lines); inside one, a bone with a "drawn" angle turned past its range is listed (ART-RANGE). A line across the body (hips, shoulders, eyes) under 0.5 of its median picture length, or reversed, for ≥ 0.15 s is listed (TURN). convert --coco coco17-sequence/1: { format, width, height, source, frames: [{ t, keypoints }] }, keypoints in COCO's order as 17 [x, y, score] or 51 numbers, or null --out the rig-pose-sequence/1 it becomes; neck = the shoulders' midpoint compare --reference rig-pose-sequence/1: the source video's keypoints --render rig-pose-sequence/1: the same detector on rigc's render of the retargeted motion, rendered at the reference's rate — same frame count, times within 1 ms --map rig-pose-map/1: its arm and leg segments are compared --retarget-report the retarget's --report: a limb finding inside a set's span suggests paint, outside rig --reference-hands --render-hands COCO-WholeBody keypoints ({ frames: [{ t, points: [[x, y, score] x 133] }] }) for hand visibility from the 21 hand points; without them, from the wrist scores --cloth-reference --cloth-render --cloth-windows cloth tracks (rig-c-cloth-track/0: hip_x and hem_mid per frame, in hip widths) and the windows, in seconds, #34's lag, swing ratio and overshoot are read over; a render track in rig world units needs --retarget-report (its scale); without the tracks, cloth reads "not measured" --report write the comparison as JSON (rig-pose-compare/1) --sheet draw the reference and render skeletons side by side at each finding's worst frame A finding is a run of frames over a bar lasting >= 0.15 s (gaps of one frame merged), worst first. The bars (docs/REFERENCE.md, "Compare"): arm and leg segment direction > 20 deg; hand visibility reference >= 0.6 while render < 0.4; foot plant render > 0.05 while reference < 0.02 hip widths/frame; eye-line tilt > 15 deg; torso length and hip height range under 0.5 x the reference's; cloth outside #34's bands. Exit 0 whenever it compared, findings or not. cloth (rig-c/pose#34) --rig the built rig (skeleton.model.json, its build directory, or a rig.json / rig directory): stepped at --fps through rig-c's core poser (poseRawAnimationEach with physicsClockStep) to measure the skirt slots in rig world units --map with --rig: rig-pose-map/1, naming the two hip points (the hip line's "a>b" aim, or the first bones of the chains starting at r_hip and l_hip) that set the hip width and mid-hip --skirt-slots with --rig: comma-separated slot names whose drawn attachments form the skirt --animation with --rig: the animation to step (default: dance) --fps with --rig: the stepping rate in frames per second (default: 24) --frames instead of --rig: one isolated skirt PNG per frame of --pose, in file-name order, the sequence's picture size, measured in picture px --pose with --frames: rig-pose-sequence/1 whose r_hip and l_hip set the hip width and mid-hip --person with --frames: the person to read when --pose holds more than one --alpha-min <1..255> with --frames: the alpha threshold for skirt pixels on transparent PNGs, and the RGB colour-distance threshold from the border median on opaque-background PNGs such as rigc render --slot (default: 16; a skirt within < --alpha-min of the background is refused as CLOTH_EMPTY_FRAME) --windows optional windows in seconds (named A, B, ...) over which #34's lag, swing ratio and overshoot are computed (stroke threshold 0.2 hip widths) and written under "skirtSwing" --out where the rig-c-cloth-track/0 JSON is written, ready for rig-pose compare Exit codes: 0 written (compare: compared), 1 refused (every reason printed), 2 bad invocation. `; class Usage extends Error {} /** * Reads `--flag value` pairs and `--switch`es. `aliases` maps a second name to the flag it stands for * (rig-c/pose#243): the value is stored under the flag's own name. A flag given twice is refused; a flag * and its alias given together are accepted when they agree and refused, naming both, when they differ. */ function parseFlags(argv: string[], flags: readonly string[], switches: readonly string[], aliases: Readonly> = {}): Map { const out = new Map(); const spelled = new Map(); for (let i = 0; i < argv.length; i++) { const a = argv[i]!; if (!a.startsWith('--')) throw new Usage(`unexpected argument "${a}"`); const name = a.slice(2); if (switches.includes(name)) { out.set(name, 'true'); continue; } const flag = aliases[name] ?? name; if (!flags.includes(flag)) throw new Usage(`unknown flag ${a}; the flags are ${[...flags, ...Object.keys(aliases), ...switches].map((f) => `--${f}`).join(', ')}`); const v = argv[++i]; if (v === undefined || v.startsWith('--')) throw new Usage(`${a} needs a value`); const before = spelled.get(flag); if (before === a) throw new Usage(`${a} is given twice`); if (before !== undefined) { const prior = out.get(flag)!; if (prior === v) continue; // One of the two is the flag's own name and the other its alias: the line names the flag first. const [own, ownV, alias, aliasV] = before === `--${flag}` ? [before, prior, a, v] : [a, v, before, prior]; throw new Usage(`${own} "${ownV}" and ${alias} "${aliasV}" are both given and differ; ${alias} is another name for ${own}, so give one`); } spelled.set(flag, a); out.set(flag, v); } return out; } function need(f: Map, name: string, alias?: string): string { const v = f.get(name); if (v === undefined) throw new Usage(alias === undefined ? `--${name} is required` : `--${alias} (or --${name}) is required`); return v; } function num(f: Map, name: string, dflt: number, ok: (n: number) => boolean, what: string): number { const v = f.get(name); if (v === undefined) return dflt; const n = Number(v); if (!Number.isFinite(n) || !ok(n)) throw new Usage(`--${name} is "${v}"; it must be ${what}`); return n; } function flipOf(f: Map): number | 'off' { if (!f.has('flip') || f.get('flip') === 'off') return 'off'; return num(f, 'flip', 90, (v) => v > 0 && v < 180, 'off, or degrees in (0, 180) — a one-frame turn is never more than 180°'); } function shortOf(f: Map): number | 'off' { if (!f.has('short') || f.get('short') === 'off') return 'off'; return num(f, 'short', 0.35, (v) => v > 0 && v < 1, 'off, or a fraction in (0, 1) of the segment\'s median picture length'); } function legScaleOf(f: Map): [number, number] | 'off' { const v = f.get('leg-scale'); if (v === undefined || v === 'off') return 'off'; const parts = v.split(',').map((x) => (x.trim() === '' ? NaN : Number(x))); if (parts.length !== 2 || !parts.every((x) => Number.isFinite(x)) || !(parts[0]! > 0) || parts[0]! > 1 || parts[1]! < 1) { throw new Usage(`--leg-scale is "${v}"; it must be off, or min,max with 0 < min ≤ 1 ≤ max (the scale of a leg segment against its straight length, e.g. 0.8,1.05)`); } return [parts[0]!, parts[1]!]; } function depthShadeOf(f: Map): number { const raw = f.get('depth-shade')!; const k = Number(raw); if (raw.trim() === '' || !Number.isFinite(k) || k < 0 || k > 1) throw new Usage(`--depth-shade is "${raw}"; expected a finite RGB multiplier in [0, 1]`); return k; } function depthShadeChainsOf(raw: string): string[] { const names = raw.split(',').map(name => name.trim()); if (names.some(name => name === '')) throw new Usage(`--depth-shade-chains is "${raw}"; expected nonempty comma-separated map chain names`); return [...new Set(names)]; } function depthScaleOf(f: Map): [number, number] { const v = f.get('depth-scale')!; const parts = v.split(',').map(x => x.trim() === '' ? NaN : Number(x)); if (parts.length !== 2 || !parts.every(Number.isFinite) || !(parts[0]! > 0 && parts[0]! <= 1 && parts[1]! >= 1)) throw new Usage(`--depth-scale is "${v}"; expected min,max with 0 < min <= 1 <= max`); return [parts[0]!, parts[1]!]; } /** * rig-c/pose#243: the names the rest of the toolchain uses for the same inputs — `rigc render --animation`, * and the exam grader's `--sequence` — accepted beside this command's own. */ const RETARGET_ALIASES = { sequence: 'pose', animation: 'name' } as const; function retargetArgs(argv: string[]): RetargetArgs { const f = parseFlags(argv, ['rig', 'map', 'pose', 'out', 'name', 'person', 'base-motion', 'images', 'min-score', 'smooth', 'flip', 'short', 'bends', 'bend-tolerance', 'switch-tolerance', 'switch-min', 'switch-at', 'profile', 'build', 'reference', 'render', 'parts', 'report', 'camera', 'leg-scale', 'depth-scale', 'depth-shade', 'depth-shade-chains', 'idle', 'merge', 'reduce', 'reduce-hip', 'stance', 'floor', 'draw-order', 'contact-keys', 'shoulder-lift', 'cloth-track', 'cloth-windows', 'skirt-slots'], ['coco', 'plant-feet', 'carry-idle', 'raised-by-head', 'reduce-keep-planted', 'verbose', 'summary'], RETARGET_ALIASES); if (f.has('depth-shade-chains') && !f.has('depth-shade')) throw new Usage('--depth-shade-chains needs --depth-shade; it selects the mapped limb chains to shade'); if (f.has('verbose') && f.has('summary')) throw new Usage('--verbose and --summary are both given; --verbose prints every line in full and --summary one line per measure, so give one'); if (f.has('reference') && !f.has('build')) throw new Usage(`--reference needs --build: the record it goes in is written beside the build (${PROVENANCE_FILE})`); if (f.has('cloth-windows') && !f.has('cloth-track')) throw new Usage('--cloth-windows is given without --cloth-track; it names the windows --cloth-track fits over'); if (f.has('skirt-slots') && !f.has('cloth-track')) throw new Usage('--skirt-slots is given without --cloth-track; it names the skirt slots --cloth-track measures'); let clothWindows: RetargetArgs['clothWindows']; if (f.has('cloth-windows')) { const w = parseWindows(f.get('cloth-windows')!); if (typeof w === 'string') throw new Usage(`--cloth-windows is "${f.get('cloth-windows')}": ${w}; it must be t0-t1[,t0-t1...] in seconds`); clothWindows = w; } let skirtSlots: RetargetArgs['skirtSlots']; if (f.has('skirt-slots')) { const raw = f.get('skirt-slots')!; const list = raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0); if (list.length === 0) throw new Usage(`--skirt-slots is "${raw}"; it must be one or more comma-separated slot names`); skirtSlots = list; } const bends = f.get('bends') ?? 'refuse'; if (bends !== 'refuse' && bends !== 'clamp') throw new Usage(`--bends is "${bends}"; it must be refuse or clamp`); const switchAt = f.get('switch-at') ?? 'first'; if (switchAt !== 'peak' && switchAt !== 'first') throw new Usage(`--switch-at is "${switchAt}"; it must be peak or first`); const rawProfile = f.get('profile') ?? 'spine'; if (rawProfile !== 'spine' && rawProfile !== 'rig-play' && rawProfile !== 'spine-html') { throw new Usage(`--profile is "${rawProfile}"; it must be spine or rig-play`); } const profile: RetargetArgs['profile'] = rawProfile === 'spine' ? 'spine' : 'rig-play'; const drawOrder = f.get('draw-order'); if (drawOrder !== undefined && drawOrder !== 'depth') throw new Usage(`--draw-order is "${drawOrder}"; it must be depth (the order is keyed from the sequence's depth, rig-c/pose#304)`); const name = f.get('name') ?? 'dance'; if (!/^[A-Za-z0-9_.-]+$/.test(name)) throw new Usage(`${argv.includes('--name') || !argv.includes('--animation') ? '--name' : '--animation'} is "${name}"; an animation name here is letters, digits, _ . -`); const parsed: RetargetArgs = { rig: need(f, 'rig'), map: need(f, 'map'), pose: need(f, 'pose', 'sequence'), out: need(f, 'out'), name, coco: f.has('coco'), person: f.get('person'), baseMotion: f.get('base-motion'), images: f.get('images'), minScore: num(f, 'min-score', 0.3, (n) => n >= 0, 'a number ≥ 0'), smoothAlias: f.get('smooth'), flip: flipOf(f), short: shortOf(f), legScale: legScaleOf(f), ...(f.has('depth-scale') ? { depthScale: depthScaleOf(f) } : {}), ...(f.has('depth-shade') ? { depthShade: depthShadeOf(f) } : {}), ...(f.has('depth-shade-chains') ? { depthShadeChains: depthShadeChainsOf(f.get('depth-shade-chains')!) } : {}), plantFeet: f.has('plant-feet'), stance: stanceOf(f), ...floorOf(f), raisedByHead: f.has('raised-by-head'), bends, bendTolerance: num(f, 'bend-tolerance', 0, (n) => n >= 0 && n < 180, 'degrees in [0, 180)'), switchTolerance: num(f, 'switch-tolerance', 25, (n) => n >= 0 && n < 180, 'degrees in [0, 180)'), switchMin: num(f, 'switch-min', 0.25, (n) => n >= 0, 'seconds ≥ 0'), switchAt, profile, build: f.get('build'), reference: f.get('reference'), render: f.get('render'), parts: f.get('parts'), report: f.get('report'), camera: f.get('camera'), idle: f.get('idle'), carryIdle: f.has('carry-idle'), merge: f.get('merge'), ...reduceOf(f), output: f.has('verbose') ? 'verbose' : f.has('summary') ? 'summary' : 'default', ...(drawOrder !== undefined ? { drawOrder: 'depth' as const } : {}), ...(f.has('shoulder-lift') ? { shoulderLiftFile: f.get('shoulder-lift')! } : {}), ...(f.has('contact-keys') ? { contactKeysFile: f.get('contact-keys')! } : {}), ...(f.has('cloth-track') ? { clothTrackFile: f.get('cloth-track')! } : {}), ...(clothWindows !== undefined ? { clothWindows } : {}), ...(skirtSlots !== undefined ? { skirtSlots } : {}), }; if (rawProfile === 'spine-html') { process.stderr.write('rig-pose: --profile spine-html is deprecated and reads as --profile rig-play, the same rules; it is accepted through 1.x — pass --profile rig-play\n'); } return parsed; } /** --stance (rig-c/pose#60): off unless given, and only with --plant-feet. */ function stanceOf(f: Map): number | 'off' { if (!f.has('stance') || f.get('stance') === 'off') return 'off'; const v = num(f, 'stance', 0, (n) => n > 0 && n < 1, 'off, or leg lengths in (0, 1)'); if (!f.has('plant-feet')) throw new Usage(`--stance is "${f.get('stance')}" without --plant-feet; it plants the free foot beside the supporting one that --plant-feet holds`); return v; } /** --floor (rig-c/pose#85): the floor's world y, only with --plant-feet; absent, the median of the spans' planted heights. */ function floorOf(f: Map): { floor?: number } { if (!f.has('floor')) return {}; const v = num(f, 'floor', 0, () => true, 'a world y in rig units (a finite number)'); if (!f.has('plant-feet')) throw new Usage(`--floor is "${f.get('floor')}" without --plant-feet; it is the floor --plant-feet plants every support span on`); return { floor: v }; } /** --reduce and --reduce-hip (rig-c/pose#32): off unless given; the hip only with the bones. --reduce-keep-planted (rig-c/pose#251): only with both --reduce and --plant-feet. */ function reduceOf(f: Map): { reduce?: number; reduceChains?: Record; reduceHip?: number; reduceKeepPlanted?: true } { if (f.has('reduce-keep-planted')) { const missing = ['reduce', 'plant-feet'].filter((x) => !f.has(x)); if (missing.length > 0) throw new Usage(`--reduce-keep-planted is given without ${missing.map((x) => `--${x}`).join(' and ')}; it keeps the support spans --plant-feet reads at dense keys inside the reduction --reduce makes`); } if (!f.has('reduce')) { if (f.has('reduce-hip')) throw new Usage('--reduce-hip is given without --reduce; the hip is thinned with the bones, not alone'); return {}; } const keep = f.has('reduce-keep-planted') ? { reduceKeepPlanted: true as const } : {}; // rig-c/pose#283: ",=,…" — the first item every chain's tolerance, then a map chain's own. const [head, ...rest] = f.get('reduce')!.split(','); const reduce = rest.length === 0 ? num(f, 'reduce', 0, (n) => n > 0 && n < 180, 'degrees in (0, 180)') : Number(head); if (rest.length > 0 && (head === '' || !(reduce > 0 && reduce < 180))) throw new Usage(`--reduce is "${f.get('reduce')}"; its first item "${head}" must be degrees in (0, 180), every chain's tolerance, before any =`); const chains: Record = {}; for (const item of rest) { const m = /^([^=\s]+)=(.*)$/.exec(item); if (m === null) throw new Usage(`--reduce is "${f.get('reduce')}"; "${item}" is not = (a chain the map names, then its tolerance in degrees)`); if (Object.hasOwn(chains, m[1]!)) throw new Usage(`--reduce is "${f.get('reduce')}"; chain "${m[1]}" is given twice`); const v = Number(m[2]); if (m[2] === '' || !Number.isFinite(v) || !(v > 0 && v < 180)) throw new Usage(`--reduce is "${f.get('reduce')}"; chain "${m[1]}" is "${m[2]}", and it must be degrees in (0, 180)`); chains[m[1]!] = v; } const per = rest.length === 0 ? {} : { reduceChains: chains }; return f.has('reduce-hip') ? { reduce, ...per, reduceHip: num(f, 'reduce-hip', 0, (n) => n > 0, 'rig units > 0'), ...keep } : { reduce, ...per, ...keep }; } function compareArgs(argv: string[]): CompareArgs { const f = parseFlags(argv, ['reference', 'render', 'map', 'retarget-report', 'reference-hands', 'render-hands', 'cloth-reference', 'cloth-render', 'cloth-windows', 'report', 'sheet'], []); const pair = (x: string, y: string) => { if (f.has(x) !== f.has(y)) throw new Usage(`--${f.has(x) ? x : y} is given without --${f.has(x) ? y : x}; the two are read together, so both sides are measured the same way`); }; pair('reference-hands', 'render-hands'); pair('cloth-reference', 'cloth-render'); let clothWindows: CompareArgs['clothWindows']; if (f.has('cloth-reference') && !f.has('cloth-windows')) throw new Usage('--cloth-reference and --cloth-render need --cloth-windows : the figures are read per window'); if (f.has('cloth-windows')) { if (!f.has('cloth-reference')) throw new Usage('--cloth-windows is given without --cloth-reference and --cloth-render'); const w = parseWindows(f.get('cloth-windows')!); if (typeof w === 'string') throw new Usage(`--cloth-windows is "${f.get('cloth-windows')}": ${w}; it must be t0-t1[,t0-t1...] in seconds`); clothWindows = w; } return { reference: need(f, 'reference'), render: need(f, 'render'), map: need(f, 'map'), retargetReport: f.get('retarget-report'), referenceHands: f.get('reference-hands'), renderHands: f.get('render-hands'), clothReference: f.get('cloth-reference'), clothRender: f.get('cloth-render'), clothWindows, report: f.get('report'), sheet: f.get('sheet'), }; } /** The stillness hold's flags (#91): `--hold off`, or the thresholds (defaults 0.015 and 0.03). */ function holdOf(f: Map): { speed: number; reach: number } | 'off' { const v = f.get('hold'); if (v !== undefined && v !== 'off') throw new Usage(`--hold is "${v}"; the hold runs by default, and the only value is "off"`); if (v === 'off') { const given = ['hold-speed', 'hold-reach'].filter((k) => f.has(k)); if (given.length > 0) throw new Usage(`${given.map((k) => `--${k}`).join(' and ')} with --hold off: the hold does not run, so ${given.length === 1 ? 'it changes' : 'they change'} nothing — drop ${given.length === 1 ? 'it' : 'them'} or the --hold off`); return 'off'; } return { speed: num(f, 'hold-speed', HOLD_SPEED, (n) => n > 0, 'a number > 0 (trunk lengths per frame)'), reach: num(f, 'hold-reach', HOLD_REACH, (n) => n > 0, 'a number > 0 (trunk lengths)'), }; } /** A window flag of clean: 1, or odd and ≥ 5 (`windowProblem`). */ function windowOf(f: Map, name: string, dflt: number): number { const v = f.get(name); if (v === undefined) return dflt; const n = Number(v); const why = windowProblem(`--${name}`, Number.isFinite(n) ? n : NaN); if (!Number.isFinite(n) || why !== null) throw new Usage(why ?? `--${name} is "${v}"; it must be 1 (none) or an odd whole number ≥ 5`); return n; } const fmt = (v: number, d = 2) => v.toFixed(d); function runsOf(frames: number[]): string { const out: string[] = []; let a = -1; let b = -1; for (const f of frames) { if (f === b + 1) b = f; else { if (a >= 0) out.push(a === b ? `${a}` : `${a}–${b}`); a = f; b = f; } } if (a >= 0) out.push(a === b ? `${a}` : `${a}–${b}`); return out.join(', '); } /** `rig-pose clean` (#67): read, clean, print each step's figures, write. */ function runClean(argv: string[], say: (l: string) => void): void { const f = parseFlags(argv, ['pose', 'out', 'legs', 'rest', 'person', 'hold', 'hold-speed', 'hold-reach', 'depth'], ['loop', 'coco', 'hips-inferred']); const input = need(f, 'pose'); const out = need(f, 'out'); const gait = f.get('depth'); if (gait !== undefined && !(DEPTH_GAITS as readonly string[]).includes(gait)) throw new Usage(`--depth is "${gait}"; it must be ${DEPTH_GAITS.join(' or ')} (the gait decides the joint --draw-order depth orders the legs by: the ankle in a walk, the knee in a run)`); const outPath = new Problems(); // Both files share a parent; plan it once, then check both actual destinations. const sidecar = figureScalePath(out); const outDirs = planOutDirs([['--out', out]], outPath); for (const [name, path] of [['--out', out], ['figure-scale sidecar', sidecar]]) { let exists = false; try { lstatSync(path); exists = true; } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT' && !outPath.any) outPath.add('ARG_PATH', `${name} ${path} — cannot inspect output: ${(e as Error).message}`); } if (!exists) continue; try { if (!statSync(path).isFile()) outPath.add('ARG_PATH', `${name} ${path} — output is not a regular file`); else accessSync(path, constants.W_OK); } catch (e) { outPath.add('ARG_PATH', `${name} ${path} — output is not writable: ${(e as Error).message}`); } } outPath.throwIfAny(); const params = { loop: f.has('loop'), legs: windowOf(f, 'legs', 5), rest: windowOf(f, 'rest', 7), hipsInferred: f.has('hips-inferred'), hold: holdOf(f), ...(gait !== undefined ? { depth: gait as DepthGait } : {}) }; const inputBytes = readFileSync(input); const text = inputBytes.toString('utf8'); const seq = f.has('coco') ? convertCoco17(text, input) : readPoseSequence(text, input); const c = clean(seq, params, f.get('person'), input); const n = seq.frames.length; const tOf = (i: number) => `t=${seq.frames[i]!.t.toFixed(3)}s`; say(`rig-pose clean: ${n} frame(s) of person "${c.person}" from ${input}${f.has('coco') ? ' (COCO-17)' : ''}; legs ${params.legs}, rest ${params.rest}, ${params.loop ? 'loop (every window wraps)' : 'no loop (windows cut at the ends)'}`); for (const line of figureScaleLines(c.figureScale, seq.camera !== undefined)) say(` ${line}`); say(` TRUNK neck → mid_hip: median ${fmt(c.trunk.length)} px over ${c.trunk.frames} frame(s); a spike is > ${fmt(SPIKE_TRUNKS * c.trunk.length)} px (${SPIKE_TRUNKS} trunk) from its ${SPIKE_WINDOW}-frame median`); for (const s of c.spikes) say(` SPIKE joint "${s.joint}" frame ${s.frame} (${tOf(s.frame)}): ${fmt(s.off)} px from its ${SPIKE_WINDOW}-frame median, over ${fmt(SPIKE_TRUNKS * c.trunk.length)} — took the median`); say(` SPIKES ${c.spikes.length} replaced; ${untestedText(c.untested)}`); const byJoint = new Map(); for (const o of c.occluded) byJoint.set(o.joint, [...(byJoint.get(o.joint) ?? []), o]); for (const [joint, os] of byJoint) say(` OCCLUDED joint "${joint}" on ${os.length} frame(s) (${runsOf(os.map((o) => o.frame))}): not observed or scored under ${OCCLUSION_SCORE}; took its ${OCCLUSION_WINDOW}-frame median, moved up to ${fmt(Math.max(...os.map((o) => o.moved)))} px`); say(` OCCLUSION ${c.occluded.length} joint-frame(s) took the median`); for (const m of c.missing) say(` MISSING joint "${m.joint}" frame${m.from === m.to ? ` ${m.from}` : `s ${m.from}–${m.to}`}: no position; left without one (retarget holds it)`); const sg = (w: number) => (w === 1 ? '1 frame (none)' : `${w} frames`); say(` SMOOTH quadratic Savitzky–Golay per joint: legs (${LEGS.join(', ')}) over ${sg(params.legs)}, the rest over ${sg(params.rest)}; ${params.loop ? 'circular' : 'the window cut at the ends'}`); if (c.pelvis !== null) say(` PELVIS pelvisTilt (${c.pelvis.source}) smoothed as its own track over ${sg(c.pelvis.window)} (the legs' window), ${params.loop ? 'circular' : 'the window cut at the ends'}, on the ${c.pelvis.read} of ${c.pelvis.frames} frame(s) that carry a reading (a null stays null); largest change ${fmt(c.pelvis.moved, 3)}°`); if (params.loop) { if (c.floor === null) say(' FLOOR no ankle has a position on any frame; not re-pinned'); else say(` FLOOR the lowest ankle over the cycle: y ${fmt(c.floor.before)} before smoothing, ${fmt(c.floor.after)} after; every joint moved ${c.floor.shift >= 0 ? '+' : ''}${fmt(c.floor.shift, 3)} px in y`); say(' TRAVEL "in-place" written (rig-c/pose#92): a loop is one cycle repeated, so the figure does not travel; retarget reads its supports and head nod in place with or without --plant-feet, and --plant-feet also lets the supporting foot follow its own track and holds the hip\'s x over the loop'); } const jit = (v: number | null) => (v === null ? 'not measured' : `${fmt(v, 3)}`); say(` JITTER mean |second difference| of y over ${c.triples} joint-frame triple(s): ${jit(c.record.jitter.before)} → ${jit(c.record.jitter.after)} px/f²${c.record.jitter.before !== null && c.record.jitter.after !== null && c.record.jitter.before > 0 ? ` (${fmt(100 * (1 - c.record.jitter.after / c.record.jitter.before), 1)}% lower)` : ''}`); if (params.hold === 'off') say(' HOLD off (--hold off): no stillness hold'); else { const h = params.hold; const span = (r: [number, number] | null, what: string) => (r === null ? `nothing ${what}` : `${what} ${r[0] === r[1] ? `frame ${r[0]}` : `frames ${r[0]}–${r[1]}`}`); for (const x of c.holds) say(` HOLD joint "${x.joint}" frames ${x.frames[0]}–${x.frames[1]} (${tOf(x.frames[0])}–${tOf(x.frames[1])}, ${fmt(x.seconds, 3)} s): ${HOLD_SPEED_WINDOW}-frame median speed under ${h.speed} trunk/frame (largest ${fmt(x.speed, 4)}), ${x.excursion === null ? `within ${h.reach} trunk of its span median (largest ${fmt(x.reach, 4)}); written as that median` : `within ${h.reach} trunk of its span median outside excursion ${x.excursion[0] === x.excursion[1] ? `frame ${x.excursion[0]}` : `frames ${x.excursion[0]}–${x.excursion[1]}`} (reach ${fmt(x.reach, 4)} with excursion); held around the excursion, which is blended in and out`}, blended in over ${span(x.blendIn, 'before').replace('nothing before', 'nothing before it')}, out over ${span(x.blendOut, 'after').replace('nothing after', 'nothing after it')}; jitter inside ${jit(x.jitter.before)} → ${jit(x.jitter.after)} px/f²${x.jitter.after !== null && x.jitter.after > 0 ? ` (${x.excursion !== null ? 'excursion' : 'ramp'})` : ''}`); for (const x of c.seams) say(` SEAM joint "${x.joint}" frame ${x.frame} (${tOf(x.frame)}): two holds ${x.gap === 0 ? 'back to back' : `${x.gap} frame(s) apart`}, their medians ${fmt(x.step, 4)} trunk (${fmt(x.step * c.trunk.length)} px) apart; cross-faded over frames ${x.frame - x.gap - HOLD_BLEND / 2}–${x.frame + HOLD_BLEND / 2 - 1}, no frame moving more than 1/${HOLD_BLEND + x.gap} of it`); for (const [a, b] of holdRegions(c.holds)) { const not = c.unheld.filter((u) => u.frames[0] >= a && u.frames[1] <= b); if (not.length > 0) say(` UNHELD frames ${a}–${b}, where other joints are held: ${not.map(unheldText({ ...h, minSeconds: HOLD_MIN_SECONDS })).join(', ')}`); } say(` HOLDS ${c.holds.length} found over ${new Set(c.holds.map((x) => x.joint)).size} joint(s) (per joint: a span ≥ ${HOLD_MIN_SECONDS} s still by speed < ${h.speed} trunk/frame and reach ≤ ${h.reach} trunk; ${HOLD_BLEND}-frame blend in and out)`); } if (c.depth !== null) { const d = c.depth; const rest = (['upper_arm', 'forearm', 'thigh', 'shin'] as const).map((k) => `${k} ${d.rest[k] === null ? 'not placed' : fmt(d.rest[k]!)}`).join(', '); say(` DEPTH derived per segment for a ${params.depth} (rig-c/pose#281): ratio = drawn ÷ rest, rest the larger side's 95th-percentile length (${rest} px); flat within ${FLAT_BAND[0]}–${FLAT_BAND[1]}; toward ${d.signs.toward}, away ${d.signs.away}, flat or undecided ${d.signs.flat} segment-frame(s); the trunk faced the camera on ${d.facing.toward}, away on ${d.facing.away}, side-on (under ${SIDE_ON} trunk wide, sign 0) on ${d.facing.side} frame(s)`); } else if (c.seq.frames.some((x) => x.depth !== undefined)) say(' DEPTH measured depth (a 3D detector\'s) carried through as read'); if (c.inferred !== null) say(` INFERRED r_hip on ${c.inferred.r_hip} frame(s), l_hip on ${c.inferred.l_hip} frame(s) of ${n} marked "inferred" (every frame where it has a position): declared at clean (--hips-inferred); positions and scores unchanged`); const sequenceText = writePoseSequence(c.seq); const sha256 = (bytes: string | Uint8Array): string => createHash('sha256').update(bytes).digest('hex'); const sidecarText = writeFigureScaleRecord({ spec: FIGURE_SCALE_SPEC, inputSHA256: sha256(inputBytes), sequenceSHA256: sha256(sequenceText), person: c.person, cameraDeclared: seq.camera !== undefined, figureScale: c.figureScale }); makeOutDirs(outDirs, say); writeFileSync(sidecar, sidecarText); writeFileSync(out, sequenceText); say(` wrote ${sidecar} (measured input figure scale)`); say(` CLEAN ${cleanLine(c.record)}`); say(` wrote ${out}`); } export function main(argv: string[]): number { const [cmd, ...rest] = argv; if (cmd === undefined || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP); return 0; } if (cmd === '--version' || cmd === '-v') { process.stdout.write(`${pkg.version}\n`); return 0; } /** retarget --verbose (rig-c/pose#238): a collapsed refusal prints the per-frame lines it stands for before itself. */ let verbose = false; try { if (rest.includes('--help')) { process.stdout.write(HELP); return 0; } if (cmd === 'retarget') { const ra = retargetArgs(rest); verbose = ra.output === 'verbose'; runRetarget(ra, (l) => process.stdout.write(`${l}\n`)); return 0; } if (cmd === 'compare') { runCompare(compareArgs(rest), (l) => process.stdout.write(`${l}\n`)); return 0; } if (cmd === 'extract') { const f = parseFlags(rest, ['model', 'map', 'animation', 'fps', 'out'], ['loop']); need(f, 'fps'); runExtract({ model: need(f, 'model'), map: need(f, 'map'), animation: need(f, 'animation'), fps: num(f, 'fps', 0, n => Number.isFinite(n) && n > 0, 'a positive finite frame rate'), loop: f.has('loop'), out: need(f, 'out') }, l => process.stdout.write(`${l}\n`)); return 0; } if (cmd === 'clean') { runClean(rest, (l) => process.stdout.write(`${l}\n`)); return 0; } if (cmd === 'pelvis') { const f = parseFlags(rest, ['pose', 'out', 'frames', 'mode', 'pelvis-keys', 'person'], []); if (f.has('frames') === f.has('pelvis-keys')) throw new Usage(f.has('frames') ? '--frames and --pelvis-keys are both given; the track is read off the frames or taken from the hand keys, so give one' : '--frames (the picture to read) or --pelvis-keys (the hand override) is required'); const mode = f.get('mode') ?? 'silhouette'; if (f.has('mode') && f.has('pelvis-keys')) throw new Usage('--mode is given with --pelvis-keys; the mode names a reader of the frames, and the hand keys read none'); if (!(PELVIS_MODES as readonly string[]).includes(mode)) throw new Usage(`--mode is "${mode}"; it must be ${PELVIS_MODES.join(' or ')}`); runPelvis({ pose: need(f, 'pose'), out: need(f, 'out'), frames: f.get('frames'), mode: mode as PelvisMode, keys: f.get('pelvis-keys'), person: f.get('person') }, (l) => process.stdout.write(`${l}\n`)); return 0; } if (cmd === 'convert') { const f = parseFlags(rest, ['coco', 'out'], []); const input = need(f, 'coco'); const out = need(f, 'out'); const p = new Problems(); const outDirs = planOutDirs([['--out', out]], p); p.throwIfAny(); const seq = convertCoco17(readFileSync(input, 'utf8'), input); makeOutDirs(outDirs, (l) => process.stdout.write(`${l}\n`)); writeFileSync(out, writePoseSequence(seq)); process.stdout.write(`rig-pose convert: ${seq.frames.length} frame(s) of COCO-17 → body-18; wrote ${out}\n`); return 0; } if (cmd === 'cloth') { const f = parseFlags(rest, ['rig', 'map', 'skirt-slots', 'animation', 'fps', 'frames', 'pose', 'person', 'alpha-min', 'windows', 'out'], []); const out = need(f, 'out'); if (f.has('rig') === f.has('frames')) { throw new Usage(f.has('rig') ? '--rig and --frames are both given; measure either a rig (--rig) or isolated PNG frames (--frames), not both' : '--rig (the rig to pose) or --frames (the skirt PNGs to read) is required'); } let windows: ClothArgs['windows']; if (f.has('windows')) { const w = parseWindows(f.get('windows')!); if (typeof w === 'string') throw new Usage(`--windows is "${f.get('windows')}": ${w}; it must be t0-t1[,t0-t1...] in seconds`); windows = w; } if (f.has('rig')) { for (const bad of ['pose', 'person', 'alpha-min']) { if (f.has(bad)) throw new Usage(`--${bad} is given with --rig; --${bad} is a --frames flag`); } const map = need(f, 'map'); const rawSlots = need(f, 'skirt-slots'); const skirtSlots = rawSlots.split(',').map((s) => s.trim()).filter((s) => s !== ''); if (skirtSlots.length === 0) throw new Usage(`--skirt-slots is "${rawSlots}"; it must name one or more slots`); const animation = f.get('animation') ?? 'dance'; if (!/^[A-Za-z0-9_.-]+$/.test(animation)) throw new Usage(`--animation is "${animation}"; an animation name here is letters, digits, _ . -`); const fps = num(f, 'fps', 24, (n) => n > 0, 'a number > 0 (frames per second)'); runCloth({ kind: 'rig', rig: f.get('rig')!, map, skirtSlots, animation, fps, windows, out }, (l) => process.stdout.write(`${l}\n`)); return 0; } for (const bad of ['map', 'skirt-slots', 'animation', 'fps']) { if (f.has(bad)) throw new Usage(`--${bad} is given with --frames; --${bad} is a --rig flag`); } const pose = need(f, 'pose'); const alphaMin = num(f, 'alpha-min', 16, (n) => Number.isInteger(n) && n >= 1 && n <= 255, 'a whole number in 1..255'); runCloth({ kind: 'frames', frames: f.get('frames')!, pose, person: f.get('person'), alphaMin, windows, out }, (l) => process.stdout.write(`${l}\n`)); return 0; } process.stderr.write(`rig-pose: unknown command "${cmd}" — the commands are: pelvis, clean, retarget, convert, compare, cloth, extract\n`); return 2; } catch (e) { if (e instanceof Usage) { process.stderr.write(`rig-pose ${cmd}: ${e.message} (rig-pose --help)\n`); return 2; } if (e instanceof Refusal) { for (const p of e.problems) { if (verbose) for (const d of p.detail ?? []) process.stderr.write(`FAIL ${lineOf(d)}\n`); process.stderr.write(`FAIL ${lineOf(p)}\n`); } process.stderr.write(`rig-pose ${cmd}: ${e.problems.length} problem(s) — ${cmd === 'compare' ? 'not compared' : 'nothing written'}\n`); return 1; } throw e; } } if (import.meta.main) process.exit(main(process.argv.slice(2)));