HG5: a character in a scene takes a thing. raea/character's take(skel, base, spec, t) makes the native call character.take (runtime/calls), which is systems/grab's take_json: the pose for <Character> and the thing's place each frame, with how far a wrist missed and how far the body was turned from its own motion. Asked as JSON it is the same frame as asked in Rust (a test; 13 pass). Rendered on a psx person: a box taken off a table with both hands and thrown, a cup moved across the table in one hand, upright, the fingers round it; 420 frames, no errors. Not fixed here: hands pass through the table (HG6), and the box's carry place wants tuning by eye

This commit is contained in:
shinyobjectz committed 2026-11-14 21:25:26 -08:00
1 parent e4add11c80
commit 986fae3c62
12 files changed
+244 -8

No files matched your search

Generated
+1
View File
@@ -14995,6 +14995,7 @@ dependencies = [
"raea-native",
"raea-runtime-plugins",
"raea-sys-fonts",
"raea-sys-grab",
"raea-sys-mix",
"raea-sys-ml",
"raea-sys-speech",
+16 -7
View File
@@ -110,18 +110,27 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri
| 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
@done
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.
# 11-14, built: raea/character's `take(skel, base, spec, t)` (sdk/character/src/take.ts) makes the native call
# character.take (runtime/calls), which is systems/grab's `take_json`; the answer is the pose for <Character>
# and the thing's place. Asked as JSON it is the same frame as asked in Rust (a test). Rendered on turbo, a
# psx person (~/Studio/internal/projects/psx/raea/take.tsx, out/take.mp4): a box taken off a table with both
# hands and thrown, and a cup moved across the table in one hand, upright, the fingers round it; 420 frames,
# no errors. Seen in those frames and not fixed here: the standing hands rest inside the table's edge and a
# hand passes through the table's top as it leaves the cup (HG6); the box is carried at arm's length, hardly
# lifted (the carry place wants tuning by eye). Shane hasn't watched it.
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
Then the engine works out each frame's pose and the thing's place, 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
And the plan:
| crate | file | lines | job |
| raea-sys-grab | src/json.rs | 120 | a frame of a take asked for as JSON |
| sdk | sdk/character/src/take.ts | 80 | take(): the call made, typed |
Rule: Next, in order
@needs:HG5
Scenario: HG6. The rig's real limits and the body's real shape
+1
View File
@@ -19,6 +19,7 @@ raea-core-scene = { path = "../../core/scene" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
raea-io-net = { path = "../../io/net" }
raea-sys-mix = { path = "../../systems/mix" }
raea-sys-grab = { path = "../../systems/grab" }
raea-sys-fonts = { path = "../../systems/fonts" }
raea-sys-ml = { path = "../../systems/ml", optional = true }
raea-sys-speech = { path = "../../systems/speech", optional = true }
+3
View File
@@ -173,6 +173,8 @@ pub fn call(name: &str, v: &Value) -> R<Value> {
n if n.starts_with("ecs.") => ecs::call(n, v),
// placement by relations (raea-core-place)
"place.solve" => raea_core_place::solve_json(v),
// a frame of a character taking a thing (raea-sys-grab, docs/hands.feature HG5)
"character.take" => raea_sys_grab::take_json(v),
"fonts.families" => Ok(families().into()),
"fonts.google" => {
let family = s(v, "family")?;
@@ -221,6 +223,7 @@ pub fn register() {
("section.op", "{ fn: \"make\" | \"circle\" | \"square\" | \"hull_points\" | \"union\" | \"minus\" | \"intersect\" | \"hull\" | \"minkowski\" | \"offset\" | \"simplify\" | \"translate\" | \"rotate\" | \"scale\" | \"mirror\" | \"decompose\"; polygons?: [number, number][][]; others?: [number, number][][][]; args?: number[] }", &format!("{SECTION} | {SECTION}[]"), "a 2D cross-section made, combined, offset or moved (Manifold's CrossSection), held by value"),
("solid.free", "{ id: number }", "null", "drop a solid"),
("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)"),
("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"),
+1
View File
@@ -22,6 +22,7 @@
"./things": "./src/things.ts",
"./character": "./src/character.tsx",
"./ragdoll": "./src/ragdoll.ts",
"./take": "./src/take.ts",
"./plugin": "./src/plugin.ts"
},
"peerDependencies": { "react": "19.2.0" },
+3
View File
@@ -17,3 +17,6 @@ export { I, handRest, B, SIDES, BODY_JOINTS, FINGER_JOINTS, sideOf, mirrorName,
export type { Quat, Joint, Skeleton, Pose, Posed, Side, Finger, HandShape, Closing, FingerSegment, SurfacePoint, HandGoal, FootGoal, SeatGoal, Goals, Placement, CharacterProps, CharacterGhost, FaceUnit, FacePreset, Face, HairLook } from "./character/all";
// a character takes a thing with its hands, with no capture of the action (docs/hands.feature)
export { take } from "./take";
export type { TakeThing, TakeSpec, Taken } from "./take";
+71
View File
@@ -0,0 +1,71 @@
// @raea/character/take: a character takes a thing with its hands, with no capture of the action (docs/hands.feature):
// it reaches, grabs with one hand or two, lifts, carries, and puts the thing down or throws it. The engine works each
// frame out (raea-sys-grab, the native call character.take); this asks it and hands back the pose to give
// <Character> and where to draw the thing.
//
// const box = { box: [0.16, 0.1, 0.12], at: [0, 1.05, 0.42] } as const; // half sizes, metres, the body's frame
// const now = take(kid, () => rest(kid), { thing: box, start: 0.5, throw: { at: 2.5, velocity: [0, 2, 3] } }, frame / fps);
// <Character body="kid" pose={now.pose} />
// <Mesh3d transform={Transform.fromXyz(...now.thing.at).withRotation(now.thing.turn)}>...</Mesh3d>
//
// `base` is the body's own motion, its pose at any time (a clip, a walk, a stand): the take only moves what the hands
// need and says how much (`moved`, degrees) and how far a wrist ended from its hold (`miss`, metres). A thing out of
// reach is missed and said so; walk the body to it first. Frame-pure: any frame can be asked for.
import { native } from "@raea/app/native";
import type { Pose, Quat, Skeleton } from "./character/core";
type Vec3 = [number, number, number];
/** A thing to take: one shape (a ball's radius; a box's half sizes; a capsule's or a cylinder's half length along its
* own y, then radius), where its centre is and how it is turned, in the frame the body is posed in. */
export interface TakeThing {
ball?: number;
box?: Vec3;
capsule?: [number, number];
cylinder?: [number, number];
at: Vec3;
turn?: Quat;
}
export interface TakeSpec {
thing: TakeThing;
/** when the hands leave the body's own motion, seconds */
start: number;
/** when they close on the thing (0.6 s after start) and when it has reached the carry (0.5 s after that) */
grab?: number;
carried?: number;
/** where the thing rides, from the chest: x to the body's left, y up, z the way it faces */
carry?: Vec3;
/** the hand that takes a thing small enough for one (the right) */
hand?: "L" | "R";
/** how far below the thing's middle the hands go, metres */
lower?: number;
/** set down: moved to `place` from `at`, standing there from `down` */
put?: { at: number; down: number; place: Vec3 };
/** let go at `at` with a velocity, metres a second; it falls to `floor` (0) */
throw?: { at: number; velocity: Vec3; floor?: number };
}
export interface Taken {
pose: Pose;
thing: { at: Vec3; turn: Quat };
phase: "Before" | "Reach" | "Lift" | "Carry" | "Release" | "After";
hands: 1 | 2;
/** the worst a wrist ended from where its hold asks, metres */
miss: number;
/** the most any joint was turned from the body's own motion, degrees */
moved: number;
}
/** The body and the thing at `t` seconds of a take. */
export function take(skel: Skeleton, base: (t: number) => Pose, spec: TakeSpec, t: number): Taken {
const grab = spec.grab ?? spec.start + 0.6;
// the moments the take reads the body's own motion at: now, the start, the grab, the release
const times = [t, spec.start, grab, spec.put?.at, spec.put?.down, spec.throw?.at].filter((x): x is number => x !== undefined);
const poses = [...new Set(times)].map((at) => {
const p = base(at);
return { t: at, root: p.root, turns: skel.joints.map((_, i) => p.turns[i] ?? ([0, 0, 0, 1] as Quat)) };
});
const joints = skel.joints.map((j) => ({ name: j.name, parent: j.parent, head: j.head, tail: j.tail }));
return native("character.take", { ...spec, joints, t, base: poses });
}
+2
View File
@@ -36,6 +36,8 @@ export interface NativeCalls {
"canvas.read": { args: { width: number; height: number; __canvas2d: unknown; x: number; y: number; w: number; h: number }; answer: { data: string } };
/** an svg <text>'s getComputedTextLength and getStartPositionOfChar: its words laid out by usvg, as the page draws an svg, in its computed font (font-*, letter-spacing, word-spacing); x from the text's own (docs/layout-reads.feature LR7) */
"canvas.svgText": { args: { text: string; style: Record<string, string> }; answer: { length: number; starts: 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; 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 } };
/** raea's command line (render, play, guide, bundle, types; the media verbs: raea media, raea ffmpeg), run in process in cwd */
"cli.raea": { args: { args: string[]; cwd: string }; answer: { exit: number; stdout: string; stderr: string } };
/** a headless run ends with this exit code */
+103
View File
@@ -0,0 +1,103 @@
//! A frame of a take asked for as JSON: the engine's native call `character.take`, which raea/character's `take`
//! makes each frame. The body's own motion comes as its poses at the times the take reads it (the frame's, the
//! grab's, the release's); the answer is the pose to draw and where the thing is.
use glam::{Quat, Vec3};
use serde_json::{Value, json};
use crate::hand::{Grip, HoldOptions, find_holds};
use crate::rig::{Pose, Side, Skeleton};
use crate::shape::{Solid, Thing};
use crate::take::{Release, Take, perform};
pub const TAKE_ARGS: &str = "{ 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; put?: { at: number; down: number; place: [number, number, number] }; throw?: { at: number; velocity: [number, number, number]; floor?: number } }";
pub const TAKE_ANSWER: &str = "{ 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 }";
fn num(v: &Value, what: &str) -> Result<f32, String> {
v.as_f64().map(|n| n as f32).ok_or_else(|| format!("character.take: {what} isn't a number"))
}
fn vec3(v: &Value, what: &str) -> Result<Vec3, String> {
let a = v.as_array().filter(|a| a.len() == 3).ok_or_else(|| format!("character.take: {what} isn't [x, y, z]"))?;
Ok(Vec3::new(num(&a[0], what)?, num(&a[1], what)?, num(&a[2], what)?))
}
fn quat(v: &Value, what: &str) -> Result<Quat, String> {
let a = v.as_array().filter(|a| a.len() == 4).ok_or_else(|| format!("character.take: {what} isn't [x, y, z, w]"))?;
Ok(Quat::from_xyzw(num(&a[0], what)?, num(&a[1], what)?, num(&a[2], what)?, num(&a[3], what)?).normalize())
}
fn solid(v: &Value) -> Result<Solid, String> {
if !v["ball"].is_null() {
return Ok(Solid::Ball { r: num(&v["ball"], "thing.ball")? });
}
if !v["box"].is_null() {
return Ok(Solid::Box { half: vec3(&v["box"], "thing.box")? });
}
// a capsule or a cylinder: half its length along its own y, then its radius
let rod = ["capsule", "cylinder"].into_iter().find(|k| !v[*k].is_null()).ok_or("character.take: the thing needs a shape: ball, box, capsule or cylinder")?;
let a = v[rod].as_array().filter(|a| a.len() == 2).ok_or_else(|| format!("character.take: thing.{rod} isn't [half its length, radius]"))?;
let (half, r) = (num(&a[0], rod)?, num(&a[1], rod)?);
Ok(if rod == "capsule" { Solid::Capsule { half, r } } else { Solid::Cylinder { half, r } })
}
pub fn take_json(v: &Value) -> Result<Value, String> {
let skel = Skeleton::from_value(v)?;
let mut base: Vec<(f32, Pose)> = Vec::new();
for b in v["base"].as_array().ok_or("character.take: no base poses")? {
let turns = b["turns"].as_array().ok_or("character.take: a base pose has no turns")?;
let mut pose = skel.rest();
pose.root = vec3(&b["root"], "a base pose's root")?;
for (slot, turn) in pose.turns.iter_mut().zip(turns) {
*slot = quat(turn, "a base pose's turn")?;
}
base.push((num(&b["t"], "a base pose's t")?, pose));
}
if base.is_empty() {
return Err("character.take: no base poses".into());
}
// the body's own motion at a time: the pose given nearest it
let own = |t: f32| base.iter().min_by(|a, b| (a.0 - t).abs().total_cmp(&(b.0 - t).abs())).map(|b| b.1.clone()).unwrap_or_else(|| skel.rest());
let shape = &v["thing"];
let turn = if shape["turn"].is_null() { Quat::IDENTITY } else { quat(&shape["turn"], "thing.turn")? };
let thing = Thing { solid: solid(shape)?, at: vec3(&shape["at"], "thing.at")?, turn };
let start = num(&v["start"], "start")?;
let mut options = HoldOptions::default();
if v["hand"] == "L" {
options.hand = Side::L;
}
if !v["lower"].is_null() {
options.lower = num(&v["lower"], "lower")?;
}
// the holds are found from where the body stands when it starts to reach
let grip = find_holds(&thing, own(start).root, options);
let mut take = Take::new(thing, grip, start);
if !v["grab"].is_null() {
take.grab = num(&v["grab"], "grab")?;
take.carried = take.grab + 0.5;
}
if !v["carried"].is_null() {
take.carried = num(&v["carried"], "carried")?;
}
if !v["carry"].is_null() {
take.carry = vec3(&v["carry"], "carry")?;
}
if let Some(p) = v.get("put").filter(|p| !p.is_null()) {
take.release = Some(Release::Put { at: num(&p["at"], "put.at")?, down: num(&p["down"], "put.down")?, place: vec3(&p["place"], "put.place")? });
} else if let Some(t) = v.get("throw").filter(|t| !t.is_null()) {
let floor = if t["floor"].is_null() { 0.0 } else { num(&t["floor"], "throw.floor")? };
take.release = Some(Release::Throw { at: num(&t["at"], "throw.at")?, velocity: vec3(&t["velocity"], "throw.velocity")?, floor });
}
let f = perform(&skel, &own, &take, num(&v["t"], "t")?);
let turns: Vec<[f32; 4]> = f.pose.turns.iter().map(|q| q.to_array()).collect();
Ok(json!({
"pose": { "root": f.pose.root.to_array(), "turns": turns },
"thing": { "at": f.thing.at.to_array(), "turn": f.thing.turn.to_array() },
"phase": format!("{:?}", f.phase),
"hands": if matches!(grip, Grip::One(_)) { 1 } else { 2 },
"miss": f.miss,
"moved": f.moved,
}))
}
+3
View File
@@ -7,14 +7,17 @@
//! - `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.
//! - `json`: a take asked for as JSON, the engine's native call `character.take` (raea/character's `take`).
pub mod arm;
pub mod hand;
pub mod json;
pub mod rig;
pub mod shape;
pub mod take;
pub use arm::{ArmOptions, IkReport, forearm_twist, reach, two_bone};
pub use json::{TAKE_ANSWER, TAKE_ARGS, take_json};
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};
+4 -1
View File
@@ -63,7 +63,10 @@ impl Skeleton {
/// 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}"))?;
Self::from_value(&serde_json::from_str(text).map_err(|e| format!("skeleton.json: {e}"))?)
}
pub fn from_value(v: &serde_json::Value) -> Result<Self, String> {
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()?;
+36
View File
@@ -271,3 +271,39 @@ fn any_frame_can_be_asked_for() {
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");
}
#[test]
fn a_take_asked_for_as_json_is_the_same_frame() {
let s = mannequin();
let joints: Vec<serde_json::Value> = s
.joints
.iter()
.map(|j| serde_json::json!({"name": j.name, "parent": j.parent.map_or(-1, |p| p as i64), "head": j.head.to_array(), "tail": j.tail.to_array()}))
.collect();
let rest = s.rest();
let turns: Vec<[f32; 4]> = rest.turns.iter().map(|q| q.to_array()).collect();
let ask = |t: f32| {
take_json(&serde_json::json!({
"joints": joints, "t": t, "start": 0.5,
"base": [{"t": t, "root": rest.root.to_array(), "turns": turns}],
"thing": {"box": [0.16, 0.1, 0.12], "at": [0.0, 1.05, 0.42]},
"throw": {"at": 2.5, "velocity": [0.0, 2.0, 3.0]},
}))
.unwrap()
};
let thing = Thing::new(Solid::Box { half: Vec3::new(0.16, 0.1, 0.12) }, Vec3::new(0.0, 1.05, 0.42));
let mut take = Take::new(thing, find_holds(&thing, rest.root, HoldOptions::default()), 0.5);
take.release = Some(Release::Throw { at: 2.5, velocity: Vec3::new(0.0, 2.0, 3.0), floor: 0.0 });
for t in [0.0, 0.8, 1.4, 2.0, 2.7] {
let (json, direct) = (ask(t), perform(&s, &|_| s.rest(), &take, t));
assert_eq!(json["phase"], format!("{:?}", direct.phase));
assert_eq!(json["hands"], 2);
let at = &json["thing"]["at"];
assert!((Vec3::new(at[0].as_f64().unwrap() as f32, at[1].as_f64().unwrap() as f32, at[2].as_f64().unwrap() as f32) - direct.thing.at).length() < 1e-5);
for (a, b) in json["pose"]["turns"].as_array().unwrap().iter().zip(&direct.pose.turns) {
let q = Quat::from_xyzw(a[0].as_f64().unwrap() as f32, a[1].as_f64().unwrap() as f32, a[2].as_f64().unwrap() as f32, a[3].as_f64().unwrap() as f32);
assert!(q.dot(*b).abs() > 0.999999, "t {t}: {q} against {b}");
}
}
assert!(take_json(&serde_json::json!({"joints": joints, "t": 0, "start": 0, "base": [], "thing": {"at": [0, 0, 0]}})).is_err());
}