Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
HG12a: motion on SOMA's skeleton plays on a raea body. SOMA (NVlabs/SOMA-X, Apache-2.0) is the 78-joint skeleton NVIDIA's motion models and datasets speak. raea-sys-body soma.rs points each of raea's bones the way SOMA's matching bone points, at raea's own lengths, fits the pose to those places, and turns each arm's and leg's first bone so its elbow or knee flexes about its own axis (settle_hinge, shared with two_bone). raea/character: readSomaUsda reads a SOMA animation saved as text USD; somaPose is the native call character.soma. A body 1.3 times the size under SOMA's names is followed within 2 degrees a bone; SOMA-X's example animation plays on turbo. 37 tests
shinyobjectz56c71ed264ec
diff --git a/docs/hands.feature b/docs/hands.featureindex a77a3f63..e463f1b7 100644--- a/docs/hands.feature+++ b/docs/hands.feature@@ -64,7 +64,9 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri| raea-sys-grab | src/take.rs | 460 | the take's timeline, each hand's part, the frame's solve || raea-sys-grab | src/grip.rs | 110 | the hand's lie at its grab, the swivel, an arm past its ranges || raea-sys-grab | src/json.rs | 150 | character.take |- | raea-sys-body | src/json.rs | 90 | character.fit, character.hand, the readers the calls share |+ | raea-sys-body | src/json.rs | 110 | character.fit, character.hand, character.soma, shared readers |+ | raea-sys-body | src/soma.rs | 110 | a pose from a SOMA body's joint places |+ | sdk | sdk/character/src/soma.ts | 80 | a SOMA animation read from text USD; somaPose || raea-sys-grab | tests/grab.rs | 470 | the hands' measures, on the stand-in body || raea-sys-grab | tests/body.rs | 150 | limits, the body out of solids, the hand prior || raea-sys-grab | tests/use.rs | 230 | passing, sliding, wind-up, a turned body, keeping out of solids |@@ -310,6 +312,22 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri# a squat, and the fingers against the body.Then a thing is carried against the body, never in it+ @done+ Scenario: HG12a. Motion on SOMA's skeleton plays on a raea body+ # 11-15, built, after the user asked what SOMA-X gives that raea lacks. Not its bodies: its skeleton is+ # the one NVIDIA's motion models and datasets speak (Kimodo, GEM-X, EgoHand, BONES-SEED), and raea had no+ # way from its 78 joints to raea's 52. raea-sys-body soma.rs `from_soma`: each of raea's bones is pointed+ # the way SOMA's matching bone points, at raea's own lengths (so proportions and bind poses needn't+ # agree), the pose fitted to those places, and each arm's and leg's first bone turned so its elbow or+ # knee flexes about its own axis (arm.rs `settle_hinge`). A posed body 1.3 times the size, in centimetres+ # and under SOMA's names, is followed with every bone within 2 degrees and no elbow or knee over 25+ # degrees sideways. raea/character's `readSomaUsda` reads a SOMA animation saved as text USD and+ # `somaPose` is the native call character.soma. Shown: SOMA-X's own example animation (900 frames, 24 a+ # second, Apache-2.0) on turbo, through arms crossed, arms overhead, a side bend and a squat. Open:+ # positions alone leave a limb's turn about itself to the hinge rule, so forearms and wrists may be+ # turned wrongly; frames are taken whole, not blended; and no model's or dataset's licence has been read.+ Then a SOMA animation plays on any raea body, bone for bone+Rule: The bar, set by the user 11-14: a complete tool, not scenariosScenario: HG14. Measured on the body's own skin, the takes are seamless and clip nothingdiff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rsindex c43159de..90b8add2 100644--- a/runtime/calls/src/lib.rs+++ b/runtime/calls/src/lib.rs@@ -177,6 +177,7 @@ pub fn call(name: &str, v: &Value) -> R<Value> {"character.take" => raea_sys_grab::take_json(v),"character.fit" => raea_sys_grab::fit_json(v),"character.hand" => raea_sys_grab::hand_json(v),+ "character.soma" => raea_sys_grab::soma_json(v),"fonts.families" => Ok(families().into()),"fonts.google" => {let family = s(v, "family")?;@@ -228,6 +229,7 @@ pub fn register() {("character.take", raea_sys_grab::TAKE_ARGS, raea_sys_grab::TAKE_ANSWER, "a frame of a character taking a thing with its hands (reach, grab, lift, carry, put down or throw): the pose to draw and where the thing is, with how far a wrist missed (metres) and how far the body was turned from its own motion (degrees)"),("character.fit", raea_sys_grab::FIT_ARGS, raea_sys_grab::FIT_ANSWER, "a pose fitted to points of the body seen somewhere (joints or marks on them, from a capture, a tracker or another rig), and their root-mean-square miss, metres"),("character.hand", raea_sys_grab::HAND_ARGS, raea_sys_grab::HAND_ANSWER, "a hand shaped by a few numbers of a model of real hand poses (none: the average relaxed hand; the first opens it, positive, and closes it), on a pose; and that hand read back: its numbers and how odd it is (0: the average hand)"),+ ("character.soma", raea_sys_grab::SOMA_ARGS, raea_sys_grab::SOMA_ANSWER, "the pose that has a body's bones pointing as a SOMA body's do (SOMA: the 78-joint skeleton of NVIDIA's motion models and datasets), from SOMA's joint names and where each joint is"),("fonts.families", "{}", "string[]", "the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them"),("fonts.google", "{ family: string }", "{ family: string }", "a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont)"),("fonts.atlases", "{ font: string; size: number; text: string }", "{ width: number; height: number; src: string }[]", "bevy_text's glyph atlases for a text in a font file at a size px, each page a PNG data: URL, as Bevy's FontAtlasSet holds them"),diff --git a/sdk/character/package.json b/sdk/character/package.jsonindex cc1219ca..db830575 100644--- a/sdk/character/package.json+++ b/sdk/character/package.json@@ -23,6 +23,7 @@"./character": "./src/character.tsx","./ragdoll": "./src/ragdoll.ts","./take": "./src/take.ts",+ "./soma": "./src/soma.ts","./plugin": "./src/plugin.ts"},"peerDependencies": { "react": "19.2.0" },diff --git a/sdk/character/src/character.tsx b/sdk/character/src/character.tsxindex a23a156b..01c8bef9 100644--- a/sdk/character/src/character.tsx+++ b/sdk/character/src/character.tsx@@ -20,3 +20,6 @@ export type { Quat, Joint, Skeleton, Pose, Posed, Side, Finger, HandShape, Closi// a character takes a thing with its hands, with no capture of the action (docs/hands.feature)export { take, fetch, fitPose, handShape, placedPose, walkUp } from "./take";export type { TakeThing, TakeSpec, Taken, Mark } from "./take";+// motion on SOMA's skeleton (NVIDIA's motion models and datasets) played on a raea body+export { readSomaUsda, somaPose } from "./soma";+export type { SomaClip } from "./soma";diff --git a/sdk/character/src/soma.ts b/sdk/character/src/soma.tsnew file mode 100644index 00000000..45a517ec--- /dev/null+++ b/sdk/character/src/soma.ts@@ -0,0 +1,65 @@+// @raea/character/soma: motion on SOMA's skeleton played on a raea body. SOMA (NVlabs/SOMA-X, Apache-2.0) is the+// 78-joint skeleton NVIDIA's motion models and datasets speak (Kimodo, GEM-X, BONES-SEED). A SOMA animation saved+// as text USD (a SkelAnimation: joints, and each frame's turns and offsets) is read into where every joint is at+// every frame; somaPose then points the body's bones the way SOMA's point at a frame (the native call+// character.soma), whatever the two bodies' proportions.+//+// import walk from "./assets/clips/soma-walk.usda?raw";+// const clip = readSomaUsda(walk);+// <Character body="kid" pose={somaPose(kid, clip, frame * (clip.fps / fps))} />+import { native } from "@raea/app/native";+import type { Pose, Quat, Skeleton } from "./character/core";+import { qmul, qrot } from "./character/vectors";++type Vec3 = [number, number, number];++export interface SomaClip {+ fps: number;+ /** SOMA's joints by name (the last part of each joint's path) */+ names: string[];+ /** each frame: where every joint is, metres, y up */+ frames: Vec3[][];+}++const numbers = (text: string): number[] => (text.match(/-?\d+(?:\.\d+)?(?:e[-+]?\d+)?/gi) ?? []).map(Number);++/** one attribute's time samples: each frame's flat list of numbers, in frame order */+function samples(usda: string, attribute: string): number[][] {+ const at = usda.indexOf(`${attribute}.timeSamples`);+ if (at < 0) throw new Error(`SOMA animation: no ${attribute}`);+ const open = usda.indexOf("{", at), close = usda.indexOf("}", open), out: [number, number[]][] = [];+ for (const line of usda.slice(open + 1, close).split("\n")) {+ const colon = line.indexOf(":");+ if (colon > 0) out.push([Number(line.slice(0, colon)), numbers(line.slice(colon + 1))]);+ }+ return out.sort((a, b) => a[0] - b[0]).map((s) => s[1]);+}++/** A SOMA animation as text USD read: forward kinematics over its joints, into where each is at each frame. */+export function readSomaUsda(usda: string): SomaClip {+ const paths = [...(/uniform token\[\] joints = \[([^\]]*)\]/.exec(usda)?.[1] ?? "").matchAll(/"([^"]+)"/g)].map((m) => m[1]);+ if (!paths.length) throw new Error("SOMA animation: no joints");+ const parent = paths.map((p) => paths.indexOf(p.slice(0, p.lastIndexOf("/"))));+ const unit = Number(/metersPerUnit = ([\d.e-]+)/.exec(usda)?.[1] ?? 0.01), fps = Number(/framesPerSecond = ([\d.]+)/.exec(usda)?.[1] ?? 24);+ const turns = samples(usda, "rotations"), offsets = samples(usda, "translations");+ const frames = turns.map((r, f) => {+ const t = offsets[Math.min(f, offsets.length - 1)], pos: Vec3[] = [], rot: Quat[] = [];+ paths.forEach((_, j) => {+ // (USD writes a quaternion w first)+ const local: Quat = [r[j * 4 + 1], r[j * 4 + 2], r[j * 4 + 3], r[j * 4]], off: Vec3 = [t[j * 3] * unit, t[j * 3 + 1] * unit, t[j * 3 + 2] * unit], p = parent[j];+ if (p < 0) { pos.push(off); rot.push(local); return; }+ const moved = qrot(rot[p], off);+ pos.push([pos[p][0] + moved[0], pos[p][1] + moved[1], pos[p][2] + moved[2]]);+ rot.push(qmul(rot[p], local));+ });+ return pos;+ });+ return { fps, names: paths.map((p) => p.slice(p.lastIndexOf("/") + 1)), frames };+}++/** The body posed as a SOMA animation has its body at a frame (a whole frame; the nearest is taken). */+export function somaPose(skel: Skeleton, clip: SomaClip, frame: number): Pose {+ const at = clip.frames[Math.max(0, Math.min(clip.frames.length - 1, Math.round(frame)))];+ const joints = skel.joints.map((j) => ({ name: j.name, parent: j.parent, head: j.head, tail: j.tail }));+ return native("character.soma", { joints, names: clip.names, at, eyes: skel.landmarks?.eyes }).pose;+}diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.tsindex da6bc862..ade2abed 100644--- a/sdk/raea/src/native-calls.ts+++ b/sdk/raea/src/native-calls.ts@@ -40,6 +40,8 @@ export interface NativeCalls {"character.fit": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; marks: { joint: string; offset?: [number, number, number]; at: [number, number, number]; weight?: number }[]; from?: { root: [number, number, number]; turns: [number, number, number, number][] }; passes?: number }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] }; miss: number } };/** a hand shaped by a few numbers of a model of real hand poses (none: the average relaxed hand; the first opens it, positive, and closes it), on a pose; and that hand read back: its numbers and how odd it is (0: the average hand) */"character.hand": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; side: "L" | "R"; z?: number[]; pose?: { root: [number, number, number]; turns: [number, number, number, number][] } }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] }; z: number[]; odd: number } };+ /** the pose that has a body's bones pointing as a SOMA body's do (SOMA: the 78-joint skeleton of NVIDIA's motion models and datasets), from SOMA's joint names and where each joint is */+ "character.soma": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; names: string[]; at: [number, number, number][]; eyes?: [number, number, number] }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] } } };/** a frame of a character taking a thing with its hands (reach, grab, lift, carry, put down or throw): the pose to draw and where the thing is, with how far a wrist missed (metres) and how far the body was turned from its own motion (degrees) */"character.take": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; t: number; base: { t: number; root: [number, number, number]; turns: [number, number, number, number][] }[]; thing: { ball?: number; box?: [number, number, number]; capsule?: [number, number]; cylinder?: [number, number]; at: [number, number, number]; turn?: [number, number, number, number] }; start: number; grab?: number; carried?: number; carry?: [number, number, number]; hand?: "L" | "R"; lower?: number; holds?: { side: "L" | "R"; at: [number, number, number]; normal: [number, number, number]; along?: [number, number, number]; shape?: number[] }[]; path?: { t: number; carry: [number, number, number]; tilt?: [number, number, number, number] }[]; weight?: number; pass?: number; slide?: { t: number; at: [number, number, number]; turn?: [number, number, number, number] }[]; leave?: number; avoid?: { ball?: number; box?: [number, number, number]; capsule?: [number, number]; cylinder?: [number, number]; at: [number, number, number]; turn?: [number, number, number, number] }[]; put?: { at: number; down: number; place: [number, number, number] }; throw?: { at: number; velocity: [number, number, number]; floor?: number } }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] }; thing: { at: [number, number, number]; turn: [number, number, number, number] }; phase: "Before" | "Reach" | "Lift" | "Carry" | "Release" | "After"; hands: 1 | 2; miss: number; moved: number; limited: boolean; stand: { at: [number, number, number]; yaw: number }; reach: { ok: boolean; move: number } } };/** raea's command line (render, play, guide, bundle, types; the media verbs: raea media, raea ffmpeg), run in process in cwd */diff --git a/systems/body/src/arm.rs b/systems/body/src/arm.rsindex fd467c37..d470292e 100644--- a/systems/body/src/arm.rs+++ b/systems/body/src/arm.rs@@ -81,23 +81,11 @@ pub fn two_bone(skel: &Skeleton, p: &Pose, limb: [usize; 3], target: Vec3, o: Arturn_a = Quat::from_axis_angle(to, angle) * swing;}}- let mut ra = (turn_a * w.rot[a]).normalize();+ let ra = (turn_a * w.rot[a]).normalize();let rb = (turn_a * flex * w.rot[b]).normalize();// the middle joint is a hinge with an axis of its own, the one the rest pose's bend is about (an elbow's, a- // knee's). The first bone is turned about itself until that axis is the one the limb is bent about, as an upper- // arm turns in its socket: so the middle joint flexes and never bends sideways. A limb at rest nearly straight- // has no such axis to read, and a limb posed nearly straight no bend to match: less turn the nearer either is.- let (bone_a, bone_b) = (skel.offset(b) / la, skel.offset(c) / lb);- let (own, bent) = (bone_a.cross(bone_b), (turn_a * u).cross(turn_a * flex * v));- let sure = (own.length() / 0.2).min(1.0) * (bent.length() / 0.2).min(1.0);- if sure > 0.0 {- let along = (turn_a * u).normalize();- let (has, wants) = ((ra * own).reject_from_normalized(along), bent.reject_from_normalized(along));- if has.length() > 1e-4 && wants.length() > 1e-4 {- let angle = has.cross(wants).dot(along).atan2(has.dot(wants));- ra = (Quat::from_axis_angle(along, angle * sure * sure * (3.0 - 2.0 * sure)) * ra).normalize();- }- }+ // knee's): the first bone is turned about itself until that axis is the one the limb is bent about (hinge_turn)+ let ra = (hinge_turn(skel, limb, ra, (turn_a * u).normalize(), (turn_a * u).cross(turn_a * flex * v)) * ra).normalize();let rc = o.end.unwrap_or(w.rot[c]);let mut pose = p.clone();@@ -196,3 +184,31 @@ pub const TWIST_SHARES: [f32; 4] = [0.05, 1.0 / 3.0, 2.0 / 3.0, 0.95];pub fn twist_joints(axis: Vec3, start: f32, end: f32, upper: bool) -> [Quat; 4] {TWIST_SHARES.map(|share| Quat::from_axis_angle(axis, if upper { -(1.0 - share) * start + share * end } else { share * end }))}++/// The turn of a limb's first bone about itself (`along`, as posed) that makes the hinge its rest pose bends about+/// the one the limb is bent about now (`bent`: the first bone crossed with the second, as posed), as an upper arm+/// turns in its socket: so the middle joint flexes and never bends sideways. `ra` is the first bone's world turn. A+/// limb at rest nearly straight has no such axis to read, and a limb posed nearly straight no bend to match: less+/// turn the nearer either is.+fn hinge_turn(skel: &Skeleton, limb: [usize; 3], ra: Quat, along: Vec3, bent: Vec3) -> Quat {+ let own = skel.offset(limb[1]).normalize_or_zero().cross(skel.offset(limb[2]).normalize_or_zero());+ let sure = (own.length() / 0.2).min(1.0) * (bent.length() / 0.2).min(1.0);+ let (has, wants) = ((ra * own).reject_from_normalized(along), bent.reject_from_normalized(along));+ if sure <= 0.0 || has.length() < 1e-4 || wants.length() < 1e-4 {+ return Quat::IDENTITY;+ }+ Quat::from_axis_angle(along, has.cross(wants).dot(along).atan2(has.dot(wants)) * sure * sure * (3.0 - 2.0 * sure))+}++/// A pose with a limb's first bone turned about itself so its middle joint flexes about its own axis, every joint+/// staying where it is: for a pose that came from places alone (a fit), which leaves that turn open.+pub fn settle_hinge(skel: &Skeleton, p: &Pose, limb: [usize; 3]) -> Pose {+ let [a, b, c] = limb;+ let w = skel.fk(p);+ let (u, v) = ((w.pos[b] - w.pos[a]).normalize_or_zero(), (w.pos[c] - w.pos[b]).normalize_or_zero());+ let ra = (hinge_turn(skel, limb, w.rot[a], u, u.cross(v)) * w.rot[a]).normalize();+ let mut pose = p.clone();+ pose.turns[a] = skel.local_for(&w, a, ra);+ pose.turns[b] = (ra.inverse() * w.rot[b]).normalize();+ pose+}diff --git a/systems/body/src/json.rs b/systems/body/src/json.rsindex 6c3fea52..9713f037 100644--- a/systems/body/src/json.rs+++ b/systems/body/src/json.rs@@ -6,7 +6,8 @@ use serde_json::{Value, json};use crate::fit::{Mark, fit};use crate::prior::{coefficients, oddness, shape};-use crate::rig::{Side, Skeleton};+use crate::rig::{Pose, Side, Skeleton};+use crate::soma::from_soma;pub fn num(v: &Value, what: &str) -> Result<f32, String> {v.as_f64().map(|n| n as f32).ok_or_else(|| format!("character.take: {what} isn't a number"))@@ -45,8 +46,7 @@ pub fn fit_json(v: &Value) -> Result<Value, String> {}let passes = v["passes"].as_u64().unwrap_or(8) as usize;let (pose, miss) = fit(&skel, &from, &marks, passes);- let turns: Vec<[f32; 4]> = pose.turns.iter().map(|q| q.to_array()).collect();- Ok(json!({ "pose": { "root": pose.root.to_array(), "turns": turns }, "miss": miss }))+ Ok(json!({ "pose": posed(&pose), "miss": miss }))}pub const HAND_ARGS: &str = "{ joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; side: \"L\" | \"R\"; z?: number[]; pose?: { root: [number, number, number]; turns: [number, number, number, number][] } }";@@ -70,6 +70,33 @@ pub fn hand_json(v: &Value) -> Result<Value, String> {}let (z, _) = coefficients(&skel, &pose, side).ok_or("character.hand: the body has no hand on that side")?;let odd = oddness(&skel, &pose, side).unwrap_or(0.0);+ Ok(json!({ "pose": posed(&pose), "z": z, "odd": odd }))+}++pub const SOMA_ARGS: &str = "{ joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; names: string[]; at: [number, number, number][]; eyes?: [number, number, number] }";+pub const SOMA_ANSWER: &str = "{ pose: { root: [number, number, number]; turns: [number, number, number, number][] } }";++/// `character.soma`: the pose that has the body's bones pointing as a SOMA body's do (soma.rs).+pub fn soma_json(v: &Value) -> Result<Value, String> {+ let skel = Skeleton::from_value(v)?;+ let mut names = Vec::new();+ for name in v["names"].as_array().ok_or("character.soma: no names")? {+ names.push(name.as_str().ok_or("character.soma: a name isn't text")?.to_string());+ }+ let mut at = Vec::with_capacity(names.len());+ for p in v["at"].as_array().ok_or("character.soma: no places")? {+ at.push(vec3(p, "a SOMA joint's place")?);+ }+ if at.len() != names.len() {+ return Err(format!("character.soma: {} names for {} places", names.len(), at.len()));+ }+ let eyes = if v["eyes"].is_null() { None } else { Some(vec3(&v["eyes"], "eyes")?) };+ let pose = from_soma(&skel, &names, &at, eyes).ok_or("character.soma: the body or the SOMA joints lack the hips or a leg")?;+ Ok(json!({ "pose": posed(&pose) }))+}++/// a pose as the calls answer it: the root's place and every joint's turn+pub fn posed(pose: &Pose) -> Value {let turns: Vec<[f32; 4]> = pose.turns.iter().map(|q| q.to_array()).collect();- Ok(json!({ "pose": { "root": pose.root.to_array(), "turns": turns }, "z": z, "odd": odd }))+ json!({ "root": pose.root.to_array(), "turns": turns })}diff --git a/systems/body/src/lib.rs b/systems/body/src/lib.rsindex 07e077a7..7e48f048 100644--- a/systems/body/src/lib.rs+++ b/systems/body/src/lib.rs@@ -8,6 +8,7 @@//! - `fit`: a pose fitted to points seen (SOMA-X's analytical pose inversion), for motion that arrives as positions.//! - `shape`: a solid as a signed distance: ray casts, normals, clearance.//! - `json`: character.fit and character.hand, asked for as JSON.+//! - `soma`: motion on SOMA's 78-joint skeleton played on the rig, by the way its bones point.//! - `prior`: SOMA-X's hand pose prior on raea's fingers: a hand's shape from a few numbers, and how odd a hand is.pub mod arm;@@ -17,10 +18,12 @@ pub mod limits;pub mod prior;pub mod rig;pub mod shape;+pub mod soma;-pub use arm::{ArmOptions, IkReport, forearm_twist, reach, twist_joints, two_bone};+pub use arm::{ArmOptions, IkReport, forearm_twist, reach, settle_hinge, twist_joints, two_bone};+pub use soma::{from_soma, raea_joint};pub use fit::{Mark, fit, marks_of};-pub use json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, fit_json, hand_json};+pub use json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, SOMA_ANSWER, SOMA_ARGS, fit_json, hand_json, soma_json};pub use limits::{Angles, angles_of, clamp_turn, violations};pub use shape::{Hit, Solid, Thing};pub use rig::{HandRest, Pose, Posed, Sample, Side, Skeleton, hand_rest, mannequin};diff --git a/systems/body/src/soma.rs b/systems/body/src/soma.rsnew file mode 100644index 00000000..f3e545a7--- /dev/null+++ b/systems/body/src/soma.rs@@ -0,0 +1,91 @@+//! Motion on SOMA's skeleton played on raea's rig. SOMA (NVlabs/SOMA-X, Apache-2.0) is the 78-joint skeleton+//! NVIDIA's motion models and datasets speak (Kimodo, GEM-X, BONES-SEED...); raea's rig is MakeHuman's game_engine,+//! 52 joints. The bridge is by direction, not by turn: each of raea's bones is pointed the way SOMA's matching bone+//! points, at raea's own lengths, so the two bodies' proportions and bind poses don't have to agree; the pose is+//! then fitted to those places (fit.rs). Positions alone leave a limb's turn about itself open: the first bone of+//! each arm and leg is turned so its elbow or knee flexes about its own axis (arm.rs).++use std::collections::HashMap;++use glam::Vec3;++use crate::arm::settle_hinge;+use crate::fit::{Mark, fit};+use crate::rig::{Pose, Side, Skeleton};++/// raea's joint for a SOMA joint: the trunk and head by name, limbs and fingers by side. A SOMA finger's 2, 3, 4 are+/// raea's 01, 02, 03 (its 1 is the metacarpal, which raea's hand has none of); the thumb's are 1, 2, 3.+pub fn raea_joint(soma: &str) -> Option<String> {+ let trunk = [("Hips", "pelvis"), ("Spine1", "spine_01"), ("Spine2", "spine_02"), ("Chest", "spine_03"), ("Neck1", "neck_01"), ("Head", "head")];+ if let Some(t) = trunk.iter().find(|t| t.0 == soma) {+ return Some(t.1.to_string());+ }+ let (side, rest) = soma.strip_prefix("Left").map(|r| ("l", r)).or_else(|| soma.strip_prefix("Right").map(|r| ("r", r)))?;+ let limb = [("Shoulder", "clavicle"), ("Arm", "upperarm"), ("ForeArm", "lowerarm"), ("Hand", "hand"), ("Leg", "thigh"), ("Shin", "calf"), ("Foot", "foot"), ("ToeBase", "ball")];+ if let Some(l) = limb.iter().find(|l| l.0 == rest) {+ return Some(format!("{}_{side}", l.1));+ }+ let finger = rest.strip_prefix("Hand")?;+ let (name, n) = finger.split_at(finger.len().checked_sub(1)?);+ let (name, n) = (name.to_lowercase(), n.parse::<usize>().ok()?);+ let k = if name == "thumb" { n } else { n.checked_sub(1)? };+ (1..=3).contains(&k).then(|| format!("{name}_0{k}_{side}"))+}++/// the SOMA joint that ends a raea joint's bone, where raea has no joint of its own there+fn bone_end(raea: &str) -> Option<String> {+ let side = if raea.ends_with("_l") { "Left" } else { "Right" };+ match raea.trim_end_matches("_l").trim_end_matches("_r") {+ "head" => Some("HeadEnd".into()),+ "ball" => Some(format!("{side}ToeEnd")),+ tip => tip.strip_suffix("_03").map(|finger| format!("{side}Hand{}{}End", finger[..1].to_uppercase(), &finger[1..])),+ }+}++/// The pose that has raea's bones pointing as a SOMA body's do. `names` and `at` are SOMA's joints and where each is+/// (any unit, y up); `eyes` is where the point between raea's eyes is at rest, when the body says (it gives the+/// head its turn about the neck). The body stands where SOMA's hips are, scaled by the two bodies' leg lengths.+pub fn from_soma(skel: &Skeleton, names: &[String], at: &[Vec3], eyes: Option<Vec3>) -> Option<Pose> {+ let soma: HashMap<&str, Vec3> = names.iter().map(String::as_str).zip(at.iter().copied()).collect();+ let seen: HashMap<usize, Vec3> = names.iter().zip(at).filter_map(|(n, p)| Some((skel.joint(&raea_joint(n)?)?, *p))).collect();+ let pelvis = skel.joint("pelvis")?;+ // the scale between the bodies: raea's leg (hip to knee to ankle) over SOMA's+ let leg = |a: Vec3, b: Vec3, c: Vec3| (b - a).length() + (c - b).length();+ let [thigh, calf, foot] = ["thigh_l", "calf_l", "foot_l"].map(|n| skel.joint(n));+ let (thigh, calf, foot) = (thigh?, calf?, foot?);+ let ours = leg(skel.joints[thigh].head, skel.joints[calf].head, skel.joints[foot].head);+ let scale = ours / leg(*seen.get(&thigh)?, *seen.get(&calf)?, *seen.get(&foot)?).max(1e-6);+ // each of raea's joints placed from its parent's, the way SOMA's matching joints lie, at raea's own length+ let mut place: Vec<Option<Vec3>> = vec![None; skel.joints.len()];+ place[pelvis] = Some(*seen.get(&pelvis)? * scale);+ let mut marks = vec![Mark { joint: pelvis, offset: Vec3::ZERO, at: place[pelvis]?, weight: 1.0 }];+ for (i, joint) in skel.joints.iter().enumerate() {+ let Some(parent) = joint.parent else { continue };+ let (Some(from), Some(a), Some(b)) = (place[parent], seen.get(&parent), seen.get(&i)) else { continue };+ let to = from + (*b - *a).normalize_or_zero() * skel.offset(i).length();+ place[i] = Some(to);+ marks.push(Mark { joint: i, offset: Vec3::ZERO, at: to, weight: 1.0 });+ // and a bone's end, where SOMA has a joint for it and raea has none+ if let Some(end) = bone_end(&joint.name).and_then(|n| soma.get(n.as_str())) {+ let bone = joint.tail - joint.head;+ marks.push(Mark { joint: i, offset: bone, at: to + (*end - *b).normalize_or_zero() * bone.length(), weight: 1.0 });+ }+ }+ // the head's turn about the neck, from SOMA's eyes+ if let (Some(eyes), Some(head), Some(l), Some(r)) = (eyes, skel.joint("head"), soma.get("LeftEye"), soma.get("RightEye")) {+ if let (Some(to), Some(at)) = (place[head], seen.get(&head)) {+ let offset = eyes - skel.joints[head].head;+ marks.push(Mark { joint: head, offset, at: to + ((*l + *r) / 2.0 - *at).normalize_or_zero() * offset.length(), weight: 1.0 });+ }+ }+ let mut pose = fit(skel, &skel.rest(), &marks, 6).0;+ for side in Side::BOTH {+ let x = side.sx();+ for limb in [["upperarm", "lowerarm", "hand"], ["thigh", "calf", "foot"]] {+ if let [Some(a), Some(b), Some(c)] = limb.map(|n| skel.joint(&format!("{n}_{x}"))) {+ pose = settle_hinge(skel, &pose, [a, b, c]);+ }+ }+ }+ Some(pose)+}diff --git a/systems/body/tests/body.rs b/systems/body/tests/body.rsindex e6c20177..7dd97113 100644--- a/systems/body/tests/body.rs+++ b/systems/body/tests/body.rs@@ -84,3 +84,60 @@ fn the_hand_prior_shapes_and_reads_hands() {assert!(odd > 2.0 * usual, "fingers bent back read {odd}, the rest hand {usual}");}}++#[test]+fn soma_names_map_onto_the_rig() {+ for (soma, raea) in [("Hips", "pelvis"), ("Chest", "spine_03"), ("LeftForeArm", "lowerarm_l"), ("RightShin", "calf_r"), ("LeftToeBase", "ball_l"), ("LeftHandThumb1", "thumb_01_l"), ("RightHandIndex2", "index_01_r"), ("LeftHandPinky4", "pinky_03_l")] {+ assert_eq!(raea_joint(soma).as_deref(), Some(raea));+ }+ // what the rig has no joint for+ for soma in ["Root", "Neck2", "Jaw", "LeftEye", "LeftHandIndex1", "RightHandMiddleEnd", "LeftToeEnd"] {+ assert_eq!(raea_joint(soma), None, "{soma}");+ }+}++#[test]+fn a_soma_body_of_other_proportions_is_followed_bone_for_bone() {+ let s = mannequin();+ // a "SOMA" body: the rig's own joints under SOMA's names, 1.3 times the size and in centimetres, posed+ let soma_name = |raea: &str| {+ ["Hips", "Spine1", "Spine2", "Chest", "Neck1", "Head"].iter().map(|n| n.to_string()).chain(["Left", "Right"].iter().flat_map(|side| {+ ["Shoulder", "Arm", "ForeArm", "Hand", "Leg", "Shin", "Foot", "ToeBase"].iter().map(move |n| format!("{side}{n}")).chain(["Thumb1", "Thumb2", "Thumb3"].iter().map(move |n| format!("{side}Hand{n}"))).chain(["Index", "Middle", "Ring", "Pinky"].iter().flat_map(move |f| [2, 3, 4].map(move |k| format!("{side}Hand{f}{k}"))))+ })).find(|n| raea_joint(n).as_deref() == Some(raea))+ };+ let mut r = {+ let mut seed = 5u32;+ move || {+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);+ (seed >> 8) as f32 / 16777216.0+ }+ };+ let mut seen = s.rest();+ seen.root += Vec3::new(0.4, -0.1, 1.0);+ for (i, turn) in seen.turns.iter_mut().enumerate() {+ if s.joints[i].parent.is_some() && !s.joints[i].name.contains("_0") {+ *turn = Quat::from_axis_angle(Vec3::new(r() - 0.5, r() - 0.5, r() - 0.5).normalize(), r() * 0.7);+ }+ }+ let w = s.fk(&seen);+ let (mut names, mut at) = (Vec::new(), Vec::new());+ for (i, joint) in s.joints.iter().enumerate() {+ names.push(soma_name(&joint.name).unwrap());+ at.push(w.pos[i] * 130.0);+ }+ let pose = from_soma(&s, &names, &at, None).unwrap();+ let got = s.fk(&pose);+ // every bone of the body points as the SOMA body's does, and it stands where that body does (to scale)+ for (i, joint) in s.joints.iter().enumerate() {+ let Some(parent) = joint.parent else { continue };+ let (ours, theirs) = ((got.pos[i] - got.pos[parent]).normalize(), (w.pos[i] - w.pos[parent]).normalize());+ assert!(ours.angle_between(theirs).to_degrees() < 2.0, "{} points {} degrees off", joint.name, ours.angle_between(theirs).to_degrees());+ }+ assert!((got.pos[0] - w.pos[0]).length() < 0.01);+ // and its elbows and knees are not bent sideways+ for name in ["lowerarm_l", "lowerarm_r", "calf_l", "calf_r"] {+ let j = s.joint(name).unwrap();+ let side = angles_of(&s, j, pose.turns[j]).unwrap().side;+ assert!(side.abs() < 25.0, "{name} bends {side} degrees sideways");+ }+}diff --git a/systems/grab/src/json.rs b/systems/grab/src/json.rsindex 3a9108d5..fb5ea21b 100644--- a/systems/grab/src/json.rs+++ b/systems/grab/src/json.rs@@ -3,7 +3,7 @@//! grab's, the release's); the answer is the pose to draw and where the thing is.use glam::Quat;-use raea_sys_body::json::{num, quat, vec3};+use raea_sys_body::json::{num, posed, quat, vec3};use serde_json::{Value, json};use crate::trunk::stand_for;@@ -125,9 +125,8 @@ pub fn take_json(v: &Value) -> Result<Value, String> {let (stand, facing) = stand_for(&thing, own(start).root);// whether the body can take it from where it stands when it starts to reach: at the grab, every wrist on its holdlet in_reach = perform(&skel, &own, &take, take.grab).miss < 0.02;- let turns: Vec<[f32; 4]> = f.pose.turns.iter().map(|q| q.to_array()).collect();Ok(json!({- "pose": { "root": f.pose.root.to_array(), "turns": turns },+ "pose": posed(&f.pose),"thing": { "at": f.thing.at.to_array(), "turn": f.thing.turn.to_array() },"phase": format!("{:?}", f.phase),"hands": if matches!(grip, Grip::One(_)) { 1 } else { 2 },diff --git a/systems/grab/src/lib.rs b/systems/grab/src/lib.rsindex fe5b2650..daba9725 100644--- a/systems/grab/src/lib.rs+++ b/systems/grab/src/lib.rs@@ -22,6 +22,6 @@ pub mod trunk;pub use hand::{Grip, Hold, HoldOptions, Touch, curl, find_holds, wrist_for};pub use interact::pick;pub use json::{TAKE_ANSWER, TAKE_ARGS, take_json};-pub use raea_sys_body::json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, fit_json, hand_json};+pub use raea_sys_body::json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, SOMA_ANSWER, SOMA_ARGS, fit_json, hand_json, soma_json};pub use take::{Frame, Key, Phase, Release, Take, perform};pub use trunk::{clear, give_for, hand_points, look, own_solids, room, spread_for, stand_for, stoop, torso};