Skip to content

armgit / raea

Public Imported from GitHub
0

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.

HG5a: the rest of both sources, in Rust. From Ik-Object-Holding: interact.rs pick (the nearest thing in reach that the eyes see past the scene's solids) and body.rs look (the head turned to the thing, neck and head sharing it), on through a take. From SOMA-X: fit.rs, the analytical pass of its pose inversion on marks (20 random poses recovered from joint heads and bone ends, every joint within 4 mm), and arm.rs twist_joints, its procedural twist-joint evaluator. raea/character's fitPose is the native call character.fit. A wrist stops at 70 degrees and the frame says so; the fingers point the level way the arm comes; the squat takes more from the hips and less from the back. 19 tests. docs/hands.feature says what of SOMA-X is not converted and why

shinyobjectza68b96cf892b
diff --git a/docs/hands.feature b/docs/hands.feature
index 81b82452..cbb5b530 100644
--- a/docs/hands.feature
+++ b/docs/hands.feature
@@ -143,14 +143,14 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri
@done
Scenario: HG7a. A low thing is taken by bending, the feet planted; and the body is told where to stand
# 11-14, built: body.rs `stoop` and `stand_for`. For hands that must go lower than 0.7 of an arm below the
- # shoulders, the hips come down (to 0.5 m) and the trunk bends at the hips and along the spine (to 57
- # degrees), by as much as the hands have got along their reach, so the body rises again as the thing is
+ # shoulders, the hips come down and the trunk bends at the hips and along the spine, by as much as the hands have got along their reach, so the body rises again as the thing is
# lifted. Leg IK keeps both ankles where they stood within 5 mm and the feet's turn. A box on the floor is
# held within 2 cm; the hips come down over 30 cm and are back up with the box carried. `stand_for` gives
# the place a forearm's length off the thing's near face, facing it; standing there both hands reach.
# character.take answers it as `stand`. Seen on turbo: a box lifted from the floor onto a table. Not right
- # yet: the squat folds the head down to the knees, and the body itself keeps out of nothing (the head went
- # into the table that stood 38 cm in front).
+ # yet: the body itself keeps out of nothing (the head went into the table that stood 38 cm in front). The
+ # squat was retuned after the first render folded the head to the knees: the hips take three quarters of it
+ # (to 0.55 m), the trunk bends to 49 degrees, and the head looks at the thing.
Given a thing lower than the arms reach, or out of reach
Then the body bends and squats for a low one with its feet where they stand
And for a far one the take says where to stand and which way to face
@@ -161,6 +161,28 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri
# elbows bend and the lift shows (it was carried at arm's length, hardly lifted).
Then a carried box is held against the belly with the elbows bent
+ @done
+ Scenario: HG5a. The rest of both sources, in Rust
+ # 11-14, built. From Ik-Object-Holding: its Interactor is interact.rs `pick` (the nearest thing in a radius
+ # that the eyes see past the scene's solids; the original takes the first collider found), and its head aim
+ # is body.rs `look` (neck two fifths, head the rest, 55 degrees at most), on through a take: the eyes go to
+ # the thing as the hands do. With HG2 and HG4 that is every script of the original that isn't Unity input or
+ # animator glue. From SOMA-X: fit.rs `fit` is the analytical pass of its pose inversion on marks instead
+ # of mesh vertices (joints refitted parents first, each aligned to what it carries; the root on its own
+ # marks), and arm.rs `twist_joints` is its procedural twist-joint evaluator (shares 0.05, 1/3, 2/3, 0.95;
+ # an upper segment undoing its own joint's twist). 20 random poses, every joint turned up to 50 degrees,
+ # are recovered from joint heads and bone ends with every joint within 4 mm. raea/character's
+ # `fitPose(skel, marks)` is the native call character.fit; on turbo a second body posed only from the
+ # first one's joint positions stands as the first does through a take (fingers aside: positions alone
+ # don't give a bone's twist). A wrist stops at 70 degrees and the frame says so (`limited`); the fingers
+ # point the level way the arm comes, so it is rarely asked for more.
+ # 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.
+ Then a body can choose what to take, look at it, and be posed from positions seen
+
Rule: Next, in order
@needs:HG5
diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rs
index 07e72663..84ba5680 100644
--- a/runtime/calls/src/lib.rs
+++ b/runtime/calls/src/lib.rs
@@ -175,6 +175,7 @@ pub fn call(name: &str, v: &Value) -> R<Value> {
"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),
+ "character.fit" => raea_sys_grab::fit_json(v),
"fonts.families" => Ok(families().into()),
"fonts.google" => {
let family = s(v, "family")?;
@@ -224,6 +225,7 @@ pub fn register() {
("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)"),
+ ("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"),
("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.tsx
index bc0c8621..0f1303a6 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 } from "./take";
-export type { TakeThing, TakeSpec, Taken } from "./take";
+export { take, fitPose } from "./take";
+export type { TakeThing, TakeSpec, Taken, Mark } from "./take";
diff --git a/sdk/character/src/take.ts b/sdk/character/src/take.ts
index 32266419..9af4e255 100644
--- a/sdk/character/src/take.ts
+++ b/sdk/character/src/take.ts
@@ -58,6 +58,8 @@ export interface Taken {
miss: number;
/** the most any joint was turned from the body's own motion, degrees */
moved: number;
+ /** a wrist was held at the most it bends (70 degrees), so its palm isn't square on its hold */
+ limited: boolean;
/** where the body would stand to take the thing, and the turn about the vertical that faces it: walk it there first
* when the thing is out of reach */
stand: { at: Vec3; yaw: number };
@@ -75,3 +77,21 @@ export function take(skel: Skeleton, base: (t: number) => Pose, spec: TakeSpec,
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 });
}
+
+/** A point of the body seen somewhere: on a joint (by name), `offset` from its head in the rest pose's axes (none: the
+ * joint itself), seen at `at`. */
+export interface Mark {
+ joint: string;
+ offset?: Vec3;
+ at: Vec3;
+ weight?: number;
+}
+
+/** A pose fitted to where points of the body were seen, so motion that arrives as positions (a capture, a tracker,
+ * another rig's joints) plays on this body; `miss` is the marks' root-mean-square distance from where they were seen,
+ * metres. It starts from `from` (the rest pose), and a turn the marks say nothing about stays as `from` has it. */
+export function fitPose(skel: Skeleton, marks: Mark[], from?: Pose, passes?: number): { pose: Pose; miss: number } {
+ const joints = skel.joints.map((j) => ({ name: j.name, parent: j.parent, head: j.head, tail: j.tail }));
+ const 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 });
+}
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index d448e146..ebe93100 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -36,8 +36,10 @@ 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 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 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; stand: { at: [number, number, number]; yaw: number } } };
+ "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 */
"cli.raea": { args: { args: string[]; cwd: string }; answer: { exit: number; stdout: string; stderr: string } };
/** a headless run ends with this exit code */
diff --git a/systems/grab/src/arm.rs b/systems/grab/src/arm.rs
index 01e1fcfc..5002ba71 100644
--- a/systems/grab/src/arm.rs
+++ b/systems/grab/src/arm.rs
@@ -166,5 +166,13 @@ pub fn twist_about(q: Quat, axis: Vec3) -> Quat {
}
/// 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.
+/// (SOMA_procedural_transforms.json): for a rig that has twist joints. 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];
+
+/// A segment's four twist joints' turns about its bone `axis`, as SOMA-X's procedural rig evaluates them: `start` is
+/// the twist (radians) of the joint the segment hangs from, `end` the twist of the joint at its far end. A forearm
+/// or shin follows its end joint by rising shares. An upper arm or thigh (`upper`) undoes its own joint's twist
+/// near the shoulder or hip, so the skin there doesn't wring, and follows the next joint toward the elbow or knee.
+pub fn twist_joints(axis: Vec3, start: f32, end: f32, upper: bool) -> [Quat; 4] {
+ TWIST_SHARES.map(|share| Quat::from_axis_angle(axis, if upper { -(1.0 - share) * start + share * end } else { share * end }))
+}
diff --git a/systems/grab/src/body.rs b/systems/grab/src/body.rs
index 2efefcc3..b19bb442 100644
--- a/systems/grab/src/body.rs
+++ b/systems/grab/src/body.rs
@@ -1,4 +1,5 @@
-//! What the rest of the body does for the hands. `stoop`: for a thing lower than the arms reach, the hips come down
+//! What the rest of the body does for the hands. `look`: the head turned to what the hands are after (the original's
+//! head aim), the neck and head sharing it, capped. `stoop`: for a thing lower than the arms reach, the hips come down
//! and the trunk bends forward at the hips and along the spine, with both feet kept where they stand by leg IK, so a
//! thing on the floor is taken by bending and squatting. `clear`: a hand's place moved the least that keeps it out of
//! the scene's solids (a table's top). `stand_for`: where the body should stand to take a thing, for whatever walks
@@ -24,8 +25,8 @@ pub fn stoop(skel: &Skeleton, own: &Pose, w: &Posed, face: Vec3, low: f32, amoun
if short <= 0.0 || amount <= 0.0 {
return own.clone();
}
- // the hips take over half of it by coming down, the trunk the rest by bending
- let (drop, pitch) = ((short * 0.6).min(0.5) * amount, (short * 1.1).min(1.0) * amount);
+ // 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);
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
@@ -78,3 +79,19 @@ pub fn stand_for(thing: &Thing, from: Vec3) -> (Vec3, f32) {
let at = thing.at + to * (edge + 0.3);
(Vec3::new(at.x, from.y, at.z), (-to.x).atan2(-to.z))
}
+
+/// The head turned toward a place by `weight` (0 to 1): the neck takes two fifths of the turn and the head the rest,
+/// no more than 55 degrees in all, so eyes go to what the hands are after.
+pub fn look(skel: &Skeleton, pose: &Pose, at: Vec3, weight: f32) -> Pose {
+ let (Some(neck), Some(head)) = (skel.joint("neck_01"), skel.joint("head")) else { return pose.clone() };
+ let mut out = pose.clone();
+ for (joint, share) in [(neck, 0.4), (head, 1.0)] {
+ let w = skel.fk(&out);
+ let Some(to) = (at - w.pos[head]).try_normalize() else { break };
+ let turn = Quat::from_rotation_arc(w.rot[head] * Vec3::Z, to);
+ let (axis, angle) = turn.to_axis_angle();
+ let angle = angle.min(55f32.to_radians()) * share * weight.clamp(0.0, 1.0);
+ out.turns[joint] = skel.local_for(&w, joint, Quat::from_axis_angle(axis, angle) * w.rot[joint]);
+ }
+ out
+}
diff --git a/systems/grab/src/fit.rs b/systems/grab/src/fit.rs
new file mode 100644
index 00000000..8d72b542
--- /dev/null
+++ b/systems/grab/src/fit.rs
@@ -0,0 +1,102 @@
+//! A pose fitted to points: joint turns recovered from where joints (or marks on the body) were seen, so motion that
+//! arrives as positions (a capture, a tracker, another rig's joints, a model's output) plays on raea's rig. This is
+//! the analytical pass of SOMA-X's pose inversion (NVlabs/SOMA-X, Apache-2.0, soma/fitting/pose_inversion.py), on
+//! marks instead of mesh vertices: joints are refitted parents first, each turned to best align everything it
+//! carries with where that was seen, the root moved onto its own marks, for a few passes. The alignment is
+//! found by turning toward the answer from the turn the joint has (Mueller et al., "A robust method to extract the
+//! rotational part of deformations"), so a joint the marks say nothing about (a twist about a bone) keeps its turn.
+
+use glam::{Mat3, Quat, Vec3};
+
+use crate::rig::{Pose, Skeleton};
+
+/// A point of the body seen somewhere: on `joint`, `offset` from its head in the rest pose's axes, seen at `at`.
+#[derive(Clone, Copy, Debug)]
+pub struct Mark {
+ pub joint: usize,
+ pub offset: Vec3,
+ pub at: Vec3,
+ pub weight: f32,
+}
+
+/// the turn that best carries the vectors `from` onto `to` (weights in `w`): the rotation nearest their covariance
+fn align(pairs: &[(Vec3, Vec3, f32)]) -> Quat {
+ let mut cov = Mat3::ZERO;
+ for &(a, b, w) in pairs {
+ cov += Mat3::from_cols(b * a.x, b * a.y, b * a.z) * w;
+ }
+ let mut q = Quat::IDENTITY;
+ for _ in 0..100 {
+ let r = Mat3::from_quat(q);
+ let omega = (r.x_axis.cross(cov.x_axis) + r.y_axis.cross(cov.y_axis) + r.z_axis.cross(cov.z_axis))
+ / ((r.x_axis.dot(cov.x_axis) + r.y_axis.dot(cov.y_axis) + r.z_axis.dot(cov.z_axis)).abs() + 1e-9);
+ let angle = omega.length();
+ if angle < 1e-7 {
+ break;
+ }
+ q = (Quat::from_axis_angle(omega / angle, angle) * q).normalize();
+ }
+ q
+}
+
+/// The pose that puts the marks where they were seen, starting from `from`, and the marks' root-mean-square miss.
+pub fn fit(skel: &Skeleton, from: &Pose, marks: &[Mark], passes: usize) -> (Pose, f32) {
+ let n = skel.joints.len();
+ // how many joints down from `j` a mark's joint is (0: on it), if `j` carries it
+ let below = |j: usize, mark: usize| {
+ let (mut i, mut depth) = (Some(mark), 0);
+ while let Some(k) = i {
+ if k == j {
+ return Some(depth);
+ }
+ (i, depth) = (skel.joints[k].parent, depth + 1);
+ }
+ None
+ };
+ let seen = |pose: &Pose| -> Vec<Vec3> {
+ let w = skel.fk(pose);
+ marks.iter().map(|m| w.pos[m.joint] + w.rot[m.joint] * m.offset).collect()
+ };
+ let mut pose = from.clone();
+ for _ in 0..passes {
+ // the root is put where its own marks were seen (any marks, when it has none)
+ let now = seen(&pose);
+ let own = |i: &usize| marks[*i].joint == 0;
+ let by: Vec<usize> = if (0..marks.len()).any(|i| own(&i)) { (0..marks.len()).filter(own).collect() } else { (0..marks.len()).collect() };
+ let total: f32 = by.iter().map(|&i| marks[i].weight).sum();
+ if total > 0.0 {
+ pose.root += by.iter().map(|&i| (marks[i].at - now[i]) * marks[i].weight).sum::<Vec3>() / total;
+ }
+ for j in 0..n {
+ let (w, now) = (skel.fk(&pose), seen(&pose));
+ // what a joint's turn alone decides counts in full: marks on it, and where its children's heads are. What
+ // lies further down also depends on the joints between, so it counts little: enough to settle a twist
+ // about a single bone, not enough to bend this joint for a fault further down
+ let pairs: Vec<(Vec3, Vec3, f32)> = (0..marks.len())
+ .filter_map(|i| {
+ let depth = below(j, marks[i].joint)?;
+ let rigid = depth == 0 || (depth == 1 && marks[i].offset.length_squared() < 1e-10);
+ Some((now[i] - w.pos[j], marks[i].at - w.pos[j], marks[i].weight * if rigid { 1.0 } else { 1e-5 }))
+ })
+ .collect();
+ if pairs.iter().all(|p| p.0.length_squared() < 1e-10) {
+ continue;
+ }
+ pose.turns[j] = skel.local_for(&w, j, align(&pairs) * w.rot[j]);
+ }
+ }
+ let now = seen(&pose);
+ let miss = (marks.iter().zip(&now).map(|(m, p)| (m.at - *p).length_squared()).sum::<f32>() / marks.len().max(1) as f32).sqrt();
+ (pose, miss)
+}
+
+/// Marks for every joint's head and bone end, as a pose draws them: what a capture of joint positions gives.
+pub fn marks_of(skel: &Skeleton, seen: &Pose) -> Vec<Mark> {
+ let w = skel.fk(seen);
+ let mut out = Vec::with_capacity(skel.joints.len() * 2);
+ for (i, j) in skel.joints.iter().enumerate() {
+ out.push(Mark { joint: i, offset: Vec3::ZERO, at: w.pos[i], weight: 1.0 });
+ out.push(Mark { joint: i, offset: j.tail - j.head, at: w.pos[i] + w.rot[i] * (j.tail - j.head), weight: 1.0 });
+ }
+ out
+}
diff --git a/systems/grab/src/interact.rs b/systems/grab/src/interact.rs
new file mode 100644
index 00000000..91266607
--- /dev/null
+++ b/systems/grab/src/interact.rs
@@ -0,0 +1,24 @@
+//! Which thing a body takes: musthafa45/Ik-Object-Holding's Interactor (MIT). There, the first collider inside a
+//! radius of the player is taken if a line from the player to it is clear. Here it is the nearest thing inside the
+//! radius that the eyes have a clear line to, past the scene's solids, so a thing behind a wall is not chosen and
+//! the choice doesn't depend on the order things were made in.
+
+use glam::Vec3;
+
+use crate::shape::Thing;
+
+/// The thing to take: the nearest of `things` within `radius` of the body at `from` that `eye` sees past `solids`.
+pub fn pick(things: &[Thing], from: Vec3, eye: Vec3, radius: f32, solids: &[Thing]) -> Option<usize> {
+ let seen = |thing: &Thing| {
+ let to = thing.at - eye;
+ let far = to.length();
+ let Some(dir) = to.try_normalize() else { return true };
+ // clear when no solid's surface comes before the thing's own
+ let met = |solid: &Thing, within: f32| solid.cast(eye, dir, within).map(|h| h.at.distance(eye));
+ let reach = met(thing, far).unwrap_or(far);
+ solids.iter().all(|s| met(s, reach).is_none_or(|d| d >= reach - 1e-3))
+ };
+ (0..things.len())
+ .filter(|&i| (things[i].at - from).length() <= radius + things[i].solid.bound() && seen(&things[i]))
+ .min_by(|&a, &b| (things[a].at - from).length().total_cmp(&(things[b].at - from).length()))
+}
diff --git a/systems/grab/src/json.rs b/systems/grab/src/json.rs
index d46ac0c1..1c2adbda 100644
--- a/systems/grab/src/json.rs
+++ b/systems/grab/src/json.rs
@@ -6,13 +6,14 @@ use glam::{Quat, Vec3};
use serde_json::{Value, json};
use crate::body::stand_for;
+use crate::fit::{Mark, fit};
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; 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 } }";
-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; stand: { at: [number, number, number]; yaw: 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; limited: boolean; stand: { at: [number, number, number]; yaw: 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"))
@@ -107,6 +108,34 @@ pub fn take_json(v: &Value) -> Result<Value, String> {
"hands": if matches!(grip, Grip::One(_)) { 1 } else { 2 },
"miss": f.miss,
"moved": f.moved,
+ "limited": f.limited,
"stand": { "at": stand.to_array(), "yaw": facing },
}))
}
+
+pub const FIT_ARGS: &str = "{ 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 }";
+pub const FIT_ANSWER: &str = "{ pose: { root: [number, number, number]; turns: [number, number, number, number][] }; miss: number }";
+
+/// `character.fit`: a pose fitted to points of the body seen somewhere (fit.rs).
+pub fn fit_json(v: &Value) -> Result<Value, String> {
+ let skel = Skeleton::from_value(v)?;
+ let mut from = skel.rest();
+ if !v["from"].is_null() {
+ from.root = vec3(&v["from"]["root"], "from.root")?;
+ for (slot, turn) in from.turns.iter_mut().zip(v["from"]["turns"].as_array().into_iter().flatten()) {
+ *slot = quat(turn, "from's turn")?;
+ }
+ }
+ let mut marks = Vec::new();
+ for m in v["marks"].as_array().ok_or("character.fit: no marks")? {
+ let name = m["joint"].as_str().ok_or("character.fit: a mark names no joint")?;
+ let joint = skel.joint(name).ok_or_else(|| format!("character.fit: the body has no joint {name}"))?;
+ let offset = if m["offset"].is_null() { Vec3::ZERO } else { vec3(&m["offset"], "a mark's offset")? };
+ let weight = if m["weight"].is_null() { 1.0 } else { num(&m["weight"], "a mark's weight")? };
+ marks.push(Mark { joint, offset, at: vec3(&m["at"], "a mark's at")?, weight });
+ }
+ let passes = v["passes"].as_u64().unwrap_or(8) as usize;
+ let (pose, miss) = fit(&skel, &from, &marks, passes);
+ let turns: Vec<[f32; 4]> = pose.turns.iter().map(|q| q.to_array()).collect();
+ Ok(json!({ "pose": { "root": pose.root.to_array(), "turns": turns }, "miss": miss }))
+}
diff --git a/systems/grab/src/lib.rs b/systems/grab/src/lib.rs
index c6235970..016d4f07 100644
--- a/systems/grab/src/lib.rs
+++ b/systems/grab/src/lib.rs
@@ -8,20 +8,26 @@
//! - `hand`: hold points found on the thing, the wrist that lays a palm on one, fingers curled onto the surface.
//! - `body`: the body bent and squatted for a low thing with its feet planted, hands kept out of the scene's solids,
//! 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.
//! - `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 body;
+pub mod fit;
pub mod hand;
+pub mod interact;
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 body::{clear, stand_for, stoop};
+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 fit::{Mark, fit, marks_of};
+pub use interact::pick;
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};
diff --git a/systems/grab/src/take.rs b/systems/grab/src/take.rs
index 5a7781f7..bca77437 100644
--- a/systems/grab/src/take.rs
+++ b/systems/grab/src/take.rs
@@ -9,7 +9,7 @@
use glam::{Quat, Vec3};
use crate::arm::{ArmOptions, forearm_twist, reach};
-use crate::body::{clear, stoop};
+use crate::body::{clear, look, stoop};
use crate::hand::{Grip, Touch, curl, facing, hand_rest, wrist_for};
use crate::rig::{Pose, Posed, Skeleton};
use crate::shape::Thing;
@@ -58,6 +58,8 @@ pub struct Frame {
/// the most any joint was turned from the body's own motion, degrees
pub 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
+ pub limited: bool,
}
const GRAVITY: f32 = 9.81;
@@ -65,6 +67,8 @@ const GRAVITY: f32 = 9.81;
const AWAY: f32 = 0.4;
/// how long the fingers take to shut, ending at the grab, seconds
const SHUT: f32 = 0.25;
+/// the most a wrist bends, radians
+const WRIST: f32 = 1.22;
fn smooth(u: f32) -> f32 {
let u = u.clamp(0.0, 1.0);
@@ -147,7 +151,7 @@ impl Take {
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] };
+ let mut frame = Frame { pose: own.clone(), thing, phase, miss: 0.0, moved: 0.0, touch: [None, None], limited: false };
// how much the hands are the take's and not the body's own: none before, all from the start, none again once away
let gone = take.let_go();
let away = gone.map_or(0.0, |g| smooth(span(t, g, g + AWAY)));
@@ -163,7 +167,18 @@ pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32)
let face = yaw(&w0) * Vec3::Z;
// in: how far along the reach; the hands are fully on the thing from the grab until they let go
let into = smooth(span(t, take.start, take.grab));
- let holds: Vec<_> = take.grip.holds().filter_map(|h| Some((h, wrist_for(skel, &held, &h, facing(&held, w0.pos[0]).lerp(face, 0.5).normalize_or(face))?))).collect();
+ // the fingers point the level way the arm comes: from the shoulder to the hold, with some of the body's facing, so the
+ // wrist is asked for as little bend as the hold allows
+ let holds: Vec<_> = take
+ .grip
+ .holds()
+ .filter_map(|h| {
+ let shoulder = w0.pos[skel.arm(h.side)?[0]];
+ let from = held.world(h.at) - shoulder;
+ let along = Vec3::new(from.x, 0.0, from.z).normalize_or(face).lerp(facing(&held, w0.pos[0]), 0.4).normalize_or(face);
+ Some((h, wrist_for(skel, &held, &h, along)?))
+ })
+ .collect();
// a thing lower than the arms reach: the body bends and squats for it, as far as the hands have got
let 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));
@@ -180,6 +195,12 @@ pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32)
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);
+ // 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;
+ }
if t >= take.grab && away <= 0.0 {
frame.miss = frame.miss.max((skel.fk(&pose).pos[arm[2]] - at).length());
}
@@ -189,6 +210,9 @@ pub fn perform(skel: &Skeleton, base: &dyn Fn(f32) -> Pose, take: &Take, t: f32)
frame.touch[hold.side as usize] = curl(skel, &mut pose.turns, (at, turn), hold.side, &held, close);
}
}
+ // the eyes go to the thing as the hands do, and mostly leave it once it is carried
+ let watching = into * (1.0 - away) * (1.0 - 0.7 * smooth(span(t, take.grab, take.carried)));
+ pose = look(skel, &pose, held.at, watching);
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 it
let w = 1.0 - smooth(span(away, 0.5, 1.0));
diff --git a/systems/grab/tests/grab.rs b/systems/grab/tests/grab.rs
index 14d8fb8b..814f7b1d 100644
--- a/systems/grab/tests/grab.rs
+++ b/systems/grab/tests/grab.rs
@@ -2,6 +2,7 @@
use glam::{Quat, Vec3};
use raea_sys_grab::hand::hand_rest;
+use raea_sys_grab::rig::Posed;
use raea_sys_grab::*;
/// a seeded random in [0, 1) (mulberry32, as sdk/body's tests use)
@@ -377,3 +378,76 @@ fn a_take_asked_for_as_json_is_the_same_frame() {
}
assert!(take_json(&serde_json::json!({"joints": joints, "t": 0, "start": 0, "base": [], "thing": {"at": [0, 0, 0]}})).is_err());
}
+
+#[test]
+fn a_pose_is_recovered_from_where_its_joints_were_seen() {
+ let s = mannequin();
+ let mut r = rng(11);
+ let mut worst = 0.0f32;
+ for _ in 0..20 {
+ // a pose of the body: every joint turned up to 50 degrees, the body moved
+ let mut seen = s.rest();
+ seen.root += Vec3::new(r() - 0.5, r() * 0.2, r() - 0.5);
+ for turn in seen.turns.iter_mut() {
+ *turn = Quat::from_axis_angle(Vec3::new(r() - 0.5, r() - 0.5, r() - 0.5).normalize(), r() * 0.87);
+ }
+ let marks = marks_of(&s, &seen);
+ let (pose, miss) = fit(&s, &s.rest(), &marks, 10);
+ worst = worst.max(miss);
+ // every joint is where it was seen
+ let (a, b) = (s.fk(&pose), s.fk(&seen));
+ for i in 0..s.joints.len() {
+ assert!((a.pos[i] - b.pos[i]).length() < 4e-3, "{} is {} m off", s.joints[i].name, (a.pos[i] - b.pos[i]).length());
+ }
+ }
+ assert!(worst < 2e-3, "root-mean-square miss {worst} m");
+ // marks that are where the pose already has them change nothing
+ let rest = s.rest();
+ let (same, miss) = fit(&s, &rest, &marks_of(&s, &rest), 3);
+ assert!(miss < 1e-5);
+ for (a, b) in same.turns.iter().zip(&rest.turns) {
+ assert!(a.dot(*b).abs() > 0.999999);
+ }
+}
+
+#[test]
+fn the_nearest_thing_in_sight_is_the_one_taken() {
+ let (from, eye) = (Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 1.7, 0.0));
+ let ball = |x: f32, z: f32| Thing::new(Solid::Ball { r: 0.1 }, Vec3::new(x, 1.0, z));
+ let things = [ball(0.0, 1.5), ball(0.3, 0.6), ball(0.0, 5.0)];
+ assert_eq!(pick(&things, from, eye, 2.0, &[]), Some(1));
+ // a wall between the body and the nearer one: the farther is taken; and nothing past the radius
+ let wall = Thing::new(Solid::Box { half: Vec3::new(0.2, 1.5, 0.02) }, Vec3::new(0.35, 1.0, 0.35));
+ assert_eq!(pick(&things, from, eye, 2.0, &[wall]), Some(0));
+ assert_eq!(pick(&things[2..], from, eye, 2.0, &[]), None);
+}
+
+#[test]
+fn the_head_turns_to_the_thing_and_a_wrist_stops_at_its_limit() {
+ let s = mannequin();
+ let head = s.joint("head").unwrap();
+ let at = Vec3::new(0.6, 1.0, 0.5);
+ let turned = look(&s, &s.rest(), at, 1.0);
+ let (w0, w) = (s.fk(&s.rest()), s.fk(&turned));
+ let toward = |w: &Posed| (w.rot[head] * Vec3::Z).dot((at - w.pos[head]).normalize());
+ 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 twist
+ let 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);
+ let upper = twist_joints(Vec3::X, 1.0, 0.0, true);
+ assert!(upper[0].angle_between(Quat::from_rotation_x(-0.95)) < 1e-3);
+}