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
HG1: systems/grab, procedural arms and hands (docs/hands.feature HG1 to HG4). A body reaches for a thing, takes it with one hand or two, carries it, and puts it down or throws it, with no capture of the action: two-bone arm IK with a pole and a reach that leans the trunk by capped shares; hold points found by casting from the holder's left and right into the thing's shape (musthafa45/Ik-Object-Holding's method, MIT), kept in the thing's frame with the surface's facing; the palm laid on a hold; each finger joint curled until its bone meets the surface; a wrist's twist moved to the forearm by SOMA-X's swing-twist split (Apache-2.0); the whole take a function of time. Plain glam, no engine yet (HG5). 12 tests on a stand-in body: 600 targets hit within 0.1 mm, palms within 6 mm of their holds from grab to release, a carried cup upright while the body turns, no body joint over 6 degrees a 60th of a second. docs/hands.feature holds what the sources and patch.gg gave and the scenarios after (HG5 to HG13)
shinyobjectze4add11c80eb
diff --git a/Cargo.lock b/Cargo.lockindex ab2b4383..19825e83 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15721,6 +15721,14 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-grab"+version = "0.1.0"+dependencies = [+ "glam 0.33.12",+ "serde_json",+]+[[package]]name = "raea-sys-grass"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 19d5a795..4805abad 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -106,6 +106,7 @@ members = ["systems/page-ops","systems/frame","systems/hold",+ "systems/grab","systems/layers","systems/splat","systems/sprite",diff --git a/docs/hands.feature b/docs/hands.featurenew file mode 100644index 00000000..02bbae47--- /dev/null+++ b/docs/hands.feature@@ -0,0 +1,182 @@+Feature: Procedural arms and hands: a character reaches for, takes, holds, carries and throws things+ Set by the user 2026-11-14: the character SDK's arms and hands should grab, hold and move things procedurally,+ built in Rust for the engine from a mixture of musthafa45/Ik-Object-Holding, NVlabs/SOMA-X and whatever else+ helps, with research into what else would broaden the character SDK (bodies, interactions, movement), and a look+ at patch.gg.++ Where this sits beside docs/character.md: that plan's actions (C5, C6) are played from captures, with IK only to+ hold a contact. This is the other half: an action with no capture of it. The same rules hold where they can:+ every solver reports how far it moved the pose and how far it missed (principle 2), the whole action is a+ function of time (principle 9), and the body's own motion (a clip, a walk) comes in untouched and is only changed+ where a hand needs it.++ What the sources gave:+ - Ik-Object-Holding (MIT, Unity C#, 484 lines of script): hold points found by casting a ray from each side of+ the holder back into the thing's collider (ColliderEdgeDetector); hands eased onto them with two-bone IK and+ an aim; the thing parented to a hold transform in front of the chest and drawn to it; drop and throw. Its+ easing is a per-frame lerp (frame-rate dependent, not frame-pure) and its hands have no fingers and no palm+ turn. Ported as: hold points in the thing's own frame with the surface's facing, eases as curves of time.+ - SOMA-X (Apache-2.0, NVIDIA): a canonical body and hand rig that other body models map onto. For this work it+ gave the swing-twist split with half-angle stabilisation and the twist shares along a segment (0.05, 1/3,+ 2/3, 0.95 over four twist joints), used here to move a wrist's twist to the forearm. Its other parts are for+ later: a wrist-local hand layer with a learned articulation prior (SOMAHand.npz: what hand shapes are+ natural), pose inversion (joint turns fitted to points), and body-model interop including Anny. It needs+ PyTorch and Warp; nothing of it runs in the engine as it is.+ - Around SOMA: Kimodo (Apache-2.0 code; the SEED weights under NVIDIA's Open Model License, said to allow+ commercial use; the SMPL-X weights are research-only) makes motion from text and constraints. MotionBricks, a+ real-time in-betweener, has preview code in GR00T-WholeBodyControl with no plain licence on the repository+ and sample motions under an evaluation-only licence: not usable until that is read. BONES-SEED (motion in+ SOMA's format) has its own licence, gated: unread. ProtoMotions (Apache-2.0) trains physically simulated+ characters.+ - Rust IK crates: bevy_mod_inverse_kinematics (to Bevy 0.16), bevy_fabrik (no multi-chain), bevy_ik (Bevy+ 0.9). None is on Bevy 0.20, none does a two-bone solve that keeps a clip's twist or reports what it changed,+ so the solver here is ours: 170 lines.+ - Grasping research (Lightning Grasp and the like) is for robot hands, has no plain licence, and solves+ grasp stability, which a character doesn't need. A character's hand needs to look right: the palm on the+ surface, the fingers wrapped to the shape. Curling each joint until its bone meets the surface does that.+ - patch.gg: a place to publish browser games and mods, with a CLI (pch), an MCP server and an asset library of+ 50,000 open-licensed models, characters and sounds. It is not an engine and has nothing for IK or hands.+ Its installer writes a "use Patch for games" section into ~/.claude/CLAUDE.md for every agent on the machine,+ which would put Patch ahead of raea in every session here: not installed. Its asset library conflicts with+ the rule that every model in a raea piece is made by us. Worth taking from Patch: its open repositories.+ anymove (Apache-2.0) captures motion for any rigged creature from one generated two-view video (about $3 a+ usable move, needs an NVIDIA card with 12 GB, 58% of clips pass) and is the one that fits: animals and+ creatures, where raea has no captures. crowdbricks (Apache-2.0) batches MotionBricks and inherits its+ licence question. Publishing a raea playable on Patch is a distribution question, not a character one.++ Rule: Built++ @done+ Scenario: HG1. An arm reaches a target, and says what it cost+ # 11-14, built: systems/grab arm.rs. On the stand-in body, 600 random targets inside the arm's reach are hit+ # within 0.1 mm; a target 20 cm past the arm is missed by 20 cm and flagged; a wrist already on its target+ # turns nothing; the pole puts the elbow on its side of the line within a degree; a reach 12 cm past the arm+ # lands within 5 mm by leaning the clavicle, chest and spine, each under its cap, and names them.+ Given a pose of the game_engine rig and a place for a wrist+ When the arm is solved for it+ Then the wrist is there when the arm reaches, the elbow bends about the hinge it had, and the pole chooses+ where the elbow points+ And past the arm's length the trunk leans, by capped shares, and the report names every joint turned+ And a wrist's twist is shared with the forearm, the hand staying where it was+ And the plan:+ | crate | file | lines | job |+ | raea-sys-grab | src/rig.rs | 210 | the rig, poses, forward kinematics, a stand-in body |+ | raea-sys-grab | src/arm.rs | 180 | two-bone IK, the reach that leans, the forearm's twist |++ @done+ Scenario: HG2. Hold points are found on the thing itself+ # 11-14, built: shape.rs, hand.rs. A box 36 cm wide gets a hold on each side face, facing out; a cup 8 cm+ # wide gets one hand; a turned thing's holds are on its surface from wherever the holder stands; the palm's+ # skin lies on the hold within 0.1 mm, facing into it, fingers the way the holder faces.+ Given a thing as a ball, a box, a capsule or a cylinder, placed and turned, and where the holder stands+ When its holds are asked for+ Then a thing wider than a hand's span gets a hold on the holder's left and one on the right, where a ray+ from that side meets its surface, each with the way the surface faces+ And a narrower thing gets one hand's hold+ And the holds are kept in the thing's own frame, so they ride with it+ And the plan:+ | crate | file | lines | job |+ | raea-sys-grab | src/shape.rs | 120 | solids as signed distances: casts, normals, clearance |+ | raea-sys-grab | src/hand.rs | 220 | holds, the wrist that lays a palm on one, the fingers' curl |++ @done+ Scenario: HG3. Fingers wrap what they hold+ # 11-14, built: hand.rs `curl`. Each joint, knuckle first, opens past rest and bends until its bone meets+ # the surface. On a carried box at least three fingers of each hand are on it and none is over 12 mm inside.+ # The curl is solved with the hand at its hold, not where the arm has got it to, so it doesn't flicker as+ # the hand comes in (it did: 24 degrees a frame).+ Given a hand at its hold on a thing+ When its fingers close+ Then each finger bends until it meets the surface, a finger that meets nothing closes loosely, and a finger+ that is inside the thing even opened is reported, not hidden++ @done+ Scenario: HG4. Reach, grab, lift, carry, put down or throw, as one function of time+ # 11-14, built: take.rs `perform`. From the grab to the release both palms stay within 6 mm of their holds+ # at 30 frames a second; a cup carried while the body turns 34 degrees and back stays upright the whole+ # way and is set down within 0.1 mm of its place; a thrown box flies, lands on the floor and stays; the+ # body is back on its own motion 0.4 s after letting go. A frame asked for twice, in any order, is the same+ # frame; no joint of the body turns over 6 degrees in a 60th of a second, no finger joint over 20.+ # `cargo run -p raea-sys-grab --example strip -- out.svg` draws a take as a filmstrip of stick figures.+ Given the body's own motion as a pose at any time, a thing, and its holds+ When a frame of the take is asked for+ Then the hands leave the body's motion, come onto the holds from off the surface, and close+ And the thing is drawn to a carry place off the chest and rides there, turned only with the body's facing+ And a put sets it down at a place, a throw lets it go with a velocity and it falls to the floor+ And every frame says how far a wrist missed and how far the body was turned from its own motion+ And the plan:+ | crate | file | lines | job |+ | raea-sys-grab | src/take.rs | 210 | the take's timeline |+ | raea-sys-grab | tests/grab.rs | 290 | the measures above, on the stand-in body |+ | raea-sys-grab | examples/strip.rs | 90 | a take drawn as an SVG filmstrip |++ Rule: Next, in order++ @needs:HG4+ Scenario: HG5. A character in a scene takes a thing+ # Nothing draws this yet: HG1 to HG4 are maths, judged on stick figures. This is the first render to watch.+ Given a <Character> and a thing in a 3D scene+ When the scene says the character takes it (which thing, when, then put where or thrown how)+ Then the engine asks systems/grab for each frame's pose and the thing's place and draws both, in a render+ and in live play alike+ And TypeScript reaches it as one native call (core/calls), typed, with the report per frame+ And the body's own motion is whatever the character was playing+ And a render of a box taken and thrown, and a cup moved across a table, is watched before anything after++ @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 only.+ Given a solved arm+ Then every joint is inside the range sdk/body's limits give, the elbow and wrist first+ And the arm, the hand and the held thing stay out of the body and off a table's top, by the least move+ And one copy of the limits serves both the TypeScript and the Rust++ @needs:HG5+ Scenario: HG7. The body goes to the thing+ # A take starts only when the body is where it can reach (docs/character.md, principle 6). Today a thing+ # out of reach is missed and reported.+ Given a thing out of reach, on the floor, a table or a shelf+ Then locomotion is asked to arrive where both holds are in reach, facing it+ And a low thing is taken from a crouch or a bend chosen from the library's pick-low and lift captures,+ with the hands' holds laid over it++ @needs:HG5+ Scenario: HG8. Things with a way to be held+ Given a thing that is held one way (a mug's handle, a sword's grip, a door's handle, a phone, a bag's strap)+ Then its holds come with the thing, as places and hand shapes, from the 35 captured hand poses+ (character/captured.ts) where one fits+ And 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++ @needs:HG5+ Scenario: HG9. Using what is held, and handing it over+ Then a held thing can be aimed, swung, drunk from, set to the ear, pushed, pulled and turned (a door, a+ drawer, a lever), each a path for the thing that the hands follow+ And a thing passes from one hand to the other, and from one character to another, with no frame where+ nobody holds it++ @needs:HG5+ Scenario: HG10. Weight+ Then a heavy thing is held low and close, the trunk leans back against it, the elbows straighten, and the+ lift is slower; a light one moves with the wrist+ And a throw's wind-up and follow-through scale with it++ Rule: Wider, for the character SDK++ Scenario: HG11. Creatures' motion from generated video+ # patch-gg/anymove, Apache-2.0. raea's animals have no captures (the dog and cat were called stiff, 11-14).+ Given a rigged creature made skeleton first+ Then its moves are captured from a generated two-view video, the joints read in both views, the rig fitted+ And the model that reads joints runs on hardware a user has, or the step is a cloud one and says so++ Scenario: HG12. Motion from words, between poses+ # Kimodo (Apache-2.0 code, weights' licence to be read in full first). MotionBricks only if its licence+ # turns out to allow it.+ Then a situation the library has no capture of is filled by generated motion on the rig, retargeted from+ SOMA's skeleton once, and judged against the captures by the same detectors++ Scenario: HG13. A body that reacts+ Then a pushed or struck character gives way and recovers (the ragdoll looked at again, with a physics+ crate chosen for the whole engine first: there is none in the workspace today)+ And a hand or a foot can brace on a wall, a rail or the floor as a contact found the way holds arediff --git a/systems/grab/Cargo.toml b/systems/grab/Cargo.tomlnew file mode 100644index 00000000..5c3d9b26--- /dev/null+++ b/systems/grab/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "raea-sys-grab"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Procedural arms and hands (docs/hands.feature): a body reaches for a thing, takes it with one hand or two, carries it and throws it. Arm IK, hold points found on the thing's shape, fingers curled onto it, all as a function of time"++[dependencies]+# the glam Bevy 0.20 uses, so a pose passes to the engine as it is+glam = "0.33"+serde_json = "1"diff --git a/systems/grab/examples/strip.rs b/systems/grab/examples/strip.rsnew file mode 100644index 00000000..cad51768--- /dev/null+++ b/systems/grab/examples/strip.rs@@ -0,0 +1,76 @@+//! A filmstrip of a take, as an SVG of stick figures, to judge the motion by eye with no engine: the stand-in body+//! takes a box with both hands and throws it (top rows), and moves a cup with one (bottom rows). Each take is drawn+//! from the front quarter and from the side.+//! cargo run -p raea-sys-grab --example strip -- out.svg++use std::fmt::Write;++use glam::{Quat, Vec3};+use raea_sys_grab::*;++/// a point of the body's frame on the page: turned about the vertical by `yaw`, y up+fn project(p: Vec3, yaw: f32, ox: f32, oy: f32) -> (f32, f32) {+ let q = Quat::from_rotation_y(yaw) * p;+ (ox + q.x * 150.0, oy - q.y * 150.0)+}++fn draw(svg: &mut String, s: &Skeleton, f: &Frame, yaw: f32, ox: f32, oy: f32) {+ let w = s.fk(&f.pose);+ let line = |svg: &mut String, a: Vec3, b: Vec3, colour: &str, width: f32| {+ let ((x1, y1), (x2, y2)) = (project(a, yaw, ox, oy), project(b, yaw, ox, oy));+ let _ = writeln!(svg, r#"<line x1="{x1:.1}" y1="{y1:.1}" x2="{x2:.1}" y2="{y2:.1}" stroke="{colour}" stroke-width="{width}" stroke-linecap="round"/>"#);+ };+ // the thing: its box, or the box round it, by its own axes+ let half = match f.thing.solid {+ Solid::Ball { r } => Vec3::splat(r),+ Solid::Box { half } => half,+ Solid::Capsule { half, r } => Vec3::new(r, half + r, r),+ Solid::Cylinder { half, r } => Vec3::new(r, half, r),+ };+ let corner = |i: usize| f.thing.world(Vec3::new(if i & 1 == 0 { -half.x } else { half.x }, if i & 2 == 0 { -half.y } else { half.y }, if i & 4 == 0 { -half.z } else { half.z }));+ for i in 0..8 {+ for bit in [1, 2, 4] {+ if i & bit == 0 {+ line(svg, corner(i), corner(i | bit), "#c2410c", 1.5);+ }+ }+ }+ for (i, j) in s.joints.iter().enumerate() {+ let Some(p) = j.parent else { continue };+ let finger = i >= s.joint("thumb_01_l").unwrap_or(usize::MAX);+ let colour = if j.name.ends_with("_l") { "#1d4ed8" } else if j.name.ends_with("_r") { "#15803d" } else { "#111827" };+ line(svg, w.pos[p], w.pos[i], colour, if finger { 1.0 } else { 2.5 });+ if finger || j.name.starts_with("hand") || j.name == "head" {+ line(svg, w.pos[i], w.pos[i] + w.rot[i] * (j.tail - j.head), colour, if finger { 1.0 } else { 2.5 });+ }+ }+}++fn main() {+ let out = std::env::args().nth(1).unwrap_or_else(|| "strip.svg".into());+ let s = mannequin();+ let stand = |_: f32| s.rest();++ let crate_ = Thing::new(Solid::Box { half: Vec3::new(0.16, 0.1, 0.12) }, Vec3::new(0.0, 1.05, 0.42));+ let mut throw = Take::new(crate_, find_holds(&crate_, s.rest().root, HoldOptions::default()), 0.2);+ throw.release = Some(Release::Throw { at: 1.9, velocity: Vec3::new(0.0, 1.5, 2.5), floor: 0.0 });++ let cup = Thing::new(Solid::Cylinder { half: 0.05, r: 0.035 }, Vec3::new(-0.2, 1.0, 0.38));+ let mut put = Take::new(cup, find_holds(&cup, s.rest().root, HoldOptions::default()), 0.2);+ put.release = Some(Release::Put { at: 1.7, down: 2.3, place: Vec3::new(0.05, 1.0, 0.4) });++ let times = [0.0, 0.45, 0.65, 0.8, 1.05, 1.3, 1.6, 1.9, 2.05, 2.3, 2.7];+ let (cell, row) = (190.0, 310.0);+ let mut svg = format!(r##"<svg xmlns="http://www.w3.org/2000/svg" width="{}" height="{}" font-family="monospace" font-size="11"><rect width="100%" height="100%" fill="#fafaf9"/>"##, cell * times.len() as f32, row * 4.0);+ for (r, (take, yaw, name)) in [(&throw, -0.6, "box, front quarter"), (&throw, -1.5708, "box, side"), (&put, -0.6, "cup, front quarter"), (&put, -1.5708, "cup, side")].into_iter().enumerate() {+ for (c, t) in times.iter().enumerate() {+ let f = perform(&s, &stand, take, *t);+ let (ox, oy) = (cell * (c as f32 + 0.5), row * (r as f32 + 1.0) - 14.0);+ draw(&mut svg, &s, &f, yaw, ox, oy);+ let _ = writeln!(svg, r##"<text x="{:.0}" y="{:.0}" fill="#44403c">{name} t={t:.2} {:?}</text><text x="{:.0}" y="{:.0}" fill="#78716c">miss {:.1} mm, moved {:.0} deg</text>"##, ox - cell / 2.0 + 6.0, oy - row + 30.0, f.phase, ox - cell / 2.0 + 6.0, oy - row + 44.0, f.miss * 1000.0, f.moved);+ }+ }+ svg.push_str("</svg>");+ std::fs::write(&out, svg).expect("the strip written");+ println!("{out}");+}diff --git a/systems/grab/src/arm.rs b/systems/grab/src/arm.rsnew file mode 100644index 00000000..01e1fcfc--- /dev/null+++ b/systems/grab/src/arm.rs@@ -0,0 +1,170 @@+//! Arm IK. `two_bone` puts a limb's end joint (wrist, ankle) on a target: the middle joint bends about the hinge it+//! already has, the limb swings the least that gets there, and `pole` chooses the swivel (where the elbow points).+//! `reach` adds the trunk: when the arm alone falls short, the clavicle, chest and spine lean the shoulder toward the+//! target, each by a capped share (sdk/body/src/reach.ts). Both report how far they missed and how far they turned+//! each joint, so a caller can tell a held contact from a pose that should never have been asked for+//! (docs/character.md, principle 2).++use glam::{Quat, Vec3};++use crate::rig::{Pose, Side, Skeleton};++#[derive(Clone, Copy, Debug, Default)]+pub struct ArmOptions {+ /// a direction (the body's frame) the middle joint should point toward, off the line to the target+ pub pole: Option<Vec3>,+ /// the end joint's world turn; by default the one it has+ pub end: Option<Quat>,+ /// 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,+}++#[derive(Clone, Debug)]+pub struct IkReport {+ pub pose: Pose,+ /// how far the end joint ended from the target, metres+ pub miss: f32,+ /// how far each joint the solver touched was turned from the pose it was given, degrees+ pub moved: Vec<(usize, f32)>,+ /// the target is farther than the limb reaches straight, or nearer than it folds+ pub out_of_reach: bool,+}++/// the distance a limb of lengths adding to `full` is asked to span, eased so it never quite locks+fn soften(d: f32, full: f32, soft: f32) -> f32 {+ if soft <= 0.0 || d <= full - soft {+ return d;+ }+ let knee = full - soft;+ knee + soft * (1.0 - (-(d - knee) / soft).exp())+}++pub fn two_bone(skel: &Skeleton, p: &Pose, limb: [usize; 3], target: Vec3, o: ArmOptions) -> IkReport {+ let [a, b, c] = limb;+ let w = skel.fk(p);+ let (pa, pb, pc) = (w.pos[a], w.pos[b], w.pos[c]);+ let (la, lb) = ((pb - pa).length(), (pc - pb).length());+ let full = la + lb;+ let asked = (target - pa).length();+ let fold = (la - lb).abs() + 1e-4;+ let out_of_reach = asked > full || asked < fold;+ let d = soften(asked, full, o.soft).clamp(fold, full - 1e-5);++ // the hinge the middle joint already bends about; a straight limb takes it from the pole, or any side+ let (u, v) = ((pb - pa) / la, (pc - pb) / lb);+ let mut hinge = u.cross(v);+ if hinge.length_squared() < 1e-8 {+ hinge = o.pole.map_or(Vec3::ZERO, |pole| pole.cross(u));+ }+ let hinge = if hinge.length_squared() < 1e-8 { u.any_orthonormal_vector() } else { hinge.normalize() };+ // the bend between the two bones now, and the one that spans d (the law of cosines)+ let bend0 = u.dot(v).clamp(-1.0, 1.0).acos();+ let bend1 = std::f32::consts::PI - ((la * la + lb * lb - d * d) / (2.0 * la * lb)).clamp(-1.0, 1.0).acos();+ let flex = Quat::from_axis_angle(hinge, bend1 - bend0);+ let pc1 = pb + flex * (pc - pb);++ // the whole limb swung so its end lies toward the target+ let to = if asked > 1e-6 { (target - pa) / asked } else { (pc1 - pa).normalize() };+ let swing = Quat::from_rotation_arc((pc1 - pa).normalize(), to);+ let mut turn_a = swing;+ if let Some(pole) = o.pole {+ // about the line to the target, the middle joint brought toward the pole+ let elbow = swing * (pb - pa);+ let (e, q) = (elbow - to * elbow.dot(to), pole - to * pole.dot(to));+ if e.length_squared() > 1e-8 && q.length_squared() > 1e-8 {+ let (e, q) = (e.normalize(), q.normalize());+ let angle = e.cross(q).dot(to).atan2(e.dot(q));+ turn_a = Quat::from_axis_angle(to, angle) * swing;+ }+ }+ let ra = (turn_a * w.rot[a]).normalize();+ let rb = (turn_a * flex * w.rot[b]).normalize();+ let rc = o.end.unwrap_or(w.rot[c]);++ let mut pose = p.clone();+ pose.turns[a] = skel.local_for(&w, a, ra);+ pose.turns[b] = (ra.inverse() * rb).normalize();+ pose.turns[c] = (rb.inverse() * rc).normalize();+ let end = skel.fk(&pose).pos[c];+ let moved = limb.iter().map(|&i| (i, p.turns[i].angle_between(pose.turns[i]).to_degrees())).collect();+ IkReport { pose, miss: (end - target).length(), moved, out_of_reach }+}++/// the trunk joints that lean a shoulder, nearest the arm first: the share of the lean each takes a pass, and the+/// most it may turn from the pose it was given, degrees+const LEAN: [(&str, f32, f32); 3] = [("clavicle", 0.35, 18.0), ("spine_03", 0.5, 30.0), ("spine_02", 0.5, 25.0)];++/// A hand's wrist put on a target the arm alone may not get to.+pub fn reach(skel: &Skeleton, p: &Pose, s: Side, target: Vec3, o: ArmOptions) -> Option<IkReport> {+ let arm = skel.arm(s)?;+ let within = 0.002;+ let mut out = two_bone(skel, p, arm, target, o);+ let lean: Vec<(usize, f32, f32)> = LEAN+ .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))+ })+ .collect();+ if out.miss <= within || !out.out_of_reach {+ return Some(out);+ }+ let hand = o.end.unwrap_or(skel.fk(p).rot[arm[2]]);+ let o = ArmOptions { end: Some(hand), ..o };+ let arm_len = skel.offset(arm[1]).length() + skel.offset(arm[2]).length();+ let mut turns = p.turns.clone();+ for _ in 0..8 {+ if out.miss <= within {+ break;+ }+ for &(i, share, cap) in &lean {+ let w = skel.fk(&Pose { root: p.root, turns: turns.clone() });+ let sh = w.pos[arm[0]];+ // where the shoulder must be for the arm, nearly straight, to touch the target+ let want = target - (target - sh).normalize_or_zero() * arm_len * 0.97;+ if (want - sh).length() < 1e-4 {+ break;+ }+ let turn = Quat::IDENTITY.slerp(Quat::from_rotation_arc((sh - w.pos[i]).normalize(), (want - w.pos[i]).normalize()), share);+ let local = skel.local_for(&w, i, turn * w.rot[i]);+ // held to its cap, measured from the pose it came with+ let from = p.turns[i];+ let off = from.angle_between(local).to_degrees();+ turns[i] = if off > cap { from.slerp(local, cap / off) } else { local };+ }+ out = two_bone(skel, &Pose { root: p.root, turns: turns.clone() }, arm, target, o);+ turns = out.pose.turns.clone();+ }+ out.moved = lean.iter().map(|l| l.0).chain(arm).map(|i| (i, p.turns[i].angle_between(out.pose.turns[i]).to_degrees())).collect();+ Some(out)+}++/// A wrist's twist shared with the forearm, where pronation happens, so the skin doesn't wring at the wrist. The hand+/// ends where it was. `share` is how much of the twist the forearm takes (1: all of it, sdk/body's library fix).+/// The split is SOMA-X's swing-twist extractor (NVlabs/SOMA-X, Apache-2.0, `local_x_swing_twist`, half-angle form).+pub fn forearm_twist(skel: &Skeleton, p: &Pose, s: Side, share: f32) -> Pose {+ let Some([_, fore, hand]) = skel.arm(s) else { return p.clone() };+ let axis = skel.offset(hand).normalize_or_zero();+ let twist = twist_about(p.turns[hand], axis);+ let part = Quat::IDENTITY.slerp(twist, share);+ let mut out = p.clone();+ out.turns[fore] = (p.turns[fore] * part).normalize();+ out.turns[hand] = (part.inverse() * p.turns[hand]).normalize();+ out+}++/// the part of a turn that is about `axis` (the twist of its swing-twist split), the short way round+pub fn twist_about(q: Quat, axis: Vec3) -> Quat {+ let along = Vec3::new(q.x, q.y, q.z).dot(axis);+ let t = Quat::from_xyzw(axis.x * along, axis.y * along, axis.z * along, q.w);+ if t.length_squared() < 1e-12 {+ return Quat::IDENTITY;+ }+ let t = t.normalize();+ if t.w < 0.0 { -t } else { t }+}++/// How SOMA-X spreads a segment's twist over four twist joints along it, nearest the start joint first+/// (SOMA_procedural_transforms.json, forearm rows): for a rig that has them. raea's game_engine rig has none.+pub const TWIST_SHARES: [f32; 4] = [0.05, 1.0 / 3.0, 2.0 / 3.0, 0.95];diff --git a/systems/grab/src/hand.rs b/systems/grab/src/hand.rsnew file mode 100644index 00000000..239d56ce--- /dev/null+++ b/systems/grab/src/hand.rs@@ -0,0 +1,204 @@+//! Where hands go on a thing, and how they lie there. Hold points are found the way musthafa45/Ik-Object-Holding's+//! ColliderEdgeDetector finds them (MIT): from the thing's centre, out to the holder's left and right, a ray cast+//! back in meets the surface, and that is where each hand goes. Here the points are kept in the thing's own frame, so+//! they ride with it, and each carries the way the surface faces, which sets the palm. A thing narrower than a hand's+//! span is taken with one hand.++use glam::{Mat3, Quat, Vec3};++use crate::rig::{Side, Skeleton};+use crate::shape::Thing;++/// where one hand holds a thing, in the thing's own frame+#[derive(Clone, Copy, Debug)]+pub struct Hold {+ pub side: Side,+ pub at: Vec3,+ /// the way the surface faces there, outward+ pub normal: Vec3,+}++#[derive(Clone, Copy, Debug)]+pub enum Grip {+ One(Hold),+ Two(Hold, Hold),+}++impl Grip {+ pub fn holds(&self) -> impl Iterator<Item = Hold> {+ let (a, b) = match *self {+ Grip::One(h) => (Some(h), None),+ Grip::Two(l, r) => (Some(l), Some(r)),+ };+ a.into_iter().chain(b)+ }+}++#[derive(Clone, Copy, Debug)]+pub struct HoldOptions {+ /// the hand that takes a thing small enough for one+ pub hand: Side,+ /// the widest thing one hand takes, metres across+ pub span: f32,+ /// how far below the thing's middle the hands go, metres (a heavy box is held low)+ pub lower: f32,+}++impl Default for HoldOptions {+ fn default() -> Self {+ HoldOptions { hand: Side::R, span: 0.11, lower: 0.0 }+ }+}++/// the level way from a holder to a thing (the way the holder faces to take it)+pub fn facing(thing: &Thing, holder: Vec3) -> Vec3 {+ let f = thing.at - holder;+ Vec3::new(f.x, 0.0, f.z).try_normalize().unwrap_or(Vec3::Z)+}++/// The holds a holder standing at `holder` takes on a thing: one on its left and one on its right, or one hand's.+pub fn find_holds(thing: &Thing, holder: Vec3, o: HoldOptions) -> Grip {+ // the body's left is its up crossed with its facing (y up, facing +z, x left)+ let left = Vec3::Y.cross(facing(thing, holder));+ let far = thing.solid.bound() + 0.1;+ let hold = |side: Side| {+ let out = left * side.sign();+ let from = thing.at + out * far - Vec3::Y * o.lower;+ // no surface on that line (the lowered ray passes under a ball): the thing's edge that way, as the original does+ let (at, normal) = thing.cast(from, -out, far).map_or((thing.at + out * thing.solid.bound(), out), |h| (h.at, h.normal));+ Hold { side, at: thing.local(at), normal: thing.turn.inverse() * normal }+ };+ let (l, r) = (hold(Side::L), hold(Side::R));+ if (l.at - r.at).length() <= o.span { Grip::One(if o.hand == Side::L { l } else { r }) } else { Grip::Two(l, r) }+}++/// A hand's frame at rest, in the body's axes: along (wrist to the middle knuckle), the way the palm faces, and where+/// the palm's skin is from the wrist.+#[derive(Clone, Copy, Debug)]+pub struct HandRest {+ pub along: Vec3,+ pub palm: Vec3,+ pub mid: Vec3,+}++pub fn hand_rest(skel: &Skeleton, s: Side) -> Option<HandRest> {+ let hand = skel.arm(s)?[2];+ let knuckle = |f: &str| Some(skel.joints[skel.finger(f, s)?[0]].head);+ let h = skel.joints[hand].head;+ let reach = knuckle("middle")? - h;+ let along = reach.normalize();+ let line = knuckle("index")? - knuckle("pinky")?;+ let across = (line - along * line.dot(along)).normalize();+ let palm = if s == Side::L { along.cross(across) } else { across.cross(along) };+ // the palm's middle: a little over half way to the knuckles, out to the skin+ Some(HandRest { along, palm, mid: reach * 0.55 + palm * 0.012 })+}++/// The wrist's place and the hand's turn that lay the palm on a hold: the palm against the surface, the fingers+/// pointing the way the holder faces, as near as the surface lets them.+pub fn wrist_for(skel: &Skeleton, thing: &Thing, hold: &Hold, facing: Vec3) -> Option<(Vec3, Quat)> {+ let rest = hand_rest(skel, hold.side)?;+ let (at, n) = (thing.world(hold.at), (thing.turn * hold.normal).normalize());+ let along = (facing - n * facing.dot(n)).try_normalize().unwrap_or_else(|| Vec3::Y.cross(n).normalize_or(Vec3::X));+ let frame = |a: Vec3, p: Vec3| Mat3::from_cols(a, p, a.cross(p));+ let turn = Quat::from_mat3(&(frame(along, -n) * frame(rest.along, rest.palm).transpose())).normalize();+ Some((at - turn * rest.mid, turn))+}++/// What the fingers of one hand found on a thing.+#[derive(Clone, Copy, Debug, Default)]+pub struct Touch {+ /// thumb, index, middle, ring, pinky: on the thing+ pub on: [bool; 5],+ /// how deep the worst finger is inside it at the pose it came with, metres (0: none is)+ pub inside: f32,+}++/// each joint's most bend from rest, degrees: fingers, then the thumb+const BEND: [[f32; 3]; 2] = [[80.0, 100.0, 70.0], [45.0, 55.0, 70.0]];+/// and how far each opens back past rest (the rest hand is a little curled, so a finger laid on a flat face opens)+const OPEN: [[f32; 3]; 2] = [[-40.0, -25.0, -20.0], [-30.0, -20.0, -20.0]];+/// how far a finger that meets nothing still closes, as a share of its most: a loose hand, not a fist+const LOOSE: f32 = 0.35;++/// The fingers of a hand curled onto a thing: each joint, knuckle first, bends toward the palm until its bone meets+/// the surface, so the finger wraps whatever shape is there. The hand is taken to be at `wrist` (its place and turn:+/// where its hold has it), not where the arm has got it to, so the shape the fingers close to is the hold's and+/// doesn't change as the hand comes in. `close` (0 to 1) is how far along that closing is, for the frames a hand+/// takes to shut. The pose's own finger turns are what it closes from.+pub fn curl(skel: &Skeleton, turns: &mut [Quat], wrist: (Vec3, Quat), s: Side, thing: &Thing, close: f32) -> Option<Touch> {+ let hand = skel.arm(s)?[2];+ let rest = hand_rest(skel, s)?;+ let mut touch = Touch::default();+ for (n, name) in crate::rig::FINGERS.iter().enumerate() {+ let js = skel.finger(name, s)?;+ let (thumb, thick) = (n == 0, if n == 0 { 0.010 } else { 0.008 });+ // the axis each joint bends about, at rest: the one that carries its bone toward the palm's side (the thumb's,+ // toward the space in front of the palm, where it meets the fingers)+ let axis = |k: usize| {+ let j = &skel.joints[js[k]];+ let bone = (j.tail - j.head).normalize();+ let toward = if thumb { (skel.joints[hand].head + rest.mid + rest.palm * 0.05 - j.head).normalize() } else { rest.palm };+ bone.cross(toward).normalize_or(Vec3::X)+ };+ let base = [turns[js[0]], turns[js[1]], turns[js[2]]];+ // the least clearance of bone k's skin with the finger bent by `bend` (radians a joint)+ let clear = |bend: [f32; 3], k: usize| {+ let (mut pp, mut pr) = wrist;+ let mut least = f32::MAX;+ for i in 0..=k {+ let j = &skel.joints[js[i]];+ let p = pp + pr * skel.offset(js[i]);+ let q = (pr * base[i] * Quat::from_axis_angle(axis(i), bend[i])).normalize();+ if i == k {+ for along in [0.45, 0.75, 1.0] {+ least = least.min(thing.distance(p + q * ((j.tail - j.head) * along)) - thick);+ }+ }+ (pp, pr) = (p, q);+ }+ least+ };+ // each joint starts opened and bends until its bone meets the surface (the last step halved down to the+ // contact), so the finger wraps whatever is there; the joints after it wait opened, out of the way+ let open = OPEN[thumb as usize].map(f32::to_radians);+ let mut bend = open;+ for k in 0..3 {+ let most = BEND[thumb as usize][k].to_radians();+ let start = clear(bend, k);+ if start < 0.0 {+ // in the thing even opened: nothing a curl can fix; said, not hidden+ touch.inside = touch.inside.max(-start);+ touch.on[n] = true;+ continue;+ }+ let step = 3.0f32.to_radians();+ let (mut lo, mut hit) = (open[k], None);+ while lo < most {+ let hi = (lo + step).min(most);+ bend[k] = hi;+ if clear(bend, k) < 0.0 {+ hit = Some(hi);+ break;+ }+ lo = hi;+ }+ match hit {+ Some(mut hi) => {+ for _ in 0..8 {+ let mid = (lo + hi) / 2.0;+ bend[k] = mid;+ if clear(bend, k) < 0.0 { hi = mid } else { lo = mid }+ }+ bend[k] = lo;+ touch.on[n] = true;+ }+ None => bend[k] = most * if touch.on[n] { 1.0 } else { LOOSE },+ }+ }+ for k in 0..3 {+ turns[js[k]] = (base[k] * Quat::from_axis_angle(axis(k), bend[k] * close.clamp(0.0, 1.0))).normalize();+ }+ }+ Some(touch)+}diff --git a/systems/grab/src/lib.rs b/systems/grab/src/lib.rsnew file mode 100644index 00000000..3afe1ba5--- /dev/null+++ b/systems/grab/src/lib.rs@@ -0,0 +1,21 @@+//! Procedural arms and hands (docs/hands.feature): a body reaches for a thing, takes it with one hand or two, carries+//! it, and puts it down or throws it, with no capture of that action. Plain maths on glam, no engine: `perform` is a+//! function of time, so a render and live play ask it the same question and get the same frame.+//!+//! - `rig`: the game_engine skeleton, poses, forward kinematics (sdk/body's, in Rust), and a stand-in body.+//! - `arm`: two-bone IK with a pole, a reach that leans the trunk, and the wrist's twist shared with the forearm.+//! - `shape`: a thing as a signed distance: ray casts, normals, clearance.+//! - `hand`: hold points found on the thing, the wrist that lays a palm on one, fingers curled onto the surface.+//! - `take`: reach, grab, lift, carry, put down or throw, as one timeline.++pub mod arm;+pub mod hand;+pub mod rig;+pub mod shape;+pub mod take;++pub use arm::{ArmOptions, IkReport, forearm_twist, reach, two_bone};+pub use hand::{Grip, Hold, HoldOptions, Touch, curl, find_holds, wrist_for};+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/rig.rs b/systems/grab/src/rig.rsnew file mode 100644index 00000000..d21b9e71--- /dev/null+++ b/systems/grab/src/rig.rs@@ -0,0 +1,201 @@+//! The rig, as sdk/body/src/rig.ts has it: MakeHuman's game_engine skeleton (docs/skeleton.feature), poses and+//! forward kinematics. The body's frame: y up, facing +z, x its left. Every joint's rest turn is none, so a joint's+//! turn is read in the body's axes as they are at rest.++use std::collections::HashMap;++use glam::{Quat, Vec3};++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Side {+ L,+ R,+}++impl Side {+ pub const BOTH: [Side; 2] = [Side::L, Side::R];+ pub fn sx(self) -> &'static str {+ if self == Side::L { "l" } else { "r" }+ }+ /// +1 on the body's left (+x), -1 on its right+ pub fn sign(self) -> f32 {+ if self == Side::L { 1.0 } else { -1.0 }+ }+}++pub const FINGERS: [&str; 5] = ["thumb", "index", "middle", "ring", "pinky"];++#[derive(Clone, Debug)]+pub struct Joint {+ pub name: String,+ /// the parent's index; None for the root (the pelvis). Parents come before their children+ pub parent: Option<usize>,+ /// where the joint and its bone's end are at rest, metres, the body's frame+ pub head: Vec3,+ pub tail: Vec3,+}++#[derive(Clone, Debug)]+pub struct Skeleton {+ pub joints: Vec<Joint>,+ index: HashMap<String, usize>,+}++/// A pose: the root's place, and each joint's turn from rest against its parent.+#[derive(Clone, Debug, PartialEq)]+pub struct Pose {+ pub root: Vec3,+ pub turns: Vec<Quat>,+}++/// A pose drawn: each joint's place and turn in the body's frame.+#[derive(Clone, Debug)]+pub struct Posed {+ pub pos: Vec<Vec3>,+ pub rot: Vec<Quat>,+}++impl Skeleton {+ pub fn new(joints: Vec<Joint>) -> Self {+ let index = joints.iter().enumerate().map(|(i, j)| (j.name.clone(), i)).collect();+ Skeleton { joints, index }+ }++ /// A character's skeleton.json (projects/psx/export.py): `joints` of name, parent (-1 for the root), head, tail.+ pub fn from_json(text: &str) -> Result<Self, String> {+ let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("skeleton.json: {e}"))?;+ let list = v["joints"].as_array().ok_or("skeleton.json: no joints")?;+ let vec3 = |a: &serde_json::Value| -> Option<Vec3> {+ let a = a.as_array()?;+ Some(Vec3::new(a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32, a.get(2)?.as_f64()? as f32))+ };+ let mut joints = Vec::with_capacity(list.len());+ for (i, j) in list.iter().enumerate() {+ let name = j["name"].as_str().ok_or_else(|| format!("skeleton.json: joint {i} has no name"))?;+ let parent = j["parent"].as_i64().ok_or_else(|| format!("skeleton.json: {name} has no parent"))?;+ if parent >= i as i64 {+ return Err(format!("skeleton.json: {name}'s parent comes after it"));+ }+ let head = vec3(&j["head"]).ok_or_else(|| format!("skeleton.json: {name} has no head"))?;+ let tail = vec3(&j["tail"]).unwrap_or(head);+ joints.push(Joint { name: name.to_string(), parent: usize::try_from(parent).ok(), head, tail });+ }+ Ok(Skeleton::new(joints))+ }++ pub fn joint(&self, name: &str) -> Option<usize> {+ self.index.get(name).copied()+ }++ fn three(&self, names: [String; 3]) -> Option<[usize; 3]> {+ Some([self.joint(&names[0])?, self.joint(&names[1])?, self.joint(&names[2])?])+ }++ /// shoulder, elbow, wrist+ pub fn arm(&self, s: Side) -> Option<[usize; 3]> {+ self.three(["upperarm", "lowerarm", "hand"].map(|n| format!("{n}_{}", s.sx())))+ }++ /// a finger's three joints, knuckle first (the thumb's first is its metacarpal)+ pub fn finger(&self, f: &str, s: Side) -> Option<[usize; 3]> {+ self.three([1, 2, 3].map(|k| format!("{f}_0{k}_{}", s.sx())))+ }++ pub fn rest(&self) -> Pose {+ Pose { root: self.joints.first().map_or(Vec3::ZERO, |j| j.head), turns: vec![Quat::IDENTITY; self.joints.len()] }+ }++ /// a joint's place at rest against its parent's+ pub fn offset(&self, i: usize) -> Vec3 {+ match self.joints[i].parent {+ Some(p) => self.joints[i].head - self.joints[p].head,+ None => Vec3::ZERO,+ }+ }++ /// Forward kinematics: each joint's place and turn.+ pub fn fk(&self, p: &Pose) -> Posed {+ let n = self.joints.len();+ let (mut pos, mut rot) = (Vec::with_capacity(n), Vec::with_capacity(n));+ for i in 0..n {+ let t = p.turns.get(i).copied().unwrap_or(Quat::IDENTITY);+ match self.joints[i].parent {+ None => {+ rot.push(t);+ pos.push(p.root);+ }+ Some(par) => {+ let (pr, pp): (Quat, Vec3) = (rot[par], pos[par]);+ rot.push((pr * t).normalize());+ pos.push(pp + pr * self.offset(i));+ }+ }+ }+ Posed { pos, rot }+ }++ /// the local turn that gives joint `i` the world turn `world`, against its drawn parent+ pub fn local_for(&self, w: &Posed, i: usize, world: Quat) -> Quat {+ let pr = self.joints[i].parent.map_or(Quat::IDENTITY, |p| w.rot[p]);+ (pr.inverse() * world).normalize()+ }+}++/// A stand-in body of the rig's joints at an adult's proportions (1.81 m), so the solvers run with no character on+/// disk: tests, examples, and a scene that hasn't loaded its body yet. A real character brings its own skeleton.json.+pub fn mannequin() -> Skeleton {+ // name, parent, head, tail; the left side only (x > 0), the right is its mirror+ const MID: [(&str, &str, [f32; 3], [f32; 3]); 6] = [+ ("pelvis", "", [0.0, 1.00, 0.01], [0.0, 1.09, -0.03]),+ ("spine_01", "pelvis", [0.0, 1.09, -0.03], [0.0, 1.16, -0.02]),+ ("spine_02", "spine_01", [0.0, 1.16, -0.02], [0.0, 1.22, -0.04]),+ ("spine_03", "spine_02", [0.0, 1.22, -0.04], [0.0, 1.36, -0.06]),+ ("neck_01", "spine_03", [0.0, 1.57, 0.01], [0.0, 1.66, 0.04]),+ ("head", "neck_01", [0.0, 1.66, 0.04], [0.0, 1.82, 0.04]),+ ];+ const LIMB: [(&str, &str, [f32; 3], [f32; 3]); 8] = [+ ("clavicle", "spine_03", [0.024, 1.490, 0.030], [0.190, 1.463, 0.013]),+ ("upperarm", "clavicle", [0.190, 1.463, 0.013], [0.401, 1.235, 0.022]),+ ("lowerarm", "upperarm", [0.401, 1.235, 0.022], [0.534, 1.109, 0.213]),+ ("hand", "lowerarm", [0.534, 1.109, 0.213], [0.545, 1.093, 0.241]),+ ("thigh", "pelvis", [0.120, 0.975, -0.004], [0.160, 0.579, 0.030]),+ ("calf", "thigh", [0.160, 0.579, 0.030], [0.192, 0.093, 0.004]),+ ("foot", "calf", [0.192, 0.093, 0.004], [0.196, 0.029, 0.138]),+ ("ball", "foot", [0.196, 0.029, 0.138], [0.192, 0.034, 0.211]),+ ];+ // each finger's knuckle, middle joint, end joint and tip+ const HAND: [(&str, [[f32; 3]; 4]); 5] = [+ ("thumb", [[0.535, 1.102, 0.259], [0.513, 1.094, 0.281], [0.501, 1.081, 0.314], [0.495, 1.064, 0.336]]),+ ("index", [[0.563, 1.070, 0.313], [0.566, 1.055, 0.335], [0.566, 1.039, 0.352], [0.562, 1.019, 0.371]]),+ ("middle", [[0.580, 1.058, 0.295], [0.587, 1.032, 0.317], [0.590, 1.010, 0.335], [0.590, 0.988, 0.352]]),+ ("ring", [[0.588, 1.049, 0.277], [0.598, 1.025, 0.293], [0.602, 1.004, 0.307], [0.604, 0.979, 0.319]]),+ ("pinky", [[0.589, 1.040, 0.257], [0.596, 1.020, 0.266], [0.597, 1.006, 0.272], [0.600, 0.987, 0.280]]),+ ];+ let mut out: Vec<(String, String, Vec3, Vec3)> = Vec::new();+ for (n, p, h, t) in MID {+ out.push((n.into(), p.into(), h.into(), t.into()));+ }+ let on = |v: [f32; 3], s: Side| Vec3::new(v[0] * s.sign(), v[1], v[2]);+ let sided = |n: &str, s: Side| if MID.iter().any(|m| m.0 == n) { n.to_string() } else { format!("{n}_{}", s.sx()) };+ for group in [&LIMB[..4], &LIMB[4..]] {+ for s in Side::BOTH {+ for (n, p, h, t) in group {+ out.push((sided(n, s), sided(p, s), on(*h, s), on(*t, s)));+ }+ }+ }+ for s in Side::BOTH {+ for (f, pts) in HAND {+ for k in 0..3 {+ let parent = if k == 0 { format!("hand_{}", s.sx()) } else { format!("{f}_0{k}_{}", s.sx()) };+ out.push((format!("{f}_0{}_{}", k + 1, s.sx()), parent, on(pts[k], s), on(pts[k + 1], s)));+ }+ }+ }+ let names: Vec<String> = out.iter().map(|j| j.0.clone()).collect();+ Skeleton::new(+ out.into_iter()+ .map(|(name, parent, head, tail)| Joint { parent: names.iter().position(|n| *n == parent), name, head, tail })+ .collect(),+ )+}diff --git a/systems/grab/src/shape.rs b/systems/grab/src/shape.rsnew file mode 100644index 00000000..6a7d7282--- /dev/null+++ b/systems/grab/src/shape.rs@@ -0,0 +1,109 @@+//! A thing to hold, as a shape with a distance: a ball, a box, a capsule or a cylinder, placed and turned. One signed+//! distance does every job the hands need: where a ray from outside meets the surface (hold points), which way the+//! surface faces there (how the palm lies), and how near a finger is (where its curl stops).++use glam::{Quat, Vec2, Vec3};++#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Solid {+ Ball { r: f32 },+ /// half its width, height and depth+ Box { half: Vec3 },+ /// a rod with rounded ends along its own y: half the straight part's length, and its radius+ Capsule { half: f32, r: f32 },+ /// a can along its own y: half its height, and its radius+ Cylinder { half: f32, r: f32 },+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Thing {+ pub solid: Solid,+ /// its centre and turn, in the frame the body is posed in+ pub at: Vec3,+ pub turn: Quat,+}++#[derive(Clone, Copy, Debug)]+pub struct Hit {+ pub at: Vec3,+ /// the way the surface faces there, outward+ pub normal: Vec3,+}++impl Solid {+ /// signed distance from a point in the solid's own frame: negative inside+ pub fn distance(&self, p: Vec3) -> f32 {+ match *self {+ Solid::Ball { r } => p.length() - r,+ Solid::Box { half } => {+ let q = p.abs() - half;+ q.max(Vec3::ZERO).length() + q.max_element().min(0.0)+ }+ Solid::Capsule { half, r } => (p - Vec3::Y * p.y.clamp(-half, half)).length() - r,+ Solid::Cylinder { half, r } => {+ let d = Vec2::new(Vec2::new(p.x, p.z).length() - r, p.y.abs() - half);+ d.max(Vec2::ZERO).length() + d.max_element().min(0.0)+ }+ }+ }++ /// the radius of a ball about its centre that holds it+ pub fn bound(&self) -> f32 {+ match *self {+ Solid::Ball { r } => r,+ Solid::Box { half } => half.length(),+ Solid::Capsule { half, r } => half + r,+ Solid::Cylinder { half, r } => Vec2::new(half, r).length(),+ }+ }+}++impl Thing {+ pub fn new(solid: Solid, at: Vec3) -> Self {+ Thing { solid, at, turn: Quat::IDENTITY }+ }++ /// a point of the frame the body is in, in the thing's own+ pub fn local(&self, p: Vec3) -> Vec3 {+ self.turn.inverse() * (p - self.at)+ }++ /// a point of the thing's own frame, out in the body's+ pub fn world(&self, p: Vec3) -> Vec3 {+ self.at + self.turn * p+ }++ pub fn distance(&self, p: Vec3) -> f32 {+ self.solid.distance(self.local(p))+ }++ /// the way out of the surface nearest a point+ pub fn normal(&self, p: Vec3) -> Vec3 {+ let (q, e) = (self.local(p), 1e-3);+ let d = |o: Vec3| self.solid.distance(q + o);+ let g = Vec3::new(d(Vec3::X * e) - d(Vec3::X * -e), d(Vec3::Y * e) - d(Vec3::Y * -e), d(Vec3::Z * e) - d(Vec3::Z * -e));+ (self.turn * g).normalize_or(Vec3::Y)+ }++ /// Where a ray starting outside first meets the surface, within `far` metres (stepping by the distance).+ pub fn cast(&self, from: Vec3, dir: Vec3, far: f32) -> Option<Hit> {+ let mut t = 0.0;+ for _ in 0..96 {+ let p = from + dir * t;+ let d = self.distance(p);+ if d < 1e-4 {+ return Some(Hit { at: p, normal: self.normal(p) });+ }+ t += d;+ if t > far {+ return None;+ }+ }+ None+ }++ /// the same thing, moved and turned with a frame it rides in+ pub fn moved(&self, at: Vec3, turn: Quat) -> Thing {+ Thing { solid: self.solid, at, turn }+ }+}diff --git a/systems/grab/src/take.rs b/systems/grab/src/take.rsnew file mode 100644index 00000000..9fe04ff5--- /dev/null+++ b/systems/grab/src/take.rs@@ -0,0 +1,193 @@+//! Taking a thing: reach, grab, lift, carry, then put it down or throw it. The whole action is a function of time+//! (docs/character.md, principle 9): any frame can be asked for, and a render and live play agree. The body's own+//! motion comes in as `base` (a clip, a walk, a stand); this only moves what the hands need, and says how much.+//!+//! The stages are musthafa45/Ik-Object-Holding's (MIT): hands eased onto the hold points, the thing drawn to a carry+//! place in front of the chest, both let go on a drop or a throw. There the easing is a per-frame lerp, which depends+//! on the frame rate and on every frame before; here each ease is a curve of time.++use glam::{Quat, Vec3};++use crate::arm::{ArmOptions, forearm_twist, reach};+use crate::hand::{Grip, Touch, curl, facing, wrist_for};+use crate::rig::{Pose, Posed, Skeleton};+use crate::shape::Thing;++#[derive(Clone, Copy, Debug)]+pub enum Release {+ /// set down: from `at` the thing is moved to `place`, standing there from `down` on, and the hands leave it+ Put { at: f32, down: f32, place: Vec3 },+ /// let go at `at` with a velocity, metres a second (none: a drop); it falls to `floor`+ Throw { at: f32, velocity: Vec3, floor: f32 },+}++#[derive(Clone, Debug)]+pub struct Take {+ /// the thing where it stands before it is taken+ pub thing: Thing,+ pub grip: Grip,+ /// when the hands leave the body's own motion, when they close on the thing, and when it has reached the carry+ pub start: f32,+ pub grab: f32,+ pub carried: f32,+ /// where the thing's centre rides, from the chest: x to the body's left, y up, z the way it faces+ pub carry: Vec3,+ pub release: Option<Release>,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Phase {+ Before,+ Reach,+ Lift,+ Carry,+ Release,+ After,+}++#[derive(Clone, Debug)]+pub struct Frame {+ pub pose: Pose,+ pub thing: Thing,+ pub phase: Phase,+ /// the worst a wrist ended from where its hold asks, metres+ pub miss: f32,+ /// the most any joint was turned from the body's own motion, degrees+ pub moved: f32,+ pub touch: [Option<Touch>; 2],+}++const GRAVITY: f32 = 9.81;+/// how long the hands take to go back to the body's own motion after letting go, seconds+const AWAY: f32 = 0.4;+/// how long the fingers take to shut, ending at the grab, seconds+const SHUT: f32 = 0.25;++fn smooth(u: f32) -> f32 {+ let u = u.clamp(0.0, 1.0);+ u * u * u * (u * (u * 6.0 - 15.0) + 10.0)+}++fn span(t: f32, a: f32, b: f32) -> f32 {+ if b <= a { (t >= b) as u8 as f32 } else { ((t - a) / (b - a)).clamp(0.0, 1.0) }+}++/// the turn about the vertical that the body faces by+fn yaw(w: &Posed) -> Quat {+ let f = w.rot[0] * Vec3::Z;+ Quat::from_rotation_y(f.x.atan2(f.z))+}++impl Take {+ /// A take with the usual timing: reach for 0.6 s from `start`, lift for 0.5 s, carried in front of the belly (a+ /// one-handed thing, off to its hand's side).+ pub fn new(thing: Thing, grip: Grip, start: f32) -> Self {+ let carry = match grip {+ Grip::One(h) => Vec3::new(0.2 * h.side.sign(), -0.22, 0.3),+ Grip::Two(..) => Vec3::new(0.0, -0.2, 0.32 + thing.solid.bound() * 0.3),+ };+ Take { thing, grip, start, grab: start + 0.6, carried: start + 1.1, carry, release: None }+ }++ /// where the thing rides at a moment of the body's motion: off the chest, turned only with the body's facing, so+ /// what stood upright is carried upright+ fn riding(&self, skel: &Skeleton, base: &dyn Fn(f32) -> Pose, t: f32) -> Thing {+ let (now, then) = (skel.fk(&base(t)), skel.fk(&base(self.grab)));+ let chest = skel.joint("spine_03").unwrap_or(0);+ let (y, y0) = (yaw(&now), yaw(&then));+ self.thing.moved(now.pos[chest] + y * self.carry, (y * y0.inverse() * self.thing.turn).normalize())+ }++ /// where the thing is at `t`, and whether the hands are on it+ fn thing_at(&self, skel: &Skeleton, base: &dyn Fn(f32) -> Pose, t: f32) -> (Thing, Phase) {+ if t < self.start {+ return (self.thing, Phase::Before);+ }+ if t < self.grab {+ return (self.thing, Phase::Reach);+ }+ let carried = |t: f32| {+ let (ride, u) = (self.riding(skel, base, t), smooth(span(t, self.grab, self.carried)));+ self.thing.moved(self.thing.at.lerp(ride.at, u), self.thing.turn.slerp(ride.turn, u))+ };+ match self.release {+ Some(Release::Put { at, down, place }) if t >= at => {+ let from = carried(at);+ let u = smooth(span(t, at, down));+ // set down level with where it stood: its own turn about the vertical kept+ let thing = from.moved(from.at.lerp(place, u), from.turn);+ (thing, if t < down { Phase::Release } else { Phase::After })+ }+ Some(Release::Throw { at, velocity, floor }) if t >= at => {+ let from = carried(at);+ let rest = floor + from.solid.bound();+ // the fall, stopped where it lands+ let fall = |dt: f32| from.at + velocity * dt - Vec3::Y * (0.5 * GRAVITY * dt * dt);+ let land = (velocity.y + (velocity.y * velocity.y + 2.0 * GRAVITY * (from.at.y - rest).max(0.0)).sqrt()) / GRAVITY;+ (from.moved(fall((t - at).min(land)), from.turn), Phase::After)+ }+ _ => (carried(t), if t < self.carried { Phase::Lift } else { Phase::Carry }),+ }+ }++ /// when the hands let go, if they do+ fn let_go(&self) -> Option<f32> {+ match self.release? {+ Release::Put { down, .. } => Some(down),+ Release::Throw { at, .. } => Some(at),+ }+ }+}++/// The body and the thing at `t`. `base` is the body's own motion: its pose at any time.+pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32) -> Frame {+ let own = base(t);+ let (thing, phase) = take.thing_at(skel, base, t);+ let mut frame = Frame { pose: own.clone(), thing, phase, miss: 0.0, moved: 0.0, touch: [None, None] };+ // how much the hands are the take's and not the body's own: none before, all from the grab, none again once away+ let gone = take.let_go();+ let weight = match gone {+ Some(g) if t >= g => 1.0 - smooth(span(t, g, g + AWAY)),+ _ => (t >= take.start) as u8 as f32,+ };+ if weight <= 0.0 {+ return frame;+ }+ // while letting go the hands ease off the place the thing was let go at, not after a thing in flight+ let held = match gone {+ Some(g) if t >= g => take.thing_at(skel, base, g).0,+ _ => thing,+ };+ let w0 = skel.fk(&own);+ let face = yaw(&w0) * Vec3::Z;+ let mut pose = own.clone();+ for hold in take.grip.holds() {+ let Some((at, turn)) = wrist_for(skel, &held, &hold, facing(&held, w0.pos[0]).lerp(face, 0.5).normalize_or(face)) else { continue };+ let Some(arm) = skel.arm(hold.side) else { continue };+ // the reach: the wrist leaves where the body has it and comes in onto the hold from off the surface+ let u = smooth(span(t, take.start, take.grab));+ let off = (held.turn * hold.normal) * 0.1 * (1.0 - u);+ let target = w0.pos[arm[2]].lerp(at + off, u);+ let end = w0.rot[arm[2]].slerp(turn, smooth(span(t, take.start, take.start + (take.grab - take.start) * 0.8)));+ // elbows out and down, the way arms hang+ let 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 };+ pose = forearm_twist(skel, &solved.pose, hold.side, 0.7);+ if t >= take.grab {+ frame.miss = frame.miss.max(solved.miss);+ }+ // the fingers shut over the last moments of the reach, and open again as the hand leaves+ let close = smooth(span(t, take.grab - SHUT, take.grab)) * weight;+ if close > 0.0 {+ frame.touch[hold.side as usize] = curl(skel, &mut pose.turns, (at, turn), hold.side, &held, close);+ }+ }+ if weight < 1.0 {+ for (mine, own) in pose.turns.iter_mut().zip(&own.turns) {+ *mine = own.slerp(*mine, weight);+ }+ }+ frame.moved = pose.turns.iter().zip(&own.turns).map(|(a, b)| a.angle_between(*b).to_degrees()).fold(0.0, f32::max);+ frame.pose = pose;+ frame+}diff --git a/systems/grab/tests/grab.rs b/systems/grab/tests/grab.rsnew file mode 100644index 00000000..cd7ab8a3--- /dev/null+++ b/systems/grab/tests/grab.rs@@ -0,0 +1,273 @@+//! The measures docs/hands.feature names, on the stand-in body.++use glam::{Quat, Vec3};+use raea_sys_grab::hand::hand_rest;+use raea_sys_grab::*;++/// a seeded random in [0, 1) (mulberry32, as sdk/body's tests use)+fn rng(mut seed: u32) -> impl FnMut() -> f32 {+ move || {+ seed = seed.wrapping_add(0x6d2b79f5);+ let mut t = (seed ^ (seed >> 15)).wrapping_mul(1 | seed);+ t = (t.wrapping_add((t ^ (t >> 7)).wrapping_mul(61 | t))) ^ t;+ ((t ^ (t >> 14)) as f32) / 4294967296.0+ }+}++#[test]+fn mannequin_is_the_rig() {+ let s = mannequin();+ assert_eq!(s.joints.len(), 52);+ for (i, j) in s.joints.iter().enumerate() {+ assert!(j.parent.is_none_or(|p| p < i), "{} comes before its parent", j.name);+ }+ // the rest pose draws every joint where the skeleton has it+ let w = s.fk(&s.rest());+ for (i, j) in s.joints.iter().enumerate() {+ assert!((w.pos[i] - j.head).length() < 1e-5, "{}", j.name);+ }+}++#[test]+fn two_bone_hits_what_the_arm_reaches() {+ let s = mannequin();+ let mut r = rng(7);+ let mut worst = 0.0f32;+ for side in Side::BOTH {+ let arm = s.arm(side).unwrap();+ let shoulder = s.joints[arm[0]].head;+ let full = s.offset(arm[1]).length() + s.offset(arm[2]).length();+ for _ in 0..300 {+ // anywhere in front of the shoulder, from a third of the arm to nearly straight+ let dir = Vec3::new(r() * 2.0 - 1.0, r() * 2.0 - 1.0, r() * 0.9 + 0.1).normalize();+ let target = shoulder + dir * full * (0.33 + 0.65 * r());+ let out = two_bone(&s, &s.rest(), arm, target, ArmOptions::default());+ assert!(!out.out_of_reach);+ worst = worst.max(out.miss);+ }+ }+ assert!(worst < 1e-4, "worst miss {worst} m");+}++#[test]+fn two_bone_says_when_it_cannot_reach_and_changes_nothing_when_there() {+ let s = mannequin();+ let arm = s.arm(Side::L).unwrap();+ let full = s.offset(arm[1]).length() + s.offset(arm[2]).length();+ let far = s.joints[arm[0]].head + Vec3::Z * (full + 0.2);+ let out = two_bone(&s, &s.rest(), arm, far, ArmOptions::default());+ assert!(out.out_of_reach);+ assert!((out.miss - 0.2).abs() < 2e-3, "missed by the distance past: {}", out.miss);+ // the wrist already there: nothing turns+ let here = two_bone(&s, &s.rest(), arm, s.joints[arm[2]].head, ArmOptions::default());+ assert!(here.miss < 1e-5 && here.moved.iter().all(|m| m.1 < 0.05), "{:?}", here.moved);+}++#[test]+fn the_pole_sets_the_elbow_and_the_end_keeps_its_turn() {+ let s = mannequin();+ let arm = s.arm(Side::R).unwrap();+ 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 w = s.fk(&out.pose);+ assert!(out.miss < 1e-4);+ // the elbow is off the shoulder-wrist line on the pole's side+ let line = (w.pos[arm[2]] - w.pos[arm[0]]).normalize();+ let elbow = w.pos[arm[1]] - w.pos[arm[0]];+ let off = elbow - line * elbow.dot(line);+ let want = pole - line * pole.dot(line);+ assert!(off.normalize().dot(want.normalize()) > 0.999, "pole {pole}");+ assert!(w.rot[arm[2]].angle_between(turn) < 1e-3);+ }+}++#[test]+fn a_reach_past_the_arm_leans_the_trunk_and_says_so() {+ let s = mannequin();+ let arm = s.arm(Side::R).unwrap();+ let full = s.offset(arm[1]).length() + s.offset(arm[2]).length();+ let target = s.joints[arm[0]].head + Vec3::new(-0.1, -0.1, 1.0).normalize() * (full + 0.12);+ let out = reach(&s, &s.rest(), Side::R, target, ArmOptions::default()).unwrap();+ assert!(out.miss < 5e-3, "12 cm past the arm, missed by {}", out.miss);+ let chest = s.joint("spine_03").unwrap();+ assert!(out.moved.iter().any(|m| m.0 == chest && m.1 > 1.0), "the chest leant: {:?}", out.moved);+}++#[test]+fn forearm_twist_leaves_the_hand_where_it_was() {+ let s = mannequin();+ let [_, fore, hand] = s.arm(Side::L).unwrap();+ let mut p = s.rest();+ let axis = s.offset(hand).normalize();+ // a twist about the forearm's bone, on a bend that has none of its own+ p.turns[hand] = Quat::from_axis_angle(axis, 0.9) * Quat::from_axis_angle(axis.any_orthonormal_vector(), 0.2);+ let before = s.fk(&p);+ let out = forearm_twist(&s, &p, Side::L, 1.0);+ let after = s.fk(&out);+ assert!((before.pos[hand] - after.pos[hand]).length() < 1e-5);+ assert!(before.rot[hand].angle_between(after.rot[hand]) < 1e-3);+ // the wrist's own twist is gone, and the forearm has it+ assert!(arm::twist_about(out.turns[hand], axis).angle_between(Quat::IDENTITY) < 1e-3);+ assert!((out.turns[fore].angle_between(Quat::IDENTITY) - 0.9).abs() < 0.05);+}++#[test]+fn casts_meet_every_solid() {+ for solid in [+ Solid::Ball { r: 0.1 },+ Solid::Box { half: Vec3::new(0.2, 0.1, 0.15) },+ Solid::Capsule { half: 0.2, r: 0.05 },+ Solid::Cylinder { half: 0.06, r: 0.04 },+ ] {+ let thing = Thing { solid, at: Vec3::new(0.3, 1.0, 0.5), turn: Quat::from_rotation_z(0.4) };+ let mut r = rng(3);+ for _ in 0..50 {+ let dir = Vec3::new(r() - 0.5, r() - 0.5, r() - 0.5).normalize();+ let hit = thing.cast(thing.at + dir, -dir, 2.0).expect("a ray at the centre meets it");+ assert!(thing.distance(hit.at).abs() < 2e-4);+ // the surface faces back along the ray, more or less+ assert!(hit.normal.dot(dir) > 0.0);+ }+ }+}++#[test]+fn a_box_gets_two_hands_and_a_cup_one() {+ let holder = Vec3::new(0.0, 1.0, 0.0);+ let crate_ = Thing::new(Solid::Box { half: Vec3::new(0.18, 0.12, 0.14) }, Vec3::new(0.0, 1.0, 0.45));+ let Grip::Two(l, r) = find_holds(&crate_, holder, HoldOptions::default()) else { panic!("a box wider than a hand takes two") };+ // each on its own side's face, facing out+ assert!((l.at - Vec3::new(0.18, 0.0, 0.0)).length() < 1e-3 && l.normal.dot(Vec3::X) > 0.99);+ assert!((r.at - Vec3::new(-0.18, 0.0, 0.0)).length() < 1e-3 && r.normal.dot(Vec3::NEG_X) > 0.99);+ let cup = Thing::new(Solid::Cylinder { half: 0.05, r: 0.04 }, Vec3::new(-0.15, 1.0, 0.4));+ let Grip::One(h) = find_holds(&cup, holder, HoldOptions::default()) else { panic!("a cup takes one hand") };+ assert_eq!(h.side, Side::R);+ // turned, a thing's holds turn with it: found from wherever the holder stands+ let turned = Thing { turn: Quat::from_rotation_y(0.7), ..crate_ };+ for h in find_holds(&turned, holder, HoldOptions::default()).holds() {+ assert!(turned.distance(turned.world(h.at)).abs() < 2e-4);+ }+}++#[test]+fn the_palm_lies_on_its_hold() {+ let s = mannequin();+ let thing = Thing::new(Solid::Box { half: Vec3::new(0.18, 0.12, 0.14) }, Vec3::new(0.0, 1.1, 0.4));+ for hold in find_holds(&thing, Vec3::new(0.0, 1.0, 0.0), HoldOptions::default()).holds() {+ let (wrist, turn) = wrist_for(&s, &thing, &hold, Vec3::Z).unwrap();+ let rest = hand_rest(&s, hold.side).unwrap();+ // the palm's skin is on the surface, facing into it, fingers forward+ assert!((wrist + turn * rest.mid - thing.world(hold.at)).length() < 1e-4);+ assert!((turn * rest.palm).dot(thing.turn * hold.normal) < -0.999);+ assert!((turn * rest.along).dot(Vec3::Z) > 0.99);+ }+}++fn stand(s: &Skeleton) -> impl Fn(f32) -> Pose + '_ {+ |_| s.rest()+}++#[test]+fn a_box_is_taken_carried_and_thrown() {+ 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 grip = find_holds(&thing, s.rest().root, HoldOptions::default());+ let mut take = Take::new(thing, grip, 0.5);+ take.release = Some(Release::Throw { at: 2.5, velocity: Vec3::new(0.0, 2.0, 3.0), floor: 0.0 });+ let base = stand(&s);++ // before: nothing is touched+ let f = perform(&s, &base, &take, 0.2);+ assert_eq!(f.phase, Phase::Before);+ assert_eq!(f.pose, s.rest());+ assert_eq!(f.thing, thing);++ // from the grab to the release both palms stay on their holds+ let mut t = take.grab;+ while t < 2.5 {+ let f = perform(&s, &base, &take, t);+ assert!(f.miss < 5e-3, "t {t}: a wrist {} m off its hold", f.miss);+ for hold in grip.holds() {+ let rest = hand_rest(&s, hold.side).unwrap();+ let w = s.fk(&f.pose);+ let hand = s.arm(hold.side).unwrap()[2];+ let palm = w.pos[hand] + w.rot[hand] * rest.mid;+ assert!((palm - f.thing.world(hold.at)).length() < 6e-3, "t {t}: palm off the hold");+ }+ t += 1.0 / 30.0;+ }+ // carried: in front of the chest, level, and the fingers are on it and not in it+ let f = perform(&s, &base, &take, 2.0);+ assert_eq!(f.phase, Phase::Carry);+ assert!(f.thing.turn.angle_between(thing.turn) < 1e-3);+ for touch in f.touch {+ let touch = touch.unwrap();+ assert!(touch.on.iter().filter(|on| **on).count() >= 3, "{touch:?}");+ assert!(touch.inside < 0.012, "{touch:?}");+ }+ // thrown: it flies forward, lands on the floor, and the body is back to its own motion+ let f = perform(&s, &base, &take, 2.7);+ assert!(f.thing.at.z > perform(&s, &base, &take, 2.5).thing.at.z + 0.4);+ let f = perform(&s, &base, &take, 6.0);+ assert_eq!(f.phase, Phase::After);+ assert!((f.thing.at.y - f.thing.solid.bound()).abs() < 1e-3);+ assert_eq!(f.pose, s.rest());+}++#[test]+fn a_cup_is_put_down_somewhere_else_upright_while_the_body_turns() {+ let s = mannequin();+ let cup = Thing::new(Solid::Cylinder { half: 0.05, r: 0.035 }, Vec3::new(-0.2, 1.0, 0.38));+ let grip = find_holds(&cup, s.rest().root, HoldOptions::default());+ let mut take = Take::new(cup, grip, 0.0);+ let place = Vec3::new(0.25, 1.0, 0.36);+ take.release = Some(Release::Put { at: 2.0, down: 2.6, place });+ // the body turns a quarter to its left between 1 s and 2 s, and back+ let base = |t: f32| {+ let mut p = s.rest();+ let u = ((t - 1.0).clamp(0.0, 1.0) * std::f32::consts::PI).sin();+ p.turns[0] = Quat::from_rotation_y(0.6 * u);+ p+ };+ let mut t = 0.0;+ while t < 3.5 {+ let f = perform(&s, &base, &take, t);+ // upright the whole way+ assert!((f.thing.turn * Vec3::Y).dot(Vec3::Y) > 0.9999, "t {t}: the cup tilts");+ t += 1.0 / 30.0;+ }+ let f = perform(&s, &base, &take, 3.4);+ assert_eq!(f.phase, Phase::After);+ assert!((f.thing.at - place).length() < 1e-4);+ assert!(f.moved < 0.01, "the hand is back: {}", f.moved);+}++#[test]+fn any_frame_can_be_asked_for() {+ let s = mannequin();+ let thing = Thing::new(Solid::Ball { r: 0.12 }, Vec3::new(0.05, 1.1, 0.4));+ let take = Take::new(thing, find_holds(&thing, s.rest().root, HoldOptions::default()), 0.0);+ let base = stand(&s);+ // asked in any order, a frame is the same frame+ let a = perform(&s, &base, &take, 0.9);+ let _ = perform(&s, &base, &take, 0.1);+ let b = perform(&s, &base, &take, 0.9);+ assert_eq!(a.pose, b.pose);+ assert_eq!(a.thing, b.thing);+ // and no joint jumps between frames, a 60th of a second apart: the body's, and the fingers as they shut+ let (mut last, mut body, mut fingers, mut t) = (perform(&s, &base, &take, 0.0).pose, 0.0f32, 0.0f32, 0.0);+ let hands = s.joint("thumb_01_l").unwrap();+ while t < 1.6 {+ t += 1.0 / 60.0;+ let now = perform(&s, &base, &take, t).pose;+ for (i, (a, b)) in now.turns.iter().zip(&last.turns).enumerate() {+ let d = a.angle_between(*b).to_degrees();+ if i < hands { body = body.max(d) } else { fingers = fingers.max(d) }+ }+ last = now;+ }+ assert!(body < 6.0, "a joint of the body turned {body} degrees in one frame");+ assert!(fingers < 20.0, "a finger joint turned {fingers} degrees in one frame");+}diff --git a/tools/layers.toml b/tools/layers.tomlindex 52147c28..fc93f76d 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -100,6 +100,7 @@ raea-sys-page-net = "systems"raea-sys-page-ops = "systems"raea-sys-frame = "systems"raea-sys-hold = "systems"+raea-sys-grab = "systems"raea-sys-splat = "systems"raea-sys-sprite = "systems"raea-sys-rt = "systems"