Files
raea/systems/notice/src/features.rs
shaneandshinyobjectz 036a2ddb5e raea scene faults: a 3D scene's faults judged as a viewer sees them, motion held to what a body does (#272)
* raea scene faults: a 3D scene's faults judged as a viewer would see them, motion held to what a body does, both learning from verdicts and fixes

The scene judge (raea-sys-notice, docs/notice.feature): each lint finding asked of every camera of the shot (in
frame, facing it, not hidden, how many pixels) and scored by a small logistic model over those features and the
words of the parts' names. It learns from verdicts (--real/--fine) and from fixes (a finding gone while its parts
remain); verdicts all one way teach only words, and a held-out check is part of train. 22 verdicts on 18 findings
from 2 projects: 19 right held out, against 16 for the prior. --seed plants faults to measure it; --ask rings the
likeliest on its frame and asks a vision model, given the scene's own words, only whether it's meant. Renders
judge their own frames at the end (runtime/endchecks faults.rs, RAEA_FAULTS_CHECK=0 skips it).

Motion (raea-sys-motionfaults): knees buckling, feet skating, joints past their limits, jolts, fingers bent or
twisted, bones through what the hand holds, and a hand that hasn't closed on it (grip). Lines set from 107 clean
ACCAD takes; 1,039 of 1,051 planted faults caught. --clip reads a clip, --motion a composition's characters with
their hands tested against the scene's triangles; it caught gambit's ladder thumb (68a505a) before its fix and is
silent after. Fixes and looks become verdicts and examples, and a critic (critic.rs) fitted to them by train says
which findings matter; a verdict on a finding's own key at its size outranks it.

The contact lint's touching test made exact-faster (lint/touching.rs, same findings, 30.6 to 8.5 s on a room),
lint_but_clips for a render's end, and core/zfight keeps a fight's patches for where it shows.

* docs/notice.feature: the judge on six gambit interiors it had never seen

41 verdicts from looks at ringed renders (3 real, 38 fine). The judge as it stood called nearly all of them faults;
refitted with each shop left out and then judged, 34 of 41 right. Floats by size and the hidden-seam clip are what it
still misses; three feature changes tried in a replay of the fit and not kept.

* docs/notice.feature: motion checks on gambit's fp labs, and the shin roll they misread

The fp character's shins read 136-165 degrees past their range (twist near 180, its foot taking the roll back);
rendered, nothing shows. Left unverdicted, since a line on limit:calf at that size would hide real broken knees;
next is reading a joint's roll with its child's.

* raea scene faults --motion: a roll its child takes back is no limit

A solve that rolls a shin half a turn and undoes it at the foot read as the shin 136-165 degrees past its range on
every crouching step of gambit's fp character, though nothing shows. Before the limit check, a roll of 15 degrees or
more about a joint's own bone moves to its child when the two are then less past their ranges together (legs.rs
settled; raea-sys-body limits::over). It moves no joint's place; a roll nothing takes back stays. Tested both ways.
Limit findings on the takedown 34 -> 17, the sneak 21 -> 6, the crowd's walkers unchanged.

* raea scene faults train: the judge held out a whole shot at a time

Besides each finding held out, train now fits without each shot and judges it (labels::shots keeps the shot with
each verdict): how it does on a scene it hasn't seen. On the 63 verdicts from 3 projects and 13 shots: 51 right
(the prior 18), where a replay had put it at 50.

* raea scene faults --motion: a roll moves only where it moves nothing else, and a change of checks is no fix

