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
HG6b, HG5b: the arms inside the rig's ranges, the head and chest out of the scene's solids, and SOMA-X's hand prior on raea's fingers. limits.rs is sdk/body's axes and limits in Rust (the same ranges); a take holds both arms inside them and says when it had to. When a solved pose puts the head, neck or chest within 9 cm of a solid the take is solved again with less bend and lean and more squat. prior.rs and data/soma_hand_prior.bin (SOMA-X, Apache-2.0; data/README.md): a 32-component model of real hand poses cut to the rig's fifteen finger joints; a hand shaped by a few numbers, any hand read back and scored; a take opens the hand as it comes in. raea/character's handShape is the native call character.hand. 23 tests. The take scene is the Character SDK project's
shinyobjectzf6b3188d9f80
diff --git a/docs/hands.feature b/docs/hands.featureindex d4ea45b2..53a7e8b2 100644--- a/docs/hands.feature+++ b/docs/hands.feature@@ -178,25 +178,55 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri# Not converted, and why: SOMA's body and hand layers, identity models and correctives are a different# mesh and a 78-joint rig driven by PyTorch and Warp, and raea's body is MakeHuman's; its hand# articulation prior (SOMAHand.npz, 32 components over SOMA's 24 finger joints, bind-relative) needs- # SOMA's finger frames mapped onto game_engine's 15 finger joints before a score means anything (HG8);- # its Lie-algebra and autograd refinements fit mesh vertices through skinning, which marks don't need.+ # SOMA's finger frames mapped onto game_engine's 15 finger joints before a score means anything (done+ # since: HG5b); its Lie-algebra and autograd refinements fit mesh vertices through skinning, which marks don't need.Then a body can choose what to take, look at it, and be posed from positions seen+ @done+ Scenario: HG6b. The arms inside the rig's ranges, and the head and chest out of the scene's solids+ # 11-14, built. limits.rs is sdk/body's axes.ts and limits.ts in Rust: each joint's turn read as flex, side+ # and twist from the rest pose, the same ranges (13 roles, the right side mirrored), a turn brought inside+ # them, a pose's violations. Through a take every joint of both arms is inside its range and a frame that+ # had to hold one says so (`limited`). body.rs `roomy`: when the solved pose puts the head's top, the neck+ # or the chest within 9 cm of a solid in a take's `avoid`, the take is solved again with less bend and+ # lean and more squat (to 0.82 m of hips), a sixth at a time. With a table 38 cm in front and a box on the+ # floor between, none of the three is in the table at any frame and the hold is kept within 5 cm; with no+ # table the same take bends over where the table was. Seen on teal: an upright deep squat beside the+ # table, the head clear, the eyes on the box. Not done: the knees and the forearms keep out of nothing,+ # and the two copies of the limits (TypeScript, Rust) are kept in step by hand.+ Then no arm joint is past its range, and bending never puts the head or chest into a solid++ @done+ Scenario: HG5b. SOMA-X's hand prior on raea's fingers+ # 11-14, built. prior.rs and data/soma_hand_prior.bin (12 KB; data/README.md has its source and licence):+ # the left hand's 32-component model of real hand poses, cut to the fifteen finger joints raea has (the+ # metacarpals and fingertip ends left out; 99% of the first component is on the kept joints). SOMA's+ # turns are from its flat bind hand in the wrist's axes (fingers along +x, palm +z); each raea finger bone+ # is pointed where SOMA's would, in the hand's own rest frame, the right hand mirrored. `shape` gives a+ # hand from a few numbers: none is the average relaxed hand, the first opens it (+2) and closes it to a+ # fist (-2). `coefficients` reads a hand back (a shape's numbers within 0.05, under half a degree left+ # over) and `oddness` compares hands: the average 0, the rig's rest hand 2.0, fingers bent back at the+ # middle joint 4.3. A take now opens the hand as it comes in (the first number at +1.5) before the+ # fingers shut. raea/character's `handShape(skel, side, z)` is the native call character.hand. Seen on+ # teal: the sweep goes from a fist to an open hand, on a hand mesh whose skinning is coarse.+ # Still not converted: SOMA's body and hand meshes, identity models and correctives (a different mesh+ # and a 78-joint rig on PyTorch and Warp), and the vertex-fitting refinements of its pose inversion.+ Then a hand can be given a natural shape by number, and any hand can be scored against real ones+Rule: Next, in order@needs:HG5- Scenario: HG6. The rig's real limits and the body's real shape- # sdk/body has both in TypeScript (limits.ts: ranges checked against 26,288 captured frames; shape.ts,- # shell.ts: the skin). systems/grab has caps on the trunk's lean and finger ranges, and HG6a for the hands.- Given a solved arm- Then every joint is inside the range sdk/body's limits give, the elbow and wrist first- And the forearm, the elbow, the trunk, the head and the held thing stay out of the body and the scene's- solids, by the least move+ Scenario: HG6. The whole body out of itself and the scene+ # HG6a keeps the hands out of solids and HG6b the head and chest; the arms are inside their ranges.+ Then the forearms, the elbows, the knees and the held thing stay out of the body's own shape (sdk/body's+ shape.ts and shell.ts) and the scene's solids, by the least moveAnd one copy of the limits serves both the TypeScript and the Rust@needs:HG5Scenario: HG7. The body walks to the thing- # HG7a says where to stand; nothing walks there yet.+ # HG7a says where to stand; nothing walks there yet. sdk/body's locomotion plays a library retargeted to a+ # body, and only the MakeHuman test people have one: the Character SDK project's characters have a single+ # walk clip each, so this waits on their library (or on locomotion taking any body's).Given a thing out of reachThen locomotion (sdk/body's) is asked to arrive at the take's standing place, facing it, and the takestarts when it has@@ -209,7 +239,7 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carriThen its holds come with the thing, as places and hand shapes, from the 35 captured hand poses(character/captured.ts) where one fitsAnd a thing with no holds of its own gets HG2's- And a hand shape is scored against SOMA-X's hand prior before it is kept+ And a hand shape is scored against the hand prior (HG5b) before it is kept@needs:HG5Scenario: HG9. Using what is held, and handing it overdiff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rsindex 84ba5680..c43159de 100644--- a/runtime/calls/src/lib.rs+++ b/runtime/calls/src/lib.rs@@ -176,6 +176,7 @@ pub fn call(name: &str, v: &Value) -> R<Value> {// a frame of a character taking a thing (raea-sys-grab, docs/hands.feature HG5)"character.take" => raea_sys_grab::take_json(v),"character.fit" => raea_sys_grab::fit_json(v),+ "character.hand" => raea_sys_grab::hand_json(v),"fonts.families" => Ok(families().into()),"fonts.google" => {let family = s(v, "family")?;@@ -226,6 +227,7 @@ pub fn register() {("place.solve", "{ objects: { id: string; size: [number, number, number]; at?: [number, number, number]; yaw?: number; fixed?: boolean }[]; rules: Record<string, string | number>[]; room?: { min: [number, number]; max: [number, number] } }", "{ objects: { id: string; at: [number, number, number]; yaw: number; size: [number, number, number] }[]; found: { part: string; check: string; level: string; says: string }[]; errors: number }", "boxes placed by relations (on, against, beside, near, apart, facing, align, clear), what can't hold found"),("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)"),("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/src/character.tsx b/sdk/character/src/character.tsxindex 0f1303a6..d9842ece 100644--- a/sdk/character/src/character.tsx+++ b/sdk/character/src/character.tsx@@ -18,5 +18,5 @@ 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, fitPose } from "./take";+export { take, fitPose, handShape } from "./take";export type { TakeThing, TakeSpec, Taken, Mark } from "./take";diff --git a/sdk/character/src/take.ts b/sdk/character/src/take.tsindex 9af4e255..735afbc1 100644--- a/sdk/character/src/take.ts+++ b/sdk/character/src/take.ts@@ -95,3 +95,13 @@ export function fitPose(skel: Skeleton, marks: Mark[], from?: Pose, passes?: numconst start = from && { root: from.root, turns: skel.joints.map((_, i) => from.turns[i] ?? ([0, 0, 0, 1] as Quat)) };return native("character.fit", { joints, marks, from: start, passes });}++/** A hand shaped by a model of real hand poses (SOMA-X's hand prior): `z` are its numbers, each in its own standard+ * deviations (none: the average relaxed hand; the first opens the hand when positive and closes it when negative).+ * The rest of `from` (the rest pose) is kept. `odd` says how far the hand is from the hands people make (0: the+ * average hand; the rig's own rest hand reads about 2). With no `z`, `from`'s own hand is read. */+export function handShape(skel: Skeleton, side: "L" | "R", z?: number[], from?: Pose): { pose: Pose; z: number[]; odd: number } {+ const joints = skel.joints.map((j) => ({ name: j.name, parent: j.parent, head: j.head, tail: j.tail }));+ const pose = from && { root: from.root, turns: skel.joints.map((_, i) => from.turns[i] ?? ([0, 0, 0, 1] as Quat)) };+ return native("character.hand", { joints, side, z, pose });+}diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.tsindex ebe93100..b583e484 100644--- a/sdk/raea/src/native-calls.ts+++ b/sdk/raea/src/native-calls.ts@@ -38,6 +38,8 @@ export interface NativeCalls {"canvas.svgText": { args: { text: string; style: Record<string, string> }; answer: { length: number; starts: number[] } };/** 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.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 } };/** 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; 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 } } };/** 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/grab/data/README.md b/systems/grab/data/README.mdnew file mode 100644index 00000000..07134da9--- /dev/null+++ b/systems/grab/data/README.md@@ -0,0 +1,18 @@+# Data in raea-sys-grab++`soma_hand_prior.bin`: the left hand's articulation prior from NVIDIA's SOMA-X (github.com/NVlabs/SOMA-X,+`assets/SOMAHand.npz`, Apache-2.0, Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES), cut down to the fifteen+finger joints raea's rig has. SOMA-X's file holds a principal-component model of hand poses (32 components over 24+finger joints, each joint a rotation vector from the bind pose in the wrist's axes). Kept here, as little-endian+f32 in this order:++| numbers | what |+|---|---|+| 45 | the mean pose: thumb 1 to 3, then index, middle, ring and pinky 2 to 4 (SOMA's 1 is the metacarpal), x y z each |+| 32 | each component's standard deviation (the square root of its eigenvalue) |+| 32 x 45 | the components, on the same fifteen joints |+| 32 x 45 | the matrix that reads a pose's coefficients back (least squares on the kept joints) |+| 45 | each kept joint's bone direction at SOMA's bind pose, in the wrist's axes |++The metacarpals and the fingertip end joints are left out: raea's hand has neither. Made once from the file above+with a script that reads the .npz with Python's standard library; `src/prior.rs` reads it.diff --git a/systems/grab/data/soma_hand_prior.bin b/systems/grab/data/soma_hand_prior.binnew file mode 100644index 00000000..b28a8370Binary files /dev/null and b/systems/grab/data/soma_hand_prior.bin differdiff --git a/systems/grab/src/arm.rs b/systems/grab/src/arm.rsindex 5002ba71..bd2ba4df 100644--- a/systems/grab/src/arm.rs+++ b/systems/grab/src/arm.rs@@ -18,6 +18,9 @@ pub struct ArmOptions {/// metres short of straight where the limb starts to ease toward its full length instead of snapping straight/// (0: exact, and an elbow that locks the frame the target passes the arm's length)pub soft: f32,+ /// how much of the trunk's lean a reach gives up (0: it leans as far as it may; 1: the arm alone), for a body+ /// with something in front of it+ pub stiff: f32,}#[derive(Clone, Debug)]@@ -104,7 +107,7 @@ pub fn reach(skel: &Skeleton, p: &Pose, s: Side, target: Vec3, o: ArmOptions) ->.iter().filter_map(|(n, share, cap)| {let name = if *n == "clavicle" { format!("clavicle_{}", s.sx()) } else { n.to_string() };- Some((skel.joint(&name)?, *share, *cap))+ Some((skel.joint(&name)?, *share, *cap * (1.0 - o.stiff.clamp(0.0, 1.0))))}).collect();if out.miss <= within || !out.out_of_reach {diff --git a/systems/grab/src/body.rs b/systems/grab/src/body.rsindex b19bb442..d3d7e2d4 100644--- a/systems/grab/src/body.rs+++ b/systems/grab/src/body.rs@@ -16,8 +16,10 @@ use crate::shape::Thing;const EASY: f32 = 0.7;/// The body bent and lowered for hands that must get down to `low` (a height, metres), by `amount` (0 to 1) of what-/// that needs. `own` drawn is `w`; `face` is the level way the body faces.-pub fn stoop(skel: &Skeleton, own: &Pose, w: &Posed, face: Vec3, low: f32, amount: f32) -> Pose {+/// that needs. `own` drawn is `w`; `face` is the level way the body faces. `give` (0 to 1) trades the bend for more+/// squat, down to an upright, deep squat at 1: for a body that can't bend forward because something stands there+/// (`roomy` says when it can).+pub fn stoop(skel: &Skeleton, own: &Pose, w: &Posed, face: Vec3, low: f32, amount: f32, give: f32) -> Pose {let (Some(l), Some(r)) = (skel.arm(Side::L), skel.arm(Side::R)) else { return own.clone() };let shoulders = (w.pos[l[0]].y + w.pos[r[0]].y) / 2.0;let arm = skel.offset(l[1]).length() + skel.offset(l[2]).length();@@ -25,8 +27,11 @@ pub fn stoop(skel: &Skeleton, own: &Pose, w: &Posed, face: Vec3, low: f32, amounif short <= 0.0 || amount <= 0.0 {return own.clone();}- // the hips take most of it by coming down (a squat), the trunk the rest by bending- let (drop, pitch) = ((short * 0.75).min(0.55) * amount, (short * 0.8).min(0.85) * amount);+ // the hips take most of it by coming down (a squat), the trunk the rest by bending; giving up the bend, the hips+ // come down by what the bend had lowered the shoulders+ let give = give.clamp(0.0, 1.0);+ let (drop, pitch) = ((short * 0.75).min(0.55), (short * 0.8).min(0.85));+ let (drop, pitch) = ((drop + 0.45 * pitch * give).min(0.82) * amount, pitch * (1.0 - give) * amount);let left = Vec3::Y.cross(face);let mut pose = own.clone();// the hips go back a little as the trunk goes forward, as a body keeps its balance@@ -43,11 +48,23 @@ pub fn stoop(skel: &Skeleton, own: &Pose, w: &Posed, face: Vec3, low: f32, amounlet leg = [format!("thigh_{x}"), format!("calf_{x}"), format!("foot_{x}")].map(|n| skel.joint(&n));let [Some(a), Some(b), Some(c)] = leg else { continue };let pole = face + left * (0.25 * s.sign());- pose = two_bone(skel, &pose, [a, b, c], w.pos[c], ArmOptions { pole: Some(pole), end: Some(w.rot[c]), soft: 0.0 }).pose;+ pose = two_bone(skel, &pose, [a, b, c], w.pos[c], ArmOptions { pole: Some(pole), end: Some(w.rot[c]), ..Default::default() }).pose;}pose}+/// Whether the head's top, the neck and the chest are a hand's breadth off every solid.+pub fn roomy(skel: &Skeleton, pose: &Pose, solids: &[Thing]) -> bool {+ if solids.is_empty() {+ return true;+ }+ let at = skel.fk(pose);+ ["head", "neck_01", "spine_03"].iter().filter_map(|n| skel.joint(n)).all(|i| {+ let tip = at.pos[i] + at.rot[i] * (skel.joints[i].tail - skel.joints[i].head);+ solids.iter().all(|s| s.distance(at.pos[i]) > 0.09 && s.distance(tip) > 0.09)+ })+}+/// A wrist's place moved the least that keeps the hand (its wrist, palm and fingers' reach) clear of every solid.pub fn clear(wrist: Vec3, turn: Quat, rest: &HandRest, solids: &[Thing]) -> Vec3 {const MARGIN: f32 = 0.02;diff --git a/systems/grab/src/json.rs b/systems/grab/src/json.rsindex 1c2adbda..2ed9d97c 100644--- a/systems/grab/src/json.rs+++ b/systems/grab/src/json.rs@@ -7,6 +7,7 @@ use serde_json::{Value, json};use crate::body::stand_for;use crate::fit::{Mark, fit};+use crate::prior::{coefficients, oddness, shape};use crate::hand::{Grip, HoldOptions, find_holds};use crate::rig::{Pose, Side, Skeleton};use crate::shape::{Solid, Thing};@@ -139,3 +140,28 @@ pub fn fit_json(v: &Value) -> Result<Value, String> {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 }))}++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][] } }";+pub const HAND_ANSWER: &str = "{ pose: { root: [number, number, number]; turns: [number, number, number, number][] }; z: number[]; odd: number }";++/// `character.hand`: a hand shaped by the hand prior's coefficients (prior.rs) on a pose, and that hand read back:+/// its coefficients and how odd it is.+pub fn hand_json(v: &Value) -> Result<Value, String> {+ let skel = Skeleton::from_value(v)?;+ let side = if v["side"] == "L" { Side::L } else { Side::R };+ let mut pose = skel.rest();+ if !v["pose"].is_null() {+ pose.root = vec3(&v["pose"]["root"], "pose.root")?;+ for (slot, turn) in pose.turns.iter_mut().zip(v["pose"]["turns"].as_array().into_iter().flatten()) {+ *slot = quat(turn, "the pose's turn")?;+ }+ }+ if let Some(z) = v["z"].as_array() {+ let z = z.iter().map(|n| num(n, "a number of z")).collect::<Result<Vec<f32>, String>>()?;+ shape(&skel, &mut pose.turns, side, &z).ok_or("character.hand: the body has no hand on that side")?;+ }+ 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);+ 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 }))+}diff --git a/systems/grab/src/lib.rs b/systems/grab/src/lib.rsindex 016d4f07..e19d0f2c 100644--- a/systems/grab/src/lib.rs+++ b/systems/grab/src/lib.rs@@ -10,6 +10,8 @@//! and where to stand to take a thing.//! - `fit`: a pose fitted to points seen (SOMA-X's analytical pose inversion), for motion that arrives as positions.//! - `interact`: which thing a body takes: the nearest in reach that its eyes see.+//! - `limits`: each joint's range as anatomical angles (sdk/body's), a turn brought inside it, a pose's violations.+//! - `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.//! - `take`: reach, grab, lift, carry, put down or throw, as one timeline.//! - `json`: a take asked for as JSON, the engine's native call `character.take` (raea/character's `take`).@@ -19,16 +21,19 @@ pub mod fit;pub mod hand;pub mod interact;pub mod json;+pub mod limits;+pub mod prior;pub mod rig;pub mod shape;pub mod take;pub use arm::{ArmOptions, IkReport, forearm_twist, reach, twist_joints, two_bone};-pub use json::{FIT_ANSWER, FIT_ARGS, TAKE_ANSWER, TAKE_ARGS, fit_json, take_json};-pub use body::{clear, look, stand_for, stoop};+pub use json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, TAKE_ANSWER, TAKE_ARGS, fit_json, hand_json, take_json};+pub use body::{clear, look, roomy, stand_for, stoop};pub use fit::{Mark, fit, marks_of};pub use interact::pick;pub use hand::{Grip, Hold, HoldOptions, Touch, curl, find_holds, wrist_for};+pub use limits::{Angles, angles_of, clamp_turn, violations};pub use rig::{Pose, Posed, Side, Skeleton, mannequin};pub use shape::{Solid, Thing};pub use take::{Frame, Phase, Release, Take, perform};diff --git a/systems/grab/src/limits.rs b/systems/grab/src/limits.rsnew file mode 100644index 00000000..d4ddf635--- /dev/null+++ b/systems/grab/src/limits.rs@@ -0,0 +1,240 @@+//! Joint limits, as sdk/body has them (axes.ts, limits.ts): each joint's turn read as anatomical angles from the+//! rig's rest pose (flex: its main bend; side: the bend across it; twist: about its bone), and the range of each,+//! degrees. The ranges are sdk/body's, set from anatomy and checked there against 26,288 captured frames. Written+//! for the left; the right is mirrored, so the same numbers mean the same motion on either side.++use glam::{Quat, Vec3};++use crate::arm::twist_about;+use crate::rig::{Pose, Skeleton};++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Angles {+ pub flex: f32,+ pub side: f32,+ pub twist: f32,+}++/// a joint's role (its name without the side), the ranges of its flex, side and twist, where its bone's tip goes as+/// it flexes (None: an elbow, which folds in the plane its rest bend makes) and as it bends sideways+type Row = (+ &'static str,+ [f32; 2],+ [f32; 2],+ [f32; 2],+ Option<Vec3>,+ Vec3,+);+const UP: Vec3 = Vec3::Y;+const AHEAD: Vec3 = Vec3::Z;+const OUT: Vec3 = Vec3::X;+const LIMITS: [Row; 13] = [+ (+ "spine_01",+ [-25.0, 45.0],+ [-20.0, 20.0],+ [-15.0, 15.0],+ Some(AHEAD),+ OUT,+ ),+ (+ "spine_02",+ [-5.0, 100.0],+ [-30.0, 30.0],+ [-20.0, 20.0],+ Some(AHEAD),+ OUT,+ ),+ (+ "spine_03",+ [-65.0, 25.0],+ [-30.0, 30.0],+ [-20.0, 20.0],+ Some(AHEAD),+ OUT,+ ),+ (+ "neck_01",+ [-60.0, 55.0],+ [-40.0, 40.0],+ [-45.0, 45.0],+ Some(AHEAD),+ OUT,+ ),+ (+ "head",+ [-45.0, 45.0],+ [-30.0, 30.0],+ [-45.0, 45.0],+ Some(AHEAD),+ OUT,+ ),+ (+ "clavicle",+ [-45.0, 25.0],+ [-20.0, 75.0],+ [-20.0, 15.0],+ Some(AHEAD),+ UP,+ ),+ (+ "upperarm",+ [-65.0, 150.0],+ [-70.0, 140.0],+ [-95.0, 80.0],+ Some(AHEAD),+ UP,+ ),+ (+ "lowerarm",+ [-50.0, 110.0],+ [-20.0, 8.0],+ [-100.0, 40.0],+ None,+ UP,+ ),+ (+ "hand",+ [-75.0, 60.0],+ [-35.0, 45.0],+ [-5.0, 25.0],+ Some(Vec3::NEG_Y),+ OUT,+ ),+ (+ "thigh",+ [-35.0, 125.0],+ [-30.0, 65.0],+ [-60.0, 30.0],+ Some(AHEAD),+ OUT,+ ),+ (+ "calf",+ [-8.0, 150.0],+ [-20.0, 8.0],+ [-15.0, 15.0],+ Some(Vec3::NEG_Z),+ OUT,+ ),+ (+ "foot",+ [-30.0, 55.0],+ [-40.0, 25.0],+ [-25.0, 35.0],+ Some(UP),+ OUT,+ ),+ (+ "ball",+ [-35.0, 65.0],+ [-25.0, 25.0],+ [-30.0, 40.0],+ Some(UP),+ OUT,+ ),+];++/// a joint's axes at rest: its bone, the axes a turn about which is its flexion and its side bend, and the hand its+/// twist is read by (+1 on the left and the midline)+struct Axes {+ bone: Vec3,+ flex: Vec3,+ side: Vec3,+ hand: f32,+ row: &'static Row,+}++fn axes(skel: &Skeleton, i: usize) -> Option<Axes> {+ let j = &skel.joints[i];+ let right = j.name.ends_with("_r");+ let role = j.name.trim_end_matches("_l").trim_end_matches("_r");+ let row = LIMITS.iter().find(|r| r.0 == role)?;+ let mirror = |v: Vec3| if right { Vec3::new(-v.x, v.y, v.z) } else { v };+ let dir = |k: usize| (skel.joints[k].tail - skel.joints[k].head).normalize();+ let bone = dir(i);+ let off = |v: Vec3, n: Vec3| v - n * v.dot(n);+ // the fold's tip direction: away from the parent's bone, in the plane the rest bend makes+ let toward = match row.4 {+ Some(d) => mirror(d),+ None => off(-dir(j.parent?), bone),+ };+ let flex = bone.cross(toward).try_normalize()?;+ let side = off(off(bone.cross(mirror(row.5)), flex), bone).try_normalize()?;+ Some(Axes {+ bone,+ flex,+ side,+ hand: if right { -1.0 } else { 1.0 },+ row,+ })+}++/// a joint's turn as anatomical angles, degrees (None for a joint with no limits: the root, the fingers)+pub fn angles_of(skel: &Skeleton, i: usize, q: Quat) -> Option<Angles> {+ let ax = axes(skel, i)?;+ Some(read(&ax, q))+}++fn read(ax: &Axes, q: Quat) -> Angles {+ let twist = twist_about(q, ax.bone);+ let swing = (q * twist.inverse()).to_scaled_axis();+ let about = 2.0+ * Vec3::new(twist.x, twist.y, twist.z)+ .dot(ax.bone)+ .atan2(twist.w);+ Angles {+ flex: swing.dot(ax.flex).to_degrees(),+ side: swing.dot(ax.side).to_degrees(),+ twist: (about * ax.hand).to_degrees(),+ }+}++fn clamped(ax: &Axes, a: Angles) -> Angles {+ let (mut flex, mut side) = (+ a.flex.clamp(ax.row.1[0], ax.row.1[1]),+ a.side.clamp(ax.row.2[0], ax.row.2[1]),+ );+ // the swing as a whole to 175 degrees, past which a swing's angles stop meaning one turn+ let whole = flex.hypot(side);+ if whole > 175.0 {+ (flex, side) = (flex * 175.0 / whole, side * 175.0 / whole);+ }+ Angles {+ flex,+ side,+ twist: a.twist.clamp(ax.row.3[0], ax.row.3[1]),+ }+}++/// A joint's turn brought inside its limit (each angle clamped), and how far that turned it, degrees.+pub fn clamp_turn(skel: &Skeleton, i: usize, q: Quat) -> (Quat, f32) {+ let Some(ax) = axes(skel, i) else {+ return (q, 0.0);+ };+ let (a, c) = (read(&ax, q), clamped(&ax, read(&ax, q)));+ if a == c {+ return (q, 0.0);+ }+ let swing =+ Quat::from_scaled_axis(ax.flex * c.flex.to_radians() + ax.side * c.side.to_radians());+ let turn =+ (swing * Quat::from_axis_angle(ax.bone, (c.twist * ax.hand).to_radians())).normalize();+ (turn, q.angle_between(turn).to_degrees())+}++/// Every joint of a pose outside its limit by more than `tolerance` degrees: its index and by how much, worst first.+pub fn violations(skel: &Skeleton, p: &Pose, tolerance: f32) -> Vec<(usize, f32)> {+ let mut out: Vec<(usize, f32)> = (0..skel.joints.len())+ .filter_map(|i| {+ let ax = axes(skel, i)?;+ let (a, c) = (read(&ax, p.turns[i]), clamped(&ax, read(&ax, p.turns[i])));+ let by = (a.flex - c.flex)+ .hypot(a.side - c.side)+ .max((a.twist - c.twist).abs());+ (by > tolerance).then_some((i, by))+ })+ .collect();+ out.sort_by_key(|v| std::cmp::Reverse((v.1 * 1000.0) as i64));+ out+}diff --git a/systems/grab/src/prior.rs b/systems/grab/src/prior.rsnew file mode 100644index 00000000..287276b9--- /dev/null+++ b/systems/grab/src/prior.rs@@ -0,0 +1,136 @@+//! What a hand looks like: SOMA-X's hand articulation prior (NVlabs/SOMA-X, Apache-2.0; data/README.md), a+//! principal-component model of real hand poses, carried onto raea's fifteen finger joints. It gives a hand a+//! shape from a few numbers (`shape`: none of them is the average relaxed hand, the first opens and closes it) and+//! says how far a hand's pose is from the hands people make (`oddness`). SOMA's poses are turns from its flat bind+//! hand in the wrist's axes; here each finger bone is pointed where SOMA's would point, in raea's hand's frame, from+//! raea's own rest hand, which is a little curled.++use std::sync::OnceLock;++use glam::{Mat3, Quat, Vec3};++use crate::hand::hand_rest;+use crate::rig::{FINGERS, Pose, Side, Skeleton};++const JOINTS: usize = 15;+const DIMS: usize = JOINTS * 3;+pub const COMPONENTS: usize = 32;++struct Table {+ mean: Vec<f32>,+ sd: Vec<f32>,+ /// COMPONENTS rows of DIMS+ components: Vec<f32>,+ back: Vec<f32>,+ dirs: Vec<Vec3>,+}++fn table() -> &'static Table {+ static TABLE: OnceLock<Table> = OnceLock::new();+ TABLE.get_or_init(|| {+ let bytes = include_bytes!("../data/soma_hand_prior.bin");+ let mut all = Vec::with_capacity(bytes.len() / 4);+ for four in bytes.as_chunks::<4>().0 {+ all.push(f32::from_le_bytes(*four));+ }+ let (mean, rest) = all.split_at(DIMS);+ let (sd, rest) = rest.split_at(COMPONENTS);+ let (components, rest) = rest.split_at(COMPONENTS * DIMS);+ let (back, dirs) = rest.split_at(COMPONENTS * DIMS);+ Table { mean: mean.into(), sd: sd.into(), components: components.into(), back: back.into(), dirs: dirs.chunks_exact(3).map(|d| Vec3::new(d[0], d[1], d[2]).normalize()).collect() }+ })+}++/// A hand of the rig set against SOMA's: its finger joints in the prior's order, the turn from SOMA's wrist axes+/// to the hand's rest frame, and for each joint the turn from its rest bone to where SOMA's bind bone points.+struct Fitted {+ joints: [usize; JOINTS],+ frame: Quat,+ to_bind: [Quat; JOINTS],+}++/// the left hand's (the prior is the left's; a right hand is read mirrored)+fn fitted(skel: &Skeleton, s: Side) -> Option<Fitted> {+ let rest = hand_rest(skel, s)?;+ let mirror = |v: Vec3| if s == Side::R { Vec3::new(-v.x, v.y, v.z) } else { v };+ // SOMA's left hand at bind: fingers along +x, the palm facing +z+ let (along, palm) = (mirror(rest.along), mirror(rest.palm));+ let frame = Quat::from_mat3(&(Mat3::from_cols(along, palm, along.cross(palm)) * Mat3::from_cols(Vec3::X, Vec3::Z, Vec3::X.cross(Vec3::Z)).transpose())).normalize();+ let mut joints = [0; JOINTS];+ let mut to_bind = [Quat::IDENTITY; JOINTS];+ for (f, name) in FINGERS.iter().enumerate() {+ for (k, j) in skel.finger(name, s)?.into_iter().enumerate() {+ let bone = mirror((skel.joints[j].tail - skel.joints[j].head).normalize());+ joints[f * 3 + k] = j;+ to_bind[f * 3 + k] = Quat::from_rotation_arc(bone, frame * table().dirs[f * 3 + k]);+ }+ }+ Some(Fitted { joints, frame, to_bind })+}++/// a turn as the left's sees it, and back: mirrored across the body's middle+fn mirrored(q: Quat, s: Side) -> Quat {+ if s == Side::R { Quat::from_xyzw(q.x, -q.y, -q.z, q.w) } else { q }+}++/// A hand's finger turns for coefficients `z` (each in its own standard deviations; missing ones are 0): written into+/// `turns` for the side's fifteen finger joints.+pub fn shape(skel: &Skeleton, turns: &mut [Quat], s: Side, z: &[f32]) -> Option<()> {+ let (t, hand) = (table(), fitted(skel, s)?);+ let mut pose = t.mean.clone();+ for (i, zi) in z.iter().take(COMPONENTS).enumerate() {+ for (p, c) in pose.iter_mut().zip(&t.components[i * DIMS..(i + 1) * DIMS]) {+ *p += zi * t.sd[i] * c;+ }+ }+ for f in 0..5 {+ // down the finger: SOMA's turns so far, and the bone turned with them from where its bind bone points+ let (mut soma, mut above) = (Quat::IDENTITY, Quat::IDENTITY);+ for k in 0..3 {+ let i = f * 3 + k;+ let turn = Quat::from_scaled_axis(Vec3::new(pose[i * 3], pose[i * 3 + 1], pose[i * 3 + 2]));+ soma = (soma * (hand.frame * turn * hand.frame.inverse())).normalize();+ let world = (soma * hand.to_bind[i]).normalize();+ turns[hand.joints[i]] = mirrored((above.inverse() * world).normalize(), s);+ above = world;+ }+ }+ Some(())+}++/// A hand's pose read as the prior's coefficients, and what of it they don't account for (degrees, root mean square+/// over the joints).+pub fn coefficients(skel: &Skeleton, pose: &Pose, s: Side) -> Option<(Vec<f32>, f32)> {+ let (t, hand) = (table(), fitted(skel, s)?);+ let mut seen = vec![0.0f32; DIMS];+ for f in 0..5 {+ let (mut soma, mut above) = (Quat::IDENTITY, Quat::IDENTITY);+ for k in 0..3 {+ let i = f * 3 + k;+ let world = (above * mirrored(pose.turns[hand.joints[i]], s)).normalize();+ let so_far = (world * hand.to_bind[i].inverse()).normalize();+ let turn = hand.frame.inverse() * (soma.inverse() * so_far) * hand.frame;+ let v = turn.to_scaled_axis();+ seen[i * 3..i * 3 + 3].copy_from_slice(&[v.x, v.y, v.z]);+ (soma, above) = (so_far, world);+ }+ }+ let off: Vec<f32> = seen.iter().zip(&t.mean).map(|(a, b)| a - b).collect();+ let z: Vec<f32> = (0..COMPONENTS).map(|i| t.back[i * DIMS..(i + 1) * DIMS].iter().zip(&off).map(|(a, b)| a * b).sum()).collect();+ let mut left = off;+ for (i, zi) in z.iter().enumerate() {+ for (l, c) in left.iter_mut().zip(&t.components[i * DIMS..(i + 1) * DIMS]) {+ *l -= zi * t.sd[i] * c;+ }+ }+ let rest = (left.iter().map(|v| v * v).sum::<f32>() / JOINTS as f32).sqrt().to_degrees();+ Some((z, rest))+}++/// How far a hand's pose is from the hands people make (the coefficients' root mean square, plus what they leave+/// over, a deviation for each 10 degrees): 0 for the average hand. It is a comparison, not a verdict: the rig's own+/// rest hand reads about 2, since its bones aren't SOMA's, and fingers bent back at the middle joint read over 4.+pub fn oddness(skel: &Skeleton, pose: &Pose, s: Side) -> Option<f32> {+ let (z, rest) = coefficients(skel, pose, s)?;+ Some((z.iter().map(|v| v * v).sum::<f32>() / COMPONENTS as f32).sqrt() + rest / 10.0)+}diff --git a/systems/grab/src/take.rs b/systems/grab/src/take.rsindex bca77437..2549fbcf 100644--- a/systems/grab/src/take.rs+++ b/systems/grab/src/take.rs@@ -9,7 +9,9 @@use glam::{Quat, Vec3};use crate::arm::{ArmOptions, forearm_twist, reach};-use crate::body::{clear, look, stoop};+use crate::body::{clear, look, roomy, stoop};+use crate::limits::clamp_turn;+use crate::prior::shape;use crate::hand::{Grip, Touch, curl, facing, hand_rest, wrist_for};use crate::rig::{Pose, Posed, Skeleton};use crate::shape::Thing;@@ -58,7 +60,7 @@ pub struct Frame {/// the most any joint was turned from the body's own motion, degreespub moved: f32,pub touch: [Option<Touch>; 2],- /// a wrist was held at the most it bends, so its palm isn't square on its hold+ /// a joint of an arm was held at its limit, so a palm may not be square on its holdpub limited: bool,}@@ -67,8 +69,8 @@ const GRAVITY: f32 = 9.81;const AWAY: f32 = 0.4;/// how long the fingers take to shut, ending at the grab, secondsconst SHUT: f32 = 0.25;-/// the most a wrist bends, radians-const WRIST: f32 = 1.22;+/// how open the hand comes in, in the hand prior's first component (its standard deviations)+const OPEN: f32 = 1.5;fn smooth(u: f32) -> f32 {let u = u.clamp(0.0, 1.0);@@ -181,8 +183,12 @@ pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32).collect();// a thing lower than the arms reach: the body bends and squats for it, as far as the hands have gotlet low = holds.iter().map(|h| h.1.0.y).fold(f32::MAX, f32::min);- let mut pose = stoop(skel, &own, &w0, face, low, into * (1.0 - away));- for (hold, (at, turn)) in holds {+ // solved with the bend the body has room for: where bending or leaning would put the head or chest into a+ // solid, less of both and more squat, a step at a time+ let solve = |give: f32, frame: &mut Frame| {+ let mut pose = stoop(skel, &own, &w0, face, low, into * (1.0 - away), give);+ frame.miss = 0.0;+ for &(hold, (at, turn)) in &holds {let (Some(arm), Some(rest)) = (skel.arm(hold.side), hand_rest(skel, hold.side)) else { continue };let normal = held.turn * hold.normal;// the wrist's path: from where the body has it, in onto the hold from off the surface and over what is in the@@ -193,18 +199,29 @@ pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32)let target = clear(w0.pos[arm[2]].lerp(at + off, u) + arc, end, &rest, &take.avoid);// elbows out and down, the way arms hanglet pole = yaw(&w0) * Vec3::new(0.7 * hold.side.sign(), -1.0, -0.4);- let Some(solved) = reach(skel, &pose, hold.side, target, ArmOptions { pole: Some(pole), end: Some(end), soft: 0.02 }) else { continue };+ let Some(solved) = reach(skel, &pose, hold.side, target, ArmOptions { pole: Some(pole), end: Some(end), soft: 0.02, stiff: give }) else { continue };pose = forearm_twist(skel, &solved.pose, hold.side, 0.7);- // a wrist bends about 70 degrees and no further- let bend = pose.turns[arm[2]].angle_between(Quat::IDENTITY);- if bend > WRIST {- pose.turns[arm[2]] = Quat::IDENTITY.slerp(pose.turns[arm[2]], WRIST / bend);- frame.limited = true;+ // each joint of the arm kept inside its range (limits.rs): a wrist bends so far and no further, and a+ // frame that needed more says so+ for joint in arm {+ let (turn, by) = clamp_turn(skel, joint, pose.turns[joint]);+ if by > 0.5 {+ pose.turns[joint] = turn;+ frame.limited = true;+ }}if t >= take.grab && away <= 0.0 {frame.miss = frame.miss.max((skel.fk(&pose).pos[arm[2]] - at).length());}+ // the hand opens as it comes in, as a hand does before it takes something (the prior's open hand), then// the fingers shut over the last moments of the reach, and open again as the hand leaves+ let mut open = pose.turns.clone();+ if shape(skel, &mut open, hold.side, &[OPEN]).is_some() {+ let wide = smooth(span(t, take.start, take.grab - SHUT));+ for (mine, open) in pose.turns.iter_mut().zip(&open) {+ *mine = mine.slerp(*open, wide);+ }+ }let close = smooth(span(t, take.grab - SHUT, take.grab)) * (1.0 - smooth(span(away, 0.0, 0.5)));if close > 0.0 {frame.touch[hold.side as usize] = curl(skel, &mut pose.turns, (at, turn), hold.side, &held, close);@@ -212,7 +229,15 @@ pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32)}// the eyes go to the thing as the hands do, and mostly leave it once it is carriedlet watching = into * (1.0 - away) * (1.0 - 0.7 * smooth(span(t, take.grab, take.carried)));- pose = look(skel, &pose, held.at, watching);+ look(skel, &pose, held.at, watching * (1.0 - 0.5 * give))+ };+ let mut pose = solve(0.0, &mut frame);+ for step in 1..=6 {+ if roomy(skel, &pose, &take.avoid) {+ break;+ }+ pose = solve(step as f32 / 6.0, &mut frame);+ }if away > 0.0 {// the last of the way back is a blend of the joints, so the arm ends exactly as the body has itlet w = 1.0 - smooth(span(away, 0.5, 1.0));diff --git a/systems/grab/tests/body.rs b/systems/grab/tests/body.rsnew file mode 100644index 00000000..e95c678e--- /dev/null+++ b/systems/grab/tests/body.rs@@ -0,0 +1,131 @@+//! The measures docs/hands.feature names for the body round the hands: joint limits, and keeping out of solids.++use glam::{Quat, Vec3};+use raea_sys_grab::*;++#[test]+fn limits_read_and_hold_a_joint() {+ let s = mannequin();+ // the rest pose is inside every range+ assert!(violations(&s, &s.rest(), 0.01).is_empty(), "{:?}", violations(&s, &s.rest(), 0.01));+ for side in Side::BOTH {+ let [upper, elbow, hand] = s.arm(side).unwrap();+ // an elbow's fold reads as flex alone, the same on both sides; bent back it is past its range, and is brought to it+ let hinge = s.offset(elbow).cross(s.offset(hand)).normalize();+ let a = angles_of(&s, elbow, Quat::from_axis_angle(hinge, 1.0)).unwrap();+ assert!((a.flex - 57.3).abs() < 1.0 && a.side.abs() < 1.0 && a.twist.abs() < 1.0, "{a:?}");+ let back = Quat::from_axis_angle(hinge, -1.2);+ let mut p = s.rest();+ p.turns[elbow] = back;+ assert_eq!(violations(&s, &p, 0.5)[0].0, elbow);+ let (held, by) = clamp_turn(&s, elbow, back);+ assert!((angles_of(&s, elbow, held).unwrap().flex + 50.0).abs() < 0.5 && by > 15.0);+ // a turn inside its range comes back as it is+ let fine = Quat::from_axis_angle(Vec3::Z, 0.3 * side.sign());+ assert_eq!(clamp_turn(&s, upper, fine), (fine, 0.0));+ // a wrist's twist past 25 degrees is held there+ let twisted = Quat::from_axis_angle((s.joints[hand].tail - s.joints[hand].head).normalize(), 0.9 * side.sign());+ let (held, _) = clamp_turn(&s, hand, twisted);+ assert!((angles_of(&s, hand, held).unwrap().twist - 25.0).abs() < 0.5);+ }+}++#[test]+fn a_take_keeps_both_arms_inside_their_ranges() {+ let s = mannequin();+ let thing = Thing::new(Solid::Box { half: Vec3::new(0.16, 0.1, 0.12) }, Vec3::new(0.0, 1.05, 0.42));+ let take = Take::new(thing, find_holds(&thing, s.rest().root, HoldOptions::default()), 0.0);+ let mut t = 0.0;+ while t < 2.0 {+ let f = perform(&s, &|_| s.rest(), &take, t);+ for side in Side::BOTH {+ for joint in s.arm(side).unwrap() {+ let out = violations(&s, &f.pose, 0.6).into_iter().find(|v| v.0 == joint);+ assert!(out.is_none(), "t {t}: {} is {:?} degrees past its range", s.joints[joint].name, out);+ }+ }+ t += 1.0 / 30.0;+ }+}++#[test]+fn the_head_and_chest_stay_out_of_a_table_when_the_body_bends() {+ let s = mannequin();+ // a table 38 cm in front, a box on the floor between it and the feet+ let table = Thing::new(Solid::Box { half: Vec3::new(0.6, 0.475, 0.34) }, Vec3::new(0.0, 0.475, 0.72));+ let thing = Thing::new(Solid::Box { half: Vec3::new(0.16, 0.1, 0.12) }, Vec3::new(0.0, 0.1, 0.2));+ let mut take = Take::new(thing, find_holds(&thing, s.rest().root, HoldOptions::default()), 0.0);+ take.avoid = vec![table];+ let upper = ["head", "neck_01", "spine_03"].map(|n| s.joint(n).unwrap());+ let top = |pose: &Pose, i: usize| {+ let w = s.fk(pose);+ (w.pos[i], w.pos[i] + w.rot[i] * (s.joints[i].tail - s.joints[i].head))+ };+ let (mut t, mut worst) = (0.0, 0.0f32);+ while t < 2.0 {+ let f = perform(&s, &|_| s.rest(), &take, t);+ for i in upper {+ let (at, tip) = top(&f.pose, i);+ assert!(table.distance(at) > 0.0 && table.distance(tip) > 0.0, "t {t}: {} is in the table", s.joints[i].name);+ }+ if t >= take.grab {+ worst = worst.max(f.miss);+ }+ t += 1.0 / 30.0;+ }+ assert!(worst < 0.05, "keeping the head out cost the hold {worst} m");+ // with no table there the same take bends further: the head goes where the table was+ take.avoid.clear();+ let head = s.joint("head").unwrap();+ assert!(table.distance(top(&perform(&s, &|_| s.rest(), &take, take.grab).pose, head).1) < 0.09);+}++#[test]+fn the_hand_prior_shapes_and_reads_hands() {+ use raea_sys_grab::hand::hand_rest;+ use raea_sys_grab::prior::{coefficients, oddness, shape};+ let s = mannequin();+ for side in Side::BOTH {+ let rest = hand_rest(&s, side).unwrap();+ let hand = s.arm(side).unwrap()[2];+ // how far each fingertip is from its knuckle, on average: longest with the hand open, shortest in a fist+ let span = |pose: &Pose| {+ let w = s.fk(pose);+ ["index", "middle", "ring", "pinky"].iter().map(|f| {+ let [knuckle, _, tip] = s.finger(f, side).unwrap();+ (w.pos[tip] + w.rot[tip] * (s.joints[tip].tail - s.joints[tip].head) - w.pos[knuckle]).length()+ }).sum::<f32>() / 4.0+ };+ let shaped = |z: &[f32]| {+ let mut p = s.rest();+ shape(&s, &mut p.turns, side, z).unwrap();+ p+ };+ let (mean, open, shut) = (shaped(&[]), shaped(&[2.0]), shaped(&[-2.0]));+ // the first component opens and closes the hand, the average hand between: open at +2, a fist at -2+ assert!(span(&open) > span(&mean) && span(&mean) > span(&shut) + 0.004, "{} {} {}", span(&open), span(&mean), span(&shut));+ // and the fingers close toward the palm, not away from it+ let w = s.fk(&shut);+ let [knuckle, _, tip] = s.finger("middle", side).unwrap();+ assert!((w.pos[tip] - w.pos[knuckle]).dot(w.rot[hand] * rest.palm) > 0.01);+ // a shape reads back as the numbers that made it, with nothing left over+ let z = [0.8, -0.5, 0.3, 1.1, -0.7];+ let (back, left) = coefficients(&s, &shaped(&z), side).unwrap();+ for (a, b) in z.iter().zip(&back) {+ assert!((a - b).abs() < 0.05, "{z:?} read back as {:?}", &back[..5]);+ }+ assert!(left < 0.5, "{left} degrees left over");+ // the average hand is the least odd; the rig's rest hand reads about 2 (it isn't SOMA's hand); fingers bent+ // back read over twice that+ assert!(oddness(&s, &mean, side).unwrap() < 0.05);+ assert!(oddness(&s, &s.rest(), side).unwrap() < 3.0);+ let mut broken = s.rest();+ for f in ["index", "middle", "ring", "pinky"] {+ let j = s.finger(f, side).unwrap()[1];+ let axis = (s.joints[j].tail - s.joints[j].head).normalize().cross(rest.palm).normalize();+ broken.turns[j] = Quat::from_axis_angle(axis, -1.2);+ }+ let (odd, usual) = (oddness(&s, &broken, side).unwrap(), oddness(&s, &s.rest(), side).unwrap());+ assert!(odd > 2.0 * usual, "fingers bent back read {odd}, the rest hand {usual}");+ }+}diff --git a/systems/grab/tests/grab.rs b/systems/grab/tests/grab.rsindex 814f7b1d..084a997f 100644--- a/systems/grab/tests/grab.rs+++ b/systems/grab/tests/grab.rs@@ -71,7 +71,7 @@ fn the_pole_sets_the_elbow_and_the_end_keeps_its_turn() {let target = s.joints[arm[0]].head + Vec3::new(-0.05, -0.15, 0.35);let turn = Quat::from_rotation_y(0.6);for pole in [Vec3::NEG_Y, Vec3::NEG_X, Vec3::Y] {- let out = two_bone(&s, &s.rest(), arm, target, ArmOptions { pole: Some(pole), end: Some(turn), soft: 0.0 });+ let out = two_bone(&s, &s.rest(), arm, target, ArmOptions { pole: Some(pole), end: Some(turn), ..Default::default() });let w = s.fk(&out.pose);assert!(out.miss < 1e-4);// the elbow is off the shoulder-wrist line on the pole's side@@ -433,18 +433,6 @@ fn the_head_turns_to_the_thing_and_a_wrist_stops_at_its_limit() {assert!(toward(&w) > toward(&w0) + 0.3, "the head faces the thing more: {} from {}", toward(&w), toward(&w0));assert!(w.rot[head].angle_between(w0.rot[head]).to_degrees() < 78.0);assert_eq!(look(&s, &s.rest(), at, 0.0), s.rest());- // through a take no wrist is bent past 70 degrees, and one held there is said- let thing = Thing::new(Solid::Box { half: Vec3::new(0.16, 0.1, 0.12) }, Vec3::new(0.0, 1.05, 0.42));- let take = Take::new(thing, find_holds(&thing, s.rest().root, HoldOptions::default()), 0.0);- let mut t = 0.0;- while t < 2.0 {- let f = perform(&s, &|_| s.rest(), &take, t);- for side in Side::BOTH {- let bend = f.pose.turns[s.arm(side).unwrap()[2]].angle_between(Quat::IDENTITY).to_degrees();- assert!(bend < 70.5, "t {t}: a wrist bent {bend} degrees");- }- t += 1.0 / 30.0;- }// SOMA's twist joints: a forearm's follow its hand by rising shares; an upper arm's undo the shoulder's twistlet fore = twist_joints(Vec3::X, 0.0, 1.0, false);assert!((fore[3].to_axis_angle().1 - 0.95).abs() < 1e-4 && (fore[0].to_axis_angle().1 - 0.05).abs() < 1e-4);