The roll fix (xos) moved a hand's roll onto one finger: that moves the other fingers, and a finger has no limits to
show it, so 77 of the crowd's wrists vanished, and the fix-to-verdict path kept every finding the change hid as a
real fix. Now a roll moves only when the joint's other children sit on its bone's line (a shin's twist joints), to a
child with limits of its own (tested on a hand); and a fix is read only between runs of the same checks
(motionfaults CHECKS, kept in motion.last). The false rows are removed from the critic's examples. Limit findings:
takedown 34 -> 14, sneak 21 -> 6, crowd unchanged, every hand finding kept; two runs each, 0 fixes.

* Fold scene faults' copies into what they copied (the dupes gate: 307/64 groups back to 293/57): one sigmoid in raea-core-ease (splat, notice, motionfaults), solid() in raea-sys-body's JSON readers (grab, motionfaults), the scene's hand stretches onto motionfaults' stretches() and its seeded Rng, one bounds() for least and most, lint_with(clips) in place of lint_but_clips, raea_runtime_bundle::flags for a repeated flag, held_out() for both held-out passes, a fault that stands in one place, the views and their frame numbers in one pass

* flag is the first of flags (raea-runtime-bundle back to 2000 lines, the size gate): one way to read a flag's values

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 16:40:52 -08:00

171 lines
8.3 KiB
Rust

//! A finding as numbers a model can weigh: what kind of fault it is, how large it shows and how often, how large it is
//! in the world, and what the parts are (structural, soft, small), with the words of their names kept apart for the
//! model to learn which ones excuse or condemn (a "map" in the air is hung; a "mug" in the air is a fault).
use bevy::math::Vec3;
use serde_json::Value;
use crate::sight::{Seen, Spot};
/// The features, in the model's order.
pub const NAMES: [&str; N] = ["bias", "seen", "share", "px", "mm", "floats", "sunk", "air", "clips", "zfight", "inside", "tilted", "seated", "structural", "soft", "small", "mounted", "stands"];
/// How many features.
pub const N: usize = 18;
/// Words of a structural surface: a join between two of them is where a room's shell meets itself.
const STRUCTURAL: [&str; 16] = ["wall", "walls", "floor", "ceiling", "carpet", "vinyl", "tile", "slab", "ground", "skirting", "baseboard", "trim", "cove", "plaster", "shell", "roof"];
/// Words of a soft thing: cloth drapes, folds into what it lies on and lifts off it a little.
const SOFT: [&str; 18] = ["cloth", "towel", "sheet", "sheets", "socks", "sock", "sweater", "jeans", "dress", "shirt", "curtain", "blanket", "spread", "pillow", "rug", "mat", "hung", "fabric"];
/// Words of a thing that stands on what's under it: mounted on a wall beside it with a gap below, it was lifted.
const STANDS: [&str; 24] = ["lamp", "phone", "cup", "cups", "mug", "glass", "bottle", "book", "vase", "plant", "pot", "chair", "stool", "table", "clock", "radio", "tv", "box", "can", "soda", "ashtray", "bag", "case", "suitcase"];
/// The words of a part's name: lower case, split at anything not a letter, with words carrying digits (r106) and
/// one-letter ones left out.
pub fn words(name: &str) -> Vec<String> {
let base = name.split(" (its").next().unwrap_or(name);
let mut out: Vec<String> = base.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| w.len() > 1 && !w.chars().any(|c| c.is_ascii_digit())).map(str::to_ascii_lowercase).filter(|w| w != "glb" && w != "gltf").collect();
// and the node it's about, inside a model ("r106_table (its \"table_lam\")")
if let Some(node) = name.split(" (its").nth(1) {
out.extend(words(node.trim_matches(|c: char| !c.is_ascii_alphanumeric())));
}
out.dedup();
out
}
fn any_of(ws: &[String], list: &[&str]) -> bool {
ws.iter().any(|w| list.contains(&w.as_str()))
}
/// A finding read once: its kind, its parts, where it would show, and its size in the world.
#[derive(Clone, Debug)]
pub struct Fault {
pub key: String,
pub check: String,
pub part: String,
pub into: Option<String>,
pub says: String,
pub spots: Vec<Spot>,
/// spots carry square metres (a z-fight), not metres
pub area: bool,
/// the fault's size in the world, metres (a z-fight's: the side of a square of its area)
pub size: f32,
pub small: bool,
}
fn v3(v: &Value) -> Option<Vec3> {
let a = v.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))
}
/// The checks a viewer could see wrong; rests, mounts, the ground and notes of what was skipped aren't faults.
pub const FAULTS: [&str; 8] = ["floats", "sunk", "air", "clips", "zfight", "tilted", "seated", "mounted"];
/// A mounted part this far over what's under it is a candidate (a picture on a wall is one, a lamp lifted against it another).
const LIFTED: f64 = 0.003;
/// A lint finding (raea-sys-contact's own row, `raea scene lint|explain --json`) as a Fault, None if it's no fault.
pub fn fault(v: &Value) -> Option<Fault> {
let check = v["check"].as_str()?.to_string();
let lifted = check == "mounted" && v["gap"].as_f64().is_some_and(|g| g > LIFTED);
if !FAULTS.contains(&check.as_str()) || (v["level"] == "ok" && !lifted) {
return None;
}
let part = v["part"].as_str()?.to_string();
let into = v["into"].as_str().or(v["on"].as_str()).map(String::from);
let into = if check == "mounted" { v["under"].as_str().map(String::from).or(into) } else { into };
let lo = v3(&v["box"]["min"]);
let hi = v3(&v["box"]["max"]);
let small = matches!((lo, hi), (Some(l), Some(h)) if (h - l).max_element() < 0.15);
let gap = v["gap"].as_f64().unwrap_or(0.0) as f32;
let mut spots = Vec::new();
let mut area = false;
let size: f32;
match check.as_str() {
"zfight" => {
area = true;
let a = v["area"].as_f64().unwrap_or(0.0) as f32;
size = a.sqrt();
for s in v["spots"].as_array().into_iter().flatten() {
let r: Vec<f32> = serde_json::from_value(s.clone()).unwrap_or_default();
if r.len() == 7 {
spots.push(Spot { at: Vec3::new(r[0], r[1], r[2]), facing: Some(Vec3::new(r[3], r[4], r[5])), size: r[6] });
}
}
if spots.is_empty()
&& let Some(at) = v3(&v["at"])
{
spots.push(Spot { at, facing: None, size: a });
}
}
"clips" => {
size = v["depth"].as_f64().unwrap_or(0.0) as f32;
for p in v["seam"].as_array().into_iter().flatten().filter_map(v3) {
spots.push(Spot { at: p, facing: None, size });
}
}
_ => {
// a gap under a part shows at its foot all round: the box's bottom edge, drawn in a little (a round foot
// sits inside its box's corners), at the height of the surface it's over
size = if check == "tilted" { 0.0 } else { gap.abs().max(if check == "air" { 0.05 } else { 0.0 }) };
// a mounted part's gap is no fault by its size (a picture hangs a metre over the floor): its spots carry
// nothing, so it shows by whether it's seen and what it is
let shown = if check == "mounted" { 0.0 } else { size };
if let (Some(l), Some(h)) = (lo, hi) {
let y = match (check.as_str(), v3(&v["at"])) {
("floats", Some(at)) => at.y + gap * 0.5,
("sunk" | "seated", Some(at)) => at.y - gap,
_ => l.y + 0.002,
};
let c = (l + h) * 0.5;
let r = (h - l) * 0.5 * 0.85;
for (dx, dz) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)] {
spots.push(Spot { at: Vec3::new(c.x + dx * r.x, y, c.z + dz * r.z), facing: None, size: shown });
}
if check == "air" || check == "tilted" || check == "mounted" {
spots.push(Spot { at: c, facing: None, size: shown });
}
}
if let Some(at) = v3(&v["at"]) {
spots.push(Spot { at, facing: None, size: shown });
}
}
}
let key = format!("{check}:{part}|{}", into.as_deref().unwrap_or(""));
Some(Fault { key, check, part, into, says: v["says"].as_str().unwrap_or("").to_string(), spots, area, size, small })
}
/// The finding's features (NAMES' order) and its words, each keyed by its kind ("air:map").
pub fn features(f: &Fault, s: &Seen) -> (Vec<f32>, Vec<String>) {
let (wp, wi) = (words(&f.part), f.into.as_deref().map(words).unwrap_or_default());
let structural = if f.into.is_some() { any_of(&wp, &STRUCTURAL) && any_of(&wi, &STRUCTURAL) } else { any_of(&wp, &STRUCTURAL) };
let soft = any_of(&wp, &SOFT) || any_of(&wi, &SOFT);
let is = |k: &str| (f.check == k) as u8 as f32;
let inside = (f.check == "zfight" && f.into.is_none()) as u8 as f32;
let x = vec![
1.0,
(s.shown > 0) as u8 as f32,
if s.frames > 0 { s.shown as f32 / s.frames as f32 } else { 0.0 },
(1.0 + s.px).log2(),
(1.0 + f.size * 1000.0).log2(),
is("floats"),
is("sunk"),
is("air"),
is("clips"),
is("zfight") - inside,
inside,
is("tilted"),
is("seated"),
structural as u8 as f32,
soft as u8 as f32,
f.small as u8 as f32,
is("mounted"),
(f.check == "mounted" && any_of(&wp, &STANDS)) as u8 as f32,
];
let mut toks: Vec<String> = wp.iter().map(|w| format!("{}:{w}", f.check)).collect();
toks.extend(wi.iter().map(|w| format!("{}:on:{w}", f.check)));
toks.sort();
toks.dedup();
(x, toks)
}