mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
609a22c9ec | ||
|
|
4c25a4263d | ||
|
|
2835c1478a | ||
|
|
ac9e2f9ba6 | ||
|
|
3cd075ae08 | ||
|
|
0909761d60 | ||
|
|
b589826e7c | ||
|
|
64c1e06ea9 |
No files matched your search
Generated
+113
-36
@@ -8490,6 +8490,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "intel_tex_2"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7980d359170e7da4bc2421aa74c49d338a3153313e006d732a3430f1af375a60"
|
||||
dependencies = [
|
||||
"ispc_rt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "interpolate_name"
|
||||
version = "0.2.4"
|
||||
@@ -8573,6 +8582,16 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "ispc_rt"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a396f76fd253fab9945bb4c6080f515d0c4036bc30219462d199b58886fd37b4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"num_cpus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.10.5"
|
||||
@@ -13986,17 +14005,13 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-body",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-motionfaults",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -14474,6 +14489,7 @@ version = "0.1.0"
|
||||
name = "raea-core-shape"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"manifold-rust",
|
||||
"raea-core-fonts",
|
||||
"raea-core-grow",
|
||||
@@ -14492,6 +14508,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-tables"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-wire"
|
||||
version = "0.1.0"
|
||||
@@ -15033,29 +15058,62 @@ dependencies = [
|
||||
"raea-gpu-device",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-render-plugins",
|
||||
"raea-render-raytrace",
|
||||
"raea-runtime-gpuframe",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-memtally",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-post",
|
||||
"raea-sys-procmat",
|
||||
"raea-sys-screen",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-splat",
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-viewbox",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-render-plugins"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-framepass",
|
||||
"raea-sys-gi",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
"raea-sys-lod",
|
||||
"raea-sys-look",
|
||||
"raea-sys-matchmove",
|
||||
"raea-sys-material",
|
||||
"raea-sys-meshseq",
|
||||
"raea-sys-page",
|
||||
"raea-sys-parity",
|
||||
"raea-sys-phase",
|
||||
"raea-sys-post",
|
||||
@@ -15069,10 +15127,8 @@ dependencies = [
|
||||
"raea-sys-sprite",
|
||||
"raea-sys-text3d",
|
||||
"raea-sys-three-shader",
|
||||
"raea-sys-viewbox",
|
||||
"raea-sys-toon",
|
||||
"raea-sys-volume",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15274,7 +15330,6 @@ name = "raea-runtime-calls"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"manifold-rust",
|
||||
"parley",
|
||||
@@ -15285,6 +15340,7 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-native",
|
||||
"raea-runtime-ecs",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-wear",
|
||||
"raea-sys-fonts",
|
||||
@@ -15359,6 +15415,14 @@ dependencies = [
|
||||
"vello",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-ecs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-edit"
|
||||
version = "0.1.0"
|
||||
@@ -15400,7 +15464,6 @@ dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-runtime-lod-plan",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-notice",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -15520,6 +15583,17 @@ dependencies = [
|
||||
"rquickjs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-kinds"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-look",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-live"
|
||||
version = "0.1.0"
|
||||
@@ -15643,6 +15717,7 @@ dependencies = [
|
||||
"raea-core-alloc",
|
||||
"raea-core-animate",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
@@ -15667,6 +15742,7 @@ dependencies = [
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
"xxhash-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15677,6 +15753,7 @@ dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-review",
|
||||
"raea-core-scene",
|
||||
"raea-runtime-kinds",
|
||||
"raea-runtime-look",
|
||||
"raea-runtime-scene2d",
|
||||
"raea-sys-frame",
|
||||
@@ -15715,6 +15792,7 @@ dependencies = [
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-share",
|
||||
"raea-sys-toon",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -16191,6 +16269,7 @@ dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-scene",
|
||||
"raea-core-tables",
|
||||
"raea-io-media",
|
||||
"raea-sys-layers",
|
||||
"raea-sys-shots",
|
||||
@@ -16412,9 +16491,11 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"blake3",
|
||||
"image",
|
||||
"intel_tex_2",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-io-home",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
@@ -16428,6 +16509,13 @@ dependencies = [
|
||||
name = "raea-sys-measure"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-memtally"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-mesh"
|
||||
version = "0.1.0"
|
||||
@@ -16501,27 +16589,6 @@ dependencies = [
|
||||
"mlx-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-motionfaults"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"glam 0.33.12",
|
||||
"raea-core-ease",
|
||||
"raea-sys-body",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-notice"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-page"
|
||||
version = "0.1.0"
|
||||
@@ -16742,7 +16809,6 @@ name = "raea-sys-splat"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-ease",
|
||||
"raea-core-program",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
@@ -16808,6 +16874,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-toon"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-touch"
|
||||
version = "0.1.0"
|
||||
|
||||
+6
-2
@@ -12,6 +12,7 @@ members = [
|
||||
"core/ease",
|
||||
"core/fonts",
|
||||
"core/program",
|
||||
"core/tables",
|
||||
"core/scene",
|
||||
"core/shape",
|
||||
"core/meshcheck",
|
||||
@@ -30,6 +31,7 @@ members = [
|
||||
"systems/phase",
|
||||
"systems/shader/wgsl",
|
||||
"systems/sampler",
|
||||
"systems/memtally",
|
||||
"systems/parity",
|
||||
"systems/shader",
|
||||
"systems/three-shader",
|
||||
@@ -105,8 +107,6 @@ members = [
|
||||
"systems/a11y",
|
||||
"systems/bake",
|
||||
"systems/contact",
|
||||
"systems/notice",
|
||||
"systems/motionfaults",
|
||||
"systems/light-meter",
|
||||
"systems/measure",
|
||||
"systems/canvas",
|
||||
@@ -151,6 +151,7 @@ members = [
|
||||
"systems/look",
|
||||
"systems/compose",
|
||||
"systems/material",
|
||||
"systems/toon",
|
||||
"systems/mesh",
|
||||
"systems/post",
|
||||
"systems/fog",
|
||||
@@ -172,6 +173,7 @@ members = [
|
||||
"tools/perceive",
|
||||
"engine/render",
|
||||
"engine/render/raytrace",
|
||||
"engine/render/plugins",
|
||||
"engine/render/denoise/bench",
|
||||
"engine/seedling",
|
||||
"engine/web",
|
||||
@@ -191,6 +193,7 @@ members = [
|
||||
"runtime/bundle/lib",
|
||||
"engine/shape-web",
|
||||
"runtime/calls",
|
||||
"runtime/ecs",
|
||||
"runtime/shots",
|
||||
"runtime/wear",
|
||||
"runtime/canvas",
|
||||
@@ -205,6 +208,7 @@ members = [
|
||||
"runtime/sound",
|
||||
"runtime/look",
|
||||
"runtime/scene",
|
||||
"runtime/kinds",
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/ask",
|
||||
|
||||
@@ -110,7 +110,7 @@ fn shape(expr: &str, out: &Path, meshes: &mut BTreeMap<String, String>) -> R<Val
|
||||
// a mesh given by its own vertices (a <BufferMesh>, a three.js geometry through raea/r3f): written as it
|
||||
// is, with its normals and texture coordinates, since it needn't be a closed solid
|
||||
Some(b) => {
|
||||
let (t, uv) = raea_core_shape::buffer_tris(b)?;
|
||||
let (t, uv) = raea_core_shape::buffer_tris(&raea_core_shape::buffer_json(b)?)?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &glb, "glb")?;
|
||||
raea_core_shape::export_tris(&t, uv.as_deref(), &obj, "obj")?;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea scene lint|explain|faults|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
description = "raea scene lint|explain|light|stage|lod: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
@@ -12,11 +12,6 @@ raea-runtime-export = { path = "../../runtime/export" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# raea scene faults: whether a viewer would notice each lint finding, and the judge learning from verdicts
|
||||
raea-sys-notice = { path = "../../systems/notice" }
|
||||
# raea scene faults --clip: a character's motion held to what a body does
|
||||
raea-sys-motionfaults = { path = "../../systems/motionfaults" }
|
||||
raea-sys-body = { path = "../../systems/body" }
|
||||
# each part's planned detail beside how large the frames show it (MK21, MK23)
|
||||
raea-runtime-lod-plan = { path = "../../runtime/lod-plan" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
@@ -25,6 +20,4 @@ raea-core-facts = { path = "../../core/facts" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
dunce = "1"
|
||||
# --ask: the fault ringed on its frame for the vision model
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
serde_json = "1"
|
||||
@@ -1,109 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx --composition ID --ask N` (docs/notice.feature NT12): a vision model asked only what
|
||||
//! geometry can't say, whether a likely fault is meant. The judge has already found it, measured it and found the
|
||||
//! frame it shows largest on; that frame is rendered, the fault's spots ringed on it, and `raea ask` (clef-omni) is
|
||||
//! handed the picture with the scene's own words for it: which part, what it's on or in, by how much. Its answer,
|
||||
//! meant or a mistake, is kept as a verdict (`by: "ask"`) when it's SURE or more, and any person's verdict on the same
|
||||
//! finding outranks it.
|
||||
//! The ringed pictures stay in the project's review/faults-ask/ for a person to look at.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_sys_notice::{FAULT, Judged, labels};
|
||||
|
||||
/// Rendered this wide (its height kept to the composition's shape).
|
||||
const WIDE: u32 = 960;
|
||||
/// An answer this sure or more is kept as a verdict; under it, said as unsure and kept out of training. On room
|
||||
/// 106's shot-window (2026-11-27) the model was 0.52-0.65 sure on chair feet pressed into carpet and a leg through a
|
||||
/// strap, and 0.72-0.78 on a sunk kit, a floating hat and a part sunk into a door.
|
||||
const SURE: f64 = 0.7;
|
||||
|
||||
/// One ring around every spot of the fault on the picture, a little out from them, in red.
|
||||
fn ring(png: &Path, marks: &[[f32; 2]]) -> Result<(), String> {
|
||||
let mut img = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();
|
||||
let (w, h) = (img.width() as f32, img.height() as f32);
|
||||
let pts: Vec<(f32, f32)> = marks.iter().map(|m| ((m[0] + 1.0) * 0.5 * w, (1.0 - m[1]) * 0.5 * h)).collect();
|
||||
let (cx, cy) = (pts.iter().map(|p| p.0).sum::<f32>() / pts.len() as f32, pts.iter().map(|p| p.1).sum::<f32>() / pts.len() as f32);
|
||||
let r = pts.iter().map(|p| (p.0 - cx).hypot(p.1 - cy)).fold(0.0f32, f32::max) + 0.03 * w;
|
||||
for y in 0..img.height() {
|
||||
for x in 0..img.width() {
|
||||
let d = (x as f32 - cx).hypot(y as f32 - cy);
|
||||
if (d - r).abs() <= 2.5 {
|
||||
img.put_pixel(x, y, image::Rgb([255, 30, 30]));
|
||||
}
|
||||
}
|
||||
}
|
||||
img.save(png).map_err(|e| format!("{}: {e}", png.display()))
|
||||
}
|
||||
|
||||
fn question(j: &Judged) -> String {
|
||||
let f = &j.fault;
|
||||
let what = match &f.into {
|
||||
Some(into) => format!("{} (against {into})", f.part),
|
||||
None => f.part.clone(),
|
||||
};
|
||||
format!(
|
||||
"This is a frame of a 3D scene. Inside the red ring is {what}. A geometry check measured: {}. Judge only what is inside the ring. Is it meant to be like this (cloth draped over an edge, something hung, feet pressed into soft carpet, something set into a wall), or a mistake a viewer would notice (something floating, sunk into something, passing through something, faces flickering)?",
|
||||
f.says
|
||||
)
|
||||
}
|
||||
|
||||
/// The likeliest `n` faults asked about, their answers kept as verdicts.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(tsx: &Path, shot: &str, judged: &[Judged], frames: &[i64], w: u32, h: u32, n: usize, dry: bool) -> Result<String, String> {
|
||||
let project = labels::project_of(tsx);
|
||||
let dir = project.join("review").join("faults-ask");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let tall = ((WIDE as f32 * h as f32 / w as f32 / 2.0).round() as u32 * 2).max(2);
|
||||
let (mut out, mut rows) = (Vec::new(), Vec::new());
|
||||
for j in judged.iter().filter(|j| j.p >= FAULT && j.seen.best.is_some() && !j.seen.marks.is_empty()).take(n) {
|
||||
let frame = frames[j.seen.best.unwrap()];
|
||||
let name = format!("{shot}-{}", j.fault.key).replace(|c: char| !(c.is_ascii_alphanumeric() || c == '-'), "_");
|
||||
let (png, mp4) = (dir.join(format!("{name}.png")), dir.join(format!("{name}.mp4")));
|
||||
// the frame as the render draws it, its own end checks left out (they'd judge the scene again)
|
||||
let drawn = Command::new(&me)
|
||||
.args(["render", &tsx.to_string_lossy(), "--composition", shot, "--frame", &frame.to_string(), "--w", &WIDE.to_string(), "--h", &tall.to_string(), "-o", &png.to_string_lossy()])
|
||||
.env("RAEA_FAULTS_CHECK", "0")
|
||||
.env("RAEA_CLIP_CHECK", "0")
|
||||
.output()
|
||||
.map_err(|e| format!("raea render: {e}"))?;
|
||||
if !drawn.status.success() {
|
||||
return Err(format!("raea render frame {frame}: {}", String::from_utf8_lossy(&drawn.stderr).lines().last().unwrap_or("")));
|
||||
}
|
||||
ring(&png, &j.seen.marks)?;
|
||||
// raea ask watches a picture move: the still as a second of video
|
||||
let made = Command::new("ffmpeg").args(["-y", "-loglevel", "error", "-loop", "1", "-i", &png.to_string_lossy(), "-t", "1", "-r", "10", "-pix_fmt", "yuv420p", &mp4.to_string_lossy()]).status().map_err(|e| format!("ffmpeg: {e}"))?;
|
||||
if !made.success() {
|
||||
return Err(format!("ffmpeg couldn't make {}", mp4.display()));
|
||||
}
|
||||
let mut cmd = Command::new(&me);
|
||||
cmd.args(["ask", &mp4.to_string_lossy(), &question(j), "--choose", "meant,mistake", "--brief", "none", "--json"]);
|
||||
if dry {
|
||||
cmd.arg("--dry");
|
||||
}
|
||||
let asked = cmd.output().map_err(|e| format!("raea ask: {e}"))?;
|
||||
let text = String::from_utf8_lossy(&asked.stdout);
|
||||
let first: Value = text.lines().find_map(|l| serde_json::from_str::<Value>(l).ok()).unwrap_or(Value::Null);
|
||||
let choice = first["choice"].as_str().or_else(|| first["answer"].as_str()).map(str::to_lowercase);
|
||||
let says = first["says"].as_str().unwrap_or("").to_string();
|
||||
let sure = first["value"].as_f64().unwrap_or(0.0);
|
||||
match choice.as_deref() {
|
||||
Some(c) if (c.contains("mistake") || c.contains("meant")) && sure < SURE => {
|
||||
out.push(format!("{:.2} {} -> unsure ({says}), not kept (frame {frame}, {})", j.p, j.fault.key, png.display()));
|
||||
}
|
||||
Some(c) if c.contains("mistake") || c.contains("meant") => {
|
||||
let real = c.contains("mistake");
|
||||
rows.push(labels::row(&j.fault.key, real, "ask", shot, &j.x, &j.toks));
|
||||
out.push(format!("{:.2} {} -> {}{} (frame {frame}, {})", j.p, j.fault.key, if real { "a mistake" } else { "meant" }, if says.is_empty() { String::new() } else { format!(": {says}") }, png.display()));
|
||||
}
|
||||
_ if dry => out.push(format!("{:.2} {} would be asked on frame {frame} ({})", j.p, j.fault.key, png.display())),
|
||||
_ => out.push(format!("{:.2} {} not answered: {}", j.p, j.fault.key, first["not_asked"].as_str().or(first["problem"].as_str()).unwrap_or(text.lines().next().unwrap_or("")))),
|
||||
}
|
||||
}
|
||||
labels::append(&project, &rows)?;
|
||||
out.push(format!("{} asked, {} answers kept as verdicts (by ask; a person's verdict outranks them) in {}", out.len(), rows.len(), project.join("review").join("faults.labels.jsonl").display()));
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters held to what a body does
|
||||
//! (raea-sys-motionfaults), read from the scene itself, with no clip written out. raea/character's `<Character>` draws
|
||||
//! each joint as a marker part named `<name>-<joint>` (its joint.glb) at the joint's place and turn, and every joint's
|
||||
//! rest frame is the world's, so a joint's turn from rest against its parent is its parent's world turn undone from its
|
||||
//! own: each frame's pose comes back exactly. The skeleton is the body's skeleton.json beside its joint.glb.
|
||||
//!
|
||||
//! And the hands against the scene: each finger bone, the thumb's too, as a segment from its joint toward its tip,
|
||||
//! tested against every other part's real triangles (raea-sys-notice's BVH). A bone that crosses a surface has gone in
|
||||
//! at least a finger's half thickness: a thumb through a grip, fingers through a mug's wall. And the other way: while
|
||||
//! two or more fingertips rest on a surface (the hand holds something), a tip left 3 cm or more off it hasn't closed:
|
||||
//! the thumb not wrapping round a post.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::math::{Quat, Vec3};
|
||||
use raea_core_scene::Item;
|
||||
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton};
|
||||
use raea_sys_motionfaults::{Clip, Fault, Hit, grip, stretches};
|
||||
use serde_json::Value;
|
||||
|
||||
/// A distal bone is tested this far toward its tip (its tip is the skin's end, which rests on what it touches).
|
||||
const ALONG: f32 = 0.85;
|
||||
|
||||
fn name(it: &Item) -> Option<&str> {
|
||||
it.props.get("name").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// The characters on a frame: each one's name and the folder its joint.glb is in.
|
||||
fn characters(its: &[Item]) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for it in its {
|
||||
let (Some(n), Some(src)) = (name(it), it.props.get("src").and_then(Value::as_str)) else { continue };
|
||||
if let (Some(body), true) = (n.strip_suffix("-body"), src.ends_with("/body.glb")) {
|
||||
let folder = src.trim_end_matches("/body.glb").to_string();
|
||||
if !out.iter().any(|o| o.0 == body) {
|
||||
out.push((body.to_string(), folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body's skeleton.json, its folder as the scene names it found from the composition's folder up.
|
||||
fn skeleton(dir: &Path, folder: &str) -> Option<(PathBuf, Skeleton)> {
|
||||
let rel = folder.trim_start_matches('/');
|
||||
for up in dir.ancestors().take(4) {
|
||||
for sub in ["", "media", "assets", "public", "compositions/media"] {
|
||||
let p = up.join(sub).join(rel).join("skeleton.json");
|
||||
if let Ok(t) = std::fs::read_to_string(&p) {
|
||||
return Skeleton::from_json(&t).ok().map(|s| (p, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A part's place and turn (its scale taken out).
|
||||
fn placed(it: &Item) -> (Vec3, Quat) {
|
||||
let (_, r, t) = it.world.to_scale_rotation_translation();
|
||||
(t, r)
|
||||
}
|
||||
|
||||
/// One character's frames as a clip, and each frame's joint places in the scene (for the hands against it).
|
||||
fn clip_of(skel: &Skeleton, who: &str, frames: &[Vec<Item>], fps: f32) -> (Clip, Vec<Vec<Option<(Vec3, Quat)>>>) {
|
||||
let (mut poses, mut places) = (Vec::new(), Vec::new());
|
||||
for its in frames {
|
||||
let at: Vec<Option<(Vec3, Quat)>> = skel.joints.iter().map(|j| its.iter().find(|it| name(it) == Some(&format!("{who}-{}", j.name))).map(placed)).collect();
|
||||
let mut p: Pose = skel.rest();
|
||||
for (i, j) in skel.joints.iter().enumerate() {
|
||||
let Some((pos, rot)) = at[i] else { continue };
|
||||
match j.parent.and_then(|q| at[q]) {
|
||||
Some((_, prot)) => p.turns[i] = (prot.inverse() * rot).normalize(),
|
||||
None if j.parent.is_none() => {
|
||||
p.turns[i] = rot;
|
||||
p.root = pos;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
poses.push(p);
|
||||
places.push(at);
|
||||
}
|
||||
(Clip { skel: skel.clone(), fps, poses, held: None }, places)
|
||||
}
|
||||
|
||||
/// The hands against the scene's other parts, frame by frame: finger bones through a surface (`through`), and tips
|
||||
/// left off what the hand holds (`grip`), as faults over the stretches they last.
|
||||
fn hands(skel: &Skeleton, who: &str, frames: &[Vec<Item>], places: &[Vec<Option<(Vec3, Quat)>>], numbers: &[i64]) -> Vec<Fault> {
|
||||
let mut hits: Vec<Hit> = Vec::new();
|
||||
let bones: Vec<usize> = Side::BOTH.iter().flat_map(|&s| FINGERS.iter().filter_map(move |f| skel.finger(f, s))).flatten().collect();
|
||||
let tips: Vec<Vec<usize>> = Side::BOTH.iter().map(|&s| FINGERS.iter().filter_map(|f| skel.finger(f, s).map(|b| b[2])).collect()).collect();
|
||||
for (k, its) in frames.iter().enumerate() {
|
||||
// the scene but the character itself (its skin is drawn at its bind pose in the parts, its markers are specks)
|
||||
let mine = format!("{who}-");
|
||||
let others: Vec<Item> = its.iter().filter(|it| !name(it).is_some_and(|n| n.starts_with(&mine))).cloned().collect();
|
||||
// every part: a mesh's place is often in its own vertices, its transform the world's origin (gambit's ladder lab),
|
||||
// so nothing can be left out by where its transform sits
|
||||
if bones.iter().all(|&i| places[k][i].is_none()) {
|
||||
continue;
|
||||
}
|
||||
let near: Vec<Item> = others.into_iter().filter(|it| it.kind != "camera").collect();
|
||||
let scene = raea_sys_notice::Scene::of(&near);
|
||||
let bone = |i: usize, along: f32| places[k][i].map(|(a, rot)| (a, a + rot * ((skel.joints[i].tail - skel.joints[i].head) * along)));
|
||||
for &i in &bones {
|
||||
if let Some((a, b)) = bone(i, ALONG)
|
||||
&& scene.blocked(a, b, 0.0)
|
||||
{
|
||||
hits.push(Hit { check: "through", joint: skel.joints[i].name.clone(), f: k, value: 0.0, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
for side in &tips {
|
||||
let off: Vec<(usize, f32)> = side.iter().filter_map(|&i| bone(i, 1.0).map(|(_, tip)| (i, scene.reach(tip, grip::LOOK)))).collect();
|
||||
for o in grip::open(&off.iter().map(|o| o.1).collect::<Vec<_>>()) {
|
||||
hits.push(Hit { check: "grip", joint: skel.joints[off[o].0].name.clone(), f: k, value: off[o].1, unit: "m", what: String::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
// one fault per check and joint while the frames run on, as a clip's are (motionfaults' stretches)
|
||||
let mut out = stretches(hits);
|
||||
for f in &mut out {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to] as usize, numbers[f.peak] as usize);
|
||||
f.says = match f.check {
|
||||
"grip" => format!("{} is {:.0} mm off what the hand holds (it hasn't closed on it), frames {}-{}", f.joint, f.value * 1000.0, f.from, f.to),
|
||||
_ => format!("{} passes through a part of the scene, frames {}-{}", f.joint, f.from, f.to),
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One character's findings over the composition's frames.
|
||||
pub struct Found {
|
||||
pub who: String,
|
||||
pub skeleton: PathBuf,
|
||||
pub frames: usize,
|
||||
pub faults: Vec<Fault>,
|
||||
}
|
||||
|
||||
/// Every character's motion faults over the frames given (their numbers alongside); a character whose skeleton.json
|
||||
/// can't be found is said in the second list.
|
||||
pub fn run(dir: &Path, frames: &[(i64, Vec<Item>)], fps: f32) -> Result<(Vec<Found>, Vec<String>), String> {
|
||||
let Some((_, first)) = frames.first() else { return Err("no frames".into()) };
|
||||
let found = characters(first);
|
||||
if found.is_empty() {
|
||||
return Err("no characters in the composition (a <Character> draws <name>-body and <name>-<joint> parts)".into());
|
||||
}
|
||||
let numbers: Vec<i64> = frames.iter().map(|f| f.0).collect();
|
||||
let items: Vec<Vec<Item>> = frames.iter().map(|f| f.1.clone()).collect();
|
||||
let (mut out, mut missing) = (Vec::new(), Vec::new());
|
||||
for (who, folder) in found {
|
||||
let Some((path, skel)) = skeleton(dir, &folder) else {
|
||||
missing.push(format!("{who}: no skeleton.json for {folder}, not checked"));
|
||||
continue;
|
||||
};
|
||||
let (clip, places) = clip_of(&skel, &who, &items, fps);
|
||||
let mut faults = raea_sys_motionfaults::check(&clip);
|
||||
// the clip's frames are the composition's from its first
|
||||
for f in &mut faults {
|
||||
(f.from, f.to, f.peak) = (numbers[f.from] as usize, numbers[f.to.min(numbers.len() - 1)] as usize, numbers[f.peak] as usize);
|
||||
}
|
||||
faults.extend(hands(&skel, &who, &items, &places, &numbers));
|
||||
out.push(Found { who, skeleton: path, frames: clip.poses.len(), faults });
|
||||
}
|
||||
Ok((out, missing))
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx`: the lint's findings judged as a viewer of the shot would see them (raea-sys-notice):
|
||||
//! every frame's camera asked where each one shows and how large, a small model saying how likely it is to read as a
|
||||
//! fault, the likeliest first. Hidden ones (walls meeting the ceiling inside the slab) are counted, not listed.
|
||||
//!
|
||||
//! It learns: `--real KEY` and `--fine KEY` keep a verdict on a finding beside the project (review/
|
||||
//! faults.labels.jsonl), and a finding the last run said that's gone while both its parts remain is kept as fixed,
|
||||
//! so real. `raea scene faults train [FOLDER]` fits the model to every project's verdicts under FOLDER.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts};
|
||||
use raea_runtime_export::{frame_of, items};
|
||||
use raea_sys_notice::{FAULT, Judged, Model, labels};
|
||||
|
||||
/// The most frames whose cameras are asked (evenly over the shot).
|
||||
const CAMERAS: usize = 48;
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let Some(edit) = args.get(2) else { return Err(crate::USAGE.into()) };
|
||||
if edit == "train" {
|
||||
return train(args.get(3).map(String::as_str));
|
||||
}
|
||||
if edit == "--clip" {
|
||||
return crate::motion::cli(args);
|
||||
}
|
||||
let tsx = dunce::canonicalize(std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let frame = frame_of(args)?;
|
||||
let opts = comp_opts(args)?;
|
||||
let shot = opts.composition.clone().unwrap_or_default();
|
||||
let js = std::env::temp_dir().join(format!("raea-faults-{}.js", std::process::id()));
|
||||
bundle_composition(&tsx, &js, &opts, None)?;
|
||||
let got = raea_runtime_export::scene_frames(&js, &dir, 0, true, &[]);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
// the composition's characters held to what a body does, read from the scene (chars.rs)
|
||||
if args.iter().any(|a| a == "--motion") {
|
||||
let all: Vec<(i64, Vec<raea_core_scene::Item>)> = frames.iter().map(|fr| (fr.0, items(&fr.1))).collect();
|
||||
let (text, v, n) = crate::motion::composition(&tsx, &shot, &dir, &all, fps as f32, args)?;
|
||||
return finish(if args.iter().any(|a| a == "--json") { serde_json::to_string_pretty(&v).unwrap_or_default() } else { text }, n);
|
||||
}
|
||||
let k = frames.iter().position(|(f, _)| *f == frame).ok_or_else(|| format!("no frame {frame}"))?;
|
||||
let other = if k + 1 < frames.len() { k + 1 } else { k.saturating_sub(1) };
|
||||
let (now, next) = (items(&frames[k].1), items(&frames[other].1));
|
||||
let (found, _) = raea_sys_contact::lint(&now, &next);
|
||||
// the cameras: the frame's own and evenly over the rest of the shot
|
||||
let step = frames.len().div_ceil(CAMERAS).max(1);
|
||||
// and each view's frame number, for the frame a fault shows largest on (--ask)
|
||||
let (mut views, mut view_frames) = (vec![now.clone()], vec![frame]);
|
||||
for (i, (f, fr)) in frames.iter().enumerate() {
|
||||
if i != k && i % step == 0 {
|
||||
views.push(items(fr));
|
||||
view_frames.push(*f);
|
||||
}
|
||||
}
|
||||
let model = Model::load();
|
||||
let judged = raea_sys_notice::judge(&found, &views, w, h, &model);
|
||||
// faults of known size planted and judged: the judge measured, nothing kept (seed.rs)
|
||||
if let Some(n) = raea_runtime_bundle::flag(args, "--seed") {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults to plant")?;
|
||||
return Ok(crate::seed::run(&now, &next, &views, &found, w, h, &model, n));
|
||||
}
|
||||
|
||||
// a vision model asked whether the likeliest faults are meant (ask.rs), its answers kept as verdicts
|
||||
if let Some(n) = raea_runtime_bundle::flag(args, "--ask") {
|
||||
let n = n.parse::<usize>().map_err(|_| "--ask takes how many of the likeliest faults to ask about")?;
|
||||
return crate::ask::run(&tsx, &shot, &judged, &view_frames, w, h, n, args.iter().any(|a| a == "--dry"));
|
||||
}
|
||||
|
||||
// what it learns from: this run against the last, and any verdict given now
|
||||
let project = labels::project_of(&tsx);
|
||||
let keys: Vec<String> = judged.iter().map(|j| j.fault.key.clone()).collect();
|
||||
let parts: Vec<String> = found.iter().flat_map(|v| ["part", "on", "into"].into_iter().filter_map(move |n| v[n].as_str())).map(String::from).collect();
|
||||
let mut rows = labels::fixed(&labels::last(&project, &shot), &keys, &parts);
|
||||
let fixed = rows.len();
|
||||
for (name, real) in [("--real", true), ("--fine", false)] {
|
||||
for key in raea_runtime_bundle::flags(args, name) {
|
||||
let j = judged.iter().find(|j| j.fault.key == key).ok_or_else(|| format!("{name} {key}: no finding by that key on this shot (keys are listed with --json, or after each line)"))?;
|
||||
rows.push(labels::row(&key, real, "marked", &shot, &j.x, &j.toks));
|
||||
}
|
||||
}
|
||||
labels::append(&project, &rows)?;
|
||||
let last: Vec<Value> = judged.iter().map(|j| json!({"key": j.fault.key, "part": j.fault.part, "into": j.fault.into, "x": j.x, "toks": j.toks, "shot": shot})).collect();
|
||||
labels::keep_last(&project, &shot, last)?;
|
||||
|
||||
let faults: Vec<&Judged> = judged.iter().filter(|j| j.p >= FAULT).collect();
|
||||
let hidden = judged.iter().filter(|j| j.seen.shown == 0).count();
|
||||
if args.iter().any(|a| a == "--json") {
|
||||
let rows: Vec<Value> = judged
|
||||
.iter()
|
||||
.map(|j| json!({"key": j.fault.key, "check": j.fault.check, "part": j.fault.part, "into": j.fault.into, "p": (j.p * 1e3).round() / 1e3, "fault": j.p >= FAULT,
|
||||
"seen": {"frames": j.seen.frames, "shown": j.seen.shown, "px": (j.seen.px * 10.0).round() / 10.0, "near": (j.seen.near * 1e3).round() / 1e3}, "says": j.fault.says}))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&json!({"frame": frame, "model": model.from, "labels": model.labels, "findings": rows, "faults": faults.len(), "hidden": hidden, "fixed": fixed})).unwrap_or_default();
|
||||
return finish(text, faults.len());
|
||||
}
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for j in &judged {
|
||||
if j.seen.shown == 0 && j.p < FAULT {
|
||||
continue;
|
||||
}
|
||||
let tag = if j.p >= FAULT { "FAULT" } else { "maybe" };
|
||||
out.push(format!("{:.2} {tag} {} (seen on {}/{} frames, {:.1} px, {:.2} m off) key: {}", j.p, j.fault.says, j.seen.shown, j.seen.frames, j.seen.px, j.seen.near, j.fault.key));
|
||||
}
|
||||
out.push(format!(
|
||||
"frame {frame}: {} findings, {} likely faults, {} seen but likely fine, {hidden} no camera sees; judged by {} ({} labels){}",
|
||||
judged.len(),
|
||||
faults.len(),
|
||||
judged.len() - faults.len() - judged.iter().filter(|j| j.seen.shown == 0 && j.p < FAULT).count(),
|
||||
model.from,
|
||||
model.labels,
|
||||
if fixed > 0 { format!("; {fixed} fixed since the last run, kept as real") } else { String::new() }
|
||||
));
|
||||
finish(out.join("\n"), faults.len())
|
||||
}
|
||||
|
||||
/// Faults fail it, as the lint's errors do.
|
||||
fn finish(text: String, faults: usize) -> Result<String, String> {
|
||||
if faults > 0 {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// `raea scene faults train [FOLDER]`: every project's verdicts under FOLDER (default: here) fitted, the model kept in
|
||||
/// raea's models folder for every run after.
|
||||
fn train(root: Option<&str>) -> Result<String, String> {
|
||||
let root = std::path::PathBuf::from(root.unwrap_or("."));
|
||||
let files = labels::files(&root, 4);
|
||||
let ex: Vec<_> = files.iter().flat_map(|f| labels::examples(f)).collect();
|
||||
if ex.is_empty() {
|
||||
return Err(format!("no verdicts under {} (review/faults.labels.jsonl: --real KEY, --fine KEY, and fixes)", root.display()));
|
||||
}
|
||||
let m = Model::fit(&ex);
|
||||
let right = ex.iter().filter(|(x, t, y)| (m.score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let before = ex.iter().filter(|(x, t, y)| (Model::prior().score(x, t) >= FAULT) == (*y >= 0.5)).count();
|
||||
let p = raea_sys_notice::model::path();
|
||||
std::fs::create_dir_all(p.parent().unwrap()).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&p, serde_json::to_string_pretty(&m.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
// held out: each finding (one finding judged on two shots shares its words) fitted without, then asked
|
||||
let (held, finds) = held_out(&ex.iter().map(|e| (e.1.clone(), e.0.clone(), e.1.clone(), e.2)).collect::<Vec<_>>());
|
||||
// and a shot at a time (each project's own shot names, so a shot is a project's view): a scene it has never seen
|
||||
let by_shot: Vec<_> = files.iter().enumerate().flat_map(|(n, f)| labels::shots(f).into_iter().map(move |(s, x, t, y)| (format!("{n}/{s}"), x, t, y))).collect();
|
||||
let (unseen, names) = held_out(&by_shot);
|
||||
Ok(format!(
|
||||
"{} verdicts on {} findings from {} projects ({real} real, {} fine): the prior agreed with {before}, the fitted judge with {right}, with {held} each fitted without its own finding (held out), and with {unseen} each fitted without its whole shot ({} shots, a scene it hasn't seen); kept in {}\n{}",
|
||||
ex.len(),
|
||||
finds,
|
||||
files.len(),
|
||||
ex.len() - real,
|
||||
names,
|
||||
p.display(),
|
||||
crate::motion::train()?
|
||||
))
|
||||
}
|
||||
|
||||
/// Verdicts a judge gets right fitted without their own group (a finding's words, a shot): each group left out in
|
||||
/// turn, fitted on the rest, then asked. With how many groups there were.
|
||||
fn held_out<K: Ord>(rows: &[(K, Vec<f32>, Vec<String>, f32)]) -> (usize, usize) {
|
||||
let mut groups: Vec<&K> = rows.iter().map(|r| &r.0).collect();
|
||||
groups.sort();
|
||||
groups.dedup();
|
||||
let (mut right, n) = (0, groups.len());
|
||||
for g in groups {
|
||||
let rest: Vec<_> = rows.iter().filter(|r| &r.0 != g).map(|r| (r.1.clone(), r.2.clone(), r.3)).collect();
|
||||
let m = Model::fit(&rest);
|
||||
right += rows.iter().filter(|r| &r.0 == g && (m.score(&r.1, &r.2) >= FAULT) == (r.3 >= 0.5)).count();
|
||||
}
|
||||
(right, n)
|
||||
}
|
||||
@@ -10,19 +10,12 @@ use raea_runtime_export::{frame_of, items};
|
||||
|
||||
// how near the camera passes to each solid part, every frame (`--clearance M`, MK16)
|
||||
pub mod clearance;
|
||||
// the lint's findings judged as a viewer of the shot would see them, learning from verdicts (raea-sys-notice)
|
||||
mod ask;
|
||||
mod chars;
|
||||
mod faults;
|
||||
mod motion;
|
||||
// faults of known size planted, to measure the judge (`faults --seed N`)
|
||||
mod seed;
|
||||
mod light;
|
||||
// each part's planned detail beside how large the frames show it (MK23)
|
||||
pub mod lod;
|
||||
mod stage;
|
||||
|
||||
pub const USAGE: &str = "raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json]";
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json]";
|
||||
|
||||
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
|
||||
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
|
||||
@@ -35,7 +28,6 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
"light" => return light::cli(args),
|
||||
"stage" => return stage::cli(args),
|
||||
"lod" => return lod::cli(args),
|
||||
"faults" => return faults::cli(args),
|
||||
"lint" | "explain" => {}
|
||||
_ => return Err(usage.into()),
|
||||
}
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
//! `raea scene faults --clip CLIP.json|FOLDER [--clip ...]`: a character's motion held to what a body does, frame by frame
|
||||
//! (raea-sys-motionfaults): knees that buckle while the foot stands, feet that skate, joints past their range, fingers
|
||||
//! twisted or bent back, jolts, and fingers through what the hand holds. A clip is the skeleton's `joints` (and its
|
||||
//! `surface`, for the palm), `fps`, and `frames` of `{ root, turns }` (with `thing` for what the hand holds).
|
||||
//!
|
||||
//! It learns: `--fine KEY` and `--real KEY` on a clip's finding (each line ends with its key: check and joint role)
|
||||
//! move that key's line for every run after (raea-sys-motionfaults' verdicts, kept beside the scene judge's model).
|
||||
|
||||
use raea_sys_motionfaults::critic;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
// each --clip a clip's JSON, or a folder of them
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
for given in args.windows(2).filter(|w| w[0] == "--clip").map(|w| &w[1]) {
|
||||
match std::fs::read_dir(given) {
|
||||
Ok(dir) => {
|
||||
let mut v: Vec<String> = dir.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).map(|p| p.to_string_lossy().into()).collect();
|
||||
v.sort();
|
||||
files.extend(v);
|
||||
}
|
||||
Err(_) => files.push(given.clone()),
|
||||
}
|
||||
}
|
||||
if let Some(n) = args.windows(2).find(|w| w[0] == "--seed").map(|w| &w[1]) {
|
||||
let n = n.parse::<usize>().map_err(|_| "--seed takes how many faults of each kind to plant in each clip")?;
|
||||
return seed(&files, n);
|
||||
}
|
||||
let as_json = args.iter().any(|a| a == "--json");
|
||||
let (mut text, mut out, mut faults) = (String::new(), Vec::new(), 0);
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let (mut given, mut held) = (0usize, 0usize);
|
||||
for file in &files {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let mut found = raea_sys_motionfaults::check(&clip);
|
||||
// verdicts given now, on this clip's findings by key, then every verdict's lines applied
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let hit: Vec<_> = found.iter().filter(|f| raea_sys_motionfaults::verdicts::key(f) == *k).collect();
|
||||
if hit.is_empty() {
|
||||
return Err(format!("{file}: no finding has the key {k} (each line ends with its key)"));
|
||||
}
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in hit {
|
||||
if f.value < from || f.value > upto {
|
||||
continue;
|
||||
}
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let before = found.len();
|
||||
found.retain(|f| stands(f, &verdicts, &judge));
|
||||
held += before - found.len();
|
||||
faults += found.len();
|
||||
let name = std::path::Path::new(file).file_stem().map_or(file.to_string(), |s| s.to_string_lossy().into());
|
||||
text += &format!("{name}: {} frames, {} fault{}\n", clip.poses.len(), found.len(), if found.len() == 1 { "" } else { "s" });
|
||||
for f in &found {
|
||||
text += &format!(" {:<8} {} key: {}\n", f.check, f.says, raea_sys_motionfaults::verdicts::key(f));
|
||||
}
|
||||
out.push(json!({"clip": file, "frames": clip.poses.len(), "faults": found.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Err("--clip takes a clip's JSON (joints, fps, frames of root and turns)".into());
|
||||
}
|
||||
if given > 0 {
|
||||
if let Some(dir) = store.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
critic::append(&epath, &examples)?;
|
||||
text += &format!("{given} verdict{} kept in {}\n", if given == 1 { "" } else { "s" }, store.display());
|
||||
}
|
||||
if held > 0 {
|
||||
text += &format!("{held} finding{} held back by earlier verdicts (fine at that size)\n", if held == 1 { " is" } else { "s are" });
|
||||
}
|
||||
if as_json {
|
||||
return Ok(serde_json::to_string_pretty(&json!({"clips": out, "faults": faults, "held": held})).unwrap());
|
||||
}
|
||||
if faults > 0 {
|
||||
eprint!("{text}");
|
||||
return Err(format!("{faults} motion fault{} in {} clip{}", if faults == 1 { "" } else { "s" }, out.len(), if out.len() == 1 { "" } else { "s" }));
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Faults of each kind planted in every clip (raea-sys-motionfaults' plant), and how many `check` finds: one that is
|
||||
/// new against the clip's own faults, of its kind, on its joint (any joint for a grip), over its frame.
|
||||
fn seed(files: &[String], n: usize) -> Result<String, String> {
|
||||
use raea_sys_motionfaults::plant::{KINDS, Rng, plant};
|
||||
use std::collections::BTreeMap;
|
||||
let mut tally: BTreeMap<&str, (usize, usize, Vec<f32>, Vec<f32>)> = BTreeMap::new();
|
||||
let mut text = String::new();
|
||||
for (k, file) in files.iter().enumerate() {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{file}: {e}"))?;
|
||||
let clip = raea_sys_motionfaults::clip_of(&v).map_err(|e| format!("{file}: {e}"))?;
|
||||
let own = raea_sys_motionfaults::check(&clip);
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15 ^ (k as u64 + 1) * 0x1000_0001);
|
||||
for kind in KINDS {
|
||||
for _ in 0..n {
|
||||
let Some((moved, p)) = plant(&clip, kind, &mut rng) else { continue };
|
||||
let near = |f: &raea_sys_motionfaults::Fault| f.check == p.check && (p.check == "through" || p.check == "skate" || f.joint == p.joint) && f.from <= p.frame + 2 && p.frame <= f.to + 2;
|
||||
let found = raea_sys_motionfaults::check(&moved);
|
||||
let caught = found.iter().any(|f| near(f) && !own.iter().any(|o| o.check == f.check && o.joint == f.joint && o.from <= f.to && f.from <= o.to));
|
||||
let t = tally.entry(p.check).or_default();
|
||||
t.0 += 1;
|
||||
if caught {
|
||||
t.1 += 1;
|
||||
t.2.push(p.size);
|
||||
} else {
|
||||
t.3.push(p.size);
|
||||
let name = std::path::Path::new(file).file_stem().map_or(String::new(), |s| s.to_string_lossy().into());
|
||||
text += &format!(" missed in {name}: {}\n", p.says);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = format!("planted in {} clips:\n", files.len());
|
||||
for (kind, (planted, caught, got, missed)) in &tally {
|
||||
out += &format!(" {kind:<8} {caught}/{planted} caught{}{}\n", if got.is_empty() { String::new() } else { format!(", smallest caught {:.3}", raea_sys_motionfaults::bounds(got).0) }, if missed.is_empty() { String::new() } else { format!(", smallest missed {:.3}", raea_sys_motionfaults::bounds(missed).0) });
|
||||
}
|
||||
Ok(out + text.as_str())
|
||||
}
|
||||
|
||||
/// Where the motion verdicts are kept: beside the scene judge's model (notice/motion.json), or RAEA_NOTICE_MOTION.
|
||||
/// `raea scene faults EDIT.tsx --composition ID --motion`: the composition's characters (chars.rs) held to the motion
|
||||
/// checks, verdicts given (`--real`/`--fine KEY`) and applied as `--clip`'s are. And what a change shows: each run's
|
||||
/// findings are kept (review/motion.last/<shot>.json), and one the last run reported that's gone now, the character
|
||||
/// and its frames the same, was fixed, so it's kept as a real verdict at its size (raea-sys-motionfaults `fixed`).
|
||||
pub fn composition(tsx: &std::path::Path, shot: &str, dir: &std::path::Path, frames: &[(i64, Vec<raea_core_scene::Item>)], fps: f32, args: &[String]) -> Result<(String, Value, usize), String> {
|
||||
use raea_sys_motionfaults::verdicts::{fixed, key, record};
|
||||
let (found, missing) = crate::chars::run(dir, frames, fps)?;
|
||||
let store = verdicts_path();
|
||||
let mut verdicts = raea_sys_motionfaults::verdicts::Verdicts::load(&store);
|
||||
let (cpath, epath) = critic::paths(&store);
|
||||
let judge = critic::Critic::load(&cpath);
|
||||
let mut examples = Vec::new();
|
||||
let lastp = raea_sys_notice::labels::project_of(tsx).join("review").join("motion.last").join(format!("{shot}.json"));
|
||||
let last: Value = std::fs::read_to_string(&lastp).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null);
|
||||
let (mut text, mut rows, mut total, mut given, mut fixes, mut held) = (missing.join("\n"), Vec::new(), 0, 0, 0, 0);
|
||||
let mut keep = serde_json::Map::new();
|
||||
for c in &found {
|
||||
for (flag, real) in [("--real", true), ("--fine", false)] {
|
||||
for k in args.windows(2).filter(|w| w[0] == flag).map(|w| &w[1]) {
|
||||
let (from, upto) = sizes(args, real);
|
||||
for f in c.faults.iter().filter(|f| key(f) == *k && f.value >= from && f.value <= upto) {
|
||||
verdicts.give(f, real);
|
||||
examples.push(critic::row(f, real, by(args)));
|
||||
given += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut lines = String::new();
|
||||
let was = &last["characters"][&c.who];
|
||||
if was["frames"].as_u64() == Some(c.frames as u64) && last["checks"] == raea_sys_motionfaults::CHECKS {
|
||||
for (k, v, n) in fixed(was["faults"].as_array().map(Vec::as_slice).unwrap_or(&[]), &c.faults) {
|
||||
verdicts.give_at(&k, v, true);
|
||||
let (check, joint) = k.split_once(':').unwrap_or((&k, ""));
|
||||
examples.push(critic::row_of(check, joint, v, n, true, "fixed"));
|
||||
fixes += 1;
|
||||
lines += &format!(" fixed {k} at {v:.3}: gone since the last run, kept as real\n");
|
||||
}
|
||||
}
|
||||
keep.insert(c.who.clone(), json!({"frames": c.frames, "faults": c.faults.iter().map(record).collect::<Vec<_>>()}));
|
||||
let mut stand: Vec<&raea_sys_motionfaults::Fault> = Vec::new();
|
||||
for f in &c.faults {
|
||||
if stands(f, &verdicts, &judge) {
|
||||
stand.push(f);
|
||||
}
|
||||
}
|
||||
held += c.faults.len() - stand.len();
|
||||
total += stand.len();
|
||||
for f in &stand {
|
||||
lines += &format!(" {:<8} {} key: {}\n", f.check, f.says, key(f));
|
||||
}
|
||||
text += &format!("{} ({}): {} frames, {} fault{}\n{lines}", c.who, c.skeleton.display(), c.frames, stand.len(), if stand.len() == 1 { "" } else { "s" });
|
||||
rows.push(json!({"character": c.who, "skeleton": c.skeleton, "frames": c.frames, "faults": stand.iter().map(|f| f.to_json()).collect::<Vec<_>>()}));
|
||||
}
|
||||
if given + fixes > 0 {
|
||||
std::fs::create_dir_all(store.parent().unwrap_or(std::path::Path::new("."))).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&store, serde_json::to_string_pretty(&verdicts.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", store.display()))?;
|
||||
}
|
||||
critic::append(&epath, &examples)?;
|
||||
if let Some(dir) = lastp.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::write(&lastp, serde_json::to_string_pretty(&json!({"checks": raea_sys_motionfaults::CHECKS, "characters": keep})).unwrap_or_default()).map_err(|e| format!("{}: {e}", lastp.display()))?;
|
||||
text += &format!("{held} held back by verdicts and the critic ({} labels), {given} verdicts given, {fixes} fixed since the last run (kept as real) in {}", judge.labels, store.display());
|
||||
Ok((text, json!({"characters": rows, "faults": total, "held": held, "fixed": fixes}), total))
|
||||
}
|
||||
|
||||
/// `--fine-upto N` / `--fine-from N` (`--real-upto`, `--real-from`): that call's verdicts only on findings of the key
|
||||
/// within those sizes, in the finding's own units (degrees past the range for a finger or a limit): a pinky's small
|
||||
/// bends fine, its big one real.
|
||||
/// A fault that stands: marked real, or not marked fine and scored a fault by the judge.
|
||||
fn stands(f: &raea_sys_motionfaults::Fault, verdicts: &raea_sys_motionfaults::verdicts::Verdicts, judge: &critic::Critic) -> bool {
|
||||
verdicts.real_at(f) || (verdicts.stands(f) && judge.score(f) >= critic::SAY)
|
||||
}
|
||||
|
||||
fn sizes(args: &[String], real: bool) -> (f32, f32) {
|
||||
let (a, b) = if real { ("--real-from", "--real-upto") } else { ("--fine-from", "--fine-upto") };
|
||||
let get = |flag: &str, or: f32| args.windows(2).find(|w| w[0] == flag).and_then(|w| w[1].parse().ok()).unwrap_or(or);
|
||||
(get(a, f32::NEG_INFINITY), get(b, f32::INFINITY))
|
||||
}
|
||||
|
||||
/// Who a verdict is by: `--by NAME` (an agent that looked: claude), else a person (marked).
|
||||
fn by(args: &[String]) -> &str {
|
||||
args.windows(2).find(|w| w[0] == "--by").map_or("marked", |w| w[1].as_str())
|
||||
}
|
||||
|
||||
/// The motion critic fitted to every example kept, held out by key, written beside the verdicts.
|
||||
pub fn train() -> Result<String, String> {
|
||||
let (cpath, epath) = critic::paths(&verdicts_path());
|
||||
let ex = critic::examples(&std::fs::read_to_string(&epath).unwrap_or_default());
|
||||
if ex.is_empty() {
|
||||
return Ok(format!("motion critic: no examples yet ({})", epath.display()));
|
||||
}
|
||||
let c = critic::Critic::fit(&ex);
|
||||
let right = ex.iter().filter(|e| (c.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let prior = ex.iter().filter(|e| (critic::Critic::prior().score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count();
|
||||
let mut keys: Vec<&String> = ex.iter().map(|e| &e.1[2]).collect();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
let held = keys.iter().map(|k| {
|
||||
let m = critic::Critic::fit(&ex.iter().filter(|e| &e.1[2] != *k).cloned().collect::<Vec<_>>());
|
||||
ex.iter().filter(|e| &e.1[2] == *k && (m.score_x(&e.0, &e.1) >= critic::SAY) == (e.2 >= 0.5)).count()
|
||||
}).sum::<usize>();
|
||||
std::fs::write(&cpath, serde_json::to_string_pretty(&c.to_json()).unwrap_or_default()).map_err(|e| format!("{}: {e}", cpath.display()))?;
|
||||
let real = ex.iter().filter(|e| e.2 >= 0.5).count();
|
||||
Ok(format!("motion critic: {} examples on {} keys ({real} real, {} fine): the prior agreed with {prior}, the fitted critic with {right}, and with {held} each fitted without its own key (held out); kept in {}", ex.len(), keys.len(), ex.len() - real, cpath.display()))
|
||||
}
|
||||
|
||||
fn verdicts_path() -> std::path::PathBuf {
|
||||
match std::env::var_os("RAEA_NOTICE_MOTION").filter(|v| !v.is_empty()) {
|
||||
Some(p) => p.into(),
|
||||
None => raea_sys_notice::model::path().with_file_name("motion.json"),
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
//! `raea scene faults EDIT.tsx --seed N`: the judge measured on faults of known size. N props that rest as they should
|
||||
//! are each moved once (sunk into what they stand on, lifted a few millimetres off it, or lifted into the air), the
|
||||
//! lint run again, and the planted fault's finding judged. What it says: how many the lint found, and of those a camera
|
||||
//! sees at two pixels or more, how many the judge calls faults; of those no camera sees, how many it still calls one.
|
||||
//! Nothing is written: a planted fault's truth is its size, which the judge's own features already carry, so it
|
||||
//! measures the judge rather than teaching it.
|
||||
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
use raea_core_scene::{Item, label};
|
||||
use raea_sys_motionfaults::plant::Rng;
|
||||
use raea_sys_notice::{Cam, FAULT, Model, Scene, camera};
|
||||
|
||||
/// Props this big across or smaller are moved.
|
||||
const PROP: f32 = 1.2;
|
||||
/// Pixels a planted fault covers at the least to count as plain to see.
|
||||
const PLAIN: f32 = 2.0;
|
||||
|
||||
|
||||
fn moved(its: &[Item], name: &str, by: Vec3) -> Vec<Item> {
|
||||
its.iter().cloned().map(|mut it| {
|
||||
if (it.kind == "mesh" || it.kind == "model") && label(&it, "") == name {
|
||||
it.world = Mat4::from_translation(by) * it.world;
|
||||
}
|
||||
it
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(now: &[Item], next: &[Item], views: &[Vec<Item>], found: &[Value], w: u32, h: u32, model: &Model, n: usize) -> String {
|
||||
let count = |name: &str| now.iter().filter(|it| (it.kind == "mesh" || it.kind == "model") && label(it, "") == name).count();
|
||||
let props: Vec<&str> = found
|
||||
.iter()
|
||||
.filter(|v| v["check"] == "rests")
|
||||
.filter(|v| {
|
||||
let (lo, hi) = (&v["box"]["min"], &v["box"]["max"]);
|
||||
(0..3).all(|k| hi[k].as_f64().unwrap_or(9.0) - lo[k].as_f64().unwrap_or(0.0) <= PROP as f64)
|
||||
})
|
||||
.filter_map(|v| v["part"].as_str())
|
||||
.filter(|p| count(p) == 1)
|
||||
.collect();
|
||||
let cams: Vec<Cam> = views.iter().filter_map(|f| camera(f)).collect();
|
||||
// only props some camera of the shot sees (the middle of the box's top): a fault planted out of view tells
|
||||
// nothing of how the judge weighs one in it
|
||||
let scene = Scene::of(now);
|
||||
let in_view = |p: &str| {
|
||||
let Some(v) = found.iter().find(|v| v["part"] == p) else { return false };
|
||||
let at = |k: usize, e: &str| v["box"][e][k].as_f64().unwrap_or(0.0) as f32;
|
||||
let top = Vec3::new((at(0, "min") + at(0, "max")) / 2.0, at(1, "max") + 0.01, (at(2, "min") + at(2, "max")) / 2.0);
|
||||
raea_sys_notice::seen(&[raea_sys_notice::sight::Spot { at: top, facing: None, size: 0.0 }], false, &cams, &scene, w as f32, h as f32).shown > 0
|
||||
};
|
||||
let props: Vec<&str> = props.into_iter().filter(|p| in_view(p)).collect();
|
||||
if props.is_empty() {
|
||||
return "no prop the shot sees rests on anything to plant a fault in".into();
|
||||
}
|
||||
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
|
||||
let (mut lines, mut lint_found, mut plain, mut plain_flagged, mut hidden, mut hidden_flagged, mut small, mut small_flagged) = (Vec::new(), 0, 0, 0, 0, 0, 0, 0);
|
||||
for i in 0..n {
|
||||
let part = props[(rng.next() * props.len() as f32) as usize % props.len()];
|
||||
let r = rng.next();
|
||||
let (kind, d) = if r < 0.4 { ("floats", 0.002 + rng.next() * 0.028) } else if r < 0.8 { ("sunk", 0.005 + rng.next() * 0.035) } else { ("air", 0.08 + rng.next() * 0.22) };
|
||||
let by = Vec3::new(0.0, if kind == "sunk" { -d } else { d }, 0.0);
|
||||
let (a, b) = (moved(now, part, by), moved(next, part, by));
|
||||
let (again, _) = raea_sys_contact::lint(&a, &b);
|
||||
let want = |c: &str| c == kind || (kind == "sunk" && c == "seated") || (kind == "air" && c == "floats") || (kind != "sunk" && c == "mounted");
|
||||
let Some(f) = again.iter().find(|v| v["part"] == part && v["check"].as_str().is_some_and(want)) else {
|
||||
// what it said of the part instead (a prop lifted against a wall reads as mounted on it)
|
||||
let said: Vec<&str> = again.iter().filter(|v| v["part"] == part).filter_map(|v| v["check"].as_str()).collect();
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: not found as {kind} (the lint said {})", d * 1000.0, said.join(", ")));
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
continue;
|
||||
};
|
||||
lint_found += 1;
|
||||
let scene = Scene::of(&a);
|
||||
let j = raea_sys_notice::judge_in(std::slice::from_ref(f), &scene, &cams, w, h, model);
|
||||
let Some(j) = j.first() else { continue };
|
||||
let flagged = j.p >= FAULT;
|
||||
if j.seen.shown == 0 {
|
||||
hidden += 1;
|
||||
hidden_flagged += flagged as usize;
|
||||
} else if j.seen.px >= PLAIN {
|
||||
plain += 1;
|
||||
plain_flagged += flagged as usize;
|
||||
} else {
|
||||
small += 1;
|
||||
small_flagged += flagged as usize;
|
||||
}
|
||||
lines.push(format!("{i:>3} {kind:<6} {:>6.1} mm {part}: seen {}/{} frames, {:.1} px -> {:.2}{}", d * 1000.0, j.seen.shown, j.seen.frames, j.seen.px, j.p, if flagged { " FAULT" } else { "" }));
|
||||
// each trial lints the scene again (half a minute on a furnished room): said as it goes
|
||||
eprintln!("{}", lines.last().unwrap());
|
||||
}
|
||||
lines.push(format!(
|
||||
"planted {n} in {} props: the lint found {lint_found}; plain to see (>= {PLAIN} px) {plain}, judged faults {plain_flagged}; seen under {PLAIN} px {small}, judged faults {small_flagged}; no camera sees {hidden}, judged faults {hidden_flagged}",
|
||||
props.len()
|
||||
));
|
||||
lines.join("\n")
|
||||
}
|
||||
@@ -8,11 +8,6 @@ pub mod easing;
|
||||
pub mod interpolate;
|
||||
pub mod spring;
|
||||
|
||||
/// The logistic curve, 1 / (1 + e^-z): a score in log-odds as a chance (a judge's), or a stored logit as an opacity.
|
||||
pub fn sigmoid(z: f32) -> f32 {
|
||||
1.0 / (1.0 + (-z).exp())
|
||||
}
|
||||
|
||||
/// 0 below `a`, 1 above `b`, and between them the cubic Hermite ease (WGSL's smoothstep), for a value that fades in
|
||||
/// over a range rather than a key's time.
|
||||
pub fn smoothstep(a: f32, b: f32, x: f32) -> f32 {
|
||||
|
||||
+29
-7
@@ -109,10 +109,26 @@ fn hash_props(m: &Map<String, Value>, h: &mut impl Hasher, take: impl Fn(&str) -
|
||||
}
|
||||
}
|
||||
|
||||
/// A standard material's maps whose picture a render swaps frame by frame (raea-sys-material's SwappedMaps,
|
||||
/// docs/render-memory.feature RM6): a change of picture keys the map's column instead of cutting the part's track.
|
||||
/// The packed roughness and metalness maps are one texture made from two pictures, so they still cut.
|
||||
pub const SWAPPED_MAPS: [(&str, &str); 5] = [("map", "map"), ("normalMap", "normal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map")];
|
||||
|
||||
/// Whether a part's standard material takes its pictures frame by frame in a render (SWAPPED_MAPS): a plain
|
||||
/// standard or physical surface, none of the surfaces built over it (a grid, paint, wear, a procedural pattern, a
|
||||
/// shader), whose maps are made into their own material once.
|
||||
pub fn swaps_maps(it: &Item) -> bool {
|
||||
let Some(m) = &it.material else { return false };
|
||||
matches!(&*m.kind, "MeshStandardMaterial" | "MeshPhysicalMaterial")
|
||||
&& !["grid", "paint", "wear", "procedural", "shader", "toon"].iter().any(|k| m.props.contains_key(*k))
|
||||
&& !["shader", "three", "surface"].iter().any(|k| it.props.contains_key(*k))
|
||||
}
|
||||
|
||||
/// A part's kept inputs as one number: what its row takes from the frame it's spawned in (its shape, its material's
|
||||
/// maps and modes, its words and their glyphs, a model's file). Two frames of a part with the same number make the
|
||||
/// same kept columns.
|
||||
pub fn spawn_sig(it: &Item) -> u64 {
|
||||
/// same kept columns. With `swapped`, a swapped map's picture is left out (whether it has one still counts), as a
|
||||
/// render keys it (SWAPPED_MAPS) rather than cutting the part's track for it; without, every picture counts.
|
||||
pub fn spawn_sig(it: &Item, swapped: bool) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
it.kind.hash(&mut h);
|
||||
match it.kind {
|
||||
@@ -120,9 +136,14 @@ pub fn spawn_sig(it: &Item) -> u64 {
|
||||
it.shape.hash(&mut h);
|
||||
if let Some(m) = &it.material {
|
||||
m.kind.hash(&mut h);
|
||||
let swap = swapped && swaps_maps(it);
|
||||
let picture = |k: &str| swap && SWAPPED_MAPS.iter().any(|(p, _)| *p == k) && m.props.get(k).and_then(Value::as_str).is_some_and(|s| !s.starts_with("render:"));
|
||||
// a three.js shader's spec is its uniforms and its source, the one keyed and the other its identity
|
||||
if &*m.kind != "ThreeShaderMaterial" {
|
||||
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k));
|
||||
hash_props(&m.props, &mut h, |k| !MAT_LIVE.contains(&k) && !picture(k));
|
||||
}
|
||||
for (p, _) in SWAPPED_MAPS.iter().filter(|(p, _)| picture(p)) {
|
||||
p.hash(&mut h);
|
||||
}
|
||||
}
|
||||
hash_props(&it.props, &mut h, |k| MESH_KEPT.contains(&k));
|
||||
@@ -147,7 +168,7 @@ pub fn spawn_sig(it: &Item) -> u64 {
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig is a track of its own
|
||||
/// Tracks cut where a part's kept inputs change: each run of frames with the same spawn_sig (swapped maps left out) is a track of its own
|
||||
/// (`ID~1`, `ID~2` after the first), so a render's row never holds one frame's shape or words over another frame's.
|
||||
pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<Option<Item>>)> {
|
||||
let mut out = Vec::with_capacity(tracks.len());
|
||||
@@ -161,7 +182,8 @@ pub fn split_kept(tracks: Vec<(String, Vec<Option<Item>>)>) -> Vec<(String, Vec<
|
||||
let mut runs: Vec<(u64, Vec<Option<Item>>)> = Vec::new();
|
||||
for (i, slot) in track.into_iter().enumerate() {
|
||||
let Some(it) = slot else { continue };
|
||||
let s = spawn_sig(&it);
|
||||
// a render keys a swapped map's picture (SWAPPED_MAPS) rather than cutting for it
|
||||
let s = spawn_sig(&it, true);
|
||||
if runs.last().is_none_or(|(r, _)| *r != s) {
|
||||
runs.push((s, vec![None; n]));
|
||||
}
|
||||
@@ -197,7 +219,7 @@ pub struct KeptInputs {
|
||||
|
||||
impl KeptInputs {
|
||||
pub fn of(it: &Item) -> KeptInputs {
|
||||
KeptInputs { sig: spawn_sig(it), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
|
||||
KeptInputs { sig: spawn_sig(it, false), props: it.props.clone(), mat: it.material.as_ref().map(|m| m.props.clone()), shape: it.shape.clone() }
|
||||
}
|
||||
|
||||
/// Whether `it` has the kept inputs these were taken from; when it has, its props are held from now on.
|
||||
@@ -210,7 +232,7 @@ impl KeptInputs {
|
||||
if Arc::ptr_eq(&self.props, &it.props) && held(&self.mat, it.material.as_ref().map(|m| &m.props)) && self.shape == it.shape {
|
||||
return true;
|
||||
}
|
||||
if spawn_sig(it) != self.sig {
|
||||
if spawn_sig(it, false) != self.sig {
|
||||
return false;
|
||||
}
|
||||
*self = KeptInputs::of(it);
|
||||
|
||||
@@ -13,6 +13,8 @@ manifold-rust = "0.16.0"
|
||||
skrifa = "0.44"
|
||||
raea-core-fonts = { path = "../fonts" }
|
||||
serde_json = "1"
|
||||
# content names for kept BufferMesh text (buffer.rs kept_buffer)
|
||||
blake3 = "1.8"
|
||||
# blended distance fields and generators (trees, lofts, terrain, rosettes), meshed then closed into solids
|
||||
raea-core-sdf = { path = "../sdf" }
|
||||
raea-core-grow = { path = "../grow" }
|
||||
@@ -128,6 +128,42 @@ pub fn export_tris(t: &Tris, uvs: Option<&[[f32; 2]]>, path: &str, format: &str)
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
/// A <BufferMesh>'s text from this long on is kept on disk and named by its content (kept_buffer).
|
||||
pub const KEEP_BUFFER_AT: usize = 1 << 16;
|
||||
|
||||
/// A long BufferMesh shape (`buffer:{json}`) as `buffer:@NAME`: its JSON written once to raea's caches
|
||||
/// (buffers/NAME.json, NAME its content's BLAKE3), so what holds the shape holds 40 characters
|
||||
/// (docs/render-memory.feature RM8). halcyon's palms were 263 MB of vertex arrays as text, held by the React scene,
|
||||
/// every frame's program row, the store and the evaluator: two of them 51 MB each. None for a short one, one already
|
||||
/// kept, or when the caches folder can't be written (the text then goes as it is).
|
||||
pub fn kept_buffer(expr: &str) -> Option<String> {
|
||||
let json = expr.strip_prefix("buffer:")?;
|
||||
if json.len() < KEEP_BUFFER_AT || json.starts_with('@') {
|
||||
return None;
|
||||
}
|
||||
let hex = blake3::hash(json.as_bytes()).to_hex();
|
||||
let name = &hex.as_str()[..32];
|
||||
let dir = crate::kept::caches()?.join("buffers");
|
||||
let p = dir.join(format!("{name}.json"));
|
||||
if !p.exists() {
|
||||
let part = dir.join(format!(".{name}.{}.part", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
std::fs::write(&part, json).ok()?;
|
||||
std::fs::rename(&part, &p).ok()?;
|
||||
}
|
||||
Some(format!("buffer:@{name}"))
|
||||
}
|
||||
|
||||
/// A buffer shape's JSON (what follows `buffer:`): its own text, or the kept file `@NAME` names (kept_buffer).
|
||||
pub fn buffer_json(b: &str) -> Result<std::borrow::Cow<'_, str>, String> {
|
||||
let Some(name) = b.strip_prefix('@') else { return Ok(std::borrow::Cow::Borrowed(b)) };
|
||||
if name.len() != 32 || !name.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(format!("buffer:@{name}: not a kept buffer's name"));
|
||||
}
|
||||
let p = crate::kept::caches().ok_or("no caches folder for a kept buffer")?.join("buffers").join(format!("{name}.json"));
|
||||
std::fs::read_to_string(&p).map(std::borrow::Cow::Owned).map_err(|e| format!("buffer:@{name}: {}: {e}", p.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -160,4 +196,16 @@ mod tests {
|
||||
assert_eq!((v.len(), i.len()), (18, 6));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_buffer_is_kept_by_its_content_and_read_back() {
|
||||
let pos: Vec<String> = (0..36000).map(|i| format!("{}", i % 7)).collect();
|
||||
let expr = format!("buffer:{{\"positions\": [{}]}}", pos.join(", "));
|
||||
assert!(expr.len() > KEEP_BUFFER_AT);
|
||||
let Some(k) = kept_buffer(&expr) else { return }; // no caches folder here: nothing to check
|
||||
assert!(k.starts_with("buffer:@") && k.len() == 8 + 32, "{k}");
|
||||
assert_eq!(kept_buffer(&expr).as_deref(), Some(k.as_str()), "the same text, the same name");
|
||||
assert_eq!(buffer_json(&k[7..]).unwrap(), &expr[7..]);
|
||||
assert!(kept_buffer("buffer:{\"positions\": [0, 0, 0]}").is_none(), "a short one stays as it is");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! A cache by key in two generations of at most `cap` bytes each, for what's costly to make and too big to keep all
|
||||
//! of: core/shape's meshes (`cached`) and runtime/calls' built Manifolds (docs/render-memory.feature). One asked for
|
||||
//! again moves to the newest generation and stays; one made and never asked for again goes a generation later, so two
|
||||
//! generations at most are held. An entry's weight is its holder's to say; its key counts too.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct Generations<V> {
|
||||
now: HashMap<String, (V, usize)>,
|
||||
old: HashMap<String, (V, usize)>,
|
||||
/// the newest generation's bytes
|
||||
bytes: usize,
|
||||
cap: usize,
|
||||
}
|
||||
|
||||
impl<V: Clone> Generations<V> {
|
||||
pub fn new(cap: usize) -> Self {
|
||||
Generations { now: HashMap::new(), old: HashMap::new(), bytes: 0, cap }
|
||||
}
|
||||
|
||||
/// What's held for `key`, in either generation: one from the older is held again in the newest.
|
||||
pub fn get(&mut self, key: &str) -> Option<V> {
|
||||
if let Some((v, _)) = self.now.get(key) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let (v, weight) = self.old.remove(key)?;
|
||||
self.hold(key, v.clone(), weight);
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// `v`, weighing `weight` bytes, held for `key` in the newest generation, which becomes the older one when it
|
||||
/// would pass the cap.
|
||||
pub fn hold(&mut self, key: &str, v: V, weight: usize) {
|
||||
let bytes = weight + key.len();
|
||||
if self.bytes + bytes > self.cap && !self.now.is_empty() {
|
||||
self.old = std::mem::take(&mut self.now);
|
||||
self.bytes = 0;
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.now.insert(key.to_string(), (v, weight));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_entries_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
|
||||
// entries of a quarter of a generation each
|
||||
let mut g = Generations::new(4000);
|
||||
g.hold("kept", 1u8, 996);
|
||||
for i in 0..12 {
|
||||
g.hold(&format!("bar {i:02}"), 1u8, 994);
|
||||
assert!(g.get("kept").is_some(), "asked each time, it stays (after bar {i})");
|
||||
}
|
||||
assert!(g.get("bar 00").is_none(), "made once and never asked again, it went");
|
||||
assert!(g.now.len() + g.old.len() <= 8, "two generations at most: {} + {}", g.now.len(), g.old.len());
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use std::path::PathBuf;
|
||||
|
||||
/// raea's caches folder, as raea-io-home names it (this crate is below it): ~/Library/Caches/raea on macOS,
|
||||
/// %LOCALAPPDATA%\raea\cache on Windows, $XDG_CACHE_HOME/raea or ~/.cache/raea elsewhere.
|
||||
fn caches() -> Option<PathBuf> {
|
||||
pub(crate) fn caches() -> Option<PathBuf> {
|
||||
let base = PathBuf::from(std::env::var_os(if cfg!(windows) { "LOCALAPPDATA" } else { "HOME" })?);
|
||||
if base.as_os_str().is_empty() {
|
||||
return None;
|
||||
|
||||
+12
-48
@@ -34,9 +34,12 @@ mod kept;
|
||||
mod mesh;
|
||||
mod parse;
|
||||
mod sphere;
|
||||
pub mod generations;
|
||||
|
||||
pub use generations::Generations;
|
||||
pub use sphere::{SphereOf, cuboid_of, cylinder_of, plane_of, sphere_of};
|
||||
|
||||
pub use buffer::{buffer_tris, export_tris};
|
||||
pub use buffer::{buffer_json, buffer_tris, export_tris, kept_buffer, KEEP_BUFFER_AT};
|
||||
pub use mesh::{export, from_mesh, read_glb, read_obj, to_mesh};
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -211,47 +214,22 @@ const KEEP_MS: f64 = 2.0;
|
||||
/// and the end checks once more.
|
||||
const GEN_BYTES: usize = 16 << 20;
|
||||
|
||||
/// The shapes held, the newest generation and the one before, and the newest's bytes.
|
||||
#[derive(Default)]
|
||||
struct Held {
|
||||
now: HashMap<String, std::sync::Arc<Tris>>,
|
||||
old: HashMap<String, std::sync::Arc<Tris>>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Held {
|
||||
fn get(&mut self, expr: &str) -> Option<std::sync::Arc<Tris>> {
|
||||
if let Some(t) = self.now.get(expr) {
|
||||
return Some(t.clone());
|
||||
}
|
||||
let t = self.old.remove(expr)?;
|
||||
self.hold(expr, &t);
|
||||
Some(t)
|
||||
}
|
||||
|
||||
/// `t` held for `expr` in the newest generation, which becomes the one before when it would pass GEN_BYTES.
|
||||
fn hold(&mut self, expr: &str, t: &std::sync::Arc<Tris>) {
|
||||
let bytes = (t.positions.len() + t.normals.len()) * 12 + expr.len();
|
||||
if self.bytes + bytes > GEN_BYTES && !self.now.is_empty() {
|
||||
self.old = std::mem::take(&mut self.now);
|
||||
self.bytes = 0;
|
||||
}
|
||||
self.bytes += bytes;
|
||||
self.now.insert(expr.to_string(), t.clone());
|
||||
}
|
||||
/// What a mesh weighs as it's held: its positions and normals.
|
||||
fn tris_bytes(t: &Tris) -> usize {
|
||||
(t.positions.len() + t.normals.len()) * 12
|
||||
}
|
||||
|
||||
/// The mesh for an expression, built once per expression (a re-cut or a key that doesn't change the shape costs nothing).
|
||||
pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
|
||||
static CACHE: OnceLock<Mutex<Held>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(Default::default);
|
||||
static CACHE: OnceLock<Mutex<Generations<std::sync::Arc<Tris>>>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(Generations::new(GEN_BYTES)));
|
||||
if let Some(t) = cache.lock().unwrap().get(expr) {
|
||||
return Ok(t);
|
||||
}
|
||||
// a buffer mesh's own triangles (buffer.rs): data already, so nothing is kept on disk for it
|
||||
if let Some(b) = expr.strip_prefix("buffer:") {
|
||||
let t = std::sync::Arc::new(buffer_tris(b)?.0);
|
||||
cache.lock().unwrap().hold(expr, &t);
|
||||
let t = std::sync::Arc::new(buffer_tris(&buffer_json(b)?)?.0);
|
||||
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
|
||||
return Ok(t);
|
||||
}
|
||||
// made by this build before, on disk (kept.rs): read back as it was written
|
||||
@@ -267,7 +245,7 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
|
||||
t
|
||||
}
|
||||
};
|
||||
cache.lock().unwrap().hold(expr, &t);
|
||||
cache.lock().unwrap().hold(expr, t.clone(), tris_bytes(&t));
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
@@ -275,20 +253,6 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_shapes_go_a_generation_at_a_time_and_what_is_asked_again_stays() {
|
||||
let mut h = Held::default();
|
||||
// a shape of a quarter of a generation
|
||||
let t = std::sync::Arc::new(Tris { positions: vec![[0.0; 3]; GEN_BYTES / 96], normals: vec![[0.0; 3]; GEN_BYTES / 96] });
|
||||
h.hold("kept", &t);
|
||||
for i in 0..12 {
|
||||
h.hold(&format!("bar {i}"), &t);
|
||||
assert!(h.get("kept").is_some(), "asked each time, it stays (after bar {i})");
|
||||
}
|
||||
assert!(h.get("bar 0").is_none(), "made once and never asked again, it went");
|
||||
assert!(h.now.len() + h.old.len() <= 8, "two generations at most: {} + {}", h.now.len(), h.old.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_mesh_reads_back_as_it_was_written() {
|
||||
let dir = std::env::temp_dir().join(format!("raea-shape-kept-{}", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "raea-core-tables"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A row's per-frame tables: the column sets that change from frame to frame (a frame's look, the camera's post-processing, a light's), laid onto the row frame by frame"
|
||||
|
||||
[dependencies]
|
||||
raea-core-program = { path = "../program" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
File renamed without changes.
@@ -142,14 +142,8 @@ pub struct Overlaps {
|
||||
/// Between two parts, faces looking straight down in the plane both parts stand on (two boxes on one floor, one
|
||||
/// set into the other): their undersides, which the floor hides.
|
||||
pub bases: Option<(usize, f32, Vec3)>,
|
||||
/// The fight's shared patches, largest first (at most SPOTS): each one's middle, the way its faces look, and its
|
||||
/// area. Where a viewer could see it flicker (raea-sys-notice asks each camera).
|
||||
pub spots: Vec<(Vec3, Vec3, f32)>,
|
||||
}
|
||||
|
||||
/// The most shared patches a fight keeps for where it shows.
|
||||
const SPOTS: usize = 32;
|
||||
|
||||
/// Corners this close (metres) are one corner.
|
||||
const CORNER: f32 = 0.0005;
|
||||
|
||||
@@ -184,15 +178,11 @@ pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
|
||||
let mut out = Overlaps::default();
|
||||
// the largest patch each kind has seen, for where to point
|
||||
let mut most = [0.0f32; 3];
|
||||
let mut spots = Vec::new();
|
||||
let mut add = |kind: usize, to: &mut Option<(usize, f32, Vec3)>, f: &Face, g: &Face| {
|
||||
let (area, mid) = shared(f, g);
|
||||
if area <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if kind == 2 {
|
||||
spots.push((mid, f.n, area));
|
||||
}
|
||||
let e = to.get_or_insert((0, 0.0, mid));
|
||||
e.0 += 1;
|
||||
e.1 += area;
|
||||
@@ -225,9 +215,6 @@ pub fn sorted(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Overlaps {
|
||||
}
|
||||
}
|
||||
}
|
||||
spots.sort_by(|a, b| b.2.total_cmp(&a.2));
|
||||
spots.truncate(SPOTS);
|
||||
out.spots = spots;
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: "raea scene"
|
||||
summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, hold every frame to the stage checks a render runs, and list each part's planned detail beside how large the frames show it."
|
||||
order: 47
|
||||
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs", "apps/scene/src/faults.rs", "apps/scene/src/seed.rs", "systems/notice/src/lib.rs", "apps/scene/src/motion.rs", "systems/motionfaults/src/lib.rs", "runtime/endchecks/src/faults.rs", "apps/scene/src/ask.rs", "apps/scene/src/chars.rs"]
|
||||
sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "apps/scene/src/lod.rs", "runtime/lod-plan/src/lib.rs", "runtime/lod-plan/src/report.rs", "runtime/lod-plan/src/plan.rs", "systems/stage/src/lib.rs", "systems/stage/src/clearance.rs", "systems/contact/src/lint.rs", "systems/contact/src/zfight.rs"]
|
||||
---
|
||||
|
||||
`raea scene` steps a composition's frames and measures its 3D scene without rendering pictures. `lint` reports
|
||||
@@ -43,41 +43,8 @@ is an error, and `lod` exits 1. `raea render`, `raea scene stage` and `raea chec
|
||||
`raea make status` holds a job at it. A part hidden behind other meshes isn't counted as seen; RAEA_LOD_CHECK=0
|
||||
leaves the check out of a render.
|
||||
|
||||
`faults` judges the lint's findings as a viewer of the shot would see them. Every frame's camera (up to 48 over the
|
||||
shot) is asked whether each finding is in frame, facing it and not behind any part, measured against the scene's real
|
||||
triangles, and how many pixels its gap, depth or overlapping patch covers there. A small model turns that, the kind of
|
||||
fault and the words of the parts' names into the chance it reads as a fault. It lists likely faults (0.5 or more,
|
||||
FAULT) and seen ones under that (maybe), counts the findings no camera sees, and exits 1 on any fault. Each line ends
|
||||
with the finding's key. `--real KEY` and `--fine KEY` keep a verdict beside the project, and a finding the last run
|
||||
reported that is gone while both its parts remain is kept as fixed, so real. `raea scene faults train [FOLDER]` fits
|
||||
the model to every project's verdicts under FOLDER and keeps it in raea's models folder (notice/faults.json), which
|
||||
every run after uses. It reports how many verdicts it gets right fitted without each one's finding, and without each one's whole shot (a scene it hasn't seen). Until then it judges by a written prior (systems/notice/src/model.rs). See docs/notice.feature.
|
||||
|
||||
`faults --clip` holds a character's motion to what a body does, frame by frame (raea-sys-motionfaults): a knee that
|
||||
gives and comes back in a snap while its foot stands (a buckle), a standing foot that slides or glides along the
|
||||
ground (a skate), a joint past its anatomical range, a finger bent back, sideways or twisted past its range, a joint or
|
||||
the root jolting in one frame, and a finger, the thumb or the palm inside what the hand holds. A clip is JSON: the
|
||||
skeleton's `joints` (and `surface`, for the palm), `fps`, and `frames` of `{ root, turns }`, with `thing` (a ball, box,
|
||||
capsule or cylinder) and each frame's `thing: { at, turn }` for what the hand holds. `--clip` takes a file or a folder
|
||||
of them. The lines sit just above what 107 retargeted ACCAD captures do; `--seed N` plants N faults of each kind in
|
||||
every clip and says how many are caught.
|
||||
|
||||
`--motion` reads the characters from the composition itself, no clip written out, and also tests every finger bone
|
||||
against the scene's real triangles. Motion findings also pass a critic, a tiny logistic model fitted by `raea scene faults train` to every motion verdict (fixes, `--real`, `--fine`): what it learns of one joint carries to its neighbours, and a verdict on the finding's own key at its size outranks it. `--ask N` puts the N likeliest faults to a vision model, the fault ringed on its
|
||||
frame and described in the scene's own words, so it answers only whether it's meant; see docs/notice.feature NT12.
|
||||
|
||||
A render runs the judge too: at its end the first frame's floating, sunk, lifted and doubled-face findings are judged
|
||||
through the render's own cameras, and only the likely faults are said (RAEA_FAULTS_CHECK=0 leaves it out).
|
||||
|
||||
```sh
|
||||
raea scene lint room.tsx
|
||||
raea scene faults room.tsx --composition shot-in # the findings a viewer of shot-in would notice
|
||||
raea scene faults room.tsx --composition shot-tv --fine 'air:r106_map|' # the draped map is meant
|
||||
raea scene faults train ~/Documents/raea # fit the judge to every project's verdicts
|
||||
raea scene faults --clip walk.json # a clip's buckles, skates, bent fingers, jolts
|
||||
raea scene faults --clip clips/ --seed 2 # what it catches of faults planted in real motion
|
||||
raea scene faults take.tsx --composition take --motion # the composition's characters, hands against the scene
|
||||
raea scene faults room.tsx --composition shot-case --ask 3 # a vision model on whether the 3 likeliest are meant
|
||||
raea scene explain room.tsx --frame 90 --json
|
||||
raea scene light room.tsx --part hero
|
||||
raea scene light film.tsx --composition shot1,shot2,shot3 # the light across the cuts
|
||||
@@ -92,34 +59,22 @@ raea scene lod walk.tsx # every part's pl
|
||||
|
||||
```sh
|
||||
raea scene export EDIT.tsx -o DIR [--composition ID] [--frame N | --at A-B] (the composition's 3D as data other tools build: DIR/scene.json, each part placed (y up, metres) with its shape, material or light, and the camera; meshes/ and models/ beside it)
|
||||
raea scene lint|explain|faults|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--real KEY] [--fine KEY] [--seed N] [--ask N [--dry]] [--motion] [--json] | raea scene faults train [FOLDER] | raea scene faults --clip CLIP.json|FOLDER [--real KEY] [--fine KEY] [--fine-from N] [--fine-upto N] [--real-from N] [--real-upto N] [--by NAME] [--seed N] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
|
||||
raea scene lint|explain|light|stage|lod EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--clearance M] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 3 arguments besides its flags.
|
||||
Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--ask` | `N` | `faults`: render the frame each of the N likeliest faults shows largest on, ring it, and ask a vision model (`raea ask`) whether it's meant or a mistake, handing it the scene's own words for the fault. An answer 0.7 sure or more is kept as a verdict (by ask), which a person's verdict outranks. The ringed pictures stay in review/faults-ask/. |
|
||||
| `--at` | `A-B` | `export`: each part's placement and the camera's field of view on every frame from A to B, for keyframes in Blender or Godot. |
|
||||
| `--by` | `NAME` | With `--real`/`--fine` on motion findings: who made the call, kept with each example (`claude` for an agent that looked at the render); a person's by default. |
|
||||
| `--clearance` | `M` | `stage`: every run of frames where the camera is nearer a solid part than M metres (0.45 carried, 0.15 on a rig). |
|
||||
| `--clip` | `CLIP.json\|FOLDER` | `faults`: a character's motion (joints, fps, frames of root and turns) held to what a body does: buckles, skates, joints and fingers past their range, jolts, fingers through what the hand holds. A folder takes every .json in it. |
|
||||
| `--composition` | `ID` | Which composition to measure. `light` takes several, comma-separated, to compare the light across their cuts. |
|
||||
| `--dry` | – | With `faults --ask`: render and ring the pictures and say what would be asked, spending nothing. |
|
||||
| `--fine` | `KEY` | `faults`: keep a verdict that the finding with this key (printed after its line) is meant as it is, in the project's review/faults.labels.jsonl. With `--clip`: the motion finding's line for that check and joint (its key, such as skate:foot_l) rises to just above its size, for every run after (notice/motion.json in raea's models folder). May repeat. |
|
||||
| `--fine-from` | `N` | With `--fine` on motion findings: only findings of the key this size or bigger, in the finding's own units (degrees past the range for a finger or a joint limit). |
|
||||
| `--fine-upto` | `N` | With `--fine` on motion findings: only findings of the key this size or smaller (a pinky's small bends fine, its big one not). |
|
||||
| `--frame` | `N` | The frame to measure (0 by default; `light` also takes `last`). |
|
||||
| `--from` | `N` | With `stage` and `lod`: the first frame held to the checks (0 when left out). Every frame before it is still stepped, so a scene that builds over time is as it would render. |
|
||||
| `--json` | – | Print as JSON: `lint` its findings (check, level, the parts they are about, frames, says, measure, fix), `explain` every part with its support, gap and box, `lod` every part's row (planned, seen, largest, at, frames, closer), the plan's names no part goes by, and its findings. |
|
||||
| `--motion` | – | `faults`: the composition's characters (each `<Character>`'s joint parts, its skeleton.json beside its joint.glb) held to what a body does on every frame, as `--clip` does, and each finger bone tested against the scene's other parts: a thumb through a grip, or left off what the hand holds. Takes `--real`/`--fine KEY` as `--clip` does, and a finding the last run reported that's gone now (review/motion.last/) is kept as a real verdict: a fix teaches it. |
|
||||
| `--part` | `NAME` | With `light`: the part to meter, in place of the shot's subject. |
|
||||
| `--real` | `KEY` | `faults`: keep a verdict that the finding with this key is a real fault, in the project's review/faults.labels.jsonl. With `--clip`: that check's line for that joint falls to the finding's size. May repeat. |
|
||||
| `--real-from` | `N` | With `--real` on motion findings: only findings of the key this size or bigger. |
|
||||
| `--real-upto` | `N` | With `--real` on motion findings: only findings of the key this size or smaller. |
|
||||
| `--seed` | `N` | `faults`: plant N faults of known size in props that rest (sunk, lifted, in the air), lint again and say how many the judge calls faults among those plain to see, seen smaller, and hidden. With `--clip`: plant N of each motion fault (buckle, skate, jolt, limit, finger, through) in every clip and say how many are caught. Writes nothing. |
|
||||
| `--to` | `N` | With `stage` and `lod`: the last frame held to the checks (the composition's last when left out). |
|
||||
| `-o` | `DIR` | `export`: the folder scene.json is written to, with meshes/ and models/ beside it. |
|
||||
|
||||
|
||||
@@ -1,277 +0,0 @@
|
||||
@spec
|
||||
Feature: Notice: a 3D scene's faults judged as a viewer of the shot would see them, by a small model that learns
|
||||
Shane, 2026-11-27: "we often have props that clip into things or walls ... everything always clips, and then a vision
|
||||
model just never picks it up because it doesn't know the context." He asked whether a model could read a scene from
|
||||
its own 3D (its parts, their names, their geometry) and say what's wrong semantically (a cup not on its surface, a
|
||||
prop through a wall, two faces in one plane flickering like camo), and learn more of it over time, small and fast
|
||||
enough to run everywhere (Core ML). Motion too: knees buckling in a walk, fingers twisting round a grip, a thumb
|
||||
through a gun's handle, which no still shows.
|
||||
|
||||
What raea already had. The geometry checks were further along than the clipping suggests: `raea scene lint`
|
||||
(raea-sys-contact) finds floating, sunk, in-the-air and clipping parts from their real triangles, and z-fighting
|
||||
(core/zfight, MK8); the render's own clip check reports overlaps where the camera sees them; the motion lint
|
||||
(sdk/character lint.ts) finds jerks and knee buckles against the motion library's own range.
|
||||
|
||||
Why clipping still got through, measured 11-27 on room 106 of the Halcyon (approved that day): `raea scene lint`
|
||||
said 32 errors and 11 warnings. Most were a room's shell meeting itself where no camera can look (wall slabs into
|
||||
the ceiling slab, the carpet's edge under the walls), beside real ones (socks 3.4 mm over the carpet, a sun hat 4 mm
|
||||
over the table). A list where most errors don't matter gets skimmed, and the clip that shows goes with the rest.
|
||||
Every exception so far was a hand-set constant (SEATED, CARCASS, ENCLOSED, INSIDE ...), one per scene's new noise.
|
||||
So what was missing was judgment, not detection: is it seen, is it large enough on screen to read, and is it meant.
|
||||
|
||||
What others do (11-27 survey). No published system finds clipping from pixels: Holodeck, LayoutVLM, Scenethesis,
|
||||
PAT3D and phi-Scene all measure collisions, penetration depth and floating distance from geometry, and use a
|
||||
vision-language model only for intent, on marked-up renders. VLMs remain weak at physical plausibility, and a CVPR
|
||||
2026 study (the Motion Turing Test) found multimodal LLMs inadequate at judging motion. For motion the
|
||||
strongest result is a small learned critic: MotionCritic (ICLR 2025, a 3-layer DSTformer on SMPL joints) agrees with
|
||||
people's preferences 85% of the time where jerk, foot contact and penetration heuristics get 54-72%.
|
||||
|
||||
The model this file sets:
|
||||
1. Geometry finds every candidate (the lint, unchanged: make's gates read it as they did).
|
||||
2. Sight judges each one per shot: every frame's camera, the scene's real triangles in a BVH, whether the fault's
|
||||
spots are in frame, facing the camera and not behind any part, and how many pixels its gap, depth or patch
|
||||
covers (systems/notice sight.rs).
|
||||
3. A small model says how likely each is to read as a fault: logistic regression over 16 features (kind, seen,
|
||||
share of frames, log pixels, log millimetres, structural, soft, small) plus learned weights for the words of
|
||||
the parts' names keyed by kind ("air:map"), starting from a written prior (model.rs). It runs in microseconds;
|
||||
Core ML isn't needed for it. A model that needs one (the motion critic, NT11) runs on MLX or Core ML.
|
||||
4. It learns from verdicts kept beside each project: findings marked real or fine, and findings that went away
|
||||
because someone moved a part (labels.rs). `raea scene faults train` fits it to every project's verdicts.
|
||||
|
||||
Rule: Judging the lint's findings by sight (built: systems/notice, apps/scene faults.rs)
|
||||
|
||||
@done
|
||||
Scenario: NT1. Every frame's camera asked
|
||||
Given `raea scene faults EDIT.tsx [--composition ID] [--frame N]`
|
||||
Then the composition is stepped without drawing, the lint runs on frame N, and each fault it finds is judged
|
||||
over up to 48 frames' cameras spread over the shot
|
||||
And a finding's spots come from the lint: a z-fight's shared patches (core/zfight `spots`, each with the way
|
||||
its faces look and its area, the largest 32), a clip's seam, a gap's foot all round the part's base at the
|
||||
surface's height (drawn in 15% from its box's corners) and its nearest point
|
||||
And a spot shows on a frame when it is inside the frame, in front, nearer than the fog's far edge, facing the
|
||||
camera (a z-fight's faces) and no triangle of any part lies between it and the eye (3 mm off it first)
|
||||
|
||||
@done
|
||||
Scenario: NT2. Size on screen, not in the world
|
||||
Then a gap's or a depth's metres are turned into pixels at the depth it shows (focal x height / 2 / depth), and
|
||||
a z-fight's patches into the square root of the pixels they cover, summed over the spots that show
|
||||
And a 4 mm gap at 1.2 m is a fault and the same gap at 5 m is less sure (systems/notice tests.rs)
|
||||
|
||||
@done
|
||||
Scenario: NT3. The prior, written down
|
||||
Then before any verdict, a finding no camera sees scores 0.05, one seen on every frame at 3 px about 0.9;
|
||||
seated parts, a room's shell meeting itself, doubled faces inside one model and soft things weigh less, and
|
||||
a thing with weight in the air weighs more at any size
|
||||
And 0.5 or more is a fault: listed as FAULT, and `faults` exits 1 on any, as `lint` does on its errors
|
||||
And seen findings under 0.5 are listed as "maybe"; findings no camera sees are counted, not listed
|
||||
|
||||
Rule: Learning from verdicts (built: systems/notice labels.rs, model.rs)
|
||||
|
||||
@done
|
||||
Scenario: NT4. Marked real or fine
|
||||
Given a finding's key, printed after its line (`floats:r106_socks|r106_carpet`)
|
||||
Then `--real KEY` or `--fine KEY` (each may repeat) keeps a verdict in the project's review/faults.labels.jsonl
|
||||
with the finding's features and words as they were, so training never re-runs a scene
|
||||
|
||||
@done
|
||||
Scenario: NT5. A fix is a verdict
|
||||
Then each run keeps its findings in review/faults.last.json per shot, and a finding the last run said that is
|
||||
gone while both its parts are still in the scene is kept as real (by "fixed"): someone moved a part for it
|
||||
|
||||
@done
|
||||
Scenario: NT6. Training
|
||||
Given `raea scene faults train [FOLDER]`
|
||||
Then every review/faults.labels.jsonl under FOLDER (4 folders deep) is read, the newest verdict on each finding
|
||||
winning, and the model fitted: each weight held toward its prior and each word's toward nothing, so a few
|
||||
verdicts nudge it and many move it; it says how many verdicts the prior and the fitted judge agree with
|
||||
And the model is kept at raea's models folder notice/faults.json, which every run after loads
|
||||
(RAEA_NOTICE_MODEL names another file, for a trial fit kept apart)
|
||||
And three maps in the air marked fine and three mugs marked real teach it that an office's map in the air is
|
||||
fine and a mug in the air is not (tests.rs)
|
||||
|
||||
Scenario: NT7. Measured on room 106 and the office (2026-11-27)
|
||||
Then see "Results" below, filled in from the runs
|
||||
|
||||
@done
|
||||
Scenario: NT8. Faults of known size
|
||||
Given `raea scene faults EDIT.tsx --seed N`
|
||||
Then N props that rest as they should are each moved once (sunk 5-40 mm, lifted 2-30 mm, or lifted 8-30 cm into
|
||||
the air), the lint run again and the planted finding judged; it says how many the lint found, and how many the
|
||||
judge calls faults among those plain to see (2 px or more), those seen smaller, and those no camera sees
|
||||
And nothing is written: a planted fault's truth is its size, which the judge already reads
|
||||
And faults are planted only in props a camera of the shot sees (the top of the prop's box in view on some frame):
|
||||
on shot-window no resting prop is in view, so it plants none and says so
|
||||
|
||||
@done
|
||||
Scenario: NT8a. Lifted against a wall, found by what it is
|
||||
Given NT8 on shot-in, where `r106_lamp_b` lifted 7 mm to 27 cm read as mounted on the wall it touches (6 of 6
|
||||
lifts missed: the lint's mount test can't tell a lamp that stands from a sconce that hangs)
|
||||
Then the lint gives a mounted part's gap to what's under it (`gap`, `under`), and a mounted part more than 3 mm over
|
||||
it is a candidate whose size counts for nothing on screen (a picture hangs a metre up)
|
||||
And two features weigh it: mounted (prior -1.5) and mounted while named as a thing that stands (lamp, phone, cup,
|
||||
mug, glass, bottle, book, vase, plant, chair, table, clock, box, bag, case: prior +4.0)
|
||||
And a lamp lifted 27 cm against the wall scores 0.88 and a picture 1.2 m up scores 0.12 (tests.rs); verdicts move
|
||||
the words further ("mounted:sconce" fine)
|
||||
|
||||
Scenario: NT9. A render judges the lint's other faults at its end (@done 2026-11-27)
|
||||
Given a render's end checks (runtime/endchecks), which already follow parts clipping each other through every
|
||||
frame with the clipping check's own sight test
|
||||
Then the first frame's parts are linted but for clips (raea_sys_contact::lint_but_clips) and each floating, sunk,
|
||||
lifted or doubled-face finding judged through the render's own cameras (up to 48), and only the likely faults
|
||||
said, as warnings, with the chance and how large they show
|
||||
And RAEA_FAULTS_CHECK=0 leaves it out
|
||||
Measured: halcyon shot-bed, a 640x360 still of frame 30: the same one fault `raea scene faults` says there
|
||||
(r106_small_kit's doubled faces, 0.93, 6.3 px). It first added 30.6 s, nearly all the lint's older `touching`
|
||||
test (every axis-aligned ray against every nearby triangle); its rays now skip what their line can't meet (the
|
||||
part's box, then each side's candidate triangles once), the lint's output the same on the same scene (60 of 60
|
||||
findings, old binary against new), and the render's judged check takes 8.5 s, the lint 7.7 of it
|
||||
|
||||
Scenario: NT10. Faults that only show in motion (@done 2026-11-27, raea-sys-motionfaults)
|
||||
Given a clip: the skeleton's joints, fps, and each frame's root and turns (and what the hand holds, if anything)
|
||||
When `raea scene faults --clip CLIP.json|FOLDER` holds every frame to what a body does
|
||||
Then it says, each once per stretch of frames with its worst frame and size:
|
||||
| check | what |
|
||||
| buckle | a standing knee that gives (folds or snaps straight) 12° or more and back in 2 frames |
|
||||
| skate | a standing foot drifting 8 cm from where it stood down, or gliding along the ground |
|
||||
| limit | a joint 10° or more past raea-sys-body's anatomical range |
|
||||
| finger | a finger joint bent back, sideways or twisted 8° or more past its range (fingers.rs) |
|
||||
| jolt | a joint's turn changing 25°/frame² or more (at 30 fps), the root's 80 mm/frame² |
|
||||
| through | a finger, the thumb or the palm more than 4 mm inside what the hand holds |
|
||||
And the lines sit just above what clean capture does: 107 ACCAD takes retargeted onto the flannel body (12,472
|
||||
frames of walks, runs, turns, crouches, lifts), whose sharpest standing knee give is 9.4°, furthest standing
|
||||
foot drift 10.5 cm, worst jolt 34°/frame² but for a retarget's 168° forearm flip
|
||||
And `--seed N` plants N of each kind in every clip as an animation tool gets it wrong (plant.rs) and counts what's
|
||||
caught (results below)
|
||||
And it learns: each finding's key is its check and joint role (skate:foot_l); `--fine KEY` raises that key's
|
||||
line to just above the finding's size and `--real KEY` lowers it, kept in raea's models folder
|
||||
(notice/motion.json; verdicts.rs)
|
||||
And `--motion` reads them from a composition itself (apps/scene/src/chars.rs): each <Character>'s joint parts
|
||||
give every frame's pose exactly (rest frames are the world's), and each finger bone is tested as a segment
|
||||
against the scene's other parts' triangles
|
||||
Measured: projects/sheet3d compositions/take.tsx, teal over 1,470 frames: 268 findings, most fingers "bent back".
|
||||
At frame 1391 (the hand model driven to 2.5 on its first axis) the render shows the right hand's fingers kinked
|
||||
and knotted: real. A pinky 20-25° back through much of the take is unconfirmed at the shot's distance, and
|
||||
values hovering at a line split one stretch into many; verdicts (--fine finger:pinky_02_r) are for that
|
||||
And a grip check: while two or more fingertips rest on a surface, a finger or thumb tip 3 cm or more off any
|
||||
surface hasn't closed on what the hand holds
|
||||
Measured on a real fault: projects/gambit fp-lab-ladder, fixed in 68a505a ("the thumb not wrapping round what the
|
||||
hand holds"). Before the fix, on the grab posts (frames 155-273), thumb and index grip findings on both hands at
|
||||
51-54 and 42-46 mm (the commit measured 3.7 and 4.1 cm); after it, none there (thumb 22 mm at most, closed over
|
||||
the fingers). Renders agree: a loose claw beside the post, then fingers round it. The rung stretches (25-155),
|
||||
untouched by the fix, are flagged in both: from across the palm (fp-lab-ladder-wrap-r, frames 100 and 140) the
|
||||
thumb points straight up past the rung, not round it, the fault 68a505a fixed on the posts, so real; the index
|
||||
looks hooked over the rung where the check measures 41 mm, so it stays unconfirmed. Through findings came up only once every part counted (a mesh's place is often
|
||||
in its vertices, its transform at the origin)
|
||||
The grip rule is raea-sys-motionfaults grip::open and the distance raea-sys-notice Scene::reach, both tested
|
||||
(the ladder's frame 200 before and after the fix among them)
|
||||
And a fix teaches it: each `--motion` run keeps its findings (review/motion.last/<shot>.json), and one the last
|
||||
run reported that's gone now, the character and its frames the same, is kept as a real verdict at its size
|
||||
(raea-sys-motionfaults verdicts::fixed, tested). Run before and at 68a505a, the ladder lab's fix kept 29: the
|
||||
thumb and index left off the posts (43-54 mm), fingers through them, the index knuckle bent 35°; a rerun keeps 0
|
||||
And the pinky, looked at close (a scratch copy of take.tsx with its hand camera on pinky_02_r, frames 448 and
|
||||
1077): bent back 20-25° it reads relaxed, round the cup, so finger:pinky_02_l/r fine at 15 past the range; frame
|
||||
1391's 34°, in the hand that knots, still stands
|
||||
Still open: the skin against what the hand holds, not bone segments; stretches that hover at a line merged
|
||||
|
||||
Scenario: NT12. A vision model given the scene's context (@done 2026-11-27, apps/scene/src/ask.rs)
|
||||
When `raea scene faults EDIT.tsx --composition ID --ask N`
|
||||
Then each of the N likeliest faults is rendered on the frame it shows largest on, ringed (its spots' places on
|
||||
that camera, raea-sys-notice's sight), and `raea ask` (clef-omni, about $0.0001 a question) asked whether it's
|
||||
meant or a mistake, told the part, what it's against and what the geometry measured
|
||||
And an answer 0.7 sure or more is kept as a verdict, `by: "ask"`; a person's verdict on the same finding outranks
|
||||
it whatever their order (labels.rs, tested)
|
||||
Measured on room 106 (shot-window, -tv, -case, -in; 16 asked): sure and plausible on doubled faces (0.92-0.95),
|
||||
the floor clothes through each other (0.74-0.77), the floating sun hat (0.72), the hanging rail (0.88); unsure
|
||||
(0.52-0.68, not kept) on chair and table feet in carpet pile and a leg through a strap; and sure the draped map
|
||||
is a mistake (0.89), most likely led by the lint's own words ("in the air, touching nothing"), where a person's
|
||||
--fine is what settles it. Asked of the hat's clip with no context it said meant (0.59), with it mistake (0.72):
|
||||
the context moves the answer, for better where the geometry is right
|
||||
|
||||
Scenario: NT11. A motion critic of our own (@done 2026-11-27, raea-sys-motionfaults critic.rs)
|
||||
Given every motion verdict as an example: a fix that took a finding away (`fixed`), a look at the render
|
||||
(`--real`/`--fine`, `--by claude`), never a planted fault (it would learn the rules back)
|
||||
When `raea scene faults train` fits it: a logistic model over a finding's size against its check's scale and the
|
||||
words of what it is (its check, its joint's family, its key), the frames it lasts held at its prior for now
|
||||
Then a motion finding is said when a verdict called its key real at its size, or the verdicts' lines let it
|
||||
stand and the critic scores it 0.5 or more
|
||||
Measured (11-27): 50 examples on 22 keys, 37 real (29 from the ladder lab's fix, 9 rung thumbs and the knotted
|
||||
hand looked at) and 13 fine (the pinky's middle joint bent back 20-25°, both hands): the prior agreed with 37,
|
||||
the fitted critic with 49, and with 50 fitted each time without the key asked about. What it learns carries:
|
||||
the pinky's family word holds back small bends on joints never judged (tested). And it over-learns: the fine
|
||||
pinky bends pulled the 34° pinky in frame 1391's knotted hand under 0.5, so a verdict on the finding's own
|
||||
key at its size outranks it (tested); the frames weight had learned that long findings were fine only because
|
||||
the fine bends ran long, so it waits for far more verdicts
|
||||
|
||||
Results (the first verdicts both ways, 2026-11-27, each from a look at its ringed render): the draped map, chair
|
||||
and table feet 12 mm into the carpet, a chair leg over a bag strap, and the AC, curtain rod and sheers mounted on
|
||||
their walls are fine; the rail, cut off at its frame's edge, has none. With 9 vision-model rows and 2 fixes: 18,
|
||||
10 real and 8 fine, on 15 findings; the prior agreed with 13, the fitted judge with 17, and with 15 fitted each
|
||||
time without the finding asked about (held out; `train` reports it).
|
||||
The first fit, on 15 verdicts all real, had raised every weight toward "fault" (one-way verdicts carry no line), so
|
||||
verdicts all one way now teach only the words (model.rs, tested) and one already scored 0.9 its way stops teaching.
|
||||
The vision model called the draped map a mistake (0.89), led by the lint's "in the air, touching nothing"
|
||||
Then two more scenes (each call from a look at its render): halcyon's office (officelab office-counter: the desk
|
||||
kit's doubled faces real, two brochures in their rack fine) and five-to-a-corner's voxel kit (its 240 m ground plane
|
||||
"in the air" over a hidden plinth, fine). 22 verdicts on 18 findings from 2 projects, 11 real and 11 fine: the prior
|
||||
agreed with 16, the fitted judge with 21, and with 19 fitted each time without the finding asked about.
|
||||
Two scenes it couldn't judge: the motel's whole exterior block (motel.tsx block-wide) made no progress in 8 minutes,
|
||||
and a plain render of that view ran past 8 minutes too: the time is the block's own shapes being built
|
||||
(raea_core_shape, sampled), then the lint's rest test, not the judge; anchor-tenant's tvroom throws before its first frame
|
||||
Then six of gambit's interiors (drugstore, baker, grocer, butcher, bank, department store), each likely fault ringed
|
||||
on its render (`--ask N --dry`) and called from a look: 41 verdicts, 3 real (the grocer's till and coffee mill 30 mm
|
||||
over the counter, which show a dark slot under them; the drugstore's scale jammed into the till) and 38 fine (tills
|
||||
and cake cases 10 mm up, which read as seated at 3.4 m; a prop's own parts pressed into each other, like a barrel's
|
||||
lid, a sign's plate, a desk's top or meat on its tray; hanging lamps "in the air" on their rods; a dress form on its
|
||||
pole). The judge as it stood (22 verdicts, none from gambit) had called nearly all 41 faults, about 2 right: what
|
||||
it had learned from a motel didn't carry to a Berlin shop. Refitted on all 63 (14 real, 49 fine, 3 projects, 13
|
||||
shots), with each gambit shop left out and then judged: 34 of 41 right; every shot held out in turn, as `train`
|
||||
now reports it: 51 of 63 (the prior: 18). What it still gets wrong: floats by size (10 mm fine, 30 mm real, a 4 mm hat real;
|
||||
seven verdicts don't fix a line, and the word "till" learned "fine" from the tills' shared faces), and the
|
||||
drugstore's scale, whose seam is truly hidden (it enters the till's far face) though the jam shows. Tried in the
|
||||
replay and not kept, none beating the fit as it stands by more than a verdict: the gap alone for floats, sunk and
|
||||
clips; "a prop's own parts" from the words of both names; naming prefixes ("prop") dropped from the words.
|
||||
Motion on gambit's fp labs (takedown, sneak, crowd street, 11-27): 82-118 findings a shot. The four crowd walkers
|
||||
read cleanly (a wrist 14° past, knees 11-13°). The fp character's shins read 136-165° past their range, always
|
||||
as flex about 74° with a twist near 180°, alternating legs in step with its crouch walk, and each time its foot
|
||||
reads the opposite roll: a roll the solve puts on the shin and takes back at the foot. Rendered side and front,
|
||||
its knees bend forward and nothing shows. Not recorded as verdicts: a line or a critic example on limit:calf at
|
||||
that size would hide a knee broken backward on every other character. Fixed (legs.rs settled): a roll of 15° or
|
||||
more about a joint's own bone moves to its child when the two are then less past their ranges together; it moves
|
||||
no joint's place, and a roll nothing takes back stays (tested both ways). Only where the joint's other children
|
||||
sit on the bone's own line (a shin's twist joints): the first cut moved a hand's roll onto one finger, which moves
|
||||
the others and has no limits to show it, hid 77 of the crowd's wrists, and the fix-to-verdict path then kept every
|
||||
finding the change hid (44 shins and feet, 77 wrists) as a real fix. Those rows are removed, and a fix is now only
|
||||
read between runs of the same checks (motionfaults CHECKS, kept in motion.last). Limit findings: takedown 34 ->
|
||||
14, sneak 21 -> 6, the crowd's 79 unchanged, every hand finding kept; run twice, 0 fixes either time. The crowd's
|
||||
wrists 14° past (a 29° twist on 120 px walkers) are fine up to 15 (by claude): the critic's first fine examples
|
||||
off the pinky, 107 on 24 keys, 106 right with each key held out; the takedown's 126-138° wrists still stand. What's left can't be judged from these cameras:
|
||||
the takedown's knife wrist hidden behind the collar, the sentry's knees under his greatcoat as he falls.
|
||||
|
||||
Results (NT10, 2026-11-27: 107 ACCAD takes retargeted onto projects/sheet3d's flannel body, 12,472 frames):
|
||||
- Clean capture: 84 of 107 takes have no finding. Of the 23 flagged, the limits and jolts are mostly the retarget's
|
||||
own errors a viewer would see (a forearm twisted 168° in a frame, toes bent 50° back, a hand bent 74° sideways);
|
||||
the skates are feet dragged in crouches and a 6 s squat's slow drift, and 6 glides where an actor slides a foot
|
||||
(getting up from lying, a turn): arguable, the place verdicts would settle.
|
||||
- Planted, 2 of each kind in every take (1,051): through 214/214 (from 6 mm in), finger 214/214 (from 35°), jolt
|
||||
214/214 (from 20°), skate 103/103 (from 10 cm), limit 205/214 (every one past the 10° line; the 9 missed were
|
||||
8-10° past), buckle 89/92 (from 15°; 3 missed in long squatting stances, 18-22°).
|
||||
- First pass before the lines were set from capture: 105 of 107 takes flagged. The causes: a quaternion's sign
|
||||
flip read as a 360° jolt, stance from height alone (a running foot near the ground counted as standing), and any
|
||||
second knee bend in a stance called a buckle (a walk bends again before toe-off). Each is fixed and tested.
|
||||
|
||||
Results (NT7, the runs of 2026-11-27 on projects/halcyon-motel compositions/interiors.tsx, prior only):
|
||||
- Lint errors per room shot 30-31 (every shot alike); likely faults per shot after judging: in 5, bed 1, stand 0,
|
||||
case 3, tv 1, window 7, vanity 0, bath 0; office 2, bell 0, keys 0, clerk 2 (the office lints with 0 errors: its
|
||||
2 are visible doubled faces inside the counter and the desk kit, which the lint calls warnings).
|
||||
- Room 106: 60 distinct findings (31 of them mounted parts with a gap under them, none over 0.12) -> 12 judged a
|
||||
fault in some shot. Seen and plausibly real: floor clothes through each other (46 px), the vanity's and the
|
||||
suitcase's doubled faces, a chair leg 22 mm through a bag strap, a sun hat 4 mm over the table (3 px). Seen and
|
||||
likely fine, for verdicts to teach: the map draped over the dresser ("air"), chair and table feet 12 mm into the
|
||||
carpet ("seated").
|
||||
- NT8 on shot-in, 16 planted: the lint found 16 (after NT8a; 10 before it); judged faults 9/9 plain to see,
|
||||
6/6 seen under 2 px, 0/1 hidden (a 7 mm lamp lift whose spots sit inside its own base: 0.38).
|
||||
- The loop on live data: another session's edit took the magazine's 12 mm float away between runs; it was kept as
|
||||
fixed (real) in the two shots that show it, and train moved "floats:magazine" and the bed's words +0.05.
|
||||
The first rule also kept it for shots where it was hidden and for gaps that became mounts; both now ruled out.
|
||||
- Cost: a judged shot takes about 45 s on the room (stepping the shot and the lint; the judge itself is
|
||||
milliseconds); --seed relints once per planted fault (about 30 s each).
|
||||
@@ -0,0 +1,169 @@
|
||||
@spec
|
||||
Feature: Render memory: a realistic set renders well under 16 GB
|
||||
Shane, 2026-11-26, as memguard's 24 GB cap killed the halcyon reel's shots one after another: "why are those renders
|
||||
so big... how do we keep them down?". Shots of a realistic set ran at 20.5-22.7 GB all morning, with no single
|
||||
regression: any small addition tipped one over the cap.
|
||||
|
||||
Why: raea's brand is local work on consumer hardware, a 16 GB Mac first. A render that needs 24 GB can't run there at
|
||||
all, and on a 64 GB machine it leaves no room for a second job.
|
||||
|
||||
The model this file sets:
|
||||
1. Memory is cut at the cause: a copy nobody reads after it was made is not made, or is let go once read. Nothing
|
||||
here changes what a frame looks like: every step is checked frame for frame against the binary before it.
|
||||
2. Every step is measured on the same probe, the halcyon reel's shot r109 (a walkway, a door, a bicycle; no pool
|
||||
water), as a still (frame 106) and as a sequence, with tools/memprobe (macOS `footprint` by category) and raea's
|
||||
own marks (RAEA_MEM_MARKS), on a binary built from the same tree with and without the step.
|
||||
3. The measures stay: RAEA_MEM_MARKS prints each world's meshes and images with the bytes they hold on the CPU and
|
||||
on the GPU, so a copy that comes back shows up as a number, not as a killed render.
|
||||
|
||||
Background:
|
||||
Given the halcyon motel project (~/Documents/raea/raea/projects/halcyon-motel, compositions/reel.tsx, shot-r109)
|
||||
And tools/memprobe/memprobe.sh (a still) and memseq.sh (a sequence), run under antsy with --mem 20G
|
||||
And the numbers of 11-26 on the 11-25 binary: the still peaks at 14.9 GB (malloc large 6.4, malloc small 4.3,
|
||||
graphics 3.9); the sequence opens its 3D at 10.3 GB of graphics and is killed at 24-25 GB before frame 0
|
||||
|
||||
Rule: the bar
|
||||
The r109 sequence peaks under 16 GB of footprint and the still under 9 GB, with the same frames as before.
|
||||
|
||||
@done
|
||||
Scenario: RM0. Each world's assets after every mark
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-memtally | systems/memtally/src/lib.rs | 140 | after each mark (raea-render's `mem_mark`) one `mem_assets` line per App: its main world's meshes, images and storage buffers with their CPU bytes, its render world's meshes and images with their GPU bytes |
|
||||
When a render runs with RAEA_MEM_MARKS=1
|
||||
Then each mark is followed, at each App's next update, by "mem_assets app N main: meshes M (K on the CPU) X MB,
|
||||
images ... MB, buffers ... MB" and "mem_assets app N render: meshes M X MB, images M Y MB"
|
||||
And the Apps are numbered in the order they opened, so a sequence that holds two 3D worlds shows two
|
||||
|
||||
@needs:RM0 @done
|
||||
Scenario: RM1. Meshes and maps on the GPU only, once nothing on the CPU reads them
|
||||
Then a mesh raea builds (systems/mesh, its indexed buffers, meshseq) and a material's maps (systems/material maps.rs)
|
||||
keep no main-world copy after they are uploaded, where nothing in the main world reads them after: their bounds
|
||||
are taken at spawn, and picking, the end checks' clipping, raea-sys-contact, LOD and Solari's traced copy are
|
||||
each checked to read what they need first
|
||||
And Solari's traced copy of a mesh is made from the CPU copy before that copy is let go, or the mesh is built in
|
||||
Solari's layout from the start so one mesh serves both (engine/render/raytrace/src/solari.rs traceable)
|
||||
And the mem_assets lines show the main world's image bytes near zero once the scene has settled (r109: 19.5 MB,
|
||||
9 of 87 images, all of them pictures raea-sys-sampler and the page read back)
|
||||
And a mesh raea builds keeps its main-world copy, because main-world systems read meshes after their first frame:
|
||||
picking (runtime/input pick.rs), a render's layers (systems/frame layer.rs), toon hulls (systems/material
|
||||
toon.rs), the screen's UVs, sprite3d, and the GI lane's emitters and cells (systems/rt). What it keeps is welded
|
||||
(RM7): r109's 618 meshes on the CPU hold 198 MB, where the 11-25 build's held 1.38 GB. Solari's traced copy
|
||||
(traceable's Copy) is on the GPU only
|
||||
|
||||
@needs:RM0 @done
|
||||
Scenario: RM2. One 3D world at a time in a sequence
|
||||
Then a render never holds two 3D engines at once: where a camera in a page element makes the 3D's rows be stepped
|
||||
again (runtime/export render.rs, fed.rs), the first engine is let go before the second opens
|
||||
And the mem_assets lines of a sequence show one 3D App's render world at a time (r109's sequence: app 0 alone)
|
||||
|
||||
@needs:RM0
|
||||
Scenario: RM3. The growth while a frame settles
|
||||
Then the CPU heap's growth while a held frame settles (about 350 MB/s, still and sequence alike) is found and cut
|
||||
And the still's footprint after its frame is written is within 10% of its footprint after warm-up
|
||||
|
||||
@needs:RM0
|
||||
Scenario: RM4. A texture whose path changes each frame is let go
|
||||
Then a texture a frame names (halcyon's pool: water/n-NN.png, g-NN.jpg, 96 of each) is let go, CPU and GPU, once
|
||||
no part shows it, so a sequence holds the frames in view and not every frame it passed
|
||||
And a pool shot's sequence (its caustics) holds as many textures at its last frame as at its first
|
||||
|
||||
# 11-26, later: Shane widened the goal ("reduce rendering memory footprint as much as possible ... no boiling and
|
||||
# amazing rendering realism ... the fastest, best looking, most efficient rendering engine for gametime performance
|
||||
# and film rendering performance"), the halcyon motel as the benchmark. The scenarios below RM4 carry it on; each is
|
||||
# measured on the same probes, and none may move the look or add boiling (raea light steady under 1.5%).
|
||||
|
||||
Rule: the measured state, 11-26 (r109, 1080x1920)
|
||||
| build | still peak | sequence peak | main-world maps | main-world meshes |
|
||||
| 11-25 frozen | 14.9 GB | killed at 24-25 GB before frame 0 | 2.4 GB | 1.38 GB |
|
||||
| RM1 | 14.6 GB | 16.1 GB, all 107 frames written | 0.02 GB | 0.56 GB |
|
||||
| RM1+RM5+RM6 | | 11.4 GB; 93 images (was 277), GPU 3.7 GB (was 5.5) | 0.02 GB | |
|
||||
| + RM7 weld, shape text out of the store | | 10.2 GB (footprint 7.1 GB), 0 errors | 0.02 GB | 0.20 GB (618 of 1226 meshes) |
|
||||
| + RM8 kept buffers | | 8.8 GB (footprint 6.7 GB), 0 errors; shape text 11.8 MB (was 274) | 0.02 GB | 0.20 GB |
|
||||
| + RM9 BC7 maps | | 8.4 GB (footprint 5.7 GB), 0 errors; GPU images 282 MB (was 733) | 0.02 GB | 0.20 GB |
|
||||
| + RM10 contact solids | | 7.8 GB (footprint 5.5 GB), 0 errors, the same findings | 0.02 GB | 0.20 GB |
|
||||
The pool's caustics shot (196 frames), from before RM6 to the weld build: peak 18.8 GB to 9.9 GB, every 8th frame
|
||||
within run-to-run noise (pixels off by more than 2 levels 0.2-1.5%, by more than 16 at most 0.03%; this tree's
|
||||
noise between two runs of one binary is about 1%).
|
||||
The weld against RAEA_NO_WELD=1 on one binary (r109 f106): a frame held 96 frames (`raea light steady`) settles to
|
||||
the same picture either way (pixels off by more than 16 levels 0.008%), boiling 0.30% welded against 0.38%
|
||||
(worst tile 1.53% against 2.98%), and two runs of the welded build differ in 0.11% of pixels against 1.2%. In the
|
||||
shot's own render, one small emitter's wash (the room sconce's light on the wall, above and below its can) has
|
||||
built up less by f106 when welded: a difference in how fast it settles, not in where it settles.
|
||||
RM9 against RAEA_NO_BC=1 on one binary (r109 f106, caustics f60, the facade's 8776-wide wear maps and the pool's
|
||||
96 water normal maps among them): pixels off by more than 16 levels 0.057% and 0.097%, all of it the bicycle's
|
||||
sub-pixel spokes' glints and a chair's shadow edge on the deck; nothing on the facade or the water (two runs of
|
||||
either build: about 0.03%).
|
||||
Still held after the weld (before RM8): shape text 274 MB in 2,526 rows, 263 MB of it 88 BufferMesh shapes (the palms' vertex
|
||||
arrays as JSON, two of them 51 MB each), half of it the same text in another row (RM8).
|
||||
|
||||
@needs:RM1 @done
|
||||
Scenario: RM5. The CPU heap, named by who holds it
|
||||
Then a still's live heap after warm-up is attributed by call tree (macOS malloc stack logging, malloc_history
|
||||
-callTree; tools/memprobe/heapwho.sh) to the crate that allocated it, and each holder over 250 MB is either cut,
|
||||
let go once read, or written here with why it stays
|
||||
And the shape cache (raea-core-shape `cached`, `solid`), the React world, wgpu's staging and the end checks' solids
|
||||
are each given a number
|
||||
And after RM5 to RM10 (tools/memprobe/heapseq.sh, r109's sequence mid-render; holders.py) what is over 250 MB stays
|
||||
for a reason: MetalFX's denoising scaler 317 MB (Apple's framework, made once a view, the denoiser's own
|
||||
working memory); JavaScriptCore's heap 300 MB in a still, up to 870 MB mid-sequence (the composition's live
|
||||
objects; collecting after every frame, RAEA_JSC_EDEN=1, frees the small heap later but not the peak); the
|
||||
contact check's solids 366 MB (RM10, every part in view the whole shot); wgpu's Metal command encoding
|
||||
250-360 MB in the first frames (inside wgpu-hal). Gone from the list: Manifold's solids (2.4 GB, RM5's cache),
|
||||
the shape text (977 MB of clones, RM8 and the store), the names cache (297 MB, RM8)
|
||||
|
||||
@needs:RM4
|
||||
Scenario: RM6. A picture sequence is one texture, streamed
|
||||
Then a map whose picture changes each frame (a water normal map, a caustic) is one GPU texture written each frame
|
||||
from the frame's file (decoded ahead on a thread), not one texture per picture made at load
|
||||
And a pool shot's sequence holds one texture per such map, its GPU bytes flat from its first frame to its last
|
||||
|
||||
@needs:RM1 @done
|
||||
Scenario: RM7. A mesh as few vertices as its corners need
|
||||
Then a Manifold shape's mesh is indexed (U32) and welded where corners share a place and a normal exactly
|
||||
(systems/mesh welded): halcyon's shapes had 4.65 corners to each vertex, so the raster mesh, its main-world copy
|
||||
and Solari's traced copy are each about a third of what they were (r109's main-world meshes 0.56 GB to 0.20 GB)
|
||||
And a shape with its own UVs or colours a corner (a <BufferMesh>) is left as it is; RAEA_NO_WELD=1 is the control
|
||||
And a frame held 96 frames settles to the same picture welded or not, with no more boiling (numbers above)
|
||||
And it is not built in Solari's layout to spare the traced copy: the main-world copy stays (RM1's readers), so
|
||||
the layout's tangents and colours would make every vertex 64 bytes on the CPU and the GPU, where today it is 32
|
||||
on the CPU and 32 + 64 on the GPU: bytes moved from the GPU to the CPU, not saved
|
||||
|
||||
@needs:RM7 @done
|
||||
Scenario: RM8. A long BufferMesh is held as a name, its text kept on disk by its content
|
||||
Given a <BufferMesh> whose shape text is 64 KB or longer (raea-core-shape KEEP_BUFFER_AT)
|
||||
Then the React read (runtime/react read.rs names3d) writes its JSON once to raea's caches (buffers/NAME.json, NAME
|
||||
its BLAKE3) and passes `buffer:@NAME` on, so the scene, every frame's row, the store and the evaluator hold 40
|
||||
characters, not the vertex arrays
|
||||
And the part is known again each frame by the text's length and xxh3 without naming it again
|
||||
And every reader of a buffer shape (raea-sys-mesh shape_mesh, the three shader's fit, interchange's export) reads
|
||||
the kept file through raea_core_shape::buffer_json, so what is drawn and exported is the same
|
||||
|
||||
@needs:RM1 @done
|
||||
Scenario: RM9. A material's maps are block-compressed on the GPU
|
||||
Given a device that samples BC textures (wgpu TEXTURE_COMPRESSION_BC: Apple silicon and Intel Macs, and desktop
|
||||
GPUs on Windows and Linux)
|
||||
Then every map raea-sys-material makes (map_image: colour as BC7 sRGB, normal, metallic-roughness, occlusion and
|
||||
emissive as BC7 linear) is BC7 with its whole mip chain, 16 bytes for each 4x4 texels, a quarter of RGBA8's
|
||||
And the blocks are encoded once (intel_tex_2's ISPC kernels, on every core) and kept in raea's caches by the
|
||||
picture's content (maps/NAME.bc7), so a later run reads them and makes no mips
|
||||
And a map whose side isn't a multiple of 4, a device without BC, or RAEA_NO_BC=1 is RGBA8 as before
|
||||
And BC7 keeps all four channels, so Bevy's and Solari's shaders read every map as they did
|
||||
|
||||
@done
|
||||
Scenario: RM10. The contact check's solids hold what it reads
|
||||
Given a sequence's parts are checked for clipping as its frames come (raea-sys-contact), every part in view held
|
||||
as a solid until the end checks let them go: in r109, 603 MB of depth grids, 368 MB of inside-cell lists and 301
|
||||
MB of surface points (the heap's biggest holder mid-render, by malloc stack logging)
|
||||
Then a cell's depth is a byte (at most half a grid's side; held at 255 past it), the inside cells are a count
|
||||
(the check reads only how many), and the surface points are three u16s across the part's box with no spare
|
||||
capacity: about 366 MB where there were 1,272, the findings the same (the crate's 18 tests)
|
||||
|
||||
Still open (11-26): a transient 1 GB of heap inside the first frame (after "resources prepared", gone within 10 s)
|
||||
sets the warm sequence's footprint peak (6.5 GB at about 49 s); JavaScriptCore collecting after every frame
|
||||
(RAEA_JSC_EDEN=1, RAEA_JSC_RELEASE_S=1) flattens the small heap later (990 to 330 MB) but not that peak. The GPU's
|
||||
2.6 GB: 282 MB of images, 455 MB of meshes, the rest Solari's and the views' own buffers and MetalFX.
|
||||
|
||||
Rule: speed and quality are measured beside memory
|
||||
Each step reports, on the r109 still and sequence: peak footprint, seconds per frame once warm, and `raea light
|
||||
steady` boiling at a held frame. A step that cuts memory and costs time or adds boiling is not done.
|
||||
@@ -17,8 +17,6 @@ raea-sys-hold = { path = "../../systems/hold" }
|
||||
# the passes, each a crate of its own (systems/)
|
||||
raea-sys-splat = { path = "../../systems/splat" }
|
||||
raea-sys-sprite = { path = "../../systems/sprite" }
|
||||
raea-sys-rt = { path = "../../systems/rt" }
|
||||
raea-sys-gi = { path = "../../systems/gi" }
|
||||
# soft shadows (experimental_pbr_pcss) are under the native feature with raea-runtime-scene3d/pcss: WebGPU refuses their sampling
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
|
||||
@@ -38,27 +36,22 @@ raea-sys-matchmove = { path = "../../systems/matchmove" }
|
||||
raea-sys-grid = { path = "../../systems/grid" }
|
||||
# the view a camera on the Engine's target draws: the frame above its tag row, or a page's box (#130)
|
||||
raea-sys-viewbox = { path = "../../systems/viewbox" }
|
||||
raea-sys-rendermap = { path = "../../systems/rendermap" }
|
||||
raea-sys-meshseq = { path = "../../systems/meshseq" }
|
||||
raea-sys-environment = { path = "../../systems/environment" }
|
||||
raea-sys-look = { path = "../../systems/look" }
|
||||
raea-sys-compose = { path = "../../systems/compose" }
|
||||
raea-sys-material = { path = "../../systems/material" }
|
||||
raea-sys-framepass = { path = "../../systems/framepass" }
|
||||
raea-sys-compute = { path = "../../systems/compute" }
|
||||
raea-sys-phase = { path = "../../systems/phase" }
|
||||
raea-sys-sampler = { path = "../../systems/sampler" }
|
||||
raea-sys-parity = { path = "../../systems/parity" }
|
||||
raea-sys-toon = { path = "../../systems/toon" }
|
||||
# raea's modules as Bevy plugins (RaeaPlugins), a crate of their own
|
||||
raea-render-plugins = { path = "plugins" }
|
||||
raea-sys-memtally = { path = "../../systems/memtally" }
|
||||
raea-sys-shader = { path = "../../systems/shader" }
|
||||
# three.js's shaders: a ShaderMaterial's GLSL and a node material's WGSL (docs/r3f.feature R3F11)
|
||||
raea-sys-three-shader = { path = "../../systems/three-shader" }
|
||||
raea-sys-post = { path = "../../systems/post" }
|
||||
raea-sys-fog = { path = "../../systems/fog" }
|
||||
raea-sys-fog-half = { path = "../../systems/fog-half" }
|
||||
raea-sys-volume = { path = "../../systems/volume" }
|
||||
# a field of grass made in tiles by distance (<Grass>)
|
||||
raea-sys-grass = { path = "../../systems/grass" }
|
||||
raea-sys-lod = { path = "../../systems/lod" }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
# the direct render's views, the 2D rows, clips' masks and the paint device (runtime/view)
|
||||
raea-runtime-view = { path = "../../runtime/view", optional = true }
|
||||
@@ -104,8 +97,3 @@ network = ["native"]
|
||||
bevy-all = ["bevy/bevy_gilrs", "bevy/gamepad", "bevy/area_light_luts", "bevy/experimental_pbr_pcss", "bevy/dfg_lut", "bevy/smaa_luts", "bevy/tonemapping_luts", "bevy/bluenoise_texture", "bevy/bevy_gizmos", "bevy/bevy_gizmos_render", "bevy/bevy_dev_tools", "bevy/debug", "bevy/bevy_ui_debug", "bevy/file_watcher", "bevy/embedded_watcher", "bevy/asset_processor", "bevy/png", "bevy/jpeg", "bevy/ktx2", "bevy/zstd_rust", "bevy/basis-universal", "bevy/exr", "bevy/hdr", "bevy/webp", "bevy/dds", "bevy/tga", "bevy/bmp", "bevy/gif", "bevy/ico", "bevy/qoi", "bevy/pnm", "bevy/tiff", "bevy/picking", "bevy/bevy_picking", "bevy/mesh_picking", "bevy/sprite_picking", "bevy/ui_picking", "bevy/meshlet", "bevy/meshlet_processor", "bevy/bevy_solari", "bevy/bevy_animation", "bevy/gltf_animation", "bevy/morph", "bevy/morph_animation", "bevy/bevy_gltf", "bevy/bevy_sprite", "bevy/bevy_sprite_render", "bevy/2d_bevy_render", "bevy/3d_bevy_render", "bevy/ui_bevy_render", "bevy/bevy_ui_widgets", "bevy/bevy_feathers", "bevy/custom_cursor", "bevy/bevy_input_focus", "bevy/bevy_camera_controller", "bevy/free_camera", "bevy/pan_camera", "bevy/bevy_text", "bevy/system_font_discovery", "bevy/scene", "bevy/bevy_state", "bevy/serialize", "bevy/reflect_functions", "bevy/reflect_documentation", "bevy/sysinfo_plugin", "bevy/bevy_clipboard", "bevy/system_clipboard", "bevy/clipboard_image", "bevy/ghost_nodes", "bevy/bevy_settings", "bevy/shader_format_spirv", "bevy/bevy_debug_stepping", "bevy/bevy_world_serialization", "bevy/bevy_audio", "bevy/mp3", "bevy/flac", "bevy/vorbis", "bevy/wav", "bevy/aac", "bevy/mp4", "bevy/http", "bevy/https", "bevy/web_asset_cache", "bevy/bevy_curve", "bevy/complex_script_segmentation", "bevy/compressed_image_saver_universal", "bevy/pan_orbit_camera", "bevy/pan_orbit_gizmo", "bevy/render_dev_tools"]
|
||||
# per-system spans as a chrome trace (RUST_LOG=info, trace-*.json in the working directory)
|
||||
trace = ["bevy/trace", "bevy/trace_chrome"]
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
# raea-core-shape is unused since a mesh row's shape went to raea_sys_material::mesh::shape_mesh. Its line sits beside
|
||||
# an unlanded branch's (scene-loop: raea-sys-procmat), so it goes, with this table, once that branch lands
|
||||
ignored = ["raea-core-shape"]
|
||||
@@ -0,0 +1,42 @@
|
||||
[package]
|
||||
name = "raea-render-plugins"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea's Engine as Bevy plugins (docs/sdk.feature S6a): RaeaPlugins, each module's install as a Plugin in Engine::new's order, so any Bevy App can draw raea's looks"
|
||||
|
||||
[dependencies]
|
||||
raea-core-program = { path = "../../../core/program" }
|
||||
raea-runtime-plugins = { path = "../../../runtime/plugins" }
|
||||
raea-runtime-scene3d = { path = "../../../runtime/scene3d" }
|
||||
raea-sys-compose = { path = "../../../systems/compose" }
|
||||
raea-sys-environment = { path = "../../../systems/environment" }
|
||||
raea-sys-fog = { path = "../../../systems/fog" }
|
||||
raea-sys-fog-half = { path = "../../../systems/fog-half" }
|
||||
raea-sys-frame = { path = "../../../systems/frame" }
|
||||
raea-sys-grid = { path = "../../../systems/grid" }
|
||||
raea-sys-look = { path = "../../../systems/look" }
|
||||
raea-sys-material = { path = "../../../systems/material" }
|
||||
raea-sys-meshseq = { path = "../../../systems/meshseq" }
|
||||
raea-sys-post = { path = "../../../systems/post" }
|
||||
raea-sys-screen = { path = "../../../systems/screen" }
|
||||
raea-sys-shader = { path = "../../../systems/shader" }
|
||||
raea-sys-splat = { path = "../../../systems/splat" }
|
||||
raea-sys-sprite = { path = "../../../systems/sprite" }
|
||||
raea-sys-text3d = { path = "../../../systems/text3d" }
|
||||
raea-sys-toon = { path = "../../../systems/toon" }
|
||||
raea-sys-volume = { path = "../../../systems/volume" }
|
||||
raea-sys-procmat = { path = "../../../systems/procmat" }
|
||||
raea-sys-rt = { path = "../../../systems/rt" }
|
||||
raea-sys-gi = { path = "../../../systems/gi" }
|
||||
raea-sys-grass = { path = "../../../systems/grass" }
|
||||
raea-sys-lod = { path = "../../../systems/lod" }
|
||||
raea-sys-three-shader = { path = "../../../systems/three-shader" }
|
||||
raea-sys-framepass = { path = "../../../systems/framepass" }
|
||||
raea-sys-compute = { path = "../../../systems/compute" }
|
||||
raea-sys-phase = { path = "../../../systems/phase" }
|
||||
raea-sys-parity = { path = "../../../systems/parity" }
|
||||
raea-sys-rendermap = { path = "../../../systems/rendermap" }
|
||||
raea-sys-sampler = { path = "../../../systems/sampler" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
|
||||
@@ -14,6 +14,27 @@ use bevy::prelude::*;
|
||||
// the frame's system sets, raea-sys-frame's: a plugin orders its systems by them
|
||||
pub use raea_sys_frame::{FrameSystems, Scene3dSystems};
|
||||
|
||||
// raea's modules, by the names Engine::new installs them under (raea-render's engine.rs)
|
||||
use raea_runtime_plugins as plugins;
|
||||
use raea_runtime_scene3d as scene3d;
|
||||
use raea_sys_compose::{compose, passes};
|
||||
use raea_sys_environment as environment;
|
||||
use raea_sys_fog::{fire, froxel, froxel_glass};
|
||||
use raea_sys_fog_half as fog_half;
|
||||
use raea_sys_frame::bevy_api;
|
||||
use raea_sys_grid as grid;
|
||||
use raea_sys_look::{look, paint};
|
||||
use raea_sys_material::{decal, shadow_catch, shadow_only};
|
||||
use raea_sys_meshseq as meshseq;
|
||||
use raea_sys_post::{cut, dof, effect_stack, lens, motion_blur, outline};
|
||||
use raea_sys_screen as screen;
|
||||
use raea_sys_shader as shader_ext;
|
||||
use raea_sys_splat as splat;
|
||||
use raea_sys_sprite as sprite2d;
|
||||
use raea_sys_text3d as text3d;
|
||||
use raea_sys_toon as toon;
|
||||
use raea_sys_volume as volume;
|
||||
|
||||
macro_rules! raea_plugin {
|
||||
($($name:ident: $install:path, $doc:literal;)*) => {
|
||||
$(
|
||||
@@ -37,46 +58,46 @@ macro_rules! raea_plugin {
|
||||
}
|
||||
|
||||
raea_plugin! {
|
||||
VolumetricFogPlugin: super::scene3d::install_fog_shader, "Volumetric fog's shader, its dither seeded from the film frame (scene3d.rs).";
|
||||
DepthOfFieldPlugin: super::dof::install, "Bevy's depth of field, keeping the frame's alpha (dof.rs).";
|
||||
EffectStackPlugin: super::effect_stack::install, "The effect stack (a <Grade>'s aberration and vignette), keeping alpha (effect_stack.rs).";
|
||||
Bevy019DefaultsPlugin: super::bevy_api::install_0_19_defaults, "Bevy 0.19's tone curve \"none\" and screen-space transmission, which 0.20 changed (bevy_api.rs).";
|
||||
HalfFogPlugin: super::fog_half::install, "Volumetric fog at a fraction of the frame's resolution, upsampled by depth (fog_half.rs).";
|
||||
EnvironmentPlugin: super::environment::install, "Each panorama's light filtered once (environment.rs).";
|
||||
FroxelFogPlugin: super::froxel::install, "Fog as one medium in a grid along the view (froxel.rs).";
|
||||
FroxelGlassPlugin: super::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
|
||||
LookPlugin: super::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
|
||||
OutlinePlugin: super::outline::install, "Ink outlines (outline.rs).";
|
||||
VolumetricFogPlugin: crate::scene3d::install_fog_shader, "Volumetric fog's shader, its dither seeded from the film frame (scene3d.rs).";
|
||||
DepthOfFieldPlugin: crate::dof::install, "Bevy's depth of field, keeping the frame's alpha (dof.rs).";
|
||||
EffectStackPlugin: crate::effect_stack::install, "The effect stack (a <Grade>'s aberration and vignette), keeping alpha (effect_stack.rs).";
|
||||
Bevy019DefaultsPlugin: crate::bevy_api::install_0_19_defaults, "Bevy 0.19's tone curve \"none\" and screen-space transmission, which 0.20 changed (bevy_api.rs).";
|
||||
HalfFogPlugin: crate::fog_half::install, "Volumetric fog at a fraction of the frame's resolution, upsampled by depth (fog_half.rs).";
|
||||
EnvironmentPlugin: crate::environment::install, "Each panorama's light filtered once (environment.rs).";
|
||||
FroxelFogPlugin: crate::froxel::install, "Fog as one medium in a grid along the view (froxel.rs).";
|
||||
FroxelGlassPlugin: crate::froxel_glass::install, "Glass seen through froxel fog (froxel_glass.rs).";
|
||||
LookPlugin: crate::look::install, "Models drawn as pixel art or the site's grain (look.rs).";
|
||||
OutlinePlugin: crate::outline::install, "Ink outlines (outline.rs).";
|
||||
SteadyPlugin: raea_sys_post::steady::install, "raea's temporal filter: each frame jittered and blended with those before it (raea-sys-post steady.rs, docs/realism.feature LT12).";
|
||||
ComposePlugin: super::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
|
||||
Text3dPlugin: super::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
|
||||
FirePlugin: super::fire::install, "Flames drawn as volumes (fire.rs).";
|
||||
SplatPlugin: super::splat::install, "Gaussian splats, sorted per frame for the scene camera (raea-sys-splat).";
|
||||
MeshSequencePlugin: super::meshseq::install, "Mesh sequences by the frame, glitches on parts (meshseq.rs).";
|
||||
ComposePlugin: crate::compose::install, "Composition passes: each object's pass mask, read by Look, Outline, Bloom and Grade (compose.rs).";
|
||||
Text3dPlugin: crate::text3d::install, "Text in the 3D world: bevy_rich_text3d and its faces (raea-sys-text3d).";
|
||||
FirePlugin: crate::fire::install, "Flames drawn as volumes (fire.rs).";
|
||||
SplatPlugin: crate::splat::install, "Gaussian splats, sorted per frame for the scene camera (raea-sys-splat).";
|
||||
MeshSequencePlugin: crate::meshseq::install, "Mesh sequences by the frame, glitches on parts (meshseq.rs).";
|
||||
Draws2dPlugin: raea_sys_sprite::install, "Plugins' 2D drawing brings up the scene's 2D camera (raea-sys-sprite's Draws2d).";
|
||||
ScreenPlugin: super::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs).";
|
||||
GridPlugin: super::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs).";
|
||||
ScreenPlugin: crate::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs).";
|
||||
GridPlugin: crate::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs).";
|
||||
ProcMatPlugin: raea_sys_procmat::install, "Procedural surfaces: wood, stone, brick, tiles and the rest, with dust and dirt (systems/procmat).";
|
||||
PaintPlugin: super::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";
|
||||
PassesPlugin: super::passes::install, "Render passes per view (passes.rs).";
|
||||
PaintPlugin: crate::paint::install, "The paint and cartoon looks' surfaces (paint.rs).";
|
||||
PassesPlugin: crate::passes::install, "Render passes per view (passes.rs).";
|
||||
TracedAoPlugin: raea_sys_rt::passes, "Traced passes: ambient occlusion, raealism's world probes and the sun's far shadow map (raea-sys-rt).";
|
||||
GiScreenPlugin: raea_sys_gi::install, "raealism's light on screen: each pixel's indirect diffuse from the world cache, read by the main pass (raea-sys-gi, RAEA_GI=1).";
|
||||
VolumePlugin: super::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
|
||||
VolumePlugin: crate::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
|
||||
GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";
|
||||
DetailPlugin: raea_sys_lod::install, "Where each part is drawn: levels by distance or size on screen, cross-faded, draw distance and shadows left to a coarser level (raea-sys-lod, docs/realism.feature LT21).";
|
||||
ShadowOnlyPlugin: super::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
|
||||
ShadowCatchPlugin: super::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";
|
||||
ShadowOnlyPlugin: crate::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
|
||||
ShadowCatchPlugin: crate::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";
|
||||
TintPlugin: raea_sys_material::tint::install, "A colour a copy over an <Instances>' surface, three's instanceColor (tint.rs).";
|
||||
ToonPlugin: super::toon::install, "The toon surface and its ink outline's materials (toon.rs).";
|
||||
ShaderExtPlugin: super::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";
|
||||
ToonPlugin: crate::toon::install, "The toon surface and its ink outline's materials (toon.rs).";
|
||||
ShaderExtPlugin: crate::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";
|
||||
ThreeShaderPlugin: raea_sys_three_shader::install, "three.js's shaders: a ShaderMaterial's GLSL (naga) and a node material's WGSL, with three's built-ins (raea-sys-three-shader).";
|
||||
FramePassPlugin: raea_sys_framepass::install, "Full-screen passes written in TypeScript (raea-sys-framepass).";
|
||||
ComputePlugin: raea_sys_compute::install, "Compute shaders written in TypeScript, run before the cameras draw (raea-sys-compute).";
|
||||
PhaseItemPlugin: raea_sys_phase::install, "Your own draws in a camera's opaque phase, as Bevy's custom_phase_item queues one (raea-sys-phase).";
|
||||
LensPlugin: super::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";
|
||||
LensPlugin: crate::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";
|
||||
ParityPlugin: raea_sys_parity::install, "The parity probe: a frame's cost and World, written when RAEA_PARITY is set (raea-sys-parity, docs/control.feature FC0a).";
|
||||
CameraCutPlugin: super::cut::install, "A camera that jumps is a cut: its history starts again and its motion blur waits (cut.rs, RT31).";
|
||||
MotionBlurPlugin: super::motion_blur::install, "Motion blur's frame counter pinned to the frame (motion_blur.rs).";
|
||||
CameraCutPlugin: crate::cut::install, "A camera that jumps is a cut: its history starts again and its motion blur waits (cut.rs, RT31).";
|
||||
MotionBlurPlugin: crate::motion_blur::install, "Motion blur's frame counter pinned to the frame (motion_blur.rs).";
|
||||
}
|
||||
|
||||
/// The frame's state that raea's plugins' systems read (the clock, the frame's rows, the loaded edit, the error), empty
|
||||
@@ -86,11 +107,11 @@ pub struct FramePlugin;
|
||||
|
||||
impl Plugin for FramePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<super::Clock>().init_resource::<super::Error>().init_resource::<super::FrameRows>();
|
||||
if !app.world().contains_resource::<super::Edit>() {
|
||||
app.init_resource::<raea_sys_frame::Clock>().init_resource::<raea_sys_frame::Error>().init_resource::<raea_sys_frame::FrameRows>();
|
||||
if !app.world().contains_resource::<raea_sys_frame::Edit>() {
|
||||
let prog = raea_core_program::ir::Program::default();
|
||||
let timeline = raea_core_program::timeline::Timeline::new(&prog, &[]).expect("an empty timeline");
|
||||
app.insert_resource(super::Edit { prog, timeline: std::sync::Arc::new(timeline), media: Vec::new() });
|
||||
app.insert_resource(raea_sys_frame::Edit { prog, timeline: std::sync::Arc::new(timeline), media: Vec::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,7 +123,7 @@ pub struct RegisteredPlugins {
|
||||
|
||||
impl Plugin for RegisteredPlugins {
|
||||
fn build(&self, app: &mut App) {
|
||||
super::plugins::install(app, self.fps);
|
||||
crate::plugins::install(app, self.fps);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,14 +132,14 @@ impl Plugin for RegisteredPlugins {
|
||||
pub fn scene3d_systems() -> ScheduleConfigs<ScheduleSystem> {
|
||||
(
|
||||
// 2D over the 3D: its camera once there's a part, then each part's place, cell and colour (raea-sys-sprite)
|
||||
(super::sprite2d::camera_2d, super::sprite2d::sync_2d).chain(),
|
||||
super::scene3d::model_setup,
|
||||
super::scene3d::instance_models,
|
||||
super::scene3d::model_shadow_markers,
|
||||
super::scene3d::toon_models,
|
||||
((super::scene3d::sync_meshes, super::scene3d::sync_instances, super::scene3d::sync_pictures, raea_sys_rendermap::sync_render_maps, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, (super::scene3d::sync_camera, super::scene3d::sync_post).chain(), super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered, super::environment::sync_suns).chain(), (super::scene3d::sync_light_sets, super::scene3d::sync_lights).chain(), super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),
|
||||
(crate::sprite2d::camera_2d, crate::sprite2d::sync_2d).chain(),
|
||||
crate::scene3d::model_setup,
|
||||
crate::scene3d::instance_models,
|
||||
crate::scene3d::model_shadow_markers,
|
||||
crate::scene3d::toon_models,
|
||||
((crate::scene3d::sync_meshes, crate::scene3d::sync_instances, crate::scene3d::sync_pictures, raea_sys_rendermap::sync_render_maps, raea_sys_material::swapped::sync_swapped_maps, crate::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), crate::toon::sync_toon, (crate::scene3d::sync_camera, crate::scene3d::sync_post).chain(), crate::motion_blur::sync_motion_blur, (crate::environment::sync_environment, crate::environment::sync_prefiltered, crate::environment::sync_suns).chain(), (crate::scene3d::sync_light_sets, crate::scene3d::sync_lights).chain(), crate::scene3d::sync_fog_volumes, crate::scene3d::sync_fog_dither, crate::scene3d::sync_models, crate::scene3d::sync_morphs, crate::scene3d::sync_attach, crate::grid::grid_models, crate::scene3d::sync_bones, crate::look::sync_frame_look, crate::look::sync_looks, crate::compose::sync_passes, crate::look::sync_flat, crate::paint::sync_paint, crate::decal::sync_decals, crate::text3d::sync_texts).chain(),
|
||||
// --clay and --review's clay half: every standard surface grey, after the rows set their colours
|
||||
super::scene3d::clay::clay_materials,
|
||||
crate::scene3d::clay::clay_materials,
|
||||
)
|
||||
.chain()
|
||||
}
|
||||
@@ -149,8 +170,8 @@ mod tests {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(FramePlugin);
|
||||
let w = app.world();
|
||||
assert!(w.contains_resource::<super::super::Clock>() && w.contains_resource::<super::super::Error>());
|
||||
assert!(w.contains_resource::<super::super::FrameRows>() && w.contains_resource::<super::super::Edit>());
|
||||
assert!(w.contains_resource::<raea_sys_frame::Clock>() && w.contains_resource::<raea_sys_frame::Error>());
|
||||
assert!(w.contains_resource::<raea_sys_frame::FrameRows>() && w.contains_resource::<raea_sys_frame::Edit>());
|
||||
assert!(RaeaPlugins.build().enabled::<FramePlugin>());
|
||||
}
|
||||
|
||||
@@ -347,7 +347,12 @@ fn traceable(src: &Mesh, mapped: bool) -> Option<Traceable> {
|
||||
let n = pos.len();
|
||||
let normal = src.attribute(Mesh::ATTRIBUTE_NORMAL)?.clone();
|
||||
let uv = src.attribute(Mesh::ATTRIBUTE_UV_0).cloned().unwrap_or(VertexAttributeValues::Float32x2(vec![[0.0, 0.0]; n]));
|
||||
let mut out = Mesh::new(PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());
|
||||
// RM1 (docs/render-memory.feature): the GPU's copy alone. Solari builds its BLAS from the render world's mesh
|
||||
// (blas.rs: RenderMesh, MeshAllocator) and nothing on the CPU reads this copy once it's made (its tangents are
|
||||
// made below, before it's added); kept in the main world too, every traced part was held twice there
|
||||
// (RAEA_KEEP_CPU_ASSETS=1 keeps it in the main world too: the A/B control)
|
||||
let usage = if std::env::var_os("RAEA_KEEP_CPU_ASSETS").is_some() { bevy::asset::RenderAssetUsages::default() } else { bevy::asset::RenderAssetUsages::RENDER_WORLD };
|
||||
let mut out = Mesh::new(PrimitiveTopology::TriangleList, usage);
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos);
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normal);
|
||||
out.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);
|
||||
|
||||
+13
-20
@@ -47,16 +47,9 @@ pub use aov::Aov;
|
||||
|
||||
// a frame's rows, the edit, the clock and the row helpers every pass reads (raea-sys-frame)
|
||||
use raea_sys_frame::*;
|
||||
use raea_sys_frame::bevy_api;
|
||||
use raea_sys_environment as environment;
|
||||
use raea_runtime_scene3d as scene3d;
|
||||
use raea_sys_look::look;
|
||||
use raea_sys_post::outline;
|
||||
// composition passes: which pass drew each pixel, and the frame-wide effects held back from some
|
||||
use raea_sys_compose::compose;
|
||||
use raea_sys_fog_half as fog_half;
|
||||
use raea_sys_fog::froxel;
|
||||
use raea_sys_fog::froxel_glass;
|
||||
use raea_sys_fog::fire;
|
||||
// text in the 3D world, a glyph an entity (raea-sys-text3d)
|
||||
use raea_sys_text3d as text3d;
|
||||
@@ -67,34 +60,25 @@ use raea_sys_sprite as sprite2d;
|
||||
use raea_sys_grid as grid;
|
||||
// footage behind the 3D and a camera's window on a larger view (<Matchmove>)
|
||||
use raea_sys_matchmove as matchmove;
|
||||
use raea_sys_look::paint;
|
||||
use raea_sys_material::decal;
|
||||
use raea_sys_compose::passes;
|
||||
use raea_sys_screen as screen;
|
||||
// the Engine's screens
|
||||
#[cfg(feature = "native")]
|
||||
mod screens;
|
||||
use raea_sys_volume as volume;
|
||||
// meshes that cast shadows without being drawn (<Mesh shadow="only">)
|
||||
use raea_sys_material::shadow_only;
|
||||
use raea_sys_material::shadow_catch;
|
||||
// baked simulations played back by the frame (<MeshSequence>, <Goo>) and glitches on any part (physics.tsx)
|
||||
use raea_sys_meshseq as meshseq;
|
||||
// toon (cel) surfaces and their ink outlines (<MeshToonMaterial>)
|
||||
use raea_sys_material::toon;
|
||||
use raea_sys_toon as toon;
|
||||
use raea_sys_shader as shader_ext;
|
||||
// the camera's lens: Fisheye and LensDistortion, a pass after tone mapping
|
||||
use raea_sys_post::lens;
|
||||
// the camera's motion blur (<MotionBlur>), a function of the frame
|
||||
use raea_sys_post::motion_blur;
|
||||
use raea_sys_post::cut;
|
||||
// Bevy's depth of field, patched to keep the frame's alpha (the paint look's sky)
|
||||
use raea_sys_post::dof;
|
||||
use raea_sys_post::effect_stack;
|
||||
// Bevy plugins compiled in by a crate that registers them, driven by generic rows and stepped by the frame index
|
||||
use raea_runtime_plugins as plugins;
|
||||
/// raea's modules as Bevy plugins, gathered in RaeaPlugins (docs/sdk.feature S6a)
|
||||
pub mod raea_plugins;
|
||||
/// raea's modules as Bevy plugins, gathered in RaeaPlugins (raea-render-plugins, docs/sdk.feature S6a)
|
||||
pub use raea_render_plugins as raea_plugins;
|
||||
|
||||
pub struct Engine {
|
||||
app: App,
|
||||
@@ -142,7 +126,8 @@ impl Drop for Engine {
|
||||
|
||||
#[cfg(feature = "native")] pub(crate) use raea_io_trace::stat; #[cfg(not(feature = "native"))] pub(crate) fn stat(_: &str) -> bool { false } // a stat channel (io/trace stats.rs, nobuild NB2a); the web's build has none
|
||||
/// RAEA_MEM_MARKS: one line on stderr per start-up phase, "mem_mark <ms since the first mark> <phys_footprint MB>
|
||||
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it).
|
||||
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it). Each App's
|
||||
/// assets follow it, as raea-sys-memtally tallies them (RM0).
|
||||
pub fn mem_mark(what: &str) {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
static T0: std::sync::OnceLock<bevy::platform::time::Instant> = std::sync::OnceLock::new();
|
||||
@@ -152,6 +137,7 @@ pub fn mem_mark(what: &str) {
|
||||
let t = T0.get_or_init(bevy::platform::time::Instant::now).elapsed().as_secs_f64() * 1e3;
|
||||
let mb = phys_footprint().map(|b| format!("{:.1}", b as f64 / 1048576.0)).unwrap_or_else(|| "?".into());
|
||||
eprintln!("mem_mark {t:.1} {mb} {what}");
|
||||
raea_sys_memtally::marked();
|
||||
}
|
||||
|
||||
/// The edit has 3D rows (a light or a mesh): its camera draws through the 3D pipeline, and the Apple encoder runs
|
||||
@@ -227,6 +213,13 @@ impl Engine {
|
||||
Engine::build(prog, inserted, dir, None, true)
|
||||
}
|
||||
|
||||
/// The live engine in `slot` (re)opened for `prog`, with its own inserted rows: the one there is let go first, so
|
||||
/// two 3D worlds are never held at once (docs/render-memory.feature RM2).
|
||||
pub fn open_in<'a>(slot: &'a mut Option<Engine>, prog: &Program, dir: &Path) -> Result<&'a mut Engine, String> {
|
||||
*slot = None;
|
||||
Ok(slot.insert(Engine::new_live(prog, &crate::inserted_of(prog), dir)?))
|
||||
}
|
||||
|
||||
/// The frame `draw` drew last, if any.
|
||||
pub fn drawn(&self) -> Option<i64> { self.drawn }
|
||||
|
||||
|
||||
@@ -40,7 +40,58 @@ impl Engine {
|
||||
store::clear(world);
|
||||
world.insert_resource(raea_sys_frame::RenderImages::default()); // its render images: this load's are made as its rows spawn
|
||||
world.despawn_all::<With<Mirror>>();
|
||||
let ents = store::load(world, inserted);
|
||||
// RM9: maps made BC7 where this device samples BC (raea-sys-material maps.rs bc7_chain)
|
||||
if let Some(d) = world.get_resource::<bevy::render::renderer::RenderDevice>() {
|
||||
raea_sys_material::maps::set_block_compression(d.features().contains(bevy::render::render_resource::WgpuFeatures::TEXTURE_COMPRESSION_BC));
|
||||
}
|
||||
let ents = store::load_for_engine(world, inserted);
|
||||
// RAEA_MEM_MARKS (docs/render-memory.feature RM5): the rows' text by kind and column, the biggest first. Each
|
||||
// string is held by the program, the store and the evaluator's gathered columns, so its bytes count three times
|
||||
if std::env::var_os("RAEA_MEM_MARKS").is_some() {
|
||||
let mut by: std::collections::HashMap<(&str, &str), (usize, usize)> = std::collections::HashMap::new();
|
||||
for t in inserted {
|
||||
for (c, v) in &t.vals {
|
||||
if let raea_core_program::ir::V::S(s) = v {
|
||||
let e = by.entry((t.kind.as_str(), c.as_str())).or_default();
|
||||
e.0 += s.len();
|
||||
e.1 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut by: Vec<_> = by.into_iter().collect();
|
||||
by.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
|
||||
let all: usize = by.iter().map(|(_, (n, _))| n).sum();
|
||||
eprintln!("mem_text all {:.1} MB in {} rows", all as f64 / 1e6, inserted.len());
|
||||
for ((k, c), (n, rows)) in by.iter().take(10) {
|
||||
eprintln!("mem_text {k}.{c} {:.1} MB over {rows} rows", *n as f64 / 1e6);
|
||||
}
|
||||
// the shapes by their outermost call, and how many are the same text as another's
|
||||
let mut heads: std::collections::HashMap<&str, (usize, usize)> = std::collections::HashMap::new();
|
||||
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
|
||||
let (mut dup, mut moved_inner) = (0usize, std::collections::HashSet::<&str>::new());
|
||||
for t in inserted.iter().filter(|t| t.kind == "mesh") {
|
||||
let Some(raea_core_program::ir::V::S(sh)) = t.vals.get("shape") else { continue };
|
||||
let head = sh.split(|c: char| c == '(' || c == ':').next().unwrap_or("");
|
||||
let e = heads.entry(head).or_default();
|
||||
e.0 += sh.len();
|
||||
e.1 += 1;
|
||||
if !seen.insert(sh.as_str()) {
|
||||
dup += sh.len();
|
||||
}
|
||||
// a moved, turned or scaled shape: its inside, which copies placed apart share
|
||||
if matches!(head, "move" | "rotate" | "scale" | "transform") {
|
||||
if let (Some(a), Some(b)) = (sh.find('('), sh.rfind(',')) {
|
||||
moved_inner.insert(&sh[a + 1..b.max(a + 1)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut heads: Vec<_> = heads.into_iter().collect();
|
||||
heads.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));
|
||||
eprintln!("mem_text shapes: {:.1} MB the same text as another row's; by outermost call: {}", dup as f64 / 1e6, heads.iter().take(8).map(|(h, (n, c))| format!("{h} {:.1} MB/{c}", *n as f64 / 1e6)).collect::<Vec<_>>().join(", "));
|
||||
let mut longest: Vec<usize> = inserted.iter().filter_map(|t| match t.vals.get("shape") { Some(raea_core_program::ir::V::S(s)) => Some(s.len()), _ => None }).collect();
|
||||
longest.sort_unstable_by(|a, b| b.cmp(a));
|
||||
eprintln!("mem_text shapes: longest {:?} chars", &longest[..longest.len().min(6)]);
|
||||
}
|
||||
#[cfg(feature = "native")]
|
||||
let mut rows2d: Vec<(String, serde_json::Value, Entity)> = Vec::new();
|
||||
let mut camera = None;
|
||||
@@ -133,7 +184,10 @@ impl Engine {
|
||||
Some(t) => t,
|
||||
None => std::sync::Arc::new(raea_core_program::timeline::Timeline::from_cols(prog, base)?),
|
||||
};
|
||||
world.insert_resource(Edit { prog: prog.clone(), timeline, media });
|
||||
// the edit's header only (its size, rate and length: all anything reads of it); a whole copy held every row's
|
||||
// text a fourth time, halcyon's shapes 274 MB (docs/render-memory.feature RM5)
|
||||
let head = Program { fps: prog.fps, width: prog.width, height: prog.height, frames: prog.frames, ..Default::default() };
|
||||
world.insert_resource(Edit { prog: head, timeline, media });
|
||||
world.insert_resource(raea_sys_frame::tables::Cuts::of(prog));
|
||||
world.insert_resource(raea_sys_frame::shots::Shots::of(prog));
|
||||
world.insert_resource(FrameRows::new(ix));
|
||||
|
||||
@@ -191,6 +191,9 @@ impl Engine {
|
||||
app.insert_non_send(Media { backend, decoders: HashMap::new(), dir: dir.to_path_buf() });
|
||||
}
|
||||
raea_sys_hold::install(&mut app, live); // a part held by a hand, and wireframe (docs/scene-feed.feature SF4c, SF3e)
|
||||
if super::stat("RAEA_MEM_MARKS") {
|
||||
raea_sys_memtally::install(&mut app); // RM0: each world's assets after a mark
|
||||
}
|
||||
mem_mark("engine: plugins built (DefaultPlugins, the render device)");
|
||||
Ok(Opening { app, prog: prog.clone(), inserted: inserted.to_vec(), dir: dir.to_path_buf(), timeline, live })
|
||||
}
|
||||
|
||||
@@ -280,7 +280,8 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
|
||||
};
|
||||
let mesh = match &three {
|
||||
Some((_, own)) => {
|
||||
let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, expr.strip_prefix("buffer:"), own)?;
|
||||
let buffer = expr.strip_prefix("buffer:").map(raea_core_shape::buffer_json).transpose().map_err(|e| format!("mesh {}: {e}", t.id))?;
|
||||
let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, buffer.as_deref(), own)?;
|
||||
scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}\0three:{}", own.join(",")), || Ok(m))?
|
||||
}
|
||||
None => mesh,
|
||||
@@ -314,6 +315,10 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
|
||||
if shared {
|
||||
world.entity_mut(e).insert(scene3d::SharedMaterial);
|
||||
}
|
||||
// a map whose picture a render keys frame by frame (RM6): swapped on this part's material
|
||||
if let Some(sw) = raea_sys_material::swapped::of(t, dir)? {
|
||||
world.entity_mut(e).insert(sw);
|
||||
}
|
||||
} else {
|
||||
grid::put(world, e, mesh, mat, vals);
|
||||
// a shader over the lit surface (shader_ext.rs): put on once the rows are applied (scene3d's shade_rows)
|
||||
|
||||
@@ -112,6 +112,18 @@ pub fn logs() -> Option<std::path::PathBuf> {
|
||||
|
||||
/// A new temp file named `raea-NAME-PID-N`, open to read and write, gone when raea is: unlinked once open on unix,
|
||||
/// delete-on-close on Windows, so a render that dies leaves nothing behind (an encoder's samples, a render's parts).
|
||||
/// `bytes` written to `path` whole or not at all: into a part file beside it (named for this process, so two
|
||||
/// writers never share one), then renamed over it, so a reader never sees half a file. Its folder is made first.
|
||||
pub fn write_whole(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
if let Some(d) = path.parent() {
|
||||
std::fs::create_dir_all(d)?;
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let part = path.with_file_name(format!(".{name}.{}.part", std::process::id()));
|
||||
std::fs::write(&part, bytes)?;
|
||||
std::fs::rename(&part, path)
|
||||
}
|
||||
|
||||
pub fn scratch_file(name: &str) -> Result<std::fs::File, String> {
|
||||
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let p = std::env::temp_dir().join(format!("raea-{name}-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
|
||||
@@ -28,12 +28,8 @@ mod tests;
|
||||
|
||||
pub type R<T> = Result<T, String>;
|
||||
|
||||
/// A flag's value (`--out x`): the first of `flags`, each value of a flag given more than once (`--real a --real b`).
|
||||
pub fn flag(args: &[String], name: &str) -> Option<String> {
|
||||
flags(args, name).into_iter().next()
|
||||
}
|
||||
pub fn flags(args: &[String], name: &str) -> Vec<String> {
|
||||
args.iter().zip(args.iter().skip(1)).filter(|(k, _)| *k == name).map(|(_, v)| v.clone()).collect()
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()
|
||||
}
|
||||
|
||||
/// The space's brand kit for a composition `w` px wide: the nearest brand/brand.css at or above the edit's folder (up
|
||||
|
||||
@@ -17,6 +17,8 @@ raea-runtime-wear = { path = "../wear" }
|
||||
raea-native = { path = "../../engine/native", default-features = false }
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
# ECS worlds on Bevy's own ECS (ecs.*), a crate of their own
|
||||
raea-runtime-ecs = { path = "../ecs" }
|
||||
raea-core-place = { path = "../../core/place" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
|
||||
@@ -26,7 +28,6 @@ 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 }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
manifold-rust = "0.16.0"
|
||||
base64 = "0.22"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
|
||||
|
||||
+2
-470
@@ -1,470 +1,2 @@
|
||||
//! raea/ecs on Bevy's own ECS: each world is a `bevy::ecs::world::World`. A component is a real Bevy component
|
||||
//! registered by name at run time (its value a JSON object, in Bevy's archetype tables); an entity holds any number of
|
||||
//! them; queries are Bevy's (QueryBuilder with/without by component id) with column conditions on top; parent and child
|
||||
//! are Bevy's `ChildOf` relationship (despawning a parent takes its children); resources and per-frame events sit beside
|
||||
//! the world. Entities carry stable ids of ours, so a world copies (for `at(frame)`) and comes back the same.
|
||||
//!
|
||||
//! The first version's calls (one kind per entity: spawn {kind, cols}, query {kind, where}, column, count, rows) are
|
||||
//! kept: a kind is a component named after it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use bevy::ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
|
||||
use bevy::ecs::entity::Entity;
|
||||
use bevy::ecs::hierarchy::{ChildOf, Children};
|
||||
use bevy::ecs::query::QueryBuilder;
|
||||
use bevy::ecs::world::World;
|
||||
use bevy::ptr::OwningPtr;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
|
||||
struct BWorld {
|
||||
w: World,
|
||||
comps: BTreeMap<String, ComponentId>,
|
||||
ids: BTreeMap<u64, Entity>,
|
||||
back: HashMap<Entity, u64>,
|
||||
/// the kind an entity was spawned with (the first version's single component)
|
||||
kind: HashMap<u64, String>,
|
||||
next: u64,
|
||||
resources: BTreeMap<String, Value>,
|
||||
events: BTreeMap<String, Vec<Value>>,
|
||||
}
|
||||
|
||||
unsafe fn drop_value(p: OwningPtr<'_>) {
|
||||
// SAFETY: every dynamic component's value is a serde_json::Value (its descriptor's layout)
|
||||
unsafe { p.drop_as::<Value>() }
|
||||
}
|
||||
|
||||
impl BWorld {
|
||||
fn new() -> BWorld {
|
||||
BWorld { w: World::new(), comps: BTreeMap::new(), ids: BTreeMap::new(), back: HashMap::new(), kind: HashMap::new(), next: 0, resources: BTreeMap::new(), events: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The component registered for `name` (made on first use).
|
||||
fn comp(&mut self, name: &str) -> ComponentId {
|
||||
if let Some(c) = self.comps.get(name) {
|
||||
return *c;
|
||||
}
|
||||
// SAFETY: the layout and drop are serde_json::Value's, which is Send + Sync; no relationship
|
||||
let d = unsafe { ComponentDescriptor::new_with_layout(name.to_string(), StorageType::Table, std::alloc::Layout::new::<Value>(), Some(drop_value), true, false, ComponentCloneBehavior::Ignore, None) };
|
||||
let id = self.w.register_component_with_descriptor(d);
|
||||
self.comps.insert(name.to_string(), id);
|
||||
id
|
||||
}
|
||||
|
||||
fn entity(&self, id: u64) -> R<Entity> {
|
||||
self.ids.get(&id).copied().ok_or_else(|| format!("no entity {id}"))
|
||||
}
|
||||
|
||||
fn insert(&mut self, e: Entity, name: &str, value: Value) {
|
||||
let c = self.comp(name);
|
||||
OwningPtr::make(value, |ptr| {
|
||||
// SAFETY: `c` was registered with Value's layout and `ptr` holds a Value
|
||||
unsafe {
|
||||
self.w.entity_mut(e).insert_by_id(c, ptr);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn get(&self, e: Entity, name: &str) -> Option<&Value> {
|
||||
let c = *self.comps.get(name)?;
|
||||
// SAFETY: as insert
|
||||
self.w.get_by_id(e, c).map(|p| unsafe { p.deref::<Value>() })
|
||||
}
|
||||
|
||||
fn spawn(&mut self, comps: &Map<String, Value>) -> u64 {
|
||||
let e = self.w.spawn_empty().id();
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.ids.insert(id, e);
|
||||
self.back.insert(e, id);
|
||||
for (k, v) in comps {
|
||||
self.insert(e, k, v.clone());
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// The names of the components an entity has, sorted.
|
||||
fn names(&self, e: Entity) -> Vec<String> {
|
||||
self.comps.iter().filter(|(_, c)| self.w.get_by_id(e, **c).is_some()).map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
fn despawn(&mut self, id: u64) -> R<()> {
|
||||
let e = self.entity(id)?;
|
||||
// Bevy despawns the children with it (ChildOf links them): their ids go too
|
||||
let mut gone = vec![e];
|
||||
let mut i = 0;
|
||||
while i < gone.len() {
|
||||
if let Some(ch) = self.w.get::<Children>(gone[i]) {
|
||||
gone.extend(ch.iter());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
self.w.despawn(e);
|
||||
for g in gone {
|
||||
if let Some(gid) = self.back.remove(&g) {
|
||||
self.ids.remove(&gid);
|
||||
self.kind.remove(&gid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entities with every `with` component and none of `without`, by Bevy's query; ours in id order.
|
||||
fn find(&mut self, with: &[String], without: &[String]) -> Vec<u64> {
|
||||
let with_ids: Vec<ComponentId> = with.iter().map(|n| self.comp(n)).collect();
|
||||
let without_ids: Vec<ComponentId> = without.iter().map(|n| self.comp(n)).collect();
|
||||
let mut qb = QueryBuilder::<Entity>::new(&mut self.w);
|
||||
for c in &with_ids {
|
||||
qb.with_id(*c);
|
||||
}
|
||||
for c in &without_ids {
|
||||
qb.without_id(*c);
|
||||
}
|
||||
let mut q = qb.build();
|
||||
let mut out: Vec<u64> = q.iter(&self.w).filter_map(|e| self.back.get(&e).copied()).collect();
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// A column condition: "Comp.field" (or "field" of the first `with` component) compared with a value.
|
||||
fn passes(&self, e: Entity, default: Option<&str>, cond: &Value) -> bool {
|
||||
let Some(a) = cond.as_array() else { return false };
|
||||
let (col, op, val) = (a.first().and_then(Value::as_str).unwrap_or(""), a.get(1).and_then(Value::as_str).unwrap_or("=="), a.get(2).cloned().unwrap_or(Value::Null));
|
||||
let (comp, field) = match col.split_once('.') {
|
||||
Some((c, f)) => (c, f),
|
||||
None => (default.unwrap_or(""), col),
|
||||
};
|
||||
let x = self.get(e, comp).and_then(|v| v.get(field)).cloned().unwrap_or(Value::Null);
|
||||
let num = |v: &Value| match v {
|
||||
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
|
||||
Value::Number(n) => n.as_f64(),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
"==" => x == val || (num(&x).is_some() && num(&x) == num(&val)),
|
||||
"!=" => !(x == val || (num(&x).is_some() && num(&x) == num(&val))),
|
||||
_ => match (num(&x), num(&val)) {
|
||||
(Some(y), Some(w)) => match op {
|
||||
"<" => y < w,
|
||||
"<=" => y <= w,
|
||||
">" => y > w,
|
||||
">=" => y >= w,
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything, to copy the world: each entity's id, kind, components and parent, plus resources and events.
|
||||
fn dump(&self) -> Value {
|
||||
let ents: Vec<Value> = self
|
||||
.ids
|
||||
.iter()
|
||||
.map(|(id, e)| {
|
||||
let comps: Map<String, Value> = self.names(*e).into_iter().filter_map(|n| self.get(*e, &n).cloned().map(|v| (n, v))).collect();
|
||||
let parent = self.w.get::<ChildOf>(*e).and_then(|c| self.back.get(&c.parent()).copied());
|
||||
json!({"id": id, "kind": self.kind.get(id), "components": comps, "parent": parent})
|
||||
})
|
||||
.collect();
|
||||
json!({"entities": ents, "next": self.next, "resources": self.resources, "events": self.events})
|
||||
}
|
||||
|
||||
fn load(d: &Value) -> BWorld {
|
||||
let mut w = BWorld::new();
|
||||
let ents = d["entities"].as_array().cloned().unwrap_or_default();
|
||||
for en in &ents {
|
||||
let id = en["id"].as_u64().unwrap_or(0);
|
||||
let e = w.w.spawn_empty().id();
|
||||
w.ids.insert(id, e);
|
||||
w.back.insert(e, id);
|
||||
if let Some(k) = en["kind"].as_str() {
|
||||
w.kind.insert(id, k.to_string());
|
||||
}
|
||||
for (k, v) in en["components"].as_object().into_iter().flatten() {
|
||||
w.insert(e, k, v.clone());
|
||||
}
|
||||
}
|
||||
for en in &ents {
|
||||
if let (Some(id), Some(p)) = (en["id"].as_u64(), en["parent"].as_u64()) {
|
||||
let (c, p) = (w.ids[&id], w.ids[&p]);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
}
|
||||
w.next = d["next"].as_u64().unwrap_or(0);
|
||||
w.resources = d["resources"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default();
|
||||
w.events = d["events"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_array().cloned().unwrap_or_default())).collect()).unwrap_or_default();
|
||||
w
|
||||
}
|
||||
|
||||
/// The first version's row: {id, kind, ...the kind component's columns}.
|
||||
fn row(&self, id: u64) -> R<Value> {
|
||||
let e = self.entity(id)?;
|
||||
let kind = self.kind.get(&id).cloned().unwrap_or_default();
|
||||
let mut m = self.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
m.insert("id".into(), json!(id));
|
||||
m.insert("kind".into(), json!(kind));
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static WORLDS: RefCell<(u64, HashMap<u64, BWorld>)> = RefCell::new((0, HashMap::new()));
|
||||
}
|
||||
|
||||
fn u(v: &Value, k: &str) -> R<u64> {
|
||||
v.get(k).and_then(Value::as_u64).ok_or_else(|| format!("{k}: a number"))
|
||||
}
|
||||
fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
|
||||
v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
|
||||
}
|
||||
fn strings(v: &Value, k: &str) -> Vec<String> {
|
||||
v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn with_world<T>(v: &Value, f: impl FnOnce(&mut BWorld) -> R<T>) -> R<T> {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
let w = ws.1.get_mut(&id).ok_or_else(|| format!("no world {id}"))?;
|
||||
f(w)
|
||||
})
|
||||
}
|
||||
|
||||
fn put(w: BWorld) -> Value {
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
ws.0 += 1;
|
||||
let id = ws.0;
|
||||
ws.1.insert(id, w);
|
||||
json!({"world": id})
|
||||
})
|
||||
}
|
||||
|
||||
/// The ecs.* calls.
|
||||
pub fn call(name: &str, v: &Value) -> R<Value> {
|
||||
match name {
|
||||
"ecs.new" => Ok(put(BWorld::new())),
|
||||
"ecs.clone" => {
|
||||
let d = with_world(v, |w| Ok(w.dump()))?;
|
||||
Ok(put(BWorld::load(&d)))
|
||||
}
|
||||
"ecs.free" => {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| ws.borrow_mut().1.remove(&id));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"ecs.spawn" => with_world(v, |w| {
|
||||
let mut comps = v.get("components").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let kind = v.get("kind").and_then(Value::as_str).map(str::to_string);
|
||||
if let Some(k) = &kind {
|
||||
comps.insert(k.clone(), Value::Object(v.get("cols").and_then(Value::as_object).cloned().unwrap_or_default()));
|
||||
}
|
||||
let id = w.spawn(&comps);
|
||||
if let Some(k) = kind {
|
||||
w.kind.insert(id, k);
|
||||
}
|
||||
if let Some(p) = v.get("parent").and_then(Value::as_u64) {
|
||||
let (c, p) = (w.entity(id)?, w.entity(p)?);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
Ok(json!({"id": id}))
|
||||
}),
|
||||
"ecs.set" => with_world(v, |w| {
|
||||
let id = u(v, "id")?;
|
||||
let e = w.entity(id)?;
|
||||
let kind = w.kind.get(&id).cloned().ok_or_else(|| format!("entity {id} has no kind (use ecs.insert)"))?;
|
||||
let mut cur = w.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
for (k, x) in v.get("cols").and_then(Value::as_object).into_iter().flatten() {
|
||||
cur.insert(k.clone(), x.clone());
|
||||
}
|
||||
w.insert(e, &kind, Value::Object(cur));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.get" => with_world(v, |w| w.row(u(v, "id")?)),
|
||||
"ecs.despawn" => with_world(v, |w| w.despawn(u(v, "id")?).map(|_| Value::Null)),
|
||||
"ecs.insert" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for (k, x) in v.get("components").and_then(Value::as_object).into_iter().flatten() {
|
||||
w.insert(e, k, x.clone());
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.remove" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for n in strings(v, "names") {
|
||||
if let Some(c) = w.comps.get(&n).copied() {
|
||||
w.w.entity_mut(e).remove_by_id(c);
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.components" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let m: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
Ok(Value::Object(m))
|
||||
}),
|
||||
"ecs.find" => with_world(v, |w| {
|
||||
let with = strings(v, "with");
|
||||
let without = strings(v, "without");
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids = w.find(&with, &without);
|
||||
let default = with.first().cloned();
|
||||
let ids: Vec<u64> = ids.into_iter().filter(|id| conds.iter().all(|c| w.passes(w.ids[id], default.as_deref(), c))).collect();
|
||||
if v.get("rows").and_then(Value::as_bool).unwrap_or(false) {
|
||||
let rows: Vec<Value> = ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let e = w.ids[id];
|
||||
let comps: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
json!({"id": id, "components": comps})
|
||||
})
|
||||
.collect();
|
||||
return Ok(json!({"ids": ids, "rows": rows}));
|
||||
}
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
// the first version's query: a kind's entities by its columns
|
||||
"ecs.query" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).filter(|id| conds.iter().all(|c| w.passes(w.ids[id], Some(&kind), c))).collect();
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
"ecs.column" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let col = s(v, "col")?;
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).collect();
|
||||
Ok(json!(ids.iter().map(|id| w.get(w.ids[id], &kind).and_then(|c| c.get(col)).and_then(Value::as_f64).map(|x| json!(x)).unwrap_or(Value::Null)).collect::<Vec<_>>()))
|
||||
}),
|
||||
"ecs.count" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
Ok(json!(w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).count()))
|
||||
}),
|
||||
"ecs.rows" => with_world(v, |w| {
|
||||
let mut ids: Vec<(String, u64)> = w.kind.iter().map(|(id, k)| (k.clone(), *id)).collect();
|
||||
ids.sort();
|
||||
Ok(Value::Array(ids.into_iter().filter_map(|(_, id)| w.row(id).ok()).collect()))
|
||||
}),
|
||||
"ecs.parent" => with_world(v, |w| {
|
||||
let c = w.entity(u(v, "id")?)?;
|
||||
match v.get("parent").and_then(Value::as_u64) {
|
||||
Some(p) => {
|
||||
let p = w.entity(p)?;
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
None if v.get("parent").is_some_and(Value::is_null) => {
|
||||
w.w.entity_mut(c).remove::<ChildOf>();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(json!(w.w.get::<ChildOf>(c).and_then(|p| w.back.get(&p.parent()).copied())))
|
||||
}),
|
||||
"ecs.children" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let mut out: Vec<u64> = w.w.get::<Children>(e).map(|c| c.iter().filter_map(|x| w.back.get(&x).copied()).collect()).unwrap_or_default();
|
||||
out.sort_unstable();
|
||||
Ok(json!(out))
|
||||
}),
|
||||
"ecs.resource" => with_world(v, |w| {
|
||||
let name = s(v, "name")?.to_string();
|
||||
if let Some(x) = v.get("value") {
|
||||
w.resources.insert(name.clone(), x.clone());
|
||||
}
|
||||
Ok(w.resources.get(&name).cloned().unwrap_or(Value::Null))
|
||||
}),
|
||||
"ecs.send" => with_world(v, |w| {
|
||||
w.events.entry(s(v, "name")?.to_string()).or_default().push(v.get("value").cloned().unwrap_or(Value::Null));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.events" => with_world(v, |w| Ok(json!(w.events.get(s(v, "name")?).cloned().unwrap_or_default()))),
|
||||
"ecs.clear_events" => with_world(v, |w| {
|
||||
w.events.clear();
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
// what renders, straight from the world: entities with a Mesh and a Transform as 3D nodes (world space,
|
||||
// parents' transforms composed), and lights; the bridge draws these without a React element per entity
|
||||
"ecs.scene" => with_world(v, |w| {
|
||||
let mut out = Vec::new();
|
||||
for id in w.find(&["Mesh".into()], &[]) {
|
||||
let e = w.ids[&id];
|
||||
let mesh = w.get(e, "Mesh").cloned().unwrap_or(Value::Null);
|
||||
let mut t = transform_of(w.get(e, "Transform"));
|
||||
let mut p = w.w.get::<ChildOf>(e).map(|c| c.parent());
|
||||
while let Some(pe) = p {
|
||||
let pt = transform_of(w.get(pe, "Transform"));
|
||||
t = compose(&pt, &t);
|
||||
p = w.w.get::<ChildOf>(pe).map(|c| c.parent());
|
||||
}
|
||||
out.push(json!({"id": id, "kind": "Mesh", "mesh": mesh, "position": [t[0], t[1], t[2]], "rotation": [t[3], t[4], t[5]], "scale": t[6]}));
|
||||
}
|
||||
for id in w.find(&["Light".into()], &[]) {
|
||||
out.push(json!({"id": id, "kind": "Light", "light": w.get(w.ids[&id], "Light").cloned().unwrap_or(Value::Null)}));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}),
|
||||
o => Err(format!("no native call {o}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// [x, y, z, rx, ry, rz, scale] from a Transform component ({x, y, z, rx, ry, rz, scale}, all optional).
|
||||
fn transform_of(t: Option<&Value>) -> [f64; 7] {
|
||||
let g = |k: &str, d: f64| t.and_then(|t| t.get(k)).and_then(Value::as_f64).unwrap_or(d);
|
||||
[g("x", 0.0), g("y", 0.0), g("z", 0.0), g("rx", 0.0), g("ry", 0.0), g("rz", 0.0), g("scale", 1.0)]
|
||||
}
|
||||
|
||||
/// A child's transform in its parent's space, made world space (rotation by z, then y, then x; uniform scale).
|
||||
fn compose(parent: &[f64; 7], child: &[f64; 7]) -> [f64; 7] {
|
||||
let (sx, cx) = parent[3].sin_cos();
|
||||
let (sy, cy) = parent[4].sin_cos();
|
||||
let (sz, cz) = parent[5].sin_cos();
|
||||
let (mut x, mut y, mut z) = (child[0] * parent[6], child[1] * parent[6], child[2] * parent[6]);
|
||||
// z
|
||||
let (x1, y1) = (x * cz - y * sz, x * sz + y * cz);
|
||||
x = x1;
|
||||
y = y1;
|
||||
// y
|
||||
let (x2, z2) = (x * cy + z * sy, -x * sy + z * cy);
|
||||
x = x2;
|
||||
z = z2;
|
||||
// x
|
||||
let (y3, z3) = (y * cx - z * sx, y * sx + z * cx);
|
||||
y = y3;
|
||||
z = z3;
|
||||
[parent[0] + x, parent[1] + y, parent[2] + z, parent[3] + child[3], parent[4] + child[4], parent[5] + child[5], parent[6] * child[6]]
|
||||
}
|
||||
|
||||
/// The ecs.* names with their TypeScript types, for the registry.
|
||||
pub const CALLS: &[(&str, &str, &str, &str)] = &[
|
||||
("ecs.new", "{}", "{ world: number }", "a new world (Bevy's)"),
|
||||
("ecs.clone", "{ world: number }", "{ world: number }", "a copy of a world"),
|
||||
("ecs.free", "{ world: number }", "null", "drop a world"),
|
||||
("ecs.spawn", "{ world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }", "{ id: number }", "a new entity: a kind with columns, and/or any components"),
|
||||
("ecs.set", "{ world: number; id: number; cols: Record<string, number | string | boolean> }", "null", "columns merged into an entity's kind"),
|
||||
("ecs.get", "{ world: number; id: number }", "{ id: number; kind: string } & Record<string, number | string | boolean>", "an entity's row (its kind's columns)"),
|
||||
("ecs.despawn", "{ world: number; id: number }", "null", "remove an entity and its children"),
|
||||
("ecs.insert", "{ world: number; id: number; components: Record<string, unknown> }", "null", "components added to (or replaced on) an entity"),
|
||||
("ecs.remove", "{ world: number; id: number; names: string[] }", "null", "components taken off an entity"),
|
||||
("ecs.components", "{ world: number; id: number }", "Record<string, unknown>", "an entity's components by name"),
|
||||
("ecs.find", "{ world: number; with?: string[]; without?: string[]; where?: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][]; rows?: boolean }", "{ ids: number[]; rows?: { id: number; components: Record<string, unknown> }[] }", "entities with every `with` component and no `without` one (Bevy's query), passing every condition (\"Comp.field\")"),
|
||||
("ecs.query", "{ world: number; kind: string; where: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][] }", "{ ids: number[] }", "ids of kind's entities passing every condition"),
|
||||
("ecs.column", "{ world: number; kind: string; col: string }", "(number | null)[]", "one numeric column of a kind, in id order"),
|
||||
("ecs.count", "{ world: number; kind: string }", "number", "how many entities of a kind"),
|
||||
("ecs.rows", "{ world: number }", "({ id: number; kind: string } & Record<string, number | string | boolean>)[]", "every kind's rows, by kind then id"),
|
||||
("ecs.parent", "{ world: number; id: number; parent?: number | null }", "number | null", "an entity's parent (set it with parent; null clears it)"),
|
||||
("ecs.children", "{ world: number; id: number }", "number[]", "an entity's children"),
|
||||
("ecs.resource", "{ world: number; name: string; value?: unknown }", "unknown", "a resource (set it with value)"),
|
||||
("ecs.send", "{ world: number; name: string; value?: unknown }", "null", "an event for this frame"),
|
||||
("ecs.events", "{ world: number; name: string }", "unknown[]", "this frame's events of a name"),
|
||||
("ecs.clear_events", "{ world: number }", "null", "the frame's events cleared (each step starts with none)"),
|
||||
("ecs.scene", "{ world: number }", "{ id: number; kind: \"Mesh\" | \"Light\"; mesh?: unknown; light?: unknown; position?: [number, number, number]; rotation?: [number, number, number]; scale?: number }[]", "the world's Mesh+Transform entities (world space) and lights, to draw"),
|
||||
];
|
||||
|
||||
/// How many worlds are alive (media.live's leak check).
|
||||
pub fn live() -> usize {
|
||||
WORLDS.with(|ws| ws.borrow().1.len())
|
||||
}
|
||||
//! raea/ecs on Bevy's own ECS: raea-runtime-ecs, its own crate since 11-29 (the crate limit).
|
||||
pub use raea_runtime_ecs::*;
|
||||
@@ -104,6 +104,8 @@ struct Picture {
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
solids: HashMap<u64, solid::Solid>,
|
||||
/// each expression's one solid (solid.rs put_later)
|
||||
solid_ids: HashMap<String, u64>,
|
||||
pictures: HashMap<u64, Picture>,
|
||||
#[cfg(target_vendor = "apple")]
|
||||
vdecs: HashMap<u64, raea_io_media::apple::packets::PacketDecoder>,
|
||||
|
||||
+64
-21
@@ -5,21 +5,48 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{R, State, args, f, s, u};
|
||||
|
||||
/// A solid by its expression, and its Manifold once something needs it. A boolean or a move only writes the
|
||||
/// expression: the renderer builds the mesh from that (raea-core-shape, which keeps it on disk), so a set made of cuts
|
||||
/// isn't cut a second time here on every open (a third of a launch-film set's script pass, 11-10). A query, a mesh,
|
||||
/// an export or an operation that works on the solid itself builds it then.
|
||||
/// A solid by its expression. A boolean or a move only writes the expression: the renderer builds the mesh from that
|
||||
/// (raea-core-shape, which keeps it on disk), so a set made of cuts isn't cut a second time here on every open (a third
|
||||
/// of a launch-film set's script pass, 11-10). A query, a mesh, an export or an operation that works on the solid
|
||||
/// itself builds its Manifold then, into BUILT.
|
||||
///
|
||||
/// docs/render-memory.feature RM5: a solid was once its expression and its Manifold for as long as the script ran. No
|
||||
/// component frees its solids (TypeScript has no finalizer to), and each render of a component makes them again, so
|
||||
/// halcyon's script held 2.4 GB of Manifolds (their colliders 1 GB) by the end of warm-up, a third of the render's
|
||||
/// heap. Now the same expression is one solid, counted (solid.free lets one holder go), and a built Manifold lives in
|
||||
/// BUILT, a bounded cache by expression: one let go is built again from its expression if it's asked for again.
|
||||
pub(crate) struct Solid {
|
||||
m: std::cell::OnceCell<Manifold>,
|
||||
expr: String,
|
||||
refs: u32,
|
||||
}
|
||||
|
||||
/// Built Manifolds by expression, two generations of at most GEN_BYTES each (raea-core-shape's Generations).
|
||||
const GEN_BYTES: usize = 192 << 20;
|
||||
|
||||
/// A Manifold's heap, roughly: its halfedges, vertices, normals and properties, and the collider a boolean builds on
|
||||
/// it (measured 11-26 on halcyon's solids: about 250 bytes a triangle in all).
|
||||
fn manifold_bytes(m: &Manifold) -> usize {
|
||||
m.num_tri() * 250 + 4096
|
||||
}
|
||||
|
||||
/// `m` kept in BUILT for `expr`, weighed by its heap.
|
||||
fn keep_built(expr: &str, m: std::rc::Rc<Manifold>) {
|
||||
let weight = manifold_bytes(&m);
|
||||
BUILT.with(|b| b.borrow_mut().hold(expr, m, weight));
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static BUILT: std::cell::RefCell<raea_core_shape::Generations<std::rc::Rc<Manifold>>> = std::cell::RefCell::new(raea_core_shape::Generations::new(GEN_BYTES));
|
||||
}
|
||||
|
||||
impl Solid {
|
||||
fn m(&self) -> R<&Manifold> {
|
||||
if self.m.get().is_none() {
|
||||
let _ = self.m.set(raea_core_shape::solid_or_empty(&self.expr)?);
|
||||
fn m(&self) -> R<std::rc::Rc<Manifold>> {
|
||||
if let Some(m) = BUILT.with(|b| b.borrow_mut().get(&self.expr)) {
|
||||
return Ok(m);
|
||||
}
|
||||
Ok(self.m.get().expect("just set"))
|
||||
let m = std::rc::Rc::new(raea_core_shape::solid_or_empty(&self.expr)?);
|
||||
keep_built(&self.expr, m.clone());
|
||||
Ok(m)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,18 +59,24 @@ fn arg_text(a: &Value) -> String {
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// A solid already built: its Manifold kept in BUILT for what asks for it next.
|
||||
fn put(&mut self, m: Manifold, expr: String) -> Value {
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.solids.insert(id, Solid { m: std::cell::OnceCell::from(m), expr: expr.clone() });
|
||||
json!({"id": id, "expr": expr})
|
||||
keep_built(&expr, std::rc::Rc::new(m));
|
||||
self.put_later(expr)
|
||||
}
|
||||
|
||||
/// A solid that is only its expression so far.
|
||||
/// A solid that is only its expression so far: the one solid of that expression, counted once more.
|
||||
fn put_later(&mut self, expr: String) -> Value {
|
||||
if let Some(&id) = self.solid_ids.get(&expr) {
|
||||
if let Some(sd) = self.solids.get_mut(&id) {
|
||||
sd.refs += 1;
|
||||
return json!({"id": id, "expr": expr});
|
||||
}
|
||||
}
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.solids.insert(id, Solid { m: std::cell::OnceCell::new(), expr: expr.clone() });
|
||||
self.solid_ids.insert(expr.clone(), id);
|
||||
self.solids.insert(id, Solid { expr: expr.clone(), refs: 1 });
|
||||
json!({"id": id, "expr": expr})
|
||||
}
|
||||
|
||||
@@ -51,6 +84,16 @@ impl State {
|
||||
self.solids.get(&id).ok_or_else(|| format!("solid {id} is gone (freed?)"))
|
||||
}
|
||||
|
||||
/// One holder of solid `id` lets it go; the last one's going frees it.
|
||||
fn free_solid(&mut self, id: u64) {
|
||||
let Some(sd) = self.solids.get_mut(&id) else { return };
|
||||
sd.refs = sd.refs.saturating_sub(1);
|
||||
if sd.refs == 0 {
|
||||
if let Some(sd) = self.solids.remove(&id) {
|
||||
self.solid_ids.remove(&sd.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A solid no expression describes (made from a mesh, a level set, a warp), written as OBJ under its content's hash; its
|
||||
@@ -176,7 +219,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
"genus" => Ok(json!(sd.m()?.genus())),
|
||||
"min_gap" => {
|
||||
let o = st.solid(u(v, "other")?)?;
|
||||
Ok(json!(sd.m()?.min_gap(o.m()?, f(v, "z")?)))
|
||||
Ok(json!(sd.m()?.min_gap(&*o.m()?, f(v, "z")?)))
|
||||
}
|
||||
"ray" => {
|
||||
let a: Vec<f64> = args(v).iter().filter_map(Value::as_f64).collect();
|
||||
@@ -225,7 +268,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
}
|
||||
"minkowski" | "minkowski_diff" => {
|
||||
let o = other.ok_or_else(|| format!("{fun} takes another solid"))?;
|
||||
let m = if fun == "minkowski" { base.m()?.minkowski_sum(o.m()?) } else { base.m()?.minkowski_difference(o.m()?) };
|
||||
let m = if fun == "minkowski" { base.m()?.minkowski_sum(&*o.m()?) } else { base.m()?.minkowski_difference(&*o.m()?) };
|
||||
(m, format!("{fun}({}, {})", base.expr, o.expr))
|
||||
}
|
||||
"simplify" | "refine_length" | "refine_tolerance" => {
|
||||
@@ -252,7 +295,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
}
|
||||
"solid.mesh" => {
|
||||
let sd = st.solid(u(v, "id")?)?;
|
||||
let (verts, tris) = raea_core_shape::to_mesh(sd.m()?);
|
||||
let (verts, tris) = raea_core_shape::to_mesh(&*sd.m()?);
|
||||
Ok(json!({"verts": verts, "tris": tris}))
|
||||
}
|
||||
"solid.from_mesh" => {
|
||||
@@ -297,7 +340,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
let sd = st.solid(u(v, "id")?)?;
|
||||
let path = s(v, "path")?;
|
||||
let format = v.get("format").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| if path.ends_with(".glb") { "glb".into() } else { "obj".into() });
|
||||
Ok(json!({"bytes": raea_core_shape::export(sd.m()?, path, &format)?}))
|
||||
Ok(json!({"bytes": raea_core_shape::export(&*sd.m()?, path, &format)?}))
|
||||
}
|
||||
"solid.import" => {
|
||||
let path = s(v, "path")?;
|
||||
@@ -330,7 +373,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
}
|
||||
let parts: Vec<&Solid> = ids.iter().map(|i| st.solid(*i)).collect::<R<_>>()?;
|
||||
let expr = if parts.len() == 1 { parts[0].expr.clone() } else { format!("union({})", parts.iter().map(|p| p.expr.as_str()).collect::<Vec<_>>().join(", ")) };
|
||||
let m = Manifold::compose(&parts.iter().map(|p| p.m().cloned()).collect::<R<Vec<_>>>()?);
|
||||
let m = Manifold::compose(&parts.iter().map(|p| p.m().map(|m| (*m).clone())).collect::<R<Vec<_>>>()?);
|
||||
Ok(st.put(m, expr))
|
||||
}
|
||||
// the convex hull of points
|
||||
@@ -428,7 +471,7 @@ pub(super) fn call(st: &mut State, name: &str, v: &Value) -> R<Value> {
|
||||
Ok(section_json(&cs))
|
||||
}
|
||||
"solid.free" => {
|
||||
st.solids.remove(&u(v, "id")?);
|
||||
st.free_solid(u(v, "id")?);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
o => Err(format!("no native call {o}")),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "raea-runtime-ecs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea/ecs on Bevy's own ECS: worlds of real Bevy components registered by name at run time, a composition's native ecs.* calls"
|
||||
|
||||
[dependencies]
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,470 @@
|
||||
//! raea/ecs on Bevy's own ECS: each world is a `bevy::ecs::world::World`. A component is a real Bevy component
|
||||
//! registered by name at run time (its value a JSON object, in Bevy's archetype tables); an entity holds any number of
|
||||
//! them; queries are Bevy's (QueryBuilder with/without by component id) with column conditions on top; parent and child
|
||||
//! are Bevy's `ChildOf` relationship (despawning a parent takes its children); resources and per-frame events sit beside
|
||||
//! the world. Entities carry stable ids of ours, so a world copies (for `at(frame)`) and comes back the same.
|
||||
//!
|
||||
//! The first version's calls (one kind per entity: spawn {kind, cols}, query {kind, where}, column, count, rows) are
|
||||
//! kept: a kind is a component named after it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use bevy::ecs::component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType};
|
||||
use bevy::ecs::entity::Entity;
|
||||
use bevy::ecs::hierarchy::{ChildOf, Children};
|
||||
use bevy::ecs::query::QueryBuilder;
|
||||
use bevy::ecs::world::World;
|
||||
use bevy::ptr::OwningPtr;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
|
||||
struct BWorld {
|
||||
w: World,
|
||||
comps: BTreeMap<String, ComponentId>,
|
||||
ids: BTreeMap<u64, Entity>,
|
||||
back: HashMap<Entity, u64>,
|
||||
/// the kind an entity was spawned with (the first version's single component)
|
||||
kind: HashMap<u64, String>,
|
||||
next: u64,
|
||||
resources: BTreeMap<String, Value>,
|
||||
events: BTreeMap<String, Vec<Value>>,
|
||||
}
|
||||
|
||||
unsafe fn drop_value(p: OwningPtr<'_>) {
|
||||
// SAFETY: every dynamic component's value is a serde_json::Value (its descriptor's layout)
|
||||
unsafe { p.drop_as::<Value>() }
|
||||
}
|
||||
|
||||
impl BWorld {
|
||||
fn new() -> BWorld {
|
||||
BWorld { w: World::new(), comps: BTreeMap::new(), ids: BTreeMap::new(), back: HashMap::new(), kind: HashMap::new(), next: 0, resources: BTreeMap::new(), events: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The component registered for `name` (made on first use).
|
||||
fn comp(&mut self, name: &str) -> ComponentId {
|
||||
if let Some(c) = self.comps.get(name) {
|
||||
return *c;
|
||||
}
|
||||
// SAFETY: the layout and drop are serde_json::Value's, which is Send + Sync; no relationship
|
||||
let d = unsafe { ComponentDescriptor::new_with_layout(name.to_string(), StorageType::Table, std::alloc::Layout::new::<Value>(), Some(drop_value), true, false, ComponentCloneBehavior::Ignore, None) };
|
||||
let id = self.w.register_component_with_descriptor(d);
|
||||
self.comps.insert(name.to_string(), id);
|
||||
id
|
||||
}
|
||||
|
||||
fn entity(&self, id: u64) -> R<Entity> {
|
||||
self.ids.get(&id).copied().ok_or_else(|| format!("no entity {id}"))
|
||||
}
|
||||
|
||||
fn insert(&mut self, e: Entity, name: &str, value: Value) {
|
||||
let c = self.comp(name);
|
||||
OwningPtr::make(value, |ptr| {
|
||||
// SAFETY: `c` was registered with Value's layout and `ptr` holds a Value
|
||||
unsafe {
|
||||
self.w.entity_mut(e).insert_by_id(c, ptr);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn get(&self, e: Entity, name: &str) -> Option<&Value> {
|
||||
let c = *self.comps.get(name)?;
|
||||
// SAFETY: as insert
|
||||
self.w.get_by_id(e, c).map(|p| unsafe { p.deref::<Value>() })
|
||||
}
|
||||
|
||||
fn spawn(&mut self, comps: &Map<String, Value>) -> u64 {
|
||||
let e = self.w.spawn_empty().id();
|
||||
self.next += 1;
|
||||
let id = self.next;
|
||||
self.ids.insert(id, e);
|
||||
self.back.insert(e, id);
|
||||
for (k, v) in comps {
|
||||
self.insert(e, k, v.clone());
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// The names of the components an entity has, sorted.
|
||||
fn names(&self, e: Entity) -> Vec<String> {
|
||||
self.comps.iter().filter(|(_, c)| self.w.get_by_id(e, **c).is_some()).map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
fn despawn(&mut self, id: u64) -> R<()> {
|
||||
let e = self.entity(id)?;
|
||||
// Bevy despawns the children with it (ChildOf links them): their ids go too
|
||||
let mut gone = vec![e];
|
||||
let mut i = 0;
|
||||
while i < gone.len() {
|
||||
if let Some(ch) = self.w.get::<Children>(gone[i]) {
|
||||
gone.extend(ch.iter());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
self.w.despawn(e);
|
||||
for g in gone {
|
||||
if let Some(gid) = self.back.remove(&g) {
|
||||
self.ids.remove(&gid);
|
||||
self.kind.remove(&gid);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entities with every `with` component and none of `without`, by Bevy's query; ours in id order.
|
||||
fn find(&mut self, with: &[String], without: &[String]) -> Vec<u64> {
|
||||
let with_ids: Vec<ComponentId> = with.iter().map(|n| self.comp(n)).collect();
|
||||
let without_ids: Vec<ComponentId> = without.iter().map(|n| self.comp(n)).collect();
|
||||
let mut qb = QueryBuilder::<Entity>::new(&mut self.w);
|
||||
for c in &with_ids {
|
||||
qb.with_id(*c);
|
||||
}
|
||||
for c in &without_ids {
|
||||
qb.without_id(*c);
|
||||
}
|
||||
let mut q = qb.build();
|
||||
let mut out: Vec<u64> = q.iter(&self.w).filter_map(|e| self.back.get(&e).copied()).collect();
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// A column condition: "Comp.field" (or "field" of the first `with` component) compared with a value.
|
||||
fn passes(&self, e: Entity, default: Option<&str>, cond: &Value) -> bool {
|
||||
let Some(a) = cond.as_array() else { return false };
|
||||
let (col, op, val) = (a.first().and_then(Value::as_str).unwrap_or(""), a.get(1).and_then(Value::as_str).unwrap_or("=="), a.get(2).cloned().unwrap_or(Value::Null));
|
||||
let (comp, field) = match col.split_once('.') {
|
||||
Some((c, f)) => (c, f),
|
||||
None => (default.unwrap_or(""), col),
|
||||
};
|
||||
let x = self.get(e, comp).and_then(|v| v.get(field)).cloned().unwrap_or(Value::Null);
|
||||
let num = |v: &Value| match v {
|
||||
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
|
||||
Value::Number(n) => n.as_f64(),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
"==" => x == val || (num(&x).is_some() && num(&x) == num(&val)),
|
||||
"!=" => !(x == val || (num(&x).is_some() && num(&x) == num(&val))),
|
||||
_ => match (num(&x), num(&val)) {
|
||||
(Some(y), Some(w)) => match op {
|
||||
"<" => y < w,
|
||||
"<=" => y <= w,
|
||||
">" => y > w,
|
||||
">=" => y >= w,
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything, to copy the world: each entity's id, kind, components and parent, plus resources and events.
|
||||
fn dump(&self) -> Value {
|
||||
let ents: Vec<Value> = self
|
||||
.ids
|
||||
.iter()
|
||||
.map(|(id, e)| {
|
||||
let comps: Map<String, Value> = self.names(*e).into_iter().filter_map(|n| self.get(*e, &n).cloned().map(|v| (n, v))).collect();
|
||||
let parent = self.w.get::<ChildOf>(*e).and_then(|c| self.back.get(&c.parent()).copied());
|
||||
json!({"id": id, "kind": self.kind.get(id), "components": comps, "parent": parent})
|
||||
})
|
||||
.collect();
|
||||
json!({"entities": ents, "next": self.next, "resources": self.resources, "events": self.events})
|
||||
}
|
||||
|
||||
fn load(d: &Value) -> BWorld {
|
||||
let mut w = BWorld::new();
|
||||
let ents = d["entities"].as_array().cloned().unwrap_or_default();
|
||||
for en in &ents {
|
||||
let id = en["id"].as_u64().unwrap_or(0);
|
||||
let e = w.w.spawn_empty().id();
|
||||
w.ids.insert(id, e);
|
||||
w.back.insert(e, id);
|
||||
if let Some(k) = en["kind"].as_str() {
|
||||
w.kind.insert(id, k.to_string());
|
||||
}
|
||||
for (k, v) in en["components"].as_object().into_iter().flatten() {
|
||||
w.insert(e, k, v.clone());
|
||||
}
|
||||
}
|
||||
for en in &ents {
|
||||
if let (Some(id), Some(p)) = (en["id"].as_u64(), en["parent"].as_u64()) {
|
||||
let (c, p) = (w.ids[&id], w.ids[&p]);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
}
|
||||
w.next = d["next"].as_u64().unwrap_or(0);
|
||||
w.resources = d["resources"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect()).unwrap_or_default();
|
||||
w.events = d["events"].as_object().map(|m| m.iter().map(|(k, v)| (k.clone(), v.as_array().cloned().unwrap_or_default())).collect()).unwrap_or_default();
|
||||
w
|
||||
}
|
||||
|
||||
/// The first version's row: {id, kind, ...the kind component's columns}.
|
||||
fn row(&self, id: u64) -> R<Value> {
|
||||
let e = self.entity(id)?;
|
||||
let kind = self.kind.get(&id).cloned().unwrap_or_default();
|
||||
let mut m = self.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
m.insert("id".into(), json!(id));
|
||||
m.insert("kind".into(), json!(kind));
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static WORLDS: RefCell<(u64, HashMap<u64, BWorld>)> = RefCell::new((0, HashMap::new()));
|
||||
}
|
||||
|
||||
fn u(v: &Value, k: &str) -> R<u64> {
|
||||
v.get(k).and_then(Value::as_u64).ok_or_else(|| format!("{k}: a number"))
|
||||
}
|
||||
fn s<'a>(v: &'a Value, k: &str) -> R<&'a str> {
|
||||
v.get(k).and_then(Value::as_str).ok_or_else(|| format!("{k}: a string"))
|
||||
}
|
||||
fn strings(v: &Value, k: &str) -> Vec<String> {
|
||||
v.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn with_world<T>(v: &Value, f: impl FnOnce(&mut BWorld) -> R<T>) -> R<T> {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
let w = ws.1.get_mut(&id).ok_or_else(|| format!("no world {id}"))?;
|
||||
f(w)
|
||||
})
|
||||
}
|
||||
|
||||
fn put(w: BWorld) -> Value {
|
||||
WORLDS.with(|ws| {
|
||||
let mut ws = ws.borrow_mut();
|
||||
ws.0 += 1;
|
||||
let id = ws.0;
|
||||
ws.1.insert(id, w);
|
||||
json!({"world": id})
|
||||
})
|
||||
}
|
||||
|
||||
/// The ecs.* calls.
|
||||
pub fn call(name: &str, v: &Value) -> R<Value> {
|
||||
match name {
|
||||
"ecs.new" => Ok(put(BWorld::new())),
|
||||
"ecs.clone" => {
|
||||
let d = with_world(v, |w| Ok(w.dump()))?;
|
||||
Ok(put(BWorld::load(&d)))
|
||||
}
|
||||
"ecs.free" => {
|
||||
let id = u(v, "world")?;
|
||||
WORLDS.with(|ws| ws.borrow_mut().1.remove(&id));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"ecs.spawn" => with_world(v, |w| {
|
||||
let mut comps = v.get("components").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let kind = v.get("kind").and_then(Value::as_str).map(str::to_string);
|
||||
if let Some(k) = &kind {
|
||||
comps.insert(k.clone(), Value::Object(v.get("cols").and_then(Value::as_object).cloned().unwrap_or_default()));
|
||||
}
|
||||
let id = w.spawn(&comps);
|
||||
if let Some(k) = kind {
|
||||
w.kind.insert(id, k);
|
||||
}
|
||||
if let Some(p) = v.get("parent").and_then(Value::as_u64) {
|
||||
let (c, p) = (w.entity(id)?, w.entity(p)?);
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
Ok(json!({"id": id}))
|
||||
}),
|
||||
"ecs.set" => with_world(v, |w| {
|
||||
let id = u(v, "id")?;
|
||||
let e = w.entity(id)?;
|
||||
let kind = w.kind.get(&id).cloned().ok_or_else(|| format!("entity {id} has no kind (use ecs.insert)"))?;
|
||||
let mut cur = w.get(e, &kind).and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
for (k, x) in v.get("cols").and_then(Value::as_object).into_iter().flatten() {
|
||||
cur.insert(k.clone(), x.clone());
|
||||
}
|
||||
w.insert(e, &kind, Value::Object(cur));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.get" => with_world(v, |w| w.row(u(v, "id")?)),
|
||||
"ecs.despawn" => with_world(v, |w| w.despawn(u(v, "id")?).map(|_| Value::Null)),
|
||||
"ecs.insert" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for (k, x) in v.get("components").and_then(Value::as_object).into_iter().flatten() {
|
||||
w.insert(e, k, x.clone());
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.remove" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
for n in strings(v, "names") {
|
||||
if let Some(c) = w.comps.get(&n).copied() {
|
||||
w.w.entity_mut(e).remove_by_id(c);
|
||||
}
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.components" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let m: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
Ok(Value::Object(m))
|
||||
}),
|
||||
"ecs.find" => with_world(v, |w| {
|
||||
let with = strings(v, "with");
|
||||
let without = strings(v, "without");
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids = w.find(&with, &without);
|
||||
let default = with.first().cloned();
|
||||
let ids: Vec<u64> = ids.into_iter().filter(|id| conds.iter().all(|c| w.passes(w.ids[id], default.as_deref(), c))).collect();
|
||||
if v.get("rows").and_then(Value::as_bool).unwrap_or(false) {
|
||||
let rows: Vec<Value> = ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let e = w.ids[id];
|
||||
let comps: Map<String, Value> = w.names(e).into_iter().filter_map(|n| w.get(e, &n).cloned().map(|x| (n, x))).collect();
|
||||
json!({"id": id, "components": comps})
|
||||
})
|
||||
.collect();
|
||||
return Ok(json!({"ids": ids, "rows": rows}));
|
||||
}
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
// the first version's query: a kind's entities by its columns
|
||||
"ecs.query" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let conds: Vec<Value> = v.get("where").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).filter(|id| conds.iter().all(|c| w.passes(w.ids[id], Some(&kind), c))).collect();
|
||||
Ok(json!({"ids": ids}))
|
||||
}),
|
||||
"ecs.column" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
let col = s(v, "col")?;
|
||||
let ids: Vec<u64> = w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).collect();
|
||||
Ok(json!(ids.iter().map(|id| w.get(w.ids[id], &kind).and_then(|c| c.get(col)).and_then(Value::as_f64).map(|x| json!(x)).unwrap_or(Value::Null)).collect::<Vec<_>>()))
|
||||
}),
|
||||
"ecs.count" => with_world(v, |w| {
|
||||
let kind = s(v, "kind")?.to_string();
|
||||
Ok(json!(w.find(std::slice::from_ref(&kind), &[]).into_iter().filter(|id| w.kind.get(id) == Some(&kind)).count()))
|
||||
}),
|
||||
"ecs.rows" => with_world(v, |w| {
|
||||
let mut ids: Vec<(String, u64)> = w.kind.iter().map(|(id, k)| (k.clone(), *id)).collect();
|
||||
ids.sort();
|
||||
Ok(Value::Array(ids.into_iter().filter_map(|(_, id)| w.row(id).ok()).collect()))
|
||||
}),
|
||||
"ecs.parent" => with_world(v, |w| {
|
||||
let c = w.entity(u(v, "id")?)?;
|
||||
match v.get("parent").and_then(Value::as_u64) {
|
||||
Some(p) => {
|
||||
let p = w.entity(p)?;
|
||||
w.w.entity_mut(c).insert(ChildOf(p));
|
||||
}
|
||||
None if v.get("parent").is_some_and(Value::is_null) => {
|
||||
w.w.entity_mut(c).remove::<ChildOf>();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(json!(w.w.get::<ChildOf>(c).and_then(|p| w.back.get(&p.parent()).copied())))
|
||||
}),
|
||||
"ecs.children" => with_world(v, |w| {
|
||||
let e = w.entity(u(v, "id")?)?;
|
||||
let mut out: Vec<u64> = w.w.get::<Children>(e).map(|c| c.iter().filter_map(|x| w.back.get(&x).copied()).collect()).unwrap_or_default();
|
||||
out.sort_unstable();
|
||||
Ok(json!(out))
|
||||
}),
|
||||
"ecs.resource" => with_world(v, |w| {
|
||||
let name = s(v, "name")?.to_string();
|
||||
if let Some(x) = v.get("value") {
|
||||
w.resources.insert(name.clone(), x.clone());
|
||||
}
|
||||
Ok(w.resources.get(&name).cloned().unwrap_or(Value::Null))
|
||||
}),
|
||||
"ecs.send" => with_world(v, |w| {
|
||||
w.events.entry(s(v, "name")?.to_string()).or_default().push(v.get("value").cloned().unwrap_or(Value::Null));
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
"ecs.events" => with_world(v, |w| Ok(json!(w.events.get(s(v, "name")?).cloned().unwrap_or_default()))),
|
||||
"ecs.clear_events" => with_world(v, |w| {
|
||||
w.events.clear();
|
||||
Ok(Value::Null)
|
||||
}),
|
||||
// what renders, straight from the world: entities with a Mesh and a Transform as 3D nodes (world space,
|
||||
// parents' transforms composed), and lights; the bridge draws these without a React element per entity
|
||||
"ecs.scene" => with_world(v, |w| {
|
||||
let mut out = Vec::new();
|
||||
for id in w.find(&["Mesh".into()], &[]) {
|
||||
let e = w.ids[&id];
|
||||
let mesh = w.get(e, "Mesh").cloned().unwrap_or(Value::Null);
|
||||
let mut t = transform_of(w.get(e, "Transform"));
|
||||
let mut p = w.w.get::<ChildOf>(e).map(|c| c.parent());
|
||||
while let Some(pe) = p {
|
||||
let pt = transform_of(w.get(pe, "Transform"));
|
||||
t = compose(&pt, &t);
|
||||
p = w.w.get::<ChildOf>(pe).map(|c| c.parent());
|
||||
}
|
||||
out.push(json!({"id": id, "kind": "Mesh", "mesh": mesh, "position": [t[0], t[1], t[2]], "rotation": [t[3], t[4], t[5]], "scale": t[6]}));
|
||||
}
|
||||
for id in w.find(&["Light".into()], &[]) {
|
||||
out.push(json!({"id": id, "kind": "Light", "light": w.get(w.ids[&id], "Light").cloned().unwrap_or(Value::Null)}));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}),
|
||||
o => Err(format!("no native call {o}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// [x, y, z, rx, ry, rz, scale] from a Transform component ({x, y, z, rx, ry, rz, scale}, all optional).
|
||||
fn transform_of(t: Option<&Value>) -> [f64; 7] {
|
||||
let g = |k: &str, d: f64| t.and_then(|t| t.get(k)).and_then(Value::as_f64).unwrap_or(d);
|
||||
[g("x", 0.0), g("y", 0.0), g("z", 0.0), g("rx", 0.0), g("ry", 0.0), g("rz", 0.0), g("scale", 1.0)]
|
||||
}
|
||||
|
||||
/// A child's transform in its parent's space, made world space (rotation by z, then y, then x; uniform scale).
|
||||
fn compose(parent: &[f64; 7], child: &[f64; 7]) -> [f64; 7] {
|
||||
let (sx, cx) = parent[3].sin_cos();
|
||||
let (sy, cy) = parent[4].sin_cos();
|
||||
let (sz, cz) = parent[5].sin_cos();
|
||||
let (mut x, mut y, mut z) = (child[0] * parent[6], child[1] * parent[6], child[2] * parent[6]);
|
||||
// z
|
||||
let (x1, y1) = (x * cz - y * sz, x * sz + y * cz);
|
||||
x = x1;
|
||||
y = y1;
|
||||
// y
|
||||
let (x2, z2) = (x * cy + z * sy, -x * sy + z * cy);
|
||||
x = x2;
|
||||
z = z2;
|
||||
// x
|
||||
let (y3, z3) = (y * cx - z * sx, y * sx + z * cx);
|
||||
y = y3;
|
||||
z = z3;
|
||||
[parent[0] + x, parent[1] + y, parent[2] + z, parent[3] + child[3], parent[4] + child[4], parent[5] + child[5], parent[6] * child[6]]
|
||||
}
|
||||
|
||||
/// The ecs.* names with their TypeScript types, for the registry.
|
||||
pub const CALLS: &[(&str, &str, &str, &str)] = &[
|
||||
("ecs.new", "{}", "{ world: number }", "a new world (Bevy's)"),
|
||||
("ecs.clone", "{ world: number }", "{ world: number }", "a copy of a world"),
|
||||
("ecs.free", "{ world: number }", "null", "drop a world"),
|
||||
("ecs.spawn", "{ world: number; kind?: string; cols?: Record<string, number | string | boolean>; components?: Record<string, unknown>; parent?: number }", "{ id: number }", "a new entity: a kind with columns, and/or any components"),
|
||||
("ecs.set", "{ world: number; id: number; cols: Record<string, number | string | boolean> }", "null", "columns merged into an entity's kind"),
|
||||
("ecs.get", "{ world: number; id: number }", "{ id: number; kind: string } & Record<string, number | string | boolean>", "an entity's row (its kind's columns)"),
|
||||
("ecs.despawn", "{ world: number; id: number }", "null", "remove an entity and its children"),
|
||||
("ecs.insert", "{ world: number; id: number; components: Record<string, unknown> }", "null", "components added to (or replaced on) an entity"),
|
||||
("ecs.remove", "{ world: number; id: number; names: string[] }", "null", "components taken off an entity"),
|
||||
("ecs.components", "{ world: number; id: number }", "Record<string, unknown>", "an entity's components by name"),
|
||||
("ecs.find", "{ world: number; with?: string[]; without?: string[]; where?: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][]; rows?: boolean }", "{ ids: number[]; rows?: { id: number; components: Record<string, unknown> }[] }", "entities with every `with` component and no `without` one (Bevy's query), passing every condition (\"Comp.field\")"),
|
||||
("ecs.query", "{ world: number; kind: string; where: [string, \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\", number | string | boolean][] }", "{ ids: number[] }", "ids of kind's entities passing every condition"),
|
||||
("ecs.column", "{ world: number; kind: string; col: string }", "(number | null)[]", "one numeric column of a kind, in id order"),
|
||||
("ecs.count", "{ world: number; kind: string }", "number", "how many entities of a kind"),
|
||||
("ecs.rows", "{ world: number }", "({ id: number; kind: string } & Record<string, number | string | boolean>)[]", "every kind's rows, by kind then id"),
|
||||
("ecs.parent", "{ world: number; id: number; parent?: number | null }", "number | null", "an entity's parent (set it with parent; null clears it)"),
|
||||
("ecs.children", "{ world: number; id: number }", "number[]", "an entity's children"),
|
||||
("ecs.resource", "{ world: number; name: string; value?: unknown }", "unknown", "a resource (set it with value)"),
|
||||
("ecs.send", "{ world: number; name: string; value?: unknown }", "null", "an event for this frame"),
|
||||
("ecs.events", "{ world: number; name: string }", "unknown[]", "this frame's events of a name"),
|
||||
("ecs.clear_events", "{ world: number }", "null", "the frame's events cleared (each step starts with none)"),
|
||||
("ecs.scene", "{ world: number }", "{ id: number; kind: \"Mesh\" | \"Light\"; mesh?: unknown; light?: unknown; position?: [number, number, number]; rotation?: [number, number, number]; scale?: number }[]", "the world's Mesh+Transform entities (world space) and lights, to draw"),
|
||||
];
|
||||
|
||||
/// How many worlds are alive (media.live's leak check).
|
||||
pub fn live() -> usize {
|
||||
WORLDS.with(|ws| ws.borrow().1.len())
|
||||
}
|
||||
@@ -11,8 +11,6 @@ raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# the lint's other faults judged as the render shows them (docs/notice.feature NT9)
|
||||
raea-sys-notice = { path = "../../systems/notice" }
|
||||
# each part held to its planned detail (MK21)
|
||||
raea-runtime-lod-plan = { path = "../lod-plan" }
|
||||
serde_json = "1"
|
||||
@@ -1,75 +0,0 @@
|
||||
//! The scene lint's other faults judged at a render's end (docs/notice.feature NT9; RAEA_FAULTS_CHECK=0 skips it):
|
||||
//! parts floating, sunk, in the air, a prop lifted against a wall, faces fighting for the same depth. The first frame's
|
||||
//! parts are linted (raea-sys-contact) and each finding judged by raea-sys-notice as a viewer of this render would see
|
||||
//! it: through every frame's camera (up to CAMERAS, evenly over the render), by its size on screen, by the learned
|
||||
//! judge. Only the likely faults are said. Parts clipping each other are the clipping check's, which already follows
|
||||
//! them through every frame, so they're left out here.
|
||||
//!
|
||||
//! A render keeps the first two frames' parts and each frame's camera (one item a frame), nothing more.
|
||||
|
||||
use raea_core_facts::{Finding, Level};
|
||||
use raea_core_scene::Item;
|
||||
|
||||
/// The most frames whose cameras are asked.
|
||||
const CAMERAS: usize = 48;
|
||||
|
||||
pub struct Faults {
|
||||
w: u32,
|
||||
h: u32,
|
||||
first: Option<(i64, Vec<Item>)>,
|
||||
second: Option<Vec<Item>>,
|
||||
cams: Vec<Item>,
|
||||
}
|
||||
|
||||
impl Faults {
|
||||
pub fn new(w: u32, h: u32) -> Faults {
|
||||
Faults { w, h, first: None, second: None, cams: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, frame: i64, its: &[Item]) {
|
||||
if its.is_empty() {
|
||||
return;
|
||||
}
|
||||
match (&self.first, &self.second) {
|
||||
(None, _) => self.first = Some((frame, its.to_vec())),
|
||||
(Some(_), None) => self.second = Some(its.to_vec()),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(c) = its.iter().find(|i| i.kind == "camera") {
|
||||
self.cams.push(c.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn told(self, by: &str) -> Vec<Finding> {
|
||||
let Some((frame, first)) = self.first else { return Vec::new() };
|
||||
let t = std::time::Instant::now();
|
||||
let next = self.second.as_deref().unwrap_or(&first);
|
||||
let (found, _) = raea_sys_contact::lint_with(&first, next, false);
|
||||
let linted = t.elapsed();
|
||||
let step = self.cams.len().div_ceil(CAMERAS).max(1);
|
||||
let mut views = vec![first.clone()];
|
||||
views.extend(self.cams.iter().step_by(step).map(|c| vec![c.clone()]));
|
||||
let model = raea_sys_notice::Model::load();
|
||||
let judged = raea_sys_notice::judge(&found, &views, self.w, self.h, &model);
|
||||
let out: Vec<Finding> = judged
|
||||
.iter()
|
||||
.filter(|j| j.p >= raea_sys_notice::FAULT && j.fault.check != "clips")
|
||||
.map(|j| {
|
||||
let f = &j.fault;
|
||||
let mut x = Finding::new(&f.check, Level::Warn, format!("{} (likely a fault, {:.2}: seen on {} of {} frames asked, {:.1} px)", f.says, j.p, j.seen.shown, j.seen.frames, j.seen.px), by).frames(frame, frame + 1).about(f.part.clone(), None).measure("likely", f64::from(j.p), "", Some(f64::from(raea_sys_notice::FAULT)));
|
||||
if let Some(into) = &f.into {
|
||||
x = x.about(into.clone(), None);
|
||||
}
|
||||
x
|
||||
})
|
||||
.collect();
|
||||
for f in &out {
|
||||
eprintln!("raea: {}", f.line());
|
||||
}
|
||||
raea_core_facts::finding::said(&out);
|
||||
if std::env::var("RAEA_TIMES").is_ok() {
|
||||
eprintln!("raea times: the judged faults {:.0} ms, the lint {:.0} of it ({} findings, {} likely faults)", t.elapsed().as_secs_f64() * 1e3, linted.as_secs_f64() * 1e3, judged.len(), out.len());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,7 @@
|
||||
//! the manifest's word on the parts (raea_sys_stage::Mounts) keep of them, and let go, so a long render never holds its
|
||||
//! frames' parts for its checks. raea-runtime-export hands each frame in as it's drawn, and a still's at its end.
|
||||
//! With them, each part held to its planned detail (raea-runtime-lod-plan; RAEA_LOD_CHECK=0 skips it): its own `lod`, else
|
||||
//! its name's on the plan above the composition (its plan.rs: `lod` on the brief's make objects, MK22). And the scene
|
||||
//! lint's other faults judged as this render shows them (faults.rs, raea-sys-notice; RAEA_FAULTS_CHECK=0 skips it).
|
||||
|
||||
mod faults;
|
||||
//! its name's on the plan above the composition (its plan.rs: `lod` on the brief's make objects, MK22).
|
||||
|
||||
use raea_core_facts::Finding;
|
||||
use raea_core_scene::Item;
|
||||
@@ -16,7 +13,6 @@ pub struct EndChecks {
|
||||
clip: Option<raea_sys_contact::Clipping>,
|
||||
stage: Option<raea_sys_stage::Staging>,
|
||||
lod: Option<raea_runtime_lod_plan::Lods>,
|
||||
faults: Option<faults::Faults>,
|
||||
mounts: raea_sys_stage::Mounts,
|
||||
any: bool,
|
||||
parts: usize,
|
||||
@@ -27,8 +23,7 @@ impl EndChecks {
|
||||
let on = |k: &str| std::env::var(k).as_deref() != Ok("0");
|
||||
let (clip, stage) = (on("RAEA_CLIP_CHECK").then(|| raea_sys_contact::Clipping::new(w, h, fps)), on("RAEA_STAGE_CHECK").then(|| raea_sys_stage::Staging::new(w, h, fps)));
|
||||
let lod = on("RAEA_LOD_CHECK").then(|| raea_runtime_lod_plan::Lods::new(w, h, fps, raea_runtime_lod_plan::plan::here(), false));
|
||||
let faults = on("RAEA_FAULTS_CHECK").then(|| faults::Faults::new(w, h));
|
||||
EndChecks { clip, stage, lod, faults, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
|
||||
EndChecks { clip, stage, lod, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
|
||||
}
|
||||
|
||||
/// The next frame (its number, `frame`): its parts, and its page where the manifest has it.
|
||||
@@ -43,9 +38,6 @@ impl EndChecks {
|
||||
if let Some(l) = &mut self.lod {
|
||||
l.push(frame, its);
|
||||
}
|
||||
if let Some(f) = &mut self.faults {
|
||||
f.push(frame, its);
|
||||
}
|
||||
self.mounts.push(frame, its);
|
||||
}
|
||||
|
||||
@@ -67,9 +59,6 @@ impl EndChecks {
|
||||
closer.iter().for_each(|f| eprintln!("raea: {}", f.line()));
|
||||
raea_core_facts::finding::said(&closer);
|
||||
found.extend(closer);
|
||||
// the lint's other faults (floating, sunk, lifted, fighting faces), judged as this render shows them
|
||||
found.extend(self.faults.map_or_else(Vec::new, |f| f.told(raea_sys_stage::BY)));
|
||||
mark("end checks: judged faults");
|
||||
// the clipping check's solids, kept for the process, aren't needed again by a render
|
||||
raea_sys_contact::forget();
|
||||
mark("end checks: done, their solids let go");
|
||||
|
||||
@@ -167,9 +167,9 @@ pub fn live_scene(world: &mut World, ls: &mut LiveScene, engine: &mut Option<rae
|
||||
None => {
|
||||
let clear = scene_clear(world);
|
||||
let p = ls.open(Shot { scene: &scene, clear: clear.as_deref() }, size.0, size.1, fps);
|
||||
let mut e = aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir).map_err(|e| format!("the 3D didn't open: {e}"))?);
|
||||
let e = raea_render::engine::Engine::open_in(engine, &p, dir).map_err(|e| format!("the 3D didn't open: {e}"))?;
|
||||
aov_on(e);
|
||||
e.set_rows(&[])?;
|
||||
*engine = Some(e);
|
||||
}
|
||||
Some(e) => {
|
||||
// the frame's own clear, keyed as a render keys a background that changes (RR1)
|
||||
@@ -268,7 +268,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
|
||||
if programmed && !restepped && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {
|
||||
restepped = true;
|
||||
if let Some(p) = scene_program_checked(js, &dir, total, Some(wanted))? {
|
||||
cx.scene3d = Some(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), &dir)?);
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, &dir)?);
|
||||
if let Some(m) = cx.manifest.as_mut() {
|
||||
m.pop();
|
||||
}
|
||||
|
||||
@@ -299,7 +299,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None };
|
||||
if fed {
|
||||
if let Some(p) = scene {
|
||||
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
raea_runtime_react::startup_mark("the 3D's engine open");
|
||||
}
|
||||
if live3d {
|
||||
@@ -312,7 +312,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
let programmed = scene.is_some();
|
||||
match scene {
|
||||
Some(p) => {
|
||||
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
raea_runtime_react::startup_mark("the 3D's engine open");
|
||||
}
|
||||
None => cx.live3d = Some(LiveScene::default()),
|
||||
@@ -337,7 +337,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
if i == 0 && programmed && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {
|
||||
let upto = wanted.iter().max().map_or(0, |m| m + 1);
|
||||
if let Some(p) = scene_program_checked(js, dir, upto, Some(&wanted))? {
|
||||
cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
px = bevy_over_3d(app.world_mut(), pg, &mut cx, fps)?;
|
||||
}
|
||||
}
|
||||
@@ -442,11 +442,10 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
}
|
||||
|
||||
/// An engine for the scene path, drawing the guide data when `--aov` asked for it.
|
||||
pub(crate) fn aov_on(mut e: raea_render::engine::Engine) -> raea_render::engine::Engine {
|
||||
pub(crate) fn aov_on(e: &mut raea_render::engine::Engine) {
|
||||
if AOV.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
e.want_aov();
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
/// Frame i's guide data (RT1) as mlxdlss run-sequence reads it: DIR/motion/frame-NNNNN.f32 (H x W x 2 float32) and
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "raea-runtime-kinds"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A 3D scene's rows for the kinds placed as a whole: glTF models, panels, decals, plates, fog volumes, fires, Gaussian splats, mesh sequences and fields of grass"
|
||||
|
||||
[dependencies]
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
raea-runtime-look = { path = "../look" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
|
||||
pub fn rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(track);
|
||||
let first = &its[0].props;
|
||||
@@ -0,0 +1,51 @@
|
||||
//! A 3D scene's rows for the kinds placed as a whole: glTF models, panels, decals, plates, fog volumes, fires, Gaussian
|
||||
//! splats, mesh sequences and fields of grass. raea-runtime-scene walks the scene into each kind's tracks and builds the
|
||||
//! rest (meshes, lights, text, the camera); a part's placement and name columns are shared by both.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use raea_core_program::ir::{Program, V};
|
||||
use raea_core_scene::*;
|
||||
use raea_runtime_look::*;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// One part's frames, by its key: the part as each frame has it, or none where it isn't there.
|
||||
pub type Track = (String, Vec<Option<Item>>);
|
||||
|
||||
mod models;
|
||||
pub use models::*;
|
||||
/// Gaussian splats' rows (<Splat>).
|
||||
pub mod splat;
|
||||
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
|
||||
pub mod meshseq;
|
||||
/// Fields of grass' rows (<Grass>).
|
||||
pub mod grass;
|
||||
|
||||
/// A part's SDK name as its row's `name` column: what a Bevy Entity field (a ChildOf's parent) names it by.
|
||||
pub fn name_column(row: &mut BTreeMap<String, V>, props: &Map<String, Value>) {
|
||||
if let Some(Value::String(n)) = props.get("name") {
|
||||
row.insert("name".into(), V::S(n.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and
|
||||
/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.
|
||||
pub fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
|
||||
let mut prev = bevy::math::Quat::IDENTITY;
|
||||
let per: Vec<[f64; 10]> = its.iter().map(|it| {
|
||||
let (s, q, t) = it.world.to_scale_rotation_translation();
|
||||
// a zero scale has no rotation (it comes out NaN, keyed on every frame since NaN never equals itself): the one before
|
||||
let q = if q.is_finite() { q } else { prev };
|
||||
prev = if q.dot(prev) < 0.0 { -q } else { q };
|
||||
[t.x as f64, t.y as f64, t.z as f64, prev.x as f64, prev.y as f64, prev.z as f64, prev.w as f64, s.x as f64, s.y as f64, s.z as f64]
|
||||
}).collect();
|
||||
for (k, name) in ["x", "y", "z", "q_x", "q_y", "q_z", "q_w"].iter().enumerate() {
|
||||
exact(p, row, id, name, &per.iter().map(|t| t[k]).collect::<Vec<_>>());
|
||||
}
|
||||
let sc: Vec<[f64; 3]> = per.iter().map(|t| [t[7], t[8], t[9]]).collect();
|
||||
if sc.iter().any(|s| s.iter().any(|v| (v - 1.0).abs() > 1e-9)) {
|
||||
for (k, name) in ["scale_x", "scale_y", "scale_z"].iter().enumerate() {
|
||||
exact(p, row, id, name, &sc.iter().map(|s| s[k]).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub(super) fn cloth_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id:
|
||||
/// Numeric props of a sequence and the columns they key (the default when a frame leaves one out).
|
||||
const KEYED: &[(&str, &str, f64)] = &[("frame", "frame", 0.0), ("roughness", "rough", 0.3), ("metalness", "metal", 0.0)];
|
||||
|
||||
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
|
||||
pub fn rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(track);
|
||||
let id = format!("meshseq{k}");
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::*;
|
||||
|
||||
/// glTF models: the file, its clip and the clip's time (keyed: the component works it out from the frame)
|
||||
pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tr.models.iter().enumerate() {
|
||||
pub fn models_rows(tracks: &[Track], names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("model{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -64,7 +64,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
// attached to another model's bone: that model's row by its name
|
||||
if let Some(a) = first.get("attach") {
|
||||
let to = a.get("to").and_then(Value::as_str).unwrap_or("");
|
||||
if let Some(j) = tr.models.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
if let Some(j) = tracks.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
row.insert("attach_to".into(), V::S(format!("model{j}")));
|
||||
row.insert("attach_bone".into(), V::S(a.get("bone").and_then(Value::as_str).unwrap_or("").into()));
|
||||
} else {
|
||||
@@ -76,7 +76,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
let (mut joints, mut rows) = (Vec::new(), Vec::new());
|
||||
for (joint, to) in b {
|
||||
let to = to.as_str().unwrap_or("");
|
||||
match tr.models.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
match tracks.iter().position(|(_, t)| t.iter().flatten().next().and_then(|i| i.props.get("name")).and_then(Value::as_str) == Some(to)) {
|
||||
Some(j) => {
|
||||
joints.push(joint.clone());
|
||||
rows.push(format!("model{j}"));
|
||||
@@ -140,8 +140,8 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
}
|
||||
|
||||
/// pictures in space (raea-render's panel: unlit, painted once, moved by the GPU)
|
||||
pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tr.panels.iter().enumerate() {
|
||||
pub fn panels_rows(tracks: &[Track], names: &[String], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("plane{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -177,8 +177,8 @@ pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
|
||||
/// decals: the picture and its surface from the first frame; placement, colour and opacity keyed (a stain that
|
||||
/// spreads, a label that fades in)
|
||||
pub(crate) fn decals_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.decals.iter().enumerate() {
|
||||
pub fn decals_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("decal{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -205,8 +205,8 @@ pub(crate) fn decals_rows(tr: &Tracks, p: &mut Program) {
|
||||
|
||||
/// footage behind the 3D (raea-render's plate: a video frame per frame on the camera's far plane, unlit): its source time
|
||||
/// keyed, the clip and its lens's distortion the first frame's
|
||||
pub(crate) fn plates_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.plates.iter().enumerate() {
|
||||
pub fn plates_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("plate{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -223,8 +223,8 @@ pub(crate) fn plates_rows(tr: &Tracks, p: &mut Program) {
|
||||
}
|
||||
|
||||
/// fog volumes (a <VolumetricFog>'s boxes of air): placement, density and colour keyed, the rest the first frame's
|
||||
pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.fogs.iter().enumerate() {
|
||||
pub fn fogs_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("fog{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -253,8 +253,8 @@ pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {
|
||||
}
|
||||
|
||||
/// fires (<Fire>: a flame drawn as a volume): its foot, its box's size, its clock, brightness and colour keyed
|
||||
pub(crate) fn fires_rows(tr: &Tracks, p: &mut Program) {
|
||||
for (k, (_, track)) in tr.fires.iter().enumerate() {
|
||||
pub fn fires_rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(&track);
|
||||
let id = format!("fire{k}");
|
||||
let mut row = BTreeMap::new();
|
||||
@@ -33,7 +33,7 @@ const KEYED: &[(&str, &str, f64)] = &[
|
||||
/// Vector props: the prop, its three columns.
|
||||
const VECS: &[(&str, [&str; 3])] = &[("wind", ["wind_x", "wind_y", "wind_z"]), ("revealFrom", ["reveal_x", "reveal_y", "reveal_z"]), ("revealAxis", ["reveal_ax", "reveal_ay", "reveal_az"])];
|
||||
|
||||
pub(super) fn rows(tracks: &[Track], p: &mut Program) {
|
||||
pub fn rows(tracks: &[Track], p: &mut Program) {
|
||||
for (k, (_, track)) in tracks.iter().enumerate() {
|
||||
let its = filled(track);
|
||||
let id = format!("splat{k}");
|
||||
@@ -51,6 +51,9 @@ raea-core-alloc = { path = "../../core/alloc" }
|
||||
# a composition's TSX bundled into the script the engine runs
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
# a long BufferMesh kept on disk by its content (read.rs names3d, docs/render-memory.feature RM8)
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
xxhash-rust = { version = "0.8", features = ["xxh3"] }
|
||||
raea-runtime-calls = { path = "../../runtime/calls" }
|
||||
raea-runtime-shared = { path = "../../runtime/shared" }
|
||||
raea-runtime-scene = { path = "../../runtime/scene" }
|
||||
|
||||
@@ -41,7 +41,7 @@ thread_local! {
|
||||
/// each part's data-props as last parsed: its text and the props, and the scene it was last read in
|
||||
static PROPS3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(String, std::sync::Arc<Map<String, Value>>, u64)>> = std::cell::RefCell::new(Default::default());
|
||||
/// each part's data-3d and data-shape as last read, shared
|
||||
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>)>> = std::cell::RefCell::new(Default::default());
|
||||
static NAMES3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<(std::sync::Arc<str>, Option<std::sync::Arc<str>>, Option<(usize, u64)>)>> = std::cell::RefCell::new(Default::default());
|
||||
/// each part's data-at (an <Instances>' placements) as last read, shared while its text is the same (issue 84)
|
||||
static AT3D: std::cell::RefCell<bevy::ecs::entity::EntityHashMap<std::sync::Arc<str>>> = std::cell::RefCell::new(Default::default());
|
||||
/// scenes read (scene_of): what's in PROPS3D but not read in the last two is let go
|
||||
|
||||
@@ -34,21 +34,33 @@ pub(crate) fn props3d(e: Entity, text: Option<&str>) -> std::sync::Arc<Map<Strin
|
||||
})
|
||||
}
|
||||
|
||||
/// A part's kind and shape, the shared ones from its last read when they're the same
|
||||
/// A part's kind and shape, the shared ones from its last read when they're the same. A long <BufferMesh> shape
|
||||
/// (`buffer:{json}`, raea_core_shape::KEEP_BUFFER_AT on) goes on as `buffer:@NAME`, its text kept on disk by its
|
||||
/// content (kept_buffer, docs/render-memory.feature RM8), and is known again by its length and xxh3 (about 2 ms for
|
||||
/// 51 MB), never named again while it's the same.
|
||||
pub(crate) fn names3d(e: Entity, kind: &str, shape: Option<&str>) -> (std::sync::Arc<str>, Option<std::sync::Arc<str>>) {
|
||||
let long = shape.filter(|s| s.len() >= raea_core_shape::KEEP_BUFFER_AT && s.starts_with("buffer:{"));
|
||||
let sig = long.map(|s| (s.len(), xxhash_rust::xxh3::xxh3_64(s.as_bytes())));
|
||||
NAMES3D.with_borrow_mut(|c| {
|
||||
if let Some((k, s)) = c.get(&e)
|
||||
if let Some((k, s, was)) = c.get(&e)
|
||||
&& &**k == kind
|
||||
&& s.as_deref() == shape
|
||||
&& match sig {
|
||||
Some(sig) => *was == Some(sig),
|
||||
None => was.is_none() && s.as_deref() == shape,
|
||||
}
|
||||
{
|
||||
return (k.clone(), s.clone());
|
||||
}
|
||||
let v: (std::sync::Arc<str>, Option<std::sync::Arc<str>>) = (kind.into(), shape.map(Into::into));
|
||||
let out: Option<std::sync::Arc<str>> = match long {
|
||||
Some(text) => Some(raea_core_shape::kept_buffer(text).map(Into::into).unwrap_or_else(|| text.into())),
|
||||
None => shape.map(Into::into),
|
||||
};
|
||||
let v: (std::sync::Arc<str>, Option<std::sync::Arc<str>>) = (kind.into(), out);
|
||||
// bounded well past a big scene's parts (many_cubes has 10,000; at 8,192 it was cleared every frame)
|
||||
if c.len() > 1 << 17 {
|
||||
c.clear();
|
||||
}
|
||||
c.insert(e, v.clone());
|
||||
c.insert(e, (v.0.clone(), v.1.clone(), sig));
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ description = "A composition's 3D as raea-render rows: the camera, lights, meshe
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
raea-runtime-look = { path = "../look" }
|
||||
# the rows of the kinds placed as a whole (models, splats, grass and the rest)
|
||||
raea-runtime-kinds = { path = "../kinds" }
|
||||
raea-runtime-scene2d = { path = "../scene2d" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -15,22 +15,15 @@ use raea_core_scene::*;
|
||||
pub use raea_runtime_look::{camera, column, rgba_of};
|
||||
use raea_runtime_look::*;
|
||||
|
||||
// the rows of the kinds placed as a whole (models, panels, decals, plates, fog, fire, splats, mesh sequences, grass)
|
||||
use raea_runtime_kinds::*;
|
||||
mod parts;
|
||||
use parts::*;
|
||||
mod models;
|
||||
use models::*;
|
||||
mod live;
|
||||
pub use live::{LiveScene, Shot};
|
||||
pub use raea_core_scene::{LIVE_GROUPS, cam_keyed, live_dynamic};
|
||||
mod fast;
|
||||
|
||||
/// Gaussian splats' rows (<Splat>).
|
||||
mod splat;
|
||||
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
|
||||
mod meshseq;
|
||||
/// Fields of grass' rows (<Grass>).
|
||||
mod grass;
|
||||
|
||||
/// The scene-wide parts placed by their parent alone, a camera column or a post effect each: node kind, item kind. An
|
||||
/// <Atmosphere> is Bevy's procedural sky round the scene, a <Skybox> Bevy's cubemap sky on the camera.
|
||||
const BY_PARENT: [(&str, &str); 19] = [("AmbientLight", "ambient"), ("Bloom", "bloom"), ("Atmosphere", "atmosphere"), ("Fog", "fog"), ("ToneMapping", "tonemapping"), ("DepthOfField", "dof"), ("Grade", "grade"), ("VolumetricFog", "volfog"), ("Environment", "environment"), ("Skybox", "skybox"),
|
||||
@@ -176,12 +169,6 @@ fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A part's SDK name as its row's `name` column: what a Bevy Entity field (a ChildOf's parent) names it by.
|
||||
fn name_column(row: &mut BTreeMap<String, V>, props: &Map<String, Value>) {
|
||||
if let Some(Value::String(n)) = props.get("name") {
|
||||
row.insert("name".into(), V::S(n.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The <BevyComponent> children of a part (a Mesh, a Model, a light, the camera) onto its item as `components`: Bevy's
|
||||
/// own reflected components, or a compiled-in plugin's, applied by raea-render through the TypeRegistry (plugins.rs).
|
||||
@@ -224,27 +211,6 @@ pub fn items_of(scene: &[Node3]) -> Vec<Item> {
|
||||
}
|
||||
|
||||
|
||||
/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and
|
||||
/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.
|
||||
fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {
|
||||
let mut prev = bevy::math::Quat::IDENTITY;
|
||||
let per: Vec<[f64; 10]> = its.iter().map(|it| {
|
||||
let (s, q, t) = it.world.to_scale_rotation_translation();
|
||||
// a zero scale has no rotation (it comes out NaN, keyed on every frame since NaN never equals itself): the one before
|
||||
let q = if q.is_finite() { q } else { prev };
|
||||
prev = if q.dot(prev) < 0.0 { -q } else { q };
|
||||
[t.x as f64, t.y as f64, t.z as f64, prev.x as f64, prev.y as f64, prev.z as f64, prev.w as f64, s.x as f64, s.y as f64, s.z as f64]
|
||||
}).collect();
|
||||
for (k, name) in ["x", "y", "z", "q_x", "q_y", "q_z", "q_w"].iter().enumerate() {
|
||||
exact(p, row, id, name, &per.iter().map(|t| t[k]).collect::<Vec<_>>());
|
||||
}
|
||||
let sc: Vec<[f64; 3]> = per.iter().map(|t| [t[7], t[8], t[9]]).collect();
|
||||
if sc.iter().any(|s| s.iter().any(|v| (v - 1.0).abs() > 1e-9)) {
|
||||
for (k, name) in ["scale_x", "scale_y", "scale_z"].iter().enumerate() {
|
||||
exact(p, row, id, name, &sc.iter().map(|s| s[k]).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lights, meshes, models and pictures in space, as rows, from each frame's parts.
|
||||
pub fn rows(all: &[Vec<Item>], p: &mut Program) {
|
||||
@@ -261,7 +227,6 @@ pub fn rows(all: &[Vec<Item>], p: &mut Program) {
|
||||
}
|
||||
}
|
||||
|
||||
type Track = (String, Vec<Option<Item>>);
|
||||
|
||||
/// Each kind group's tracks, worked out once (a live frame worked them out twice: in rows_into and again for its ids)
|
||||
struct Tracks {
|
||||
@@ -315,12 +280,12 @@ fn rows_into_of(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
|
||||
meshes_rows(tr, &names, p);
|
||||
entities_rows(tr, p);
|
||||
texts_rows(tr, &names, p);
|
||||
models_rows(tr, &names, p);
|
||||
panels_rows(tr, &names, p);
|
||||
decals_rows(tr, p);
|
||||
plates_rows(tr, p);
|
||||
fogs_rows(tr, p);
|
||||
fires_rows(tr, p);
|
||||
models_rows(&tr.models, &names, p);
|
||||
panels_rows(&tr.panels, &names, p);
|
||||
decals_rows(&tr.decals, p);
|
||||
plates_rows(&tr.plates, p);
|
||||
fogs_rows(&tr.fogs, p);
|
||||
fires_rows(&tr.fires, p);
|
||||
// fields of grass (<Grass>): grass.rs
|
||||
grass::rows(&tr.grasses, p);
|
||||
// gaussian splats (<Splat>): splat.rs
|
||||
|
||||
@@ -134,6 +134,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
let mat = |i: &Item| i.material.as_ref().map(|m| m.props.clone()).unwrap_or_default();
|
||||
let mats: Vec<std::sync::Arc<Map<String, Value>>> = its.iter().map(mat).collect();
|
||||
let basic = its[0].material.as_ref().is_some_and(|m| &*m.kind == "MeshBasicMaterial");
|
||||
let swaps = raea_core_scene::swaps_maps(&its[0]);
|
||||
let colors: Vec<String> = mats.iter().map(|m| hex(m.get("color")).unwrap_or("#cccccc".into())).collect();
|
||||
row.insert("color".into(), V::S(colors[0].clone()));
|
||||
if colors.iter().any(|c| *c != colors[0]) {
|
||||
@@ -171,7 +172,17 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {
|
||||
for (prop, col) in [("map", "map"), ("normalMap", "normal_map"), ("roughnessMap", "rough_map"), ("metalnessMap", "metal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map"), ("depthMap", "depth_map"), ("clearcoatNormalMap", "clearcoat_normal_map")] {
|
||||
let Some(src) = m0.get(prop).and_then(Value::as_str) else { continue };
|
||||
// render images an app ping-pongs between are keyed frame by frame (R3F23c: raea-sys-rendermap); a picture is its first frame's
|
||||
let srcs: Vec<String> = if src.starts_with("render:") { mats.iter().map(|m| match m.get(prop) { Some(Value::String(s)) => s.clone(), _ => src.to_string() }).collect() } else { vec![src_path(src)] };
|
||||
// a swapped map (raea_core_scene::SWAPPED_MAPS on a plain standard surface: raea-sys-material's SwappedMaps,
|
||||
// docs/render-memory.feature RM6) is keyed too: one texture whose picture the engine swaps, where each
|
||||
// picture once cut a part of its own, all of them made at load (a pool's 96 water normal maps)
|
||||
let swapped = swaps && raea_core_scene::SWAPPED_MAPS.iter().any(|(p, _)| *p == prop);
|
||||
let srcs: Vec<String> = if src.starts_with("render:") {
|
||||
mats.iter().map(|m| match m.get(prop) { Some(Value::String(s)) => s.clone(), _ => src.to_string() }).collect()
|
||||
} else if swapped {
|
||||
mats.iter().map(|m| src_path(m.get(prop).and_then(Value::as_str).filter(|s| !s.starts_with("render:")).unwrap_or(src))).collect()
|
||||
} else {
|
||||
vec![src_path(src)]
|
||||
};
|
||||
keyed_strings(p, &mut row, &id, col, &srcs);
|
||||
}
|
||||
if let Some(Value::Array(r)) = m0.get("repeat") {
|
||||
|
||||
@@ -10,6 +10,7 @@ description = "The 3D kinds raea's 3D SDK writes, drawn with Bevy: meshes, light
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
raea-sys-frame = { path = "../../systems/frame" }
|
||||
raea-sys-material = { path = "../../systems/material" }
|
||||
raea-sys-toon = { path = "../../systems/toon" }
|
||||
raea-sys-framepass = { path = "../../systems/framepass" }
|
||||
raea-sys-compute = { path = "../../systems/compute" }
|
||||
raea-sys-sampler = { path = "../../systems/sampler" }
|
||||
|
||||
@@ -36,7 +36,8 @@ use raea_core_program::eval::Tup;
|
||||
use raea_core_program::ir::V;
|
||||
use raea_sys_frame::*;
|
||||
use raea_sys_frame::bevy_api;
|
||||
use raea_sys_material::{decal, surface, toon};
|
||||
use raea_sys_material::{decal, surface};
|
||||
use raea_sys_toon as toon;
|
||||
use raea_sys_fog::{froxel, froxel_glass};
|
||||
use raea_sys_post::lens;
|
||||
use raea_sys_look::paint;
|
||||
|
||||
@@ -7,7 +7,6 @@ use serde_json::{Value, json};
|
||||
use crate::fit::{Mark, fit};
|
||||
use crate::prior::{coefficients, oddness, shape};
|
||||
use crate::rig::{Pose, Side, Skeleton};
|
||||
use crate::shape::Solid;
|
||||
use crate::soma::from_soma;
|
||||
use crate::turns::{from_turns, with_twists};
|
||||
|
||||
@@ -15,21 +14,6 @@ pub 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"))
|
||||
}
|
||||
|
||||
/// A held thing's shape: a ball's radius, a box's half sizes, or a capsule's or cylinder's [half length, radius].
|
||||
pub 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 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)?))
|
||||
|
||||
@@ -247,13 +247,6 @@ pub fn clamp_turn(skel: &Skeleton, i: usize, q: Quat) -> (Quat, f32) {
|
||||
(turn, q.angle_between(turn).to_degrees())
|
||||
}
|
||||
|
||||
/// How far one joint's turn is outside its limit, degrees (0 inside it, or for a joint with no limits).
|
||||
pub fn over(skel: &Skeleton, i: usize, q: Quat) -> f32 {
|
||||
let Some(ax) = axes(skel, i) else { return 0.0 };
|
||||
let (a, c) = (read(&ax, q), clamped(&ax, read(&ax, q)));
|
||||
(a.flex - c.flex).hypot(a.side - c.side).max((a.twist - c.twist).abs())
|
||||
}
|
||||
|
||||
/// Every joint of a pose outside its limit by more than `tolerance` degrees: its index and by how much, worst first.
|
||||
pub fn violations(skel: &Skeleton, p: &Pose, tolerance: f32) -> Vec<(usize, f32)> {
|
||||
let mut out: Vec<(usize, f32)> = (0..skel.joints.len())
|
||||
|
||||
@@ -23,7 +23,7 @@ use raea_core_scene::{Item, excused, gltf_tris, src_path, vec3};
|
||||
|
||||
// what each part rests on, and the parts that float, sink or clip (`raea scene lint|explain`)
|
||||
pub mod lint;
|
||||
pub use lint::{lint, lint_with};
|
||||
pub use lint::lint;
|
||||
// a model's box and a seat's facing (scene.bounds, scene.facing)
|
||||
mod assets;
|
||||
pub use assets::assets;
|
||||
@@ -149,8 +149,8 @@ fn pierce(x: &Solid, wx: &Mat4, into: &Solid, wi: &Mat4) -> Option<Hit> {
|
||||
let (mut n, mut depth, mut top, mut bottom) = (0usize, 0f32, f32::MIN, f32::MAX);
|
||||
let (mut dlo, mut dhi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
let mut seam = Vec::new();
|
||||
for p in &x.surf {
|
||||
let w = wx.transform_point3(*p);
|
||||
for p in x.surf_points() {
|
||||
let w = wx.transform_point3(p);
|
||||
if w.cmplt(lo).any() || w.cmpgt(hi).any() {
|
||||
continue;
|
||||
}
|
||||
@@ -200,7 +200,7 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
|
||||
let vol = |s: &Solid, k: f32| s.volume() * k.powi(3);
|
||||
let small_first = vol(a, sa) <= vol(b, sb);
|
||||
let (s, ws, ks, o, wo, ko) = if small_first { (a, wa, sa, b, wb, sb) } else { (b, wb, sb, a, wa, sa) };
|
||||
if s.inside.is_empty() {
|
||||
if s.inside == 0 {
|
||||
return None;
|
||||
}
|
||||
let (slo, shi) = world_box(s, ws);
|
||||
@@ -242,7 +242,7 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
|
||||
continue;
|
||||
}
|
||||
let i = ((z * s.n[1] + y) * s.n[0] + x) as u32;
|
||||
let ds = s.depth[i as usize];
|
||||
let ds = s.depth[i as usize] as u16;
|
||||
if ds < 3 {
|
||||
continue;
|
||||
}
|
||||
@@ -262,7 +262,7 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let share = (hits * stride) as f32 / s.inside.len() as f32;
|
||||
let share = (hits * stride) as f32 / s.inside as f32;
|
||||
// shallow, a sliver, or wholly inside (no seam to see: a decal in a decal, a part hidden in another)
|
||||
if depth < DEPTH_SHARE * size || share < VOLUME_SHARE || share > ENCLOSED {
|
||||
return None;
|
||||
@@ -351,7 +351,7 @@ mod tests {
|
||||
// a 1.2 m slab 3 cm thick, its fine solid closed: deepest in the middle
|
||||
let sill = voxelize(&boxed(Vec3::ZERO, Vec3::new(1.2, 0.03, 0.22))).unwrap();
|
||||
let f = sill.fine.as_deref().expect("a thin part's fine solid");
|
||||
assert!(sill.inside.is_empty() && sill.solid(), "a cell thick at RES, solid in its fine one");
|
||||
assert!(sill.inside == 0 && sill.solid(), "a cell thick at RES, solid in its fine one");
|
||||
assert!(f.at(Vec3::ZERO) >= 6, "{}", f.at(Vec3::ZERO));
|
||||
}
|
||||
|
||||
|
||||
+56
-37
@@ -14,7 +14,7 @@ use std::collections::HashMap;
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use raea_core_scene::{Item, Part, base_ident, face, feet, glows, label, parts_of, unparked, wall};
|
||||
use raea_core_scene::{Item, Part, base_ident, face, feet, glows, label, parts_of, ray_tri, unparked, wall};
|
||||
|
||||
use super::solid_of;
|
||||
|
||||
@@ -195,6 +195,52 @@ fn rest_of(parts: &[Part], grid: &Grid, insets: &[Option<usize>], i: usize) -> R
|
||||
Rest::Air { below: nearest_below }
|
||||
}
|
||||
|
||||
/// The closest other part within MOUNT of this one's top or sides: rays out from points on its box's faces, up and
|
||||
/// along ±x and ±z, against the parts whose boxes come within reach.
|
||||
fn touching(parts: &[Part], i: usize) -> Option<(usize, u32, f32)> {
|
||||
let p = &parts[i];
|
||||
let reach = CARCASS.max(2.0 * MOUNT);
|
||||
let near: Vec<usize> = (0..parts.len())
|
||||
.filter(|&j| j != i && !(parts[j].lo.cmpgt(p.hi + Vec3::splat(reach)).any() || p.lo.cmpgt(parts[j].hi + Vec3::splat(reach)).any()))
|
||||
.collect();
|
||||
if near.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// the points of the part nearest each face of its box, out along that face's normal
|
||||
let dirs = [Vec3::Y, Vec3::X, -Vec3::X, Vec3::Z, -Vec3::Z];
|
||||
let mut best: Option<(usize, u32, f32)> = None;
|
||||
for d in dirs {
|
||||
let extent = |q: Vec3| q.dot(d);
|
||||
let far = p.tris.iter().flatten().map(|q| extent(*q)).fold(f32::MIN, f32::max);
|
||||
let tol = 0.003f32.max(0.01 * (p.hi - p.lo).max_element());
|
||||
let mut pts: Vec<Vec3> = p.tris.iter().flatten().filter(|q| extent(**q) >= far - tol).copied().collect();
|
||||
pts.dedup_by(|a, b| (*a - *b).length() < 1e-5);
|
||||
let step = (pts.len() / 24).max(1);
|
||||
for o in pts.into_iter().step_by(step) {
|
||||
for &j in &near {
|
||||
for (k, t) in parts[j].tris.iter().enumerate() {
|
||||
// the ray starts a touch inside, so a face flush with it is found at ~0
|
||||
if let Some(s) = ray_tri(o - d * 0.0005, d, *t) {
|
||||
let gap = s - 0.0005;
|
||||
// close, or a door a reveal in front of the carcass that covers it (not a shelf off its wall)
|
||||
let ok = gap <= MOUNT || (gap <= CARCASS && !wall(&parts[j]) && covers(&parts[j], p, d));
|
||||
if ok && best.is_none_or(|(_, _, g)| gap.abs() < g.abs()) {
|
||||
best = Some((j, parts[j].node[k], gap));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Whether `back`'s box covers `front`'s across the two axes square to `d` (within a centimetre): a carcass behind its
|
||||
/// door, a ceiling over its lamp.
|
||||
fn covers(back: &Part, front: &Part, d: Vec3) -> bool {
|
||||
(0..3).filter(|&k| d[k].abs() < 0.5).all(|k| back.lo[k] <= front.lo[k] + 0.01 && back.hi[k] >= front.hi[k] - 0.01)
|
||||
}
|
||||
|
||||
fn named(parts: &[Part], j: usize, node: u32) -> String {
|
||||
let p = &parts[j];
|
||||
match p.nodes.get(node as usize).filter(|n| !n.is_empty() && p.nodes.len() > 1) {
|
||||
@@ -225,12 +271,6 @@ fn moving(now: &[Item], other: &[Item]) -> Vec<bool> {
|
||||
/// One frame's parts, each with what it rests on, and the faults: (findings as JSON, the error count).
|
||||
/// `now` is the frame's parts, `next` the next frame's (or the one before, at the end) to see what moves.
|
||||
pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
|
||||
lint_with(now, next, true)
|
||||
}
|
||||
|
||||
/// The lint, with or without parts passing into each other (`clips`): without, for a render's end, whose clipping
|
||||
/// check has followed those through every frame already (the pair test is most of the lint's time).
|
||||
pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize) {
|
||||
let moving = moving(now, next);
|
||||
let (parts, items, mut skipped) = parts_of(now, &moving);
|
||||
let (parts, items) = unparked(parts, items, &mut skipped);
|
||||
@@ -288,23 +328,14 @@ pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize
|
||||
// parent group moving it)
|
||||
let y = items[i].world.w_axis.y;
|
||||
match &r {
|
||||
Rest::On { under, node, gap, at, .. } => {
|
||||
Rest::On { under, node, gap, .. } => {
|
||||
v["on"] = json!(named(&parts, *under, *node));
|
||||
v["gap"] = json!((gap * 1e5).round() / 1e5);
|
||||
v["at"] = json!([at.x, at.y, at.z]);
|
||||
if level == "error" {
|
||||
v["fix"] = json!({"y": ((y - gap) * 1e5).round() / 1e5, "dy": (-gap * 1e5).round() / 1e5});
|
||||
}
|
||||
}
|
||||
Rest::Mounted { on, node, below, .. } => {
|
||||
v["on"] = json!(named(&parts, *on, *node));
|
||||
// how far above what's under it: a table lamp lifted against a wall reads as mounted on the wall, and
|
||||
// only what the thing is can say whether it should hang there (raea-sys-notice judges it by name)
|
||||
if let Some((j, g)) = below {
|
||||
v["gap"] = json!((g * 1e5).round() / 1e5);
|
||||
v["under"] = json!(parts[*j].label);
|
||||
}
|
||||
}
|
||||
Rest::Mounted { on, node, .. } => v["on"] = json!(named(&parts, *on, *node)),
|
||||
_ => {}
|
||||
}
|
||||
out.push(v);
|
||||
@@ -321,9 +352,9 @@ pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize
|
||||
}
|
||||
// parts passing into each other, wherever (the clipping check's own test: deep for the smaller part's size, a
|
||||
// real share of it, not resting contact and not a foot seated in what's below)
|
||||
let solids: Vec<_> = if clips { items.iter().map(|it| solid_of(it).ok()).collect() } else { Vec::new() };
|
||||
for i in 0..solids.len() {
|
||||
for j in i + 1..solids.len() {
|
||||
let solids: Vec<_> = items.iter().map(|it| solid_of(it).ok()).collect();
|
||||
for i in 0..parts.len() {
|
||||
for j in i + 1..parts.len() {
|
||||
if parts[i].excused || parts[j].excused || parts[i].lo.cmpgt(parts[j].hi).any() || parts[j].lo.cmpgt(parts[i].hi).any() {
|
||||
continue;
|
||||
}
|
||||
@@ -348,9 +379,7 @@ pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize
|
||||
fix["dy"] = json!((-gap * 1e4).round() / 1e4);
|
||||
then = format!(" and {:+.3} m along y to rest on {}", -gap, named(&parts, under, node));
|
||||
}
|
||||
// where the two surfaces meet, for where a viewer would see it (raea-sys-notice)
|
||||
let seam: Vec<[f32; 3]> = h.seam.iter().step_by((h.seam.len() / 16).max(1)).map(|p| p.to_array()).collect();
|
||||
out.push(json!({"part": small, "into": big, "check": "clips", "level": "error", "depth": (h.depth * 1e4).round() / 1e4, "share": (h.share * 1e3).round() / 1e3, "fix": fix, "seam": seam,
|
||||
out.push(json!({"part": small, "into": big, "check": "clips", "level": "error", "depth": (h.depth * 1e4).round() / 1e4, "share": (h.share * 1e3).round() / 1e3, "fix": fix,
|
||||
"says": format!("{small} passes {} into {big} ({:.0}% of it inside): move it {by:+.3} m along world {axis_name}{then}", mm(h.depth), h.share * 100.0)}));
|
||||
}
|
||||
}
|
||||
@@ -372,7 +401,7 @@ pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize
|
||||
if level == "error" {
|
||||
errors += 1;
|
||||
}
|
||||
out.push(json!({"part": parts[i].label, "into": parts[j].label, "check": "zfight", "level": level, "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z], "spots": spots(&over.spots),
|
||||
out.push(json!({"part": parts[i].label, "into": parts[j].label, "check": "zfight", "level": level, "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z],
|
||||
"says": format!("{} and {} have faces in one plane over each other ({n} pair{}, {:.1} cm² shared, most at [{:.3}, {:.3}, {:.3}]): they flicker as the camera moves; lift one by a millimetre or cut the overlap", parts[i].label, parts[j].label, if n == 1 { "" } else { "s" }, area * 1e4, at.x, at.y, at.z)}));
|
||||
}
|
||||
// the same triangles in both (a slab built into two neighbouring chunks) draw alike whichever wins, unless
|
||||
@@ -382,20 +411,14 @@ pub fn lint_with(now: &[Item], next: &[Item], clips: bool) -> (Vec<Value>, usize
|
||||
"says": format!("{} and {} both hold the same {n} face{} ({:.1} cm², most at [{:.3}, {:.3}, {:.3}]): nothing to see where they look alike; take them out of one", parts[i].label, parts[j].label, if n == 1 { "" } else { "s" }, area * 1e4, at.x, at.y, at.z)}));
|
||||
}
|
||||
}
|
||||
let inside = raea_core_zfight::sorted(&parts[i].tris, None);
|
||||
if let Some((n, area, at)) = inside.fight {
|
||||
out.push(json!({"part": parts[i].label, "check": "zfight", "level": "warning", "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z], "spots": spots(&inside.spots),
|
||||
if let Some((n, area, at)) = raea_core_zfight::overlaps(&parts[i].tris, None) {
|
||||
out.push(json!({"part": parts[i].label, "check": "zfight", "level": "warning", "faces": n, "area": (area * 1e6).round() / 1e6, "at": [at.x, at.y, at.z],
|
||||
"says": format!("{} has faces doubled in one plane inside it ({n} pair{}, {:.1} cm² shared): they flicker where they show; delete the doubles (raea gen check -o)", parts[i].label, if n == 1 { "" } else { "s" }, area * 1e4)}));
|
||||
}
|
||||
}
|
||||
(out, errors)
|
||||
}
|
||||
|
||||
/// A fight's shared patches as [x, y, z, nx, ny, nz, area] rows.
|
||||
fn spots(s: &[(Vec3, Vec3, f32)]) -> Vec<[f32; 7]> {
|
||||
s.iter().map(|(p, n, a)| [p.x, p.y, p.z, n.x, n.y, n.z, *a]).collect()
|
||||
}
|
||||
|
||||
/// The surface a part would land on and how far it is (negative: sunk): what it rests on, or the nearest surface
|
||||
/// under it when it's in the air.
|
||||
fn landing(r: &Rest) -> Option<(usize, u32, f32)> {
|
||||
@@ -419,10 +442,6 @@ fn rest_after(parts: &[Part], insets: &[Option<usize>], i: usize, v: Vec3) -> Re
|
||||
rest_of(&moved, &grid, insets, i)
|
||||
}
|
||||
|
||||
#[path = "lint/touching.rs"]
|
||||
mod touching;
|
||||
use touching::touching;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lint/tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,87 +0,0 @@
|
||||
//! What a part touches at its top or sides (a wall it's mounted on, the carcass behind a door): rays out from its box's
|
||||
//! faces against the parts near it.
|
||||
|
||||
use bevy::math::Vec3;
|
||||
use raea_core_scene::{Part, ray_tri, wall};
|
||||
|
||||
use super::{CARCASS, MOUNT};
|
||||
|
||||
/// The closest other part within MOUNT of this one's top or sides: rays out from points on its box's faces, up and
|
||||
/// along ±x and ±z, against the parts whose boxes come within reach.
|
||||
pub(super) fn touching(parts: &[Part], i: usize) -> Option<(usize, u32, f32)> {
|
||||
let p = &parts[i];
|
||||
let reach = CARCASS.max(2.0 * MOUNT);
|
||||
let near: Vec<usize> = (0..parts.len())
|
||||
.filter(|&j| j != i && !(parts[j].lo.cmpgt(p.hi + Vec3::splat(reach)).any() || p.lo.cmpgt(parts[j].hi + Vec3::splat(reach)).any()))
|
||||
.collect();
|
||||
if near.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// the points of the part nearest each face of its box, out along that face's normal
|
||||
let dirs = [Vec3::Y, Vec3::X, -Vec3::X, Vec3::Z, -Vec3::Z];
|
||||
let mut best: Option<(usize, u32, f32)> = None;
|
||||
for d in dirs {
|
||||
let extent = |q: Vec3| q.dot(d);
|
||||
let far = p.tris.iter().flatten().map(|q| extent(*q)).fold(f32::MIN, f32::max);
|
||||
let tol = 0.003f32.max(0.01 * (p.hi - p.lo).max_element());
|
||||
let mut pts: Vec<Vec3> = p.tris.iter().flatten().filter(|q| extent(**q) >= far - tol).copied().collect();
|
||||
pts.dedup_by(|a, b| (*a - *b).length() < 1e-5);
|
||||
let step = (pts.len() / 24).max(1);
|
||||
// the rays run along an axis: a triangle (or a part) whose box doesn't straddle the ray's line, or lies past
|
||||
// its reach, can't be met in reach, so it's passed over before the full test (the same answer; on room 106 the
|
||||
// full test of every triangle was nearly all of a lint's 30 s)
|
||||
let a = (0..3).find(|&k| d[k] != 0.0).unwrap();
|
||||
let (b, c) = ((a + 1) % 3, (a + 2) % 3);
|
||||
let span = |o: Vec3| if d[a] > 0.0 { (o[a] - 0.001, o[a] + reach + 0.001) } else { (o[a] - reach - 0.001, o[a] + 0.001) };
|
||||
let meets = |o: Vec3, lo: Vec3, hi: Vec3| {
|
||||
let (from, to) = span(o);
|
||||
lo[b] <= o[b] + 1e-5 && hi[b] >= o[b] - 1e-5 && lo[c] <= o[c] + 1e-5 && hi[c] >= o[c] - 1e-5 && lo[a] <= to && hi[a] >= from
|
||||
};
|
||||
let pts: Vec<Vec3> = pts.into_iter().step_by(step).collect();
|
||||
// and the triangles any of this side's rays could meet, found once: those whose box meets the box the rays
|
||||
// sweep (the points' own, out by the reach along the axis)
|
||||
let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
for o in &pts {
|
||||
(lo, hi) = (lo.min(*o), hi.max(*o));
|
||||
}
|
||||
lo[a] -= reach + 0.001;
|
||||
hi[a] += reach + 0.001;
|
||||
let boxes = |l: Vec3, h: Vec3| (l - Vec3::splat(1e-5)).cmple(hi).all() && (lo - Vec3::splat(1e-5)).cmple(h).all();
|
||||
let cands: Vec<(usize, Vec<usize>)> = near
|
||||
.iter()
|
||||
.filter(|&&j| boxes(parts[j].lo, parts[j].hi))
|
||||
.map(|&j| (j, parts[j].tris.iter().enumerate().filter(|(_, t)| boxes(t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2]))).map(|(k, _)| k).collect()))
|
||||
.collect();
|
||||
for &o in &pts {
|
||||
for (j, ks) in &cands {
|
||||
let j = *j;
|
||||
if !meets(o, parts[j].lo, parts[j].hi) {
|
||||
continue;
|
||||
}
|
||||
for &k in ks {
|
||||
let t = &parts[j].tris[k];
|
||||
if !meets(o, t[0].min(t[1]).min(t[2]), t[0].max(t[1]).max(t[2])) {
|
||||
continue;
|
||||
}
|
||||
// the ray starts a touch inside, so a face flush with it is found at ~0
|
||||
if let Some(s) = ray_tri(o - d * 0.0005, d, *t) {
|
||||
let gap = s - 0.0005;
|
||||
// close, or a door a reveal in front of the carcass that covers it (not a shelf off its wall)
|
||||
let ok = gap <= MOUNT || (gap <= CARCASS && !wall(&parts[j]) && covers(&parts[j], p, d));
|
||||
if ok && best.is_none_or(|(_, _, g)| gap.abs() < g.abs()) {
|
||||
best = Some((j, parts[j].node[k], gap));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Whether `back`'s box covers `front`'s across the two axes square to `d` (within a centimetre): a carcass behind its
|
||||
/// door, a ceiling over its lamp.
|
||||
fn covers(back: &Part, front: &Part, d: Vec3) -> bool {
|
||||
(0..3).filter(|&k| d[k].abs() < 0.5).all(|k| back.lo[k] <= front.lo[k] + 0.01 && back.hi[k] >= front.hi[k] - 0.01)
|
||||
}
|
||||
|
||||
@@ -9,12 +9,16 @@ pub(crate) struct Solid {
|
||||
pub(crate) min: Vec3,
|
||||
pub(crate) cell: f32,
|
||||
pub(crate) n: [usize; 3],
|
||||
pub(crate) depth: Vec<u16>,
|
||||
/// the cells at least one cell under the surface
|
||||
pub(crate) inside: Vec<u32>,
|
||||
/// each cell's depth, a byte (docs/render-memory.feature RM10: a depth is at most half the grid's longest side,
|
||||
/// THIN_MOST * RES / 2 in a fine solid, and is held at 255 past it; as u16 the grids were 603 MB of halcyon r109's
|
||||
/// sequence, every part in view the whole shot)
|
||||
pub(crate) depth: Vec<u8>,
|
||||
/// how many cells are at least one cell under the surface (only counted: the list of them was 368 MB in r109)
|
||||
pub(crate) inside: usize,
|
||||
/// points on its real surface (from its triangles), SURF_GRAIN of a cell apart: what the pierce test puts in
|
||||
/// another part
|
||||
pub(crate) surf: Vec<Vec3>,
|
||||
/// another part. Each kept as three u16s across lo..hi (surf_points gives them back: a 10 m part's to 0.08 mm),
|
||||
/// with no spare capacity: as Vec3s grown point by point they were 301 MB in r109
|
||||
pub(crate) surf: Vec<[u16; 3]>,
|
||||
/// a thin part's finer solid, the pierce test's depths in it
|
||||
pub(crate) fine: Option<Box<Solid>>,
|
||||
pub(crate) lo: Vec3,
|
||||
@@ -31,7 +35,12 @@ impl Solid {
|
||||
if x >= self.n[0] || y >= self.n[1] || z >= self.n[2] {
|
||||
return 0;
|
||||
}
|
||||
self.depth[(z * self.n[1] + y) * self.n[0] + x]
|
||||
self.depth[(z * self.n[1] + y) * self.n[0] + x] as u16
|
||||
}
|
||||
/// The surface points in the part's own space.
|
||||
pub(crate) fn surf_points(&self) -> impl Iterator<Item = Vec3> + '_ {
|
||||
let step = (self.hi - self.lo) / 65535.0;
|
||||
self.surf.iter().map(move |q| self.lo + Vec3::new(q[0] as f32, q[1] as f32, q[2] as f32) * step)
|
||||
}
|
||||
pub(crate) fn centre(&self, i: u32) -> Vec3 {
|
||||
let i = i as usize;
|
||||
@@ -40,12 +49,12 @@ impl Solid {
|
||||
}
|
||||
/// whether it has an inside at all: at RES, or in its fine solid (a sill a cell thick at RES)
|
||||
pub(crate) fn solid(&self) -> bool {
|
||||
!self.inside.is_empty() || self.fine.as_ref().is_some_and(|f| !f.inside.is_empty())
|
||||
self.inside > 0 || self.fine.as_ref().is_some_and(|f| f.inside > 0)
|
||||
}
|
||||
/// its volume, from the finer of its solids
|
||||
pub(crate) fn volume(&self) -> f32 {
|
||||
let s = self.fine.as_deref().filter(|f| !f.inside.is_empty()).unwrap_or(self);
|
||||
s.inside.len() as f32 * s.cell.powi(3)
|
||||
let s = self.fine.as_deref().filter(|f| f.inside > 0).unwrap_or(self);
|
||||
s.inside as f32 * s.cell.powi(3)
|
||||
}
|
||||
/// how far under the surface a cell of this depth is, in the part's own units (the surface was thickened a cell
|
||||
/// to close pinholes)
|
||||
@@ -72,13 +81,24 @@ pub(crate) fn voxelize(tris: &[[Vec3; 3]]) -> Option<Solid> {
|
||||
let cell = ext.max_element() / RES;
|
||||
let thin = (ext.min_element() / THIN).max(ext.max_element() / (RES * THIN_MOST));
|
||||
let mut solid = grid(tris, lo, hi, cell);
|
||||
solid.surf = surface(tris, cell * SURF_GRAIN);
|
||||
solid.surf = quantized(&surface(tris, cell * SURF_GRAIN), lo, hi);
|
||||
if thin < 0.5 * cell {
|
||||
solid.fine = Some(Box::new(grid(tris, lo, hi, thin)));
|
||||
}
|
||||
Some(solid)
|
||||
}
|
||||
|
||||
/// Points as three u16s each across lo..hi (Solid::surf_points reads them back), exactly as many as there are.
|
||||
fn quantized(points: &[Vec3], lo: Vec3, hi: Vec3) -> Vec<[u16; 3]> {
|
||||
let scale = Vec3::splat(65535.0) / (hi - lo).max(Vec3::splat(f32::MIN_POSITIVE));
|
||||
let mut out = Vec::with_capacity(points.len());
|
||||
out.extend(points.iter().map(|p| {
|
||||
let q = ((*p - lo) * scale).round().clamp(Vec3::ZERO, Vec3::splat(65535.0));
|
||||
[q.x as u16, q.y as u16, q.z as u16]
|
||||
}));
|
||||
out
|
||||
}
|
||||
|
||||
/// Points on the triangles, one per `grain` cube they cross.
|
||||
pub(crate) fn surface(tris: &[[Vec3; 3]], grain: f32) -> Vec<Vec3> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
@@ -191,7 +211,8 @@ pub(crate) fn grid(tris: &[[Vec3; 3]], lo: Vec3, hi: Vec3, cell: f32) -> Solid {
|
||||
}
|
||||
}
|
||||
}
|
||||
let inside: Vec<u32> = (0..depth.len() as u32).filter(|&i| depth[i as usize] >= 3).collect();
|
||||
let inside = depth.iter().filter(|&&d| d >= 3).count();
|
||||
let depth: Vec<u8> = depth.into_iter().map(|d| d.min(255) as u8).collect();
|
||||
Solid { name: String::new(), min, cell, n, depth, inside, surf: Vec::new(), fine: None, lo, hi }
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ description = "A frame's rows as raea's passes read them: FrameRows, the loaded
|
||||
native = ["dep:raea-io-media"]
|
||||
|
||||
[dependencies]
|
||||
# a row's per-frame tables (tables), split out at the crate limit (11-29)
|
||||
raea-core-tables = { path = "../../core/tables" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_ui"] }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
# cuts between cameras (systems/shots), as raea_sys_frame::shots
|
||||
|
||||
@@ -33,7 +33,7 @@ pub use state::*;
|
||||
pub mod render_image;
|
||||
pub use render_image::RenderKind;
|
||||
/// a row's per-frame tables (a frame's look, the camera's post-processing), laid onto it frame by frame
|
||||
pub mod tables;
|
||||
pub use raea_core_tables as tables;
|
||||
/// the frames where another camera becomes the piece's (a cut between cameras, RR2)
|
||||
pub use raea_sys_shots as shots;
|
||||
|
||||
@@ -49,6 +49,8 @@ pub struct ModelReady;
|
||||
/// r-th row) and its media rows (for resolving sources).
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct Edit {
|
||||
/// the edit's size, rate and length; the engine's load leaves its rows and keys out (they are the store's and the
|
||||
/// timeline's), so it doesn't hold every row a second time
|
||||
pub prog: Program,
|
||||
/// every frame, evaluated once per load from the base gathered out of the store (row r is the store's r-th row)
|
||||
pub timeline: std::sync::Arc<raea_core_program::timeline::Timeline>,
|
||||
|
||||
@@ -76,8 +76,13 @@ pub fn find(world: &World, kind: &str, id: &str) -> Option<Entity> {
|
||||
|
||||
/// Add a row at the end; its columns become components.
|
||||
pub fn spawn(world: &mut World, t: &Tup) -> Entity {
|
||||
spawn_with(world, t, t.vals.iter())
|
||||
}
|
||||
|
||||
/// spawn, with only the columns given (the engine's load leaves its spawn_only ones out of the store).
|
||||
fn spawn_with<'a>(world: &mut World, t: &Tup, cols: impl Iterator<Item = (&'a String, &'a V)>) -> Entity {
|
||||
let e = world.spawn(RowKey { kind: t.kind.clone(), id: t.id.clone() }).id();
|
||||
for (c, v) in &t.vals {
|
||||
for (c, v) in cols {
|
||||
set(world, e, c, v.clone());
|
||||
}
|
||||
let s = schema(world);
|
||||
@@ -131,6 +136,19 @@ pub fn load(world: &mut World, rows: &[Tup]) -> Vec<Entity> {
|
||||
rows.iter().map(|t| spawn(world, t)).collect()
|
||||
}
|
||||
|
||||
/// A column the engine reads only as its row spawns, from the program's rows, never from the store or a frame: a
|
||||
/// mesh's shape (one per row: a change of shape is another row). docs/render-memory.feature RM5: halcyon's shapes were
|
||||
/// 274 MB of text, held by the program, the store and the evaluator's columns.
|
||||
pub fn spawn_only(kind: &str, col: &str) -> bool {
|
||||
kind == "mesh" && col == "shape"
|
||||
}
|
||||
|
||||
/// load, for an engine: the rows without their spawn_only columns (the engine spawns from the rows themselves).
|
||||
pub fn load_for_engine(world: &mut World, rows: &[Tup]) -> Vec<Entity> {
|
||||
clear(world);
|
||||
rows.iter().map(|t| spawn_with(world, t, t.vals.iter().filter(|(c, _)| !spawn_only(&t.kind, c)))).collect()
|
||||
}
|
||||
|
||||
/// One value of a row's column (None: the row doesn't have it).
|
||||
pub fn get(world: &World, e: Entity, col: &str) -> Option<V> {
|
||||
let kind = &world.get::<RowKey>(e)?.kind;
|
||||
|
||||
@@ -3,18 +3,31 @@
|
||||
//! grab's, the release's); the answer is the pose to draw and where the thing is.
|
||||
|
||||
use glam::Quat;
|
||||
use raea_sys_body::json::{num, posed, quat, solid, vec3};
|
||||
use raea_sys_body::json::{num, posed, quat, vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::trunk::stand_for;
|
||||
use crate::hand::{Grip, Hold, HoldOptions, find_holds};
|
||||
use raea_sys_body::rig::{Pose, Side, Skeleton};
|
||||
use raea_sys_body::shape::Thing;
|
||||
use raea_sys_body::shape::{Solid, Thing};
|
||||
use crate::take::{Key, 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; holds?: { side: \"L\" | \"R\"; at: [number, number, number]; normal: [number, number, number]; along?: [number, number, number]; shape?: number[] }[]; path?: { t: number; carry: [number, number, number]; tilt?: [number, number, number, number] }[]; weight?: number; pass?: number; slide?: { t: number; at: [number, number, number]; turn?: [number, number, number, number] }[]; leave?: 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; limited: boolean; stand: { at: [number, number, number]; yaw: number }; reach: { ok: boolean; move: number } }";
|
||||
|
||||
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)?;
|
||||
|
||||
@@ -23,8 +23,12 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defa
|
||||
serde_json = "1"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
|
||||
raea-io-net = { path = "../../io/net" }
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
raea-sys-mesh = { path = "../mesh" }
|
||||
# BC7 maps (maps.rs bc7_chain, docs/render-memory.feature RM9): Intel's ISPC texture kernels, prebuilt for macOS, Linux
|
||||
# and Windows on x86_64 and arm64; content names for the encoded blocks kept in raea's caches
|
||||
intel_tex_2 = "0.5"
|
||||
blake3 = "1.8"
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# a texture given as a data:image/svg+xml URL, drawn on the CPU (the resvg raea-runtime-js draws SVG with)
|
||||
resvg = { version = "=0.48.1", default-features = false, features = ["text"], optional = true }
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ pub mod lightmap;
|
||||
pub mod maps;
|
||||
pub use raea_sys_mesh as mesh;
|
||||
pub mod surface;
|
||||
pub mod toon;
|
||||
pub mod swapped;
|
||||
pub mod shadow_only;
|
||||
pub mod shadow_catch;
|
||||
pub mod shader_material;
|
||||
|
||||
+127
-193
@@ -3,6 +3,10 @@ use std::path::Path;
|
||||
use raea_core_program::eval::Tup;
|
||||
use bevy::render::render_resource::TextureFormat;
|
||||
|
||||
// pictures given inline (data: URLs, SVG) and a panel's, with their mip chain
|
||||
mod pictures;
|
||||
pub use pictures::*;
|
||||
|
||||
/// A material's maps, made once per load (file or data: URL, colour or data, clamped or repeating): a floor of tiles
|
||||
/// and its plinths share one texture each. Cleared at each load, so a reload frees the last one's.
|
||||
#[derive(Resource, Default)]
|
||||
@@ -26,13 +30,25 @@ pub enum MapKind {
|
||||
pub fn map_image(pic: image::RgbaImage, kind: MapKind, repeat: bool, sampling: Option<&raea_sys_sampler::Sampling>) -> Image {
|
||||
let (w, h) = pic.dimensions();
|
||||
let srgb = kind == MapKind::Colour;
|
||||
let (data, levels) = mips_rgba8(pic.into_raw(), w, h, srgb);
|
||||
// RM9: block-compressed (BC7) where the GPU reads it, a quarter of RGBA8's bytes; else RGBA8 with its mips
|
||||
let (data, levels, format, w, h) = match bc7_chain(&pic, srgb) {
|
||||
Some((data, levels, bw, bh)) => (data, levels, if srgb { TextureFormat::Bc7RgbaUnormSrgb } else { TextureFormat::Bc7RgbaUnorm }, bw, bh),
|
||||
None => {
|
||||
let (data, levels) = mips_rgba8(pic.into_raw(), w, h, srgb);
|
||||
(data, levels, if srgb { TextureFormat::Rgba8UnormSrgb } else { TextureFormat::Rgba8Unorm }, w, h)
|
||||
}
|
||||
};
|
||||
let mut img = Image::new(
|
||||
bevy::render::render_resource::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
bevy::render::render_resource::TextureDimension::D2,
|
||||
data,
|
||||
if srgb { TextureFormat::Rgba8UnormSrgb } else { TextureFormat::Rgba8Unorm },
|
||||
bevy::asset::RenderAssetUsages::default(),
|
||||
format,
|
||||
// RM1 (docs/render-memory.feature): the GPU's copy alone. Nothing on the CPU reads a material's map once it's
|
||||
// made (its mips are made here; texture arrays are raea-sys-sampler's own pictures), and the main-world copy
|
||||
// was the whole picture again for the render's length: 2.4 GB of halcyon r109's 21.5 as a sequence, where every
|
||||
// frame's pool maps (96 of each) are loaded at its start
|
||||
// RAEA_KEEP_CPU_ASSETS=1 keeps the main-world copy too (the A/B control, or a reader found to need it)
|
||||
if std::env::var_os("RAEA_KEEP_CPU_ASSETS").is_some() { bevy::asset::RenderAssetUsages::default() } else { bevy::asset::RenderAssetUsages::RENDER_WORLD },
|
||||
);
|
||||
img.texture_descriptor.mip_level_count = levels;
|
||||
let address = if repeat { bevy::image::ImageAddressMode::Repeat } else { bevy::image::ImageAddressMode::ClampToEdge };
|
||||
@@ -50,6 +66,114 @@ pub fn map_image(pic: image::RgbaImage, kind: MapKind, repeat: bool, sampling: O
|
||||
img
|
||||
}
|
||||
|
||||
/// Whether the device samples BC textures (wgpu's TEXTURE_COMPRESSION_BC): set by the engine from its RenderDevice
|
||||
/// before an edit's maps are made (set_block_compression); off until then, so a map is RGBA8 where nothing said.
|
||||
static BLOCK_COMPRESSION: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// The device's answer for BC textures, given once it's made.
|
||||
pub fn set_block_compression(on: bool) {
|
||||
BLOCK_COMPRESSION.store(on, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A map as BC7 with its mip chain (docs/render-memory.feature RM9): 16 bytes for each 4x4 texels, a quarter of
|
||||
/// RGBA8's, on the GPU and in the bandwidth every sample reads. halcyon r109's 87 maps were 733 MB as RGBA8. BC7 keeps
|
||||
/// all four channels, so a normal map or a metallic-roughness map is read as it was by Bevy's shaders and Solari's.
|
||||
/// Encoded once (Intel's ISPC kernels, intel_tex_2, on every core) and kept in raea's caches by the picture's content
|
||||
/// (maps/NAME.bc7), so a later run reads the blocks and makes no mips. BC's blocks need each side of the base level a
|
||||
/// multiple of 4, so a picture that isn't is resampled to the next one up (8775 texels to 8776: the picture still
|
||||
/// runs 0 to 1 across the part, so nothing moves; halcyon's two widest surfaces, 8775 and 5849 across, were 223 MB
|
||||
/// of RGBA8 for this alone). The blocks and the size they're for; None where the device has no BC, or RAEA_NO_BC=1
|
||||
/// (the A/B control).
|
||||
fn bc7_chain(pic: &image::RgbaImage, srgb: bool) -> Option<(Vec<u8>, u32, u32, u32)> {
|
||||
let (w0, h0) = pic.dimensions();
|
||||
if !BLOCK_COMPRESSION.load(std::sync::atomic::Ordering::Relaxed) || std::env::var_os("RAEA_NO_BC").is_some() || w0 == 0 || h0 == 0 {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = (w0.next_multiple_of(4), h0.next_multiple_of(4));
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(&[srgb as u8, 1]); // 1: this encoding (opaque or alpha basic, box mips); bump to make them again
|
||||
hasher.update(&w.to_le_bytes());
|
||||
hasher.update(&h.to_le_bytes());
|
||||
hasher.update(&w0.to_le_bytes());
|
||||
hasher.update(&h0.to_le_bytes());
|
||||
hasher.update(pic.as_raw());
|
||||
let name = hasher.finalize().to_hex();
|
||||
let dir = raea_io_home::caches().map(|c| c.join("maps"));
|
||||
let path = dir.as_ref().map(|d| d.join(format!("{}.bc7", &name.as_str()[..32])));
|
||||
let levels = 32 - w.max(h).leading_zeros();
|
||||
let size: usize = (0..levels).map(|l| (((w >> l).max(1) + 3) / 4 * (((h >> l).max(1) + 3) / 4) * 16) as usize).sum();
|
||||
if let Some(p) = &path
|
||||
&& let Ok(b) = std::fs::read(p)
|
||||
&& b.len() == size
|
||||
{
|
||||
return Some((b, levels, w, h));
|
||||
}
|
||||
let resized;
|
||||
let pic = if (w, h) == (w0, h0) {
|
||||
pic
|
||||
} else {
|
||||
resized = image::imageops::resize(pic, w, h, image::imageops::FilterType::CatmullRom);
|
||||
&resized
|
||||
};
|
||||
let opaque = pic.as_raw().chunks_exact(4).all(|p| p[3] == 255);
|
||||
let settings = if opaque { intel_tex_2::bc7::opaque_basic_settings() } else { intel_tex_2::bc7::alpha_basic_settings() };
|
||||
let (data, mip_levels) = mips_rgba8(pic.as_raw().clone(), w, h, srgb);
|
||||
if mip_levels != levels {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(size);
|
||||
let mut at = 0usize;
|
||||
for l in 0..levels {
|
||||
let (lw, lh) = ((w >> l).max(1), (h >> l).max(1));
|
||||
let texels = &data[at..at + (lw * lh * 4) as usize];
|
||||
at += (lw * lh * 4) as usize;
|
||||
out.extend_from_slice(&bc7_level(&settings, texels, lw, lh));
|
||||
}
|
||||
if out.len() != size {
|
||||
return None;
|
||||
}
|
||||
if let Some(p) = &path {
|
||||
let _ = raea_io_home::write_whole(p, &out);
|
||||
}
|
||||
Some((out, levels, w, h))
|
||||
}
|
||||
|
||||
/// One mip level's BC7 blocks, row by row of blocks: a level under 4 texels a side padded out by its edge texels, and
|
||||
/// a big one cut into bands of block rows encoded on as many threads as there are cores.
|
||||
fn bc7_level(settings: &intel_tex_2::bc7::EncodeSettings, texels: &[u8], w: u32, h: u32) -> Vec<u8> {
|
||||
let (pw, ph) = ((w + 3) / 4 * 4, (h + 3) / 4 * 4);
|
||||
let padded: std::borrow::Cow<[u8]> = if (pw, ph) == (w, h) {
|
||||
std::borrow::Cow::Borrowed(texels)
|
||||
} else {
|
||||
let mut p = vec![0u8; (pw * ph * 4) as usize];
|
||||
for y in 0..ph {
|
||||
for x in 0..pw {
|
||||
let s = (((y.min(h - 1)) * w + x.min(w - 1)) * 4) as usize;
|
||||
let d = ((y * pw + x) * 4) as usize;
|
||||
p[d..d + 4].copy_from_slice(&texels[s..s + 4]);
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(p)
|
||||
};
|
||||
let block_rows = ph / 4;
|
||||
let row_bytes = (pw / 4 * 16) as usize;
|
||||
let mut out = vec![0u8; block_rows as usize * row_bytes];
|
||||
let threads = std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(4).min(block_rows).max(1);
|
||||
let band = block_rows.div_ceil(threads);
|
||||
std::thread::scope(|sc| {
|
||||
for (i, chunk) in out.chunks_mut(band as usize * row_bytes).enumerate() {
|
||||
let y0 = i as u32 * band * 4;
|
||||
let rows = (chunk.len() / row_bytes) as u32 * 4;
|
||||
let src = &padded[(y0 * pw * 4) as usize..((y0 + rows) * pw * 4) as usize];
|
||||
sc.spawn(move || {
|
||||
let surface = intel_tex_2::RgbaSurface { data: src, width: pw, height: rows, stride: pw * 4 };
|
||||
intel_tex_2::bc7::compress_blocks_into(settings, &surface, chunk);
|
||||
});
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// RGBA8 texels with every mip level after them (2x2 box averages; in linear light when `srgb`): the data and the
|
||||
/// level count.
|
||||
pub fn mips_rgba8(mut data: Vec<u8>, w: u32, h: u32, srgb: bool) -> (Vec<u8>, u32) {
|
||||
@@ -296,193 +420,3 @@ pub fn material(world: &mut World, t: &Tup, inserted: &[Tup], dir: &Path) -> Res
|
||||
super::fields::apply(&mut m, vals, &format!("mesh {}", t.id))?;
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// A picture given inline as a data: URL (`data:image/png;base64,...`, `data:image/svg+xml;utf8,<svg ...>`), decoded in
|
||||
/// memory: a raster through `image`, an SVG drawn by usvg and vello_cpu at its own size (at least 512 px on its long
|
||||
/// side, at most 4096). Before this a data: URL was read as a file path and failed ("map: .../data:image/svg+xml...: No
|
||||
/// such file"), the way the legacy app's agent first wrote a label into a perfume shot.
|
||||
pub fn data_picture(src: &str) -> Result<image::RgbaImage, String> {
|
||||
let (mime, bytes) = raea_io_net::data_url(src).ok_or("a data: URL that doesn't decode")?;
|
||||
let svg = mime == "image/svg+xml" || (mime.is_empty() && bytes.trim_ascii_start().starts_with(b"<svg"));
|
||||
if !svg {
|
||||
return image::load_from_memory(&bytes).map(|i| i.to_rgba8()).map_err(|e| format!("a {mime} picture: {e}"));
|
||||
}
|
||||
svg_picture(&bytes)
|
||||
}
|
||||
|
||||
/// An SVG's bytes drawn by resvg, at least 512 px on its long side, at most 4096.
|
||||
#[cfg(feature = "native")]
|
||||
pub fn svg_picture(bytes: &[u8]) -> Result<image::RgbaImage, String> {
|
||||
let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).map_err(|e| format!("its SVG: {e}"))?;
|
||||
let (sw, sh) = (tree.size().width().max(1.0), tree.size().height().max(1.0));
|
||||
let k = (512.0 / sw.max(sh)).max(1.0).min(4096.0 / sw.max(sh));
|
||||
let (w, h) = ((sw * k).round().max(1.0) as u32, (sh * k).round().max(1.0) as u32);
|
||||
let mut pm = resvg::tiny_skia::Pixmap::new(w, h).ok_or("the SVG's size")?;
|
||||
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(k, k), &mut pm.as_mut());
|
||||
let mut px = pm.take();
|
||||
// resvg paints premultiplied alpha; a texture wants it straight
|
||||
for p in px.chunks_exact_mut(4) {
|
||||
let a = p[3] as u32;
|
||||
if a > 0 && a < 255 {
|
||||
for c in &mut p[..3] {
|
||||
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "the SVG's pixels".to_string())
|
||||
}
|
||||
|
||||
/// Without native the CPU's SVG renderer isn't linked (a browser build can draw an SVG in the page instead).
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn svg_picture(_bytes: &[u8]) -> Result<image::RgbaImage, String> {
|
||||
Err("an SVG picture: SVG textures are drawn only in the native build".into())
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "native"))]
|
||||
mod data_url_tests {
|
||||
/// data: URL pictures decode in memory: an SVG (utf8, percent-escaped) drawn at least 512 px wide with its fill, and
|
||||
/// a base64 PNG to its own pixels
|
||||
#[test]
|
||||
fn data_pictures_decode() {
|
||||
let svg = super::data_picture("data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"32\"><rect width=\"64\" height=\"32\" fill=\"%23ff0000\"/></svg>").unwrap();
|
||||
assert_eq!(svg.dimensions(), (512, 256));
|
||||
assert_eq!(svg.get_pixel(100, 100).0, [255, 0, 0, 255]);
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(3, 2, image::Rgba([0, 128, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
use base64::Engine as _;
|
||||
let url = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(&png));
|
||||
let pic = super::data_picture(&url).unwrap();
|
||||
assert_eq!((pic.dimensions(), pic.get_pixel(2, 1).0), ((3, 2), [0, 128, 255, 255]));
|
||||
assert!(super::data_picture("data:image/png;base64,!!!").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel's picture: inline (a data: URL, raster or SVG) or a file.
|
||||
pub fn panel_picture(src: &str, inserted: &[Tup], dir: &Path) -> Result<image::RgbaImage, String> {
|
||||
if src.starts_with("data:") {
|
||||
return data_picture(src).map_err(|e| format!("src (a data: URL): {e}"));
|
||||
}
|
||||
let path = resolve_src(inserted, src, dir)?;
|
||||
Ok(image::open(&path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8())
|
||||
}
|
||||
|
||||
/// A panel's texture. A panel is usually drawn smaller than it was painted: a full mip chain and trilinear, anisotropic
|
||||
/// sampling keep its text from shimmering as it moves (without them a 2x minified glyph flickers).
|
||||
pub fn panel_image(pic: image::RgbaImage) -> Image {
|
||||
let (pw, ph) = pic.dimensions();
|
||||
let (data, levels) = mip_chain(pic.into_raw(), pw, ph);
|
||||
let mut img = Image::new(
|
||||
bevy::render::render_resource::Extent3d { width: pw, height: ph, depth_or_array_layers: 1 },
|
||||
bevy::render::render_resource::TextureDimension::D2,
|
||||
data,
|
||||
TextureFormat::Rgba8UnormSrgb,
|
||||
bevy::asset::RenderAssetUsages::default(),
|
||||
);
|
||||
img.texture_descriptor.mip_level_count = levels;
|
||||
img.sampler = bevy::image::ImageSampler::Descriptor(bevy::image::ImageSamplerDescriptor {
|
||||
anisotropy_clamp: 16,
|
||||
..bevy::image::ImageSamplerDescriptor::linear()
|
||||
});
|
||||
img
|
||||
}
|
||||
|
||||
/// Straight-alpha RGBA8 (sRGB) as premultiplied-alpha RGBA8 (the colour premultiplied in linear light, then encoded), with
|
||||
/// every mip level after it (2x2 box averages of the premultiplied linear values): the data and the level count, for a
|
||||
/// texture sampled trilinearly and blended premultiplied.
|
||||
pub fn mip_chain(data: Vec<u8>, w: u32, h: u32) -> (Vec<u8>, u32) {
|
||||
let to_lin: Vec<f32> = (0..256).map(|i| {
|
||||
let c = i as f32 / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}).collect();
|
||||
let to_srgb = |l: f32| -> u8 {
|
||||
let c = if l <= 0.0031308 { l * 12.92 } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 };
|
||||
(c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
|
||||
};
|
||||
// level 0, premultiplied, kept in linear floats for the averages
|
||||
let mut cur: Vec<[f32; 4]> = data.chunks_exact(4).map(|p| {
|
||||
let a = p[3] as f32 / 255.0;
|
||||
[to_lin[p[0] as usize] * a, to_lin[p[1] as usize] * a, to_lin[p[2] as usize] * a, a]
|
||||
}).collect();
|
||||
let encode = |px: &[[f32; 4]], out: &mut Vec<u8>| {
|
||||
for p in px {
|
||||
out.extend_from_slice(&[to_srgb(p[0]), to_srgb(p[1]), to_srgb(p[2]), (p[3].clamp(0.0, 1.0) * 255.0 + 0.5) as u8]);
|
||||
}
|
||||
};
|
||||
let mut out = Vec::with_capacity(data.len() * 4 / 3 + 16);
|
||||
encode(&cur, &mut out);
|
||||
let (mut cw, mut ch) = (w as usize, h as usize);
|
||||
let mut levels = 1;
|
||||
while cw > 1 || ch > 1 {
|
||||
let (nw, nh) = ((cw / 2).max(1), (ch / 2).max(1));
|
||||
let mut next = vec![[0f32; 4]; nw * nh];
|
||||
for y in 0..nh {
|
||||
for x in 0..nw {
|
||||
let mut acc = [0f32; 4];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let p = cur[(y * 2 + dy).min(ch - 1) * cw + (x * 2 + dx).min(cw - 1)];
|
||||
for c in 0..4 {
|
||||
acc[c] += p[c] / 4.0;
|
||||
}
|
||||
}
|
||||
next[y * nw + x] = acc;
|
||||
}
|
||||
}
|
||||
encode(&next, &mut out);
|
||||
cur = next;
|
||||
(cw, ch) = (nw, nh);
|
||||
levels += 1;
|
||||
}
|
||||
(out, levels)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod screen_map_tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Resource)]
|
||||
struct Panel(Handle<Image>);
|
||||
|
||||
fn named(world: &mut World, src: &str) -> Option<Handle<Image>> {
|
||||
(src == "raea-screen:panel@8x4").then(|| world.resource::<Panel>().0.clone())
|
||||
}
|
||||
|
||||
/// A UiTexture's image (raea-screen:name@WxH) is the texture of whichever map names it, the same handle its UI is
|
||||
/// drawn into: as the emissive map a panel glows, and shows under Solari, which draws no unlit surface. Before, only
|
||||
/// the base colour looked it up and an emissive one was refused as a missing file.
|
||||
#[test]
|
||||
fn a_screen_image_is_the_texture_of_any_map() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<Assets<Image>>();
|
||||
let h = world.resource_mut::<Assets<Image>>().add(Image::default());
|
||||
world.insert_resource(Panel(h.clone()));
|
||||
world.insert_resource(NamedImages(named));
|
||||
let mut vals = BTreeMap::new();
|
||||
for k in ["map", "emissive_map", "normal_map", "ao_map", "mr_map"] {
|
||||
vals.insert(k.to_string(), V::S("raea-screen:panel@8x4".into()));
|
||||
}
|
||||
let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };
|
||||
let m = material(&mut world, &t, &[], Path::new(".")).unwrap();
|
||||
for (slot, tex) in [("map", &m.base_color_texture), ("emissive", &m.emissive_texture), ("normal", &m.normal_map_texture), ("ao", &m.occlusion_texture), ("mr", &m.metallic_roughness_texture)] {
|
||||
assert_eq!(tex.as_ref(), Some(&h), "{slot}");
|
||||
}
|
||||
// a screen nobody draws is still a file name, and a missing file is refused
|
||||
let mut vals = BTreeMap::new();
|
||||
vals.insert("emissive_map".to_string(), V::S("raea-screen:other@8x4".into()));
|
||||
let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };
|
||||
assert!(material(&mut world, &t, &[], Path::new(".")).is_err());
|
||||
}
|
||||
|
||||
/// A camera's image ("render:NAME:WxH", docs/r3f.feature R3F23a) is the texture of a map that names it: the image
|
||||
/// that camera draws into, whichever of them names it first.
|
||||
#[test]
|
||||
fn a_render_image_is_the_texture_of_a_map() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<Assets<Image>>();
|
||||
let mut vals = BTreeMap::new();
|
||||
vals.insert("map".to_string(), V::S("render:fbo:64x32".into()));
|
||||
let t = Tup { kind: "mesh".into(), id: "plane".into(), vals };
|
||||
let m = material(&mut world, &t, &[], Path::new(".")).unwrap();
|
||||
let drawn = RenderImages::image(&mut world, "render:fbo:64x32", None).unwrap();
|
||||
assert_eq!(m.base_color_texture, Some(drawn));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Pictures given inline (a data: URL, raster or SVG) and a panel's, as RGBA, and the mip chain a panel's texture takes.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A picture given inline as a data: URL (`data:image/png;base64,...`, `data:image/svg+xml;utf8,<svg ...>`), decoded in
|
||||
/// memory: a raster through `image`, an SVG drawn by usvg and vello_cpu at its own size (at least 512 px on its long
|
||||
/// side, at most 4096). Before this a data: URL was read as a file path and failed ("map: .../data:image/svg+xml...: No
|
||||
/// such file"), the way the legacy app's agent first wrote a label into a perfume shot.
|
||||
pub fn data_picture(src: &str) -> Result<image::RgbaImage, String> {
|
||||
let (mime, bytes) = raea_io_net::data_url(src).ok_or("a data: URL that doesn't decode")?;
|
||||
let svg = mime == "image/svg+xml" || (mime.is_empty() && bytes.trim_ascii_start().starts_with(b"<svg"));
|
||||
if !svg {
|
||||
return image::load_from_memory(&bytes).map(|i| i.to_rgba8()).map_err(|e| format!("a {mime} picture: {e}"));
|
||||
}
|
||||
svg_picture(&bytes)
|
||||
}
|
||||
|
||||
/// An SVG's bytes drawn by resvg, at least 512 px on its long side, at most 4096.
|
||||
#[cfg(feature = "native")]
|
||||
pub fn svg_picture(bytes: &[u8]) -> Result<image::RgbaImage, String> {
|
||||
let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).map_err(|e| format!("its SVG: {e}"))?;
|
||||
let (sw, sh) = (tree.size().width().max(1.0), tree.size().height().max(1.0));
|
||||
let k = (512.0 / sw.max(sh)).max(1.0).min(4096.0 / sw.max(sh));
|
||||
let (w, h) = ((sw * k).round().max(1.0) as u32, (sh * k).round().max(1.0) as u32);
|
||||
let mut pm = resvg::tiny_skia::Pixmap::new(w, h).ok_or("the SVG's size")?;
|
||||
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(k, k), &mut pm.as_mut());
|
||||
let mut px = pm.take();
|
||||
// resvg paints premultiplied alpha; a texture wants it straight
|
||||
for p in px.chunks_exact_mut(4) {
|
||||
let a = p[3] as u32;
|
||||
if a > 0 && a < 255 {
|
||||
for c in &mut p[..3] {
|
||||
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "the SVG's pixels".to_string())
|
||||
}
|
||||
|
||||
/// Without native the CPU's SVG renderer isn't linked (a browser build can draw an SVG in the page instead).
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn svg_picture(_bytes: &[u8]) -> Result<image::RgbaImage, String> {
|
||||
Err("an SVG picture: SVG textures are drawn only in the native build".into())
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "native"))]
|
||||
mod data_url_tests {
|
||||
/// data: URL pictures decode in memory: an SVG (utf8, percent-escaped) drawn at least 512 px wide with its fill, and
|
||||
/// a base64 PNG to its own pixels
|
||||
#[test]
|
||||
fn data_pictures_decode() {
|
||||
let svg = super::data_picture("data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"64\" height=\"32\"><rect width=\"64\" height=\"32\" fill=\"%23ff0000\"/></svg>").unwrap();
|
||||
assert_eq!(svg.dimensions(), (512, 256));
|
||||
assert_eq!(svg.get_pixel(100, 100).0, [255, 0, 0, 255]);
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(3, 2, image::Rgba([0, 128, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
use base64::Engine as _;
|
||||
let url = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(&png));
|
||||
let pic = super::data_picture(&url).unwrap();
|
||||
assert_eq!((pic.dimensions(), pic.get_pixel(2, 1).0), ((3, 2), [0, 128, 255, 255]));
|
||||
assert!(super::data_picture("data:image/png;base64,!!!").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel's picture: inline (a data: URL, raster or SVG) or a file.
|
||||
pub fn panel_picture(src: &str, inserted: &[Tup], dir: &Path) -> Result<image::RgbaImage, String> {
|
||||
if src.starts_with("data:") {
|
||||
return data_picture(src).map_err(|e| format!("src (a data: URL): {e}"));
|
||||
}
|
||||
let path = resolve_src(inserted, src, dir)?;
|
||||
Ok(image::open(&path).map_err(|e| format!("{}: {e}", path.display()))?.to_rgba8())
|
||||
}
|
||||
|
||||
/// A panel's texture. A panel is usually drawn smaller than it was painted: a full mip chain and trilinear, anisotropic
|
||||
/// sampling keep its text from shimmering as it moves (without them a 2x minified glyph flickers).
|
||||
pub fn panel_image(pic: image::RgbaImage) -> Image {
|
||||
let (pw, ph) = pic.dimensions();
|
||||
let (data, levels) = mip_chain(pic.into_raw(), pw, ph);
|
||||
let mut img = Image::new(
|
||||
bevy::render::render_resource::Extent3d { width: pw, height: ph, depth_or_array_layers: 1 },
|
||||
bevy::render::render_resource::TextureDimension::D2,
|
||||
data,
|
||||
TextureFormat::Rgba8UnormSrgb,
|
||||
bevy::asset::RenderAssetUsages::default(),
|
||||
);
|
||||
img.texture_descriptor.mip_level_count = levels;
|
||||
img.sampler = bevy::image::ImageSampler::Descriptor(bevy::image::ImageSamplerDescriptor {
|
||||
anisotropy_clamp: 16,
|
||||
..bevy::image::ImageSamplerDescriptor::linear()
|
||||
});
|
||||
img
|
||||
}
|
||||
|
||||
/// Straight-alpha RGBA8 (sRGB) as premultiplied-alpha RGBA8 (the colour premultiplied in linear light, then encoded), with
|
||||
/// every mip level after it (2x2 box averages of the premultiplied linear values): the data and the level count, for a
|
||||
/// texture sampled trilinearly and blended premultiplied.
|
||||
pub fn mip_chain(data: Vec<u8>, w: u32, h: u32) -> (Vec<u8>, u32) {
|
||||
let to_lin: Vec<f32> = (0..256).map(|i| {
|
||||
let c = i as f32 / 255.0;
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}).collect();
|
||||
let to_srgb = |l: f32| -> u8 {
|
||||
let c = if l <= 0.0031308 { l * 12.92 } else { 1.055 * l.powf(1.0 / 2.4) - 0.055 };
|
||||
(c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
|
||||
};
|
||||
// level 0, premultiplied, kept in linear floats for the averages
|
||||
let mut cur: Vec<[f32; 4]> = data.chunks_exact(4).map(|p| {
|
||||
let a = p[3] as f32 / 255.0;
|
||||
[to_lin[p[0] as usize] * a, to_lin[p[1] as usize] * a, to_lin[p[2] as usize] * a, a]
|
||||
}).collect();
|
||||
let encode = |px: &[[f32; 4]], out: &mut Vec<u8>| {
|
||||
for p in px {
|
||||
out.extend_from_slice(&[to_srgb(p[0]), to_srgb(p[1]), to_srgb(p[2]), (p[3].clamp(0.0, 1.0) * 255.0 + 0.5) as u8]);
|
||||
}
|
||||
};
|
||||
let mut out = Vec::with_capacity(data.len() * 4 / 3 + 16);
|
||||
encode(&cur, &mut out);
|
||||
let (mut cw, mut ch) = (w as usize, h as usize);
|
||||
let mut levels = 1;
|
||||
while cw > 1 || ch > 1 {
|
||||
let (nw, nh) = ((cw / 2).max(1), (ch / 2).max(1));
|
||||
let mut next = vec![[0f32; 4]; nw * nh];
|
||||
for y in 0..nh {
|
||||
for x in 0..nw {
|
||||
let mut acc = [0f32; 4];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let p = cur[(y * 2 + dy).min(ch - 1) * cw + (x * 2 + dx).min(cw - 1)];
|
||||
for c in 0..4 {
|
||||
acc[c] += p[c] / 4.0;
|
||||
}
|
||||
}
|
||||
next[y * nw + x] = acc;
|
||||
}
|
||||
}
|
||||
encode(&next, &mut out);
|
||||
cur = next;
|
||||
(cw, ch) = (nw, nh);
|
||||
levels += 1;
|
||||
}
|
||||
(out, levels)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod screen_map_tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Resource)]
|
||||
struct Panel(Handle<Image>);
|
||||
|
||||
fn named(world: &mut World, src: &str) -> Option<Handle<Image>> {
|
||||
(src == "raea-screen:panel@8x4").then(|| world.resource::<Panel>().0.clone())
|
||||
}
|
||||
|
||||
/// A UiTexture's image (raea-screen:name@WxH) is the texture of whichever map names it, the same handle its UI is
|
||||
/// drawn into: as the emissive map a panel glows, and shows under Solari, which draws no unlit surface. Before, only
|
||||
/// the base colour looked it up and an emissive one was refused as a missing file.
|
||||
#[test]
|
||||
fn a_screen_image_is_the_texture_of_any_map() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<Assets<Image>>();
|
||||
let h = world.resource_mut::<Assets<Image>>().add(Image::default());
|
||||
world.insert_resource(Panel(h.clone()));
|
||||
world.insert_resource(NamedImages(named));
|
||||
let mut vals = BTreeMap::new();
|
||||
for k in ["map", "emissive_map", "normal_map", "ao_map", "mr_map"] {
|
||||
vals.insert(k.to_string(), V::S("raea-screen:panel@8x4".into()));
|
||||
}
|
||||
let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };
|
||||
let m = material(&mut world, &t, &[], Path::new(".")).unwrap();
|
||||
for (slot, tex) in [("map", &m.base_color_texture), ("emissive", &m.emissive_texture), ("normal", &m.normal_map_texture), ("ao", &m.occlusion_texture), ("mr", &m.metallic_roughness_texture)] {
|
||||
assert_eq!(tex.as_ref(), Some(&h), "{slot}");
|
||||
}
|
||||
// a screen nobody draws is still a file name, and a missing file is refused
|
||||
let mut vals = BTreeMap::new();
|
||||
vals.insert("emissive_map".to_string(), V::S("raea-screen:other@8x4".into()));
|
||||
let t = Tup { kind: "mesh".into(), id: "panel".into(), vals };
|
||||
assert!(material(&mut world, &t, &[], Path::new(".")).is_err());
|
||||
}
|
||||
|
||||
/// A camera's image ("render:NAME:WxH", docs/r3f.feature R3F23a) is the texture of a map that names it: the image
|
||||
/// that camera draws into, whichever of them names it first.
|
||||
#[test]
|
||||
fn a_render_image_is_the_texture_of_a_map() {
|
||||
let mut world = World::new();
|
||||
world.init_resource::<Assets<Image>>();
|
||||
let mut vals = BTreeMap::new();
|
||||
vals.insert("map".to_string(), V::S("render:fbo:64x32".into()));
|
||||
let t = Tup { kind: "mesh".into(), id: "plane".into(), vals };
|
||||
let m = material(&mut world, &t, &[], Path::new(".")).unwrap();
|
||||
let drawn = RenderImages::image(&mut world, "render:fbo:64x32", None).unwrap();
|
||||
assert_eq!(m.base_color_texture, Some(drawn));
|
||||
}
|
||||
|
||||
/// RM9: a map's BC7 chain is 16 bytes a block on every level (a level under 4 texels a side is one block), is
|
||||
/// the same blocks read back from the cache, and a picture whose sides aren't multiples of 4 is resampled to whole blocks
|
||||
#[test]
|
||||
fn a_map_is_bc7_with_its_mips_and_read_back_the_same() {
|
||||
super::set_block_compression(true);
|
||||
let pic = image::RgbaImage::from_fn(64, 16, |x, y| image::Rgba([(x * 4) as u8, (y * 16) as u8, ((x ^ y) * 9) as u8, 255]));
|
||||
let Some((a, levels, ..)) = super::bc7_chain(&pic, true) else { panic!("no BC7 chain") };
|
||||
assert_eq!(levels, 7, "64x16 to 1x1");
|
||||
// 16x4 blocks, 8x2, 4x1, 2x1, 1x1, 1x1, 1x1
|
||||
assert_eq!(a.len(), (64 + 16 + 4 + 2 + 1 + 1 + 1) * 16);
|
||||
let (b, ..) = super::bc7_chain(&pic, true).unwrap();
|
||||
assert_eq!(a, b, "the kept blocks are the ones made");
|
||||
let odd = image::RgbaImage::from_pixel(30, 15, image::Rgba([9, 9, 9, 255]));
|
||||
let (_, _, w, h) = super::bc7_chain(&odd, false).unwrap();
|
||||
assert_eq!((w, h), (32, 16), "resampled up to whole blocks");
|
||||
let img = super::map_image(pic, super::MapKind::Data, true, None);
|
||||
assert_eq!(img.texture_descriptor.format, TextureFormat::Bc7RgbaUnorm);
|
||||
assert_eq!(img.texture_descriptor.mip_level_count, 7);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! A standard material's maps whose picture changes frame by frame, swapped on one material (docs/render-memory.feature
|
||||
//! RM6). raea-runtime-scene's parts.rs keys such a map's column (`normal_maps`, one picture a line, and `normal_map_k`,
|
||||
//! keyed by step: raea-core-scene's SWAPPED_MAPS) where each picture once cut the part into a row of its own, every one
|
||||
//! of them spawned with its own material and textures at load: halcyon's pool water (96 normal maps) held 96 meshes and
|
||||
//! 186 textures, 1.7 GB on the GPU, in every shot of the reel, the pool in view or not. Now the part is one row and
|
||||
//! one material, and the frame's picture is made when the frame shows it; the last one goes when nothing holds it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use raea_core_program::eval::Tup;
|
||||
use raea_core_program::ir::V;
|
||||
use raea_sys_frame::FrameRows;
|
||||
|
||||
use crate::maps::{map_image, panel_picture, MapKind};
|
||||
|
||||
/// One map of a part whose picture is keyed: its column, how it's read, and the picture it shows now.
|
||||
struct Slot {
|
||||
col: &'static str,
|
||||
kind: MapKind,
|
||||
sampling: Option<raea_sys_sampler::Sampling>,
|
||||
shown: String,
|
||||
}
|
||||
|
||||
/// The part's swapped maps (spawned with the row when one of its maps is keyed) and where its pictures are found.
|
||||
#[derive(Component)]
|
||||
pub struct SwappedMaps {
|
||||
slots: Vec<Slot>,
|
||||
repeat: bool,
|
||||
dir: PathBuf,
|
||||
}
|
||||
|
||||
/// The maps a mesh row swaps, by column, with how each is read (as maps::material makes them).
|
||||
const COLS: [(&str, &str, MapKind); 5] = [("map", "map", MapKind::Colour), ("normal_map", "normalMap", MapKind::Data), ("mr_map", "metallicRoughnessMap", MapKind::Data), ("ao_map", "aoMap", MapKind::Data), ("emissive_map", "emissiveMap", MapKind::Colour)];
|
||||
|
||||
/// The row's swapped maps, if any of its maps is keyed (`{col}s`): put on the part's entity as it spawns.
|
||||
pub fn of(t: &Tup, dir: &std::path::Path) -> Result<Option<SwappedMaps>, String> {
|
||||
let vals = &t.vals;
|
||||
let all = raea_sys_sampler::Sampling::col(vals, "sampler").map_err(|e| format!("mesh {}: {e}", t.id))?;
|
||||
let own: std::collections::BTreeMap<String, raea_sys_sampler::Sampling> = match vals.get("samplers") {
|
||||
Some(V::S(js)) => {
|
||||
let o: serde_json::Map<String, serde_json::Value> = serde_json::from_str(js).map_err(|e| format!("mesh {}: samplers: {e}", t.id))?;
|
||||
o.iter().filter_map(|(k, v)| raea_sys_sampler::Sampling::of(v).ok().map(|s| (k.clone(), s))).collect()
|
||||
}
|
||||
_ => Default::default(),
|
||||
};
|
||||
let slots: Vec<Slot> = COLS
|
||||
.iter()
|
||||
.filter(|(col, ..)| matches!(vals.get(&format!("{col}s")), Some(V::S(_))))
|
||||
.filter_map(|&(col, prop, kind)| match vals.get(col) {
|
||||
Some(V::S(s)) if !s.is_empty() && !s.starts_with("render:") => Some(Slot { col, kind, sampling: own.get(prop).or(all.as_ref()).cloned(), shown: s.clone() }),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if slots.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let g = |k: &str| match vals.get(k) { Some(V::N(n)) => *n as f32, _ => 1.0 };
|
||||
Ok(Some(SwappedMaps { slots, repeat: g("repeat_u") != 1.0 || g("repeat_v") != 1.0, dir: dir.to_path_buf() }))
|
||||
}
|
||||
|
||||
/// The frame's picture on each swapped map: made when the frame names another than the one shown. A material shared
|
||||
/// with other parts (one per value: share.rs) is made the part's own first, so the swap shows on this part alone.
|
||||
pub fn sync_swapped_maps(
|
||||
frame: Res<FrameRows>,
|
||||
mut q: Query<(Entity, &mut SwappedMaps, &mut MeshMaterial3d<StandardMaterial>)>,
|
||||
mut mats: ResMut<Assets<StandardMaterial>>,
|
||||
mut images: ResMut<Assets<Image>>,
|
||||
) {
|
||||
if q.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (e, mut sw, mut mat) in &mut q {
|
||||
let Some(v) = frame.vals(e) else { continue };
|
||||
let mut changed: Vec<(usize, Handle<Image>)> = Vec::new();
|
||||
for (i, slot) in sw.slots.iter().enumerate() {
|
||||
let Some(src) = raea_sys_frame::keyed(|c| v.get(c).cloned(), slot.col) else { continue };
|
||||
if src == slot.shown || src.is_empty() || src.starts_with("render:") {
|
||||
continue;
|
||||
}
|
||||
let pic = panel_picture(&src, &[], &sw.dir);
|
||||
match pic {
|
||||
Ok(pic) => changed.push((i, images.add(map_image(pic, slot.kind, sw.repeat, slot.sampling.as_ref())))),
|
||||
Err(err) => warn!("a swapped map ({}): {src}: {err}", slot.col),
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(cur) = mats.get(&mat.0).cloned() else { continue };
|
||||
let mut own = cur;
|
||||
for (i, h) in changed {
|
||||
let slot = &mut sw.slots[i];
|
||||
match slot.col {
|
||||
"map" => own.base_color_texture = Some(h),
|
||||
"normal_map" => own.normal_map_texture = Some(h),
|
||||
"mr_map" => own.metallic_roughness_texture = Some(h),
|
||||
"ao_map" => own.occlusion_texture = Some(h),
|
||||
_ => own.emissive_texture = Some(h),
|
||||
}
|
||||
slot.shown = raea_sys_frame::keyed(|c| v.get(c).cloned(), slot.col).unwrap_or_default();
|
||||
}
|
||||
// a material of its own with the frame's pictures: a shared one is left to the parts that share it, and the
|
||||
// part's last material and the pictures it showed go with their last holder
|
||||
mat.0 = mats.add(own);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "raea-sys-memtally"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Where a render's memory goes (docs/render-memory.feature RM0): after each RAEA_MEM_MARKS mark, each App's meshes, images and storage buffers with their CPU bytes, and its render world's meshes and images with their GPU bytes"
|
||||
|
||||
[dependencies]
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
|
||||
@@ -0,0 +1,131 @@
|
||||
//! RM0 (docs/render-memory.feature): where a render's memory goes, by world and by copy. With RAEA_MEM_MARKS, every
|
||||
//! mark (`mem_mark`) is followed, at each world's next update, by a `mem_assets` line per world: its main world's
|
||||
//! meshes, images and storage buffers with the bytes they still hold on the CPU, and its render world's meshes and
|
||||
//! images with the bytes they take on the GPU. A sequence opens more than one App (React's, the 3D's), so each line
|
||||
//! names its App by the order it opened in.
|
||||
|
||||
use bevy::prelude::*;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
|
||||
/// Marks made so far: a world prints its tally when this has moved since it last did.
|
||||
static MARKS: AtomicU64 = AtomicU64::new(0);
|
||||
/// Apps tallied so far, to name each one.
|
||||
static APPS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// A mark was made (raea-render's `mem_mark`): each App tallied prints its assets at its next update.
|
||||
pub fn marked() {
|
||||
MARKS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The App's tally systems (the caller adds them only with RAEA_MEM_MARKS): its main world's in Last, its render
|
||||
/// world's after it renders.
|
||||
pub fn install(app: &mut App) {
|
||||
let n = APPS.fetch_add(1, Ordering::Relaxed);
|
||||
app.add_systems(Last, main_tally(n));
|
||||
if let Some(sub) = app.get_sub_app_mut(bevy::render::RenderApp) {
|
||||
sub.add_systems(bevy::render::Render, render_tally(n).after(bevy::render::RenderSystems::Render));
|
||||
}
|
||||
}
|
||||
|
||||
fn mb(b: u64) -> f64 {
|
||||
b as f64 / 1048576.0
|
||||
}
|
||||
|
||||
/// A mesh's bytes still on the CPU: its attributes and indices (none once its data went to the GPU alone).
|
||||
pub fn mesh_cpu_bytes(m: &Mesh) -> u64 {
|
||||
let attrs = m.try_attributes().map(|a| a.map(|(_, v)| v.get_bytes().len() as u64).sum()).unwrap_or(0);
|
||||
let idx = match m.try_indices_option() {
|
||||
Ok(Some(bevy::mesh::Indices::U16(v))) => v.len() as u64 * 2,
|
||||
Ok(Some(bevy::mesh::Indices::U32(v))) => v.len() as u64 * 4,
|
||||
_ => 0,
|
||||
};
|
||||
attrs + idx
|
||||
}
|
||||
|
||||
fn main_tally(app: u32) -> impl FnMut(Res<Assets<Mesh>>, Res<Assets<Image>>, Option<Res<Assets<bevy::render::storage::ShaderBuffer>>>) {
|
||||
let mut seen = 0u64;
|
||||
move |meshes, images, buffers| {
|
||||
let now = MARKS.load(Ordering::Relaxed);
|
||||
if now == seen {
|
||||
return;
|
||||
}
|
||||
seen = now;
|
||||
let (mut mn, mut mk, mut mbytes) = (0u64, 0u64, 0u64);
|
||||
for (_, m) in meshes.iter() {
|
||||
let b = mesh_cpu_bytes(m);
|
||||
mn += 1;
|
||||
mk += (b > 0) as u64;
|
||||
mbytes += b;
|
||||
}
|
||||
let (mut inn, mut ik, mut ibytes) = (0u64, 0u64, 0u64);
|
||||
for (_, i) in images.iter() {
|
||||
let b = i.data.as_ref().map_or(0, |d| d.len() as u64);
|
||||
inn += 1;
|
||||
ik += (b > 0) as u64;
|
||||
ibytes += b;
|
||||
}
|
||||
let (mut bn, mut bbytes) = (0u64, 0u64);
|
||||
for (_, s) in buffers.iter().flat_map(|b| b.iter()) {
|
||||
bn += 1;
|
||||
if let bevy::render::storage::ShaderBufferData::Initialized { data, .. } = &s.data {
|
||||
bbytes += data.len() as u64;
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"mem_assets app {app} main: meshes {mn} ({mk} on the CPU) {:.1} MB, images {inn} ({ik} on the CPU) {:.1} MB, buffers {bn} {:.1} MB",
|
||||
mb(mbytes),
|
||||
mb(ibytes),
|
||||
mb(bbytes)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture's bytes on the GPU: every mip level of every layer, by its format's blocks.
|
||||
pub fn texture_bytes(d: &bevy::render::render_resource::TextureDescriptor) -> u64 {
|
||||
let (bw, bh) = d.format.block_dimensions();
|
||||
let block = d.format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
let layers = if d.dimension == bevy::render::render_resource::TextureDimension::D3 { 1 } else { d.size.depth_or_array_layers as u64 };
|
||||
let mut sum = 0u64;
|
||||
for l in 0..d.mip_level_count.max(1) {
|
||||
let w = (d.size.width >> l).max(1);
|
||||
let h = (d.size.height >> l).max(1);
|
||||
let z = if d.dimension == bevy::render::render_resource::TextureDimension::D3 { (d.size.depth_or_array_layers >> l).max(1) as u64 } else { 1 };
|
||||
sum += w.div_ceil(bw) as u64 * h.div_ceil(bh) as u64 * block * z;
|
||||
}
|
||||
sum * layers
|
||||
}
|
||||
|
||||
fn render_tally(app: u32) -> impl FnMut(Res<bevy::render::render_asset::RenderAssets<bevy::render::mesh::RenderMesh>>, Res<bevy::render::render_asset::RenderAssets<bevy::render::texture::GpuImage>>) {
|
||||
let mut seen = 0u64;
|
||||
move |meshes, images| {
|
||||
let now = MARKS.load(Ordering::Relaxed);
|
||||
if now == seen {
|
||||
return;
|
||||
}
|
||||
seen = now;
|
||||
let (mut mn, mut mbytes) = (0u64, 0u64);
|
||||
for (_, m) in meshes.iter() {
|
||||
mn += 1;
|
||||
mbytes += m.vertex_count as u64 * m.layout.0.layout().array_stride;
|
||||
if let bevy::render::mesh::RenderMeshBufferInfo::Indexed { count, index_format } = m.buffer_info {
|
||||
mbytes += count as u64 * if index_format == bevy::render::render_resource::IndexFormat::Uint16 { 2 } else { 4 };
|
||||
}
|
||||
}
|
||||
let (mut inn, mut ibytes) = (0u64, 0u64);
|
||||
let mut each: Vec<(u64, String)> = Vec::new();
|
||||
for (_, i) in images.iter() {
|
||||
inn += 1;
|
||||
let d = &i.texture_descriptor;
|
||||
let b = texture_bytes(d);
|
||||
ibytes += b;
|
||||
each.push((b, format!("{}x{}x{} {:?} mips {}{}", d.size.width, d.size.height, d.size.depth_or_array_layers, d.format, d.mip_level_count, d.label.map(|l| format!(" ({l})")).unwrap_or_default())));
|
||||
}
|
||||
eprintln!("mem_assets app {app} render: meshes {mn} {:.1} MB, images {inn} {:.1} MB", mb(mbytes), mb(ibytes));
|
||||
// the biggest images, by what they are: which ones to make smaller next
|
||||
each.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
let top: Vec<String> = each.iter().take(12).map(|(b, what)| format!("{:.1} MB {what}", mb(*b))).collect();
|
||||
if !top.is_empty() {
|
||||
eprintln!("mem_images app {app} render, biggest: {}", top.join("; "));
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
-5
@@ -230,6 +230,24 @@ pub fn box_uvs(pos: &[[f32; 3]], nor: &[[f32; 3]]) -> Vec<[f32; 2]> {
|
||||
}
|
||||
|
||||
|
||||
/// Triangle corners as an indexed mesh: each distinct (place, normal) once, by its exact bits, and each corner's index.
|
||||
pub fn welded(pos: &[[f32; 3]], nor: &[[f32; 3]]) -> (Vec<[f32; 3]>, Vec<[f32; 3]>, Vec<u32>) {
|
||||
let n = pos.len().min(nor.len());
|
||||
let mut at: std::collections::HashMap<[u32; 6], u32> = std::collections::HashMap::with_capacity(n / 3);
|
||||
let (mut p, mut q, mut idx) = (Vec::with_capacity(n / 3), Vec::with_capacity(n / 3), Vec::with_capacity(n));
|
||||
for i in 0..n {
|
||||
let (a, b) = (pos[i], nor[i]);
|
||||
let key = [a[0].to_bits(), a[1].to_bits(), a[2].to_bits(), b[0].to_bits(), b[1].to_bits(), b[2].to_bits()];
|
||||
let k = *at.entry(key).or_insert_with(|| {
|
||||
p.push(a);
|
||||
q.push(b);
|
||||
(p.len() - 1) as u32
|
||||
});
|
||||
idx.push(k);
|
||||
}
|
||||
(p, q, idx)
|
||||
}
|
||||
|
||||
/// A mesh row's shape as a Bevy Mesh (docs/media.feature M2): a sphere alone is Bevy's Sphere::mesh() (icosphere or UV
|
||||
/// sphere), a cuboid alone its Cuboid's (UVs a face each) and a cylinder its Cylinder's, as a Bevy Mesh3d's; a <BufferMesh> ("buffer:{positions,
|
||||
/// indices, normals, uvs, colors}") its own vertex buffers; anything else Manifold's, flat-shaded. `uvs` gives it
|
||||
@@ -248,13 +266,15 @@ pub fn shape_mesh(id: &str, expr: &str, uvs: bool, tangents: bool) -> Result<Mes
|
||||
}
|
||||
return Ok(m);
|
||||
}
|
||||
if let Some(mut m) = expr.strip_prefix("buffer:").map(|b| indexed::buffer_indexed(b, uvs, vertex_colors)).transpose().map_err(|e| format!("mesh {id}: {e}"))?.flatten() {
|
||||
// a <BufferMesh>'s JSON, its own text or the kept file it names (raea-core-shape kept_buffer, RM8)
|
||||
let buffer = expr.strip_prefix("buffer:").map(raea_core_shape::buffer_json).transpose().map_err(|e| format!("mesh {id}: {e}"))?;
|
||||
if let Some(mut m) = buffer.as_deref().map(|b| indexed::buffer_indexed(b, uvs, vertex_colors)).transpose().map_err(|e| format!("mesh {id}: {e}"))?.flatten() {
|
||||
if tangents {
|
||||
m.generate_tangents().map_err(|e| format!("mesh {id}: normalMap: its tangents: {e}"))?;
|
||||
}
|
||||
return Ok(m);
|
||||
}
|
||||
let (tris, own_uvs, own_colors) = match expr.strip_prefix("buffer:") {
|
||||
let (tris, own_uvs, own_colors) = match buffer.as_deref() {
|
||||
Some(b) => {
|
||||
let c = buffer_colors(b).map_err(|e| format!("mesh {id}: {e}"))?;
|
||||
let (t, u) = buffer_tris(b).map_err(|e| format!("mesh {id}: {e}"))?;
|
||||
@@ -263,17 +283,62 @@ pub fn shape_mesh(id: &str, expr: &str, uvs: bool, tangents: bool) -> Result<Mes
|
||||
None => (raea_core_shape::cached(expr).map_err(|e| format!("mesh {id}: {e}"))?, None, None),
|
||||
};
|
||||
let mut m = Mesh::new(bevy::render::render_resource::PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_POSITION, tris.positions.clone());
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, tris.normals.clone());
|
||||
// Manifold's triangles welded where a corner is another's exactly (its place and its normal), as an indexed mesh
|
||||
// (docs/render-memory.feature RM7): halcyon's shapes had 4.65 corners to each distinct vertex, so the welded mesh
|
||||
// is about a third of the bytes on the CPU, on the GPU and in Solari's traced copy, and a third of the vertices
|
||||
// to shade. Only a shape with nothing given per corner (a <BufferMesh>'s own UVs or colours) is welded; box UVs
|
||||
// are a vertex's own (from its place and normal), so welded corners had the same ones. RAEA_NO_WELD=1 draws them
|
||||
// unwelded (the A/B control).
|
||||
let weld = own_uvs.is_none() && own_colors.is_none() && std::env::var_os("RAEA_NO_WELD").is_none();
|
||||
let (pos, nor) = if weld {
|
||||
let (pos, nor, idx) = welded(&tris.positions, &tris.normals);
|
||||
m.insert_indices(bevy::mesh::Indices::U32(idx));
|
||||
(std::borrow::Cow::Owned(pos), std::borrow::Cow::Owned(nor))
|
||||
} else {
|
||||
(std::borrow::Cow::Borrowed(&tris.positions), std::borrow::Cow::Borrowed(&tris.normals))
|
||||
};
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos.to_vec());
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, nor.to_vec());
|
||||
// a <BufferMesh colors>: per-vertex colours, which StandardMaterial multiplies its colour by
|
||||
if let Some(c) = own_colors {
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_COLOR, c);
|
||||
}
|
||||
if own_uvs.is_some() || uvs {
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_UV_0, own_uvs.unwrap_or_else(|| box_uvs(&tris.positions, &tris.normals)));
|
||||
m.insert_attribute(Mesh::ATTRIBUTE_UV_0, own_uvs.unwrap_or_else(|| box_uvs(&pos, &nor)));
|
||||
if tangents {
|
||||
m.generate_tangents().map_err(|e| format!("mesh {id}: normalMap: its tangents: {e}"))?;
|
||||
}
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_shapes_corners_weld_where_place_and_normal_are_the_same() {
|
||||
// a square as two triangles: six corners, four vertices; the crease's other side (another normal) stays apart
|
||||
let up = [0.0, 1.0, 0.0];
|
||||
let pos = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]];
|
||||
let nor = [up, up, up, up, up, up, [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0]];
|
||||
let (p, n, idx) = welded(&pos, &nor);
|
||||
assert_eq!(p.len(), 7, "4 on the top, 3 on the side: {p:?}");
|
||||
assert_eq!(n.len(), p.len());
|
||||
assert_eq!(idx.len(), 9);
|
||||
for (c, &i) in idx.iter().enumerate() {
|
||||
assert_eq!((p[i as usize], n[i as usize]), (pos[c], nor[c]), "corner {c} draws where it was");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_welded_shape_is_indexed_and_draws_the_same_triangles() {
|
||||
let m = shape_mesh("t", "box(1, 1, 1)", true, true).unwrap();
|
||||
let _ = m;
|
||||
let m = shape_mesh("t", "minus(box(2, 2, 2), cylinder(0.5, 3))", true, true).unwrap();
|
||||
assert!(m.indices().is_some(), "a Manifold shape is indexed");
|
||||
let t = raea_core_shape::cached("minus(box(2, 2, 2), cylinder(0.5, 3))").unwrap();
|
||||
assert_eq!(m.indices().unwrap().len(), t.positions.len(), "every triangle kept");
|
||||
assert!(m.count_vertices() < t.positions.len(), "fewer vertices than corners: {} of {}", m.count_vertices(), t.positions.len());
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
[package]
|
||||
name = "raea-sys-motionfaults"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A clip's faults that only show in motion (docs/notice.feature NT10, NT11): knees buckling while the foot stands, feet skating, joints past their range, fingers twisted or bent back, jolts, and fingers through what the hand holds"
|
||||
|
||||
[dependencies]
|
||||
raea-core-ease = { path = "../../core/ease" }
|
||||
raea-sys-body = { path = "../body" }
|
||||
glam = "0.33"
|
||||
serde_json = "1"
|
||||
@@ -1,55 +0,0 @@
|
||||
//! A clip as JSON: the skeleton (`joints`, as skeleton.json and `character.take` have them), `fps`, and `frames`, each
|
||||
//! `{ root, turns }` as a pose is everywhere in raea/character. A clip that holds something says the thing's shape
|
||||
//! once (`thing`: ball, box, capsule or cylinder, as `character.take` takes it) and where it is on each frame
|
||||
//! (`frames[i].thing: { at, turn }`, what `character.take` answers), in the frame the body is posed in.
|
||||
|
||||
use glam::Quat;
|
||||
use raea_sys_body::json::{quat, solid, vec3};
|
||||
use raea_sys_body::rig::{Pose, Posed, Skeleton};
|
||||
use raea_sys_body::shape::Thing;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::Held;
|
||||
|
||||
pub struct Clip {
|
||||
pub skel: Skeleton,
|
||||
pub fps: f32,
|
||||
pub poses: Vec<Pose>,
|
||||
pub held: Option<Held>,
|
||||
}
|
||||
|
||||
|
||||
impl Clip {
|
||||
/// Every frame posed: each joint's place and turn, in the clip's frame.
|
||||
pub fn world(&self) -> Vec<Posed> {
|
||||
self.poses.iter().map(|p| self.skel.fk(p)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip read from its JSON.
|
||||
pub fn clip_of(v: &Value) -> Result<Clip, String> {
|
||||
let skel = Skeleton::from_value(v)?;
|
||||
let fps = v["fps"].as_f64().unwrap_or(30.0) as f32;
|
||||
let frames = v["frames"].as_array().ok_or("the clip has no frames")?;
|
||||
let shape = if v["thing"].is_null() { None } else { Some(solid(&v["thing"])?) };
|
||||
let (mut poses, mut held) = (Vec::with_capacity(frames.len()), Vec::with_capacity(frames.len()));
|
||||
for (k, f) in frames.iter().enumerate() {
|
||||
let mut p = skel.rest();
|
||||
p.root = vec3(&f["root"], &format!("frame {k}'s root"))?;
|
||||
for (slot, t) in p.turns.iter_mut().zip(f["turns"].as_array().ok_or_else(|| format!("frame {k} has no turns"))?) {
|
||||
*slot = quat(t, &format!("frame {k}'s turn"))?;
|
||||
}
|
||||
poses.push(p);
|
||||
held.push(match (shape, f.get("thing").filter(|t| !t.is_null())) {
|
||||
(Some(solid), Some(t)) => {
|
||||
let turn = if t["turn"].is_null() { Quat::IDENTITY } else { quat(&t["turn"], "a thing's turn")? };
|
||||
Some(Thing { solid, at: vec3(&t["at"], "a thing's at")?, turn })
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
}
|
||||
if poses.len() < 3 {
|
||||
return Err("a clip needs three frames or more to say how it moves".into());
|
||||
}
|
||||
Ok(Clip { skel, fps, poses, held: shape.map(|_| held) })
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
//! The motion critic: a logistic model over a finding's size and length and the words of what it is (its check, its
|
||||
//! joint's family, its key), the chance a person would call it wrong. The checks find; the critic says which findings
|
||||
//! matter. It learns only from real verdicts, never from planted faults (it would learn the rules back): a fix that
|
||||
//! took a finding away, or a look at the render (`--real`, `--fine`). Unlike a key's line (verdicts.rs), a word it
|
||||
//! learns carries to its neighbours: a pinky called fine bent back says something about the ring finger.
|
||||
//! Its examples are kept beside its model (raea's models folder, notice/motion.labels.jsonl); `raea scene faults
|
||||
//! train` fits it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Fault;
|
||||
|
||||
pub const N: usize = 3;
|
||||
/// bias, size over the check's scale (at most 5), ln(1 + frames it lasts)
|
||||
pub const NAMES: [&str; N] = ["bias", "size", "frames"];
|
||||
/// Before any verdict, what the checks flag is a fault, the more so the bigger (a finding at its check's scale, 0.88).
|
||||
pub const PRIOR: [f32; N] = [1.0, 1.0, 0.0];
|
||||
/// A finding scored this or more is said.
|
||||
pub const SAY: f32 = 0.5;
|
||||
/// A verdict already scored this sure its way stops teaching.
|
||||
const MARGIN: f32 = 0.9;
|
||||
|
||||
/// The size a check's findings are read against: one unit is a clear fault of that kind.
|
||||
fn scale(check: &str) -> f32 {
|
||||
match check {
|
||||
"skate" => 0.05,
|
||||
"grip" | "through" => 0.03,
|
||||
"jolt" => 25.0,
|
||||
"buckle" => 12.0,
|
||||
_ => 10.0, // finger, limit: degrees past the range
|
||||
}
|
||||
}
|
||||
|
||||
/// A joint's family: its name without its segment number and side (pinky_02_r -> pinky, calf_l -> calf).
|
||||
fn family(joint: &str) -> String {
|
||||
let base = joint.trim_end_matches("_l").trim_end_matches("_r");
|
||||
base.split('_').next().unwrap_or(base).to_lowercase()
|
||||
}
|
||||
|
||||
/// A finding's features and words, from its check, joint, size and the frames it lasts.
|
||||
pub fn features_of(check: &str, joint: &str, value: f32, frames: usize) -> (Vec<f32>, Vec<String>) {
|
||||
let role = raea_sys_body::rig::role_name(joint);
|
||||
// a bone through a surface has no size of its own (its value is 0): it's a clear one, a unit
|
||||
let size = if check == "through" { 1.0 } else { (value.max(0.0) / scale(check)).min(5.0) };
|
||||
let x = vec![1.0, size, (1.0 + frames as f32).ln()];
|
||||
let toks = vec![format!("check:{check}"), format!("{check}:{}", family(&role)), format!("{check}:{role}")];
|
||||
(x, toks)
|
||||
}
|
||||
|
||||
pub fn features(f: &Fault) -> (Vec<f32>, Vec<String>) {
|
||||
features_of(f.check, &f.joint, f.value, f.to.saturating_sub(f.from) + 1)
|
||||
}
|
||||
|
||||
/// A verdict as an example row.
|
||||
pub fn row_of(check: &str, joint: &str, value: f32, frames: usize, real: bool, by: &str) -> Value {
|
||||
let (x, toks) = features_of(check, joint, value, frames);
|
||||
json!({"key": toks[2], "label": if real { 1 } else { 0 }, "by": by, "x": x, "toks": toks})
|
||||
}
|
||||
|
||||
pub fn row(f: &Fault, real: bool, by: &str) -> Value {
|
||||
row_of(f.check, &f.joint, f.value, f.to.saturating_sub(f.from) + 1, real, by)
|
||||
}
|
||||
|
||||
/// The critic's model and its examples: beside the motion verdicts (`verdicts`, notice/motion.json).
|
||||
pub fn paths(verdicts: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) {
|
||||
(verdicts.with_file_name("motion-critic.json"), verdicts.with_file_name("motion.labels.jsonl"))
|
||||
}
|
||||
|
||||
/// Rows appended to the examples file.
|
||||
pub fn append(file: &std::path::Path, rows: &[Value]) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
if rows.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(d) = file.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
for r in rows {
|
||||
writeln!(f, "{r}").map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Critic {
|
||||
pub w: [f32; N],
|
||||
pub tokens: BTreeMap<String, f32>,
|
||||
pub labels: usize,
|
||||
}
|
||||
|
||||
use raea_core_ease::sigmoid;
|
||||
|
||||
impl Critic {
|
||||
pub fn prior() -> Critic {
|
||||
Critic { w: PRIOR, tokens: BTreeMap::new(), labels: 0 }
|
||||
}
|
||||
|
||||
pub fn score_x(&self, x: &[f32], toks: &[String]) -> f32 {
|
||||
let z: f32 = self.w.iter().zip(x).map(|(w, x)| w * x).sum::<f32>() + toks.iter().map(|t| self.tokens.get(t).copied().unwrap_or(0.0)).sum::<f32>();
|
||||
sigmoid(z)
|
||||
}
|
||||
|
||||
pub fn score(&self, f: &Fault) -> f32 {
|
||||
let (x, t) = features(f);
|
||||
self.score_x(&x, &t)
|
||||
}
|
||||
|
||||
/// Fitted to examples (features, words, 1 real / 0 fine): each weight held toward its prior, each word's toward
|
||||
/// nothing. Examples all one way teach only the words (they say what's wrong, not where the line is), and one
|
||||
/// already MARGIN sure its way stops teaching, as the scene judge does (raea-sys-notice model.rs).
|
||||
pub fn fit(ex: &[(Vec<f32>, Vec<String>, f32)]) -> Critic {
|
||||
let mut m = Critic::prior();
|
||||
m.labels = ex.len();
|
||||
if ex.is_empty() {
|
||||
return m;
|
||||
}
|
||||
let (hold_w, hold_t, rate, n) = (0.5f32, 0.3f32, 0.3f32, ex.len() as f32);
|
||||
for (_, toks, _) in ex {
|
||||
for t in toks {
|
||||
m.tokens.entry(t.clone()).or_insert(0.0);
|
||||
}
|
||||
}
|
||||
let both = ex.iter().any(|e| e.2 >= 0.5) && ex.iter().any(|e| e.2 < 0.5);
|
||||
for _ in 0..3000 {
|
||||
let mut gw = [0f32; N];
|
||||
let mut gt: BTreeMap<&str, f32> = BTreeMap::new();
|
||||
for (x, toks, y) in ex {
|
||||
let p = m.score_x(x, toks);
|
||||
if (*y >= 0.5 && p >= MARGIN) || (*y < 0.5 && p <= 1.0 - MARGIN) {
|
||||
continue;
|
||||
}
|
||||
let e = p - y;
|
||||
for k in 0..N {
|
||||
gw[k] += e * x[k];
|
||||
}
|
||||
for t in toks {
|
||||
*gt.entry(t).or_insert(0.0) += e;
|
||||
}
|
||||
}
|
||||
if both {
|
||||
// the frames a finding lasts stays at its prior until there's far more than a few dozen verdicts: on
|
||||
// the first 50 (11-27) it learned that long ones were fine only because the pinky's fine bends ran long
|
||||
for k in 0..N - 1 {
|
||||
m.w[k] -= rate * (gw[k] / n + hold_w * (m.w[k] - PRIOR[k]) / n);
|
||||
}
|
||||
}
|
||||
for (t, g) in gt {
|
||||
let w = m.tokens.get_mut(t).unwrap();
|
||||
*w -= rate * (g / n + hold_t * *w / n);
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({"weights": NAMES.iter().zip(self.w).map(|(n, w)| (n.to_string(), json!(w))).collect::<serde_json::Map<_, _>>(),
|
||||
"tokens": self.tokens.iter().filter(|(_, w)| w.abs() >= 1e-3).map(|(k, w)| (k.clone(), json!(w))).collect::<serde_json::Map<_, _>>(),
|
||||
"labels": self.labels})
|
||||
}
|
||||
|
||||
pub fn of_json(v: &Value) -> Critic {
|
||||
let mut w = PRIOR;
|
||||
for (k, n) in NAMES.iter().enumerate() {
|
||||
if let Some(x) = v["weights"][n].as_f64() {
|
||||
w[k] = x as f32;
|
||||
}
|
||||
}
|
||||
let tokens = v["tokens"].as_object().into_iter().flatten().filter_map(|(k, x)| Some((k.clone(), x.as_f64()? as f32))).collect();
|
||||
Critic { w, tokens, labels: v["labels"].as_u64().unwrap_or(0) as usize }
|
||||
}
|
||||
|
||||
pub fn load(path: &std::path::Path) -> Critic {
|
||||
crate::read_json(path).map_or_else(Critic::prior, |v| Critic::of_json(&v))
|
||||
}
|
||||
}
|
||||
|
||||
/// Example rows read back (a later row on the same finding, by key and size, replaces an earlier one).
|
||||
pub fn examples(rows: &str) -> Vec<(Vec<f32>, Vec<String>, f32)> {
|
||||
let mut by: BTreeMap<String, (Vec<f32>, Vec<String>, f32)> = BTreeMap::new();
|
||||
for v in rows.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()) {
|
||||
let x: Vec<f32> = serde_json::from_value(v["x"].clone()).unwrap_or_default();
|
||||
let toks: Vec<String> = v["toks"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(String::from)).collect();
|
||||
if x.len() != N {
|
||||
continue;
|
||||
}
|
||||
let id = format!("{}|{:.3}|{:.3}", v["key"].as_str().unwrap_or(""), x[1], x[2]);
|
||||
by.insert(id, (x, toks, v["label"].as_f64().unwrap_or(0.0) as f32));
|
||||
}
|
||||
by.into_values().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn f(check: &'static str, joint: &str, value: f32) -> Fault {
|
||||
Fault { check, joint: joint.into(), from: 10, to: 12, peak: 10, value, unit: "", says: String::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untrained_it_says_what_the_checks_flag() {
|
||||
assert!(Critic::prior().score(&f("finger", "pinky_02_r", 15.0)) >= SAY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_called_fine_carries_to_its_other_joint_and_not_to_other_checks() {
|
||||
// the pinky's middle joint bent back a little is fine on both hands, a big bend real; the critic learns the
|
||||
// family's word and the size together
|
||||
let mut ex = Vec::new();
|
||||
for (j, v, real) in [("pinky_02_r", 12.0, false), ("pinky_02_l", 13.0, false), ("pinky_02_r", 11.0, false), ("pinky_02_r", 24.0, true), ("thumb_03_r", 20.0, true)] {
|
||||
let (x, t) = features(&f("finger", j, v));
|
||||
ex.push((x, t, if real { 1.0 } else { 0.0 }));
|
||||
}
|
||||
let c = Critic::fit(&ex);
|
||||
// the pinky's end joint was never judged: its family word says a small bend is fine
|
||||
assert!(c.score(&f("finger", "pinky_03_r", 12.0)) < SAY, "{}", c.score(&f("finger", "pinky_03_r", 12.0)));
|
||||
assert!(c.score(&f("finger", "pinky_02_r", 24.0)) >= SAY);
|
||||
// a buckle shares none of its words
|
||||
assert!(c.score(&f("buckle", "calf_l", 15.0)) >= SAY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn examples_keep_the_latest_verdict_on_a_finding() {
|
||||
let a = row(&f("grip", "thumb_03_r", 0.05), true, "fixed").to_string();
|
||||
let b = row(&f("grip", "thumb_03_r", 0.05), false, "claude").to_string();
|
||||
let ex = examples(&format!("{a}\n{b}\n"));
|
||||
assert_eq!(ex.len(), 1);
|
||||
assert_eq!(ex[0].2, 0.0);
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
//! Fingers held to their range, which raea-sys-body's limits table leaves out. Each finger joint's turn from rest is
|
||||
//! read about three axes of its own bone at rest: its twist about the bone; its flex, about the axis that curls the
|
||||
//! bone toward the palm (bone x palm: a flex past zero the other way is the finger bent back); and its side bend,
|
||||
//! across that. The palm is raea-sys-body's hand_rest. Ranges in degrees, from hand anatomy (a knuckle bends back
|
||||
//! about 30 and sideways about 30; the middle and end joints are hinges that hardly bend sideways or twist).
|
||||
|
||||
use glam::{Quat, Vec3};
|
||||
use raea_sys_body::arm::twist_about;
|
||||
use raea_sys_body::rig::{FINGERS, Pose, Side, Skeleton, hand_rest};
|
||||
|
||||
use crate::Hit;
|
||||
|
||||
/// flex, side and twist ranges of a finger's knuckle (01), middle (02) and end (03) joints
|
||||
const RANGE: [([f32; 2], [f32; 2], [f32; 2]); 3] = [([-30.0, 100.0], [-30.0, 30.0], [-20.0, 20.0]), ([-10.0, 115.0], [-12.0, 12.0], [-15.0, 15.0]), ([-20.0, 95.0], [-12.0, 12.0], [-15.0, 15.0])];
|
||||
/// the thumb turns round more than any finger: only its twist and how far it swings in all
|
||||
const THUMB_TWIST: f32 = 35.0;
|
||||
const THUMB_SWING: f32 = 110.0;
|
||||
/// Past its range by more than this before it's said.
|
||||
const SLACK: f32 = 8.0;
|
||||
|
||||
/// A turn read about a bone at rest: (flex about `curl`, side about the third axis, twist about `bone`), degrees.
|
||||
fn read(q: Quat, bone: Vec3, curl: Vec3) -> (f32, f32, f32) {
|
||||
let twist = twist_about(q, bone);
|
||||
let swing = q * twist.inverse();
|
||||
let swing = if swing.w < 0.0 { -swing } else { swing }.to_scaled_axis();
|
||||
let t = 2.0 * Vec3::new(twist.x, twist.y, twist.z).dot(bone).atan2(twist.w);
|
||||
let side = bone.cross(curl);
|
||||
(swing.dot(curl).to_degrees(), swing.dot(side).to_degrees(), t.to_degrees())
|
||||
}
|
||||
|
||||
fn over(v: f32, r: [f32; 2]) -> f32 {
|
||||
(r[0] - v).max(v - r[1]).max(0.0)
|
||||
}
|
||||
|
||||
pub(crate) fn check(skel: &Skeleton, poses: &[Pose]) -> Vec<Hit> {
|
||||
let mut hits = Vec::new();
|
||||
for s in Side::BOTH {
|
||||
let Some(hand) = hand_rest(skel, s) else { continue };
|
||||
for f in FINGERS {
|
||||
let Some(js) = skel.finger(f, s) else { continue };
|
||||
for (k, &i) in js.iter().enumerate() {
|
||||
let j = &skel.joints[i];
|
||||
let bone = (j.tail - j.head).normalize_or_zero();
|
||||
let palm = (hand.palm - bone * hand.palm.dot(bone)).normalize_or_zero();
|
||||
if bone == Vec3::ZERO || palm == Vec3::ZERO {
|
||||
continue;
|
||||
}
|
||||
// a turn about bone x palm by a positive angle carries the bone toward the palm: a curl
|
||||
let curl = bone.cross(palm).normalize();
|
||||
for (n, p) in poses.iter().enumerate() {
|
||||
let (flex, side, twist) = read(p.turns[i], bone, curl);
|
||||
let (by, what) = if f == "thumb" {
|
||||
let swing = flex.hypot(side);
|
||||
if twist.abs() - THUMB_TWIST > swing - THUMB_SWING { (twist.abs() - THUMB_TWIST, format!("twisted {twist:.0}° about its bone (it turns {THUMB_TWIST}° at most)")) } else { (swing - THUMB_SWING, format!("swung {swing:.0}° (it swings {THUMB_SWING}° at most)")) }
|
||||
} else {
|
||||
let (rf, rs, rt) = RANGE[k];
|
||||
let cands = [
|
||||
(over(flex, rf), if flex < rf[0] { format!("bent back {:.0}° (it bends back {:.0}° at most)", -flex, -rf[0]) } else { format!("folded {flex:.0}° (it folds {:.0}° at most)", rf[1]) }),
|
||||
(over(side, rs), format!("bent {:.0}° sideways (it bends {:.0}° at most)", side.abs(), rs[1])),
|
||||
(over(twist, rt), format!("twisted {:.0}° about its bone (it turns {:.0}° at most)", twist.abs(), rt[1])),
|
||||
];
|
||||
cands.into_iter().max_by(|a, b| a.0.total_cmp(&b.0)).unwrap()
|
||||
};
|
||||
if by > SLACK {
|
||||
hits.push(Hit { check: "finger", joint: j.name.clone(), f: n, value: by, unit: "degrees", what: format!("{} is {what}, frame {n}", j.name) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
//! A hand that holds something and hasn't closed on it: a thumb left beside a ladder post, a finger off a grip.
|
||||
//! Given a hand's fingertips' distances to the nearest surface (raea-sys-notice's `Scene::reach`), which of them are
|
||||
//! open. A hand holds when two or more tips rest on a surface; while it does, a tip left OFF or more away hasn't
|
||||
//! closed round what it holds.
|
||||
|
||||
/// A fingertip this close to a surface is on it.
|
||||
pub const ON: f32 = 0.015;
|
||||
/// While a hand holds, a tip this far off any surface hasn't closed on what it holds. Gambit's ladder lab before
|
||||
/// 68a505a ("the thumb not wrapping round what the hand holds"): with the fingers on the grab post, the thumb 50-54 mm
|
||||
/// off it and the index 26-46 mm; after, the thumb 22 mm at most (closed over the fingers, a finger's thickness out)
|
||||
/// and the fingertips 1-2 mm.
|
||||
pub const OFF: f32 = 0.03;
|
||||
/// How far out a surface is looked for from a tip.
|
||||
pub const LOOK: f32 = 0.06;
|
||||
|
||||
/// The tips (their places in `d`) open while the hand holds; none when it doesn't.
|
||||
pub fn open(d: &[f32]) -> Vec<usize> {
|
||||
if d.iter().filter(|&&x| x <= ON).count() < 2 {
|
||||
return Vec::new();
|
||||
}
|
||||
(0..d.len()).filter(|&i| d[i] >= OFF).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::open;
|
||||
|
||||
#[test]
|
||||
fn the_ladder_labs_thumb_before_and_after_its_fix() {
|
||||
// thumb, index, middle, ring, pinky: frame 200 of fp-lab-ladder-hand-r, right hand
|
||||
assert_eq!(open(&[0.052, 0.046, 0.008, 0.002, 0.001]), vec![0, 1], "before 68a505a: thumb and index off the post");
|
||||
assert!(open(&[0.022, 0.002, 0.002, 0.002, 0.001]).is_empty(), "after: the thumb closed over the fingers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_that_holds_nothing_is_never_open() {
|
||||
assert!(open(&[0.06, 0.06, 0.06, 0.06, 0.06]).is_empty(), "in the air");
|
||||
assert!(open(&[0.003, 0.05, 0.05, 0.05, 0.05]).is_empty(), "one tip touching is a touch, not a hold");
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
//! Fingers, the thumb and the palm inside what the hand holds: each finger bone a capsule of a finger's thickness,
|
||||
//! sampled along its length against the thing's signed distance (raea-sys-body's shape), on every frame it's held.
|
||||
//! A finger resting on a grip is a little into it at most (skin gives); deeper is a thumb through a pistol's handle.
|
||||
|
||||
use glam::Vec3;
|
||||
use raea_sys_body::rig::{FINGERS, Posed, Side, Skeleton, hand_rest};
|
||||
|
||||
use crate::{Held, Hit, tip};
|
||||
|
||||
/// A finger's half thickness, and the thumb's, metres.
|
||||
const FINGER_R: f32 = 0.008;
|
||||
const THUMB_R: f32 = 0.010;
|
||||
/// The palm's: the thick of the hand over its middle.
|
||||
const PALM_R: f32 = 0.012;
|
||||
/// Skin pressed this far into a held thing is a grip; further is through it.
|
||||
const GIVE: f32 = 0.004;
|
||||
/// Points along each bone.
|
||||
const ALONG: usize = 6;
|
||||
|
||||
pub(crate) fn through(skel: &Skeleton, world: &[Posed], held: &Held) -> Vec<Hit> {
|
||||
let mut hits = Vec::new();
|
||||
for (n, (w, thing)) in world.iter().zip(held).enumerate() {
|
||||
let Some(thing) = thing else { continue };
|
||||
for s in Side::BOTH {
|
||||
// the palm's middle, carried by the hand
|
||||
if let (Some(arm), Some(rest)) = (skel.arm(s), hand_rest(skel, s)) {
|
||||
let h = arm[2];
|
||||
let mid = w.pos[h] + w.rot[h] * rest.mid;
|
||||
let depth = PALM_R - thing.distance(mid);
|
||||
if depth > GIVE {
|
||||
let name = skel.joints[h].name.clone();
|
||||
hits.push(Hit { check: "through", joint: name.clone(), f: n, value: depth, unit: "m", what: format!("{name}'s palm is {:.1} mm inside what it holds, frame {n}", depth * 1000.0) });
|
||||
}
|
||||
}
|
||||
for f in FINGERS {
|
||||
let Some(js) = skel.finger(f, s) else { continue };
|
||||
let r = if f == "thumb" { THUMB_R } else { FINGER_R };
|
||||
for &i in &js {
|
||||
let (a, b): (Vec3, Vec3) = (w.pos[i], tip(skel, w, i));
|
||||
let depth = (0..=ALONG).map(|k| r - thing.distance(a.lerp(b, k as f32 / ALONG as f32))).fold(f32::MIN, f32::max);
|
||||
if depth > GIVE {
|
||||
let name = skel.joints[i].name.clone();
|
||||
hits.push(Hit { check: "through", joint: name.clone(), f: n, value: depth, unit: "m", what: format!("{name} passes {:.1} mm into what the hand holds, frame {n}", depth * 1000.0) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
//! The body's joints held to their range, jolts, and the legs while a foot stands: a knee that buckles and a foot that
|
||||
//! skates. A foot stands on a frame its ball or its ankle is within REACH of the lowest that joint goes in the clip
|
||||
//! (the ground, as the clip itself has it: no scene needed) and slower along the ground than STILL. The lines:
|
||||
//! - limit: raea-sys-body's anatomical ranges, past by more than SLACK degrees; a roll about a joint's own bone that
|
||||
//! its child takes back (a solve rolling a shin and undoing it at the foot) is moved to the child first: it moves
|
||||
//! nothing in the world, so it's no limit (settled);
|
||||
//! - jolt: a joint's turn changing by more than JOLT degrees a frame² (at 30 fps), and more than JOLT_OVER times its
|
||||
//! own usual change; the root's place by more than ROOT_JOLT metres a frame²;
|
||||
//!
|
||||
//! The lines sit just above what 107 ACCAD takes retargeted onto a raea body do (12,472 frames of walks, runs, turns,
|
||||
//! crouches and lifts, 2026-11-27): a standing knee's sharpest give 9.4° there, a standing foot's drift 10.5 cm at
|
||||
//! most (a 6 s crouch; 99% of stances under 6.7 cm), a joint's jolt 34°/frame² but for a retarget's forearm flip (63,
|
||||
//! a fault), the root's 70 mm/frame².
|
||||
//! - buckle: a standing knee that gives (folds, or snaps straight) by more than GIVE degrees and comes back within SNAP
|
||||
//! frames each side: a walk's knee folds and straightens over a stance and a squat folds slowly, neither in a snap;
|
||||
//! - skate: a standing foot drifting SLIDE metres or more along the ground from where it stood down, or a foot
|
||||
//! gliding: its ball within HUG of the ground for GLIDE frames or more and carried SLIDE over them, however fast.
|
||||
|
||||
use glam::Vec3;
|
||||
use raea_sys_body::arm::twist_about;
|
||||
use raea_sys_body::limits::{angles_of, over, violations};
|
||||
use raea_sys_body::rig::{Pose, Posed, Side, Skeleton};
|
||||
|
||||
use crate::{Fault, Hit};
|
||||
|
||||
const SLACK: f32 = 10.0;
|
||||
const JOLT: f32 = 25.0;
|
||||
const JOLT_OVER: f32 = 4.0;
|
||||
const ROOT_JOLT: f32 = 0.08;
|
||||
const REACH: f32 = 0.03;
|
||||
const STILL: f32 = 0.6;
|
||||
const STANCE: usize = 4;
|
||||
const SNAP: usize = 2;
|
||||
const GIVE: f32 = 12.0;
|
||||
const SLIDE: f32 = 0.08;
|
||||
const HUG: f32 = 0.015;
|
||||
const GLIDE: usize = 6;
|
||||
|
||||
/// Frames at 30 fps per frame of the clip: speeds and changes are read as if at 30 fps.
|
||||
fn per30(fps: f32) -> f32 {
|
||||
fps / 30.0
|
||||
}
|
||||
|
||||
/// A roll this far about a joint's own bone is looked at for its child taking it back.
|
||||
const ROLL: f32 = 15.0;
|
||||
|
||||
/// The pose with each roll its child takes back moved to the child. A turn about a joint's own bone moves no joint's
|
||||
/// place (the child's head is on that bone), so the world pose is the same; the roll is moved only where the two
|
||||
/// joints together are then less past their ranges, so a roll nothing takes back stays where it is.
|
||||
pub(crate) fn settled(skel: &Skeleton, p: &Pose) -> Pose {
|
||||
let mut p = p.clone();
|
||||
for i in 0..skel.joints.len() {
|
||||
let j = &skel.joints[i];
|
||||
let Some(bone) = (j.tail - j.head).try_normalize() else { continue };
|
||||
// the child at its tail, with limits of its own (a roll moved to a joint with none would only be hidden there),
|
||||
// and every other child on the bone's own line (a shin's twist joints): a turn about the bone moves none of
|
||||
// them, where a hand's roll moved to one finger would move the rest
|
||||
let kids: Vec<usize> = (0..skel.joints.len()).filter(|&k| skel.joints[k].parent == Some(i)).collect();
|
||||
let Some(&c) = kids.iter().find(|&&k| skel.joints[k].head.distance(j.tail) < 1e-3) else { continue };
|
||||
let on_line = |k: usize| {
|
||||
let d = skel.joints[k].head - j.head;
|
||||
(d - bone * d.dot(bone)).length() < 1e-3
|
||||
};
|
||||
if angles_of(skel, c, p.turns[c]).is_none() || !kids.iter().all(|&k| k == c || on_line(k)) {
|
||||
continue;
|
||||
}
|
||||
let t = twist_about(p.turns[i], bone);
|
||||
if t.angle_between(glam::Quat::IDENTITY).to_degrees() < ROLL {
|
||||
continue;
|
||||
}
|
||||
let (qi, qc) = ((p.turns[i] * t.inverse()).normalize(), (t * p.turns[c]).normalize());
|
||||
if over(skel, i, qi) + over(skel, c, qc) + 1.0 < over(skel, i, p.turns[i]) + over(skel, c, p.turns[c]) {
|
||||
(p.turns[i], p.turns[c]) = (qi, qc);
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
pub(crate) fn limits(skel: &Skeleton, poses: &[Pose]) -> Vec<Hit> {
|
||||
let mut hits = Vec::new();
|
||||
for (n, p) in poses.iter().enumerate() {
|
||||
let p = &settled(skel, p);
|
||||
for (i, by) in violations(skel, p, SLACK) {
|
||||
let name = skel.joints[i].name.clone();
|
||||
let a = angles_of(skel, i, p.turns[i]);
|
||||
let how = a.map(|a| format!(" (flex {:.0}°, side {:.0}°, twist {:.0}°)", a.flex, a.side, a.twist)).unwrap_or_default();
|
||||
hits.push(Hit { check: "limit", joint: name.clone(), f: n, value: by, unit: "degrees", what: format!("{name} is {by:.0}° past its range{how}, frame {n}") });
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f32>) -> f32 {
|
||||
if v.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let mid = v.len() / 2;
|
||||
*v.select_nth_unstable_by(mid, f32::total_cmp).1
|
||||
}
|
||||
|
||||
/// The least and the most of `v` (f32::MAX and f32::MIN when it's empty).
|
||||
pub fn bounds(v: &[f32]) -> (f32, f32) {
|
||||
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
|
||||
for &x in v {
|
||||
(lo, hi) = (lo.min(x), hi.max(x));
|
||||
}
|
||||
(lo, hi)
|
||||
}
|
||||
|
||||
pub(crate) fn jolts(skel: &Skeleton, poses: &[Pose], fps: f32) -> Vec<Hit> {
|
||||
let k = per30(fps);
|
||||
let mut hits = Vec::new();
|
||||
let n = poses.len();
|
||||
for i in 0..skel.joints.len() {
|
||||
// each frame's turn as a step from the last (in the parent's frame), and how much that step changed
|
||||
// (the short way round: a turn and its negative are one turn)
|
||||
let step: Vec<Vec3> = (1..n)
|
||||
.map(|f| {
|
||||
let q = poses[f].turns[i] * poses[f - 1].turns[i].inverse();
|
||||
if q.w < 0.0 { -q } else { q }.to_scaled_axis()
|
||||
})
|
||||
.collect();
|
||||
let change: Vec<f32> = (1..step.len()).map(|f| (step[f] - step[f - 1]).length().to_degrees() * k * k).collect();
|
||||
let usual = median(change.clone());
|
||||
for (f, &c) in change.iter().enumerate() {
|
||||
if c > JOLT && c > JOLT_OVER * usual.max(0.5) {
|
||||
let name = skel.joints[i].name.clone();
|
||||
hits.push(Hit { check: "jolt", joint: name.clone(), f: f + 1, value: c, unit: "degrees/frame²", what: format!("{name} jolts {c:.1}°/frame² at frame {} (it usually changes {usual:.1})", f + 1) });
|
||||
}
|
||||
}
|
||||
}
|
||||
for f in 1..n - 1 {
|
||||
let a = (poses[f + 1].root - poses[f].root) - (poses[f].root - poses[f - 1].root);
|
||||
let c = a.length() * k * k;
|
||||
if c > ROOT_JOLT {
|
||||
hits.push(Hit { check: "jolt", joint: "root".into(), f, value: c, unit: "m/frame²", what: format!("the body's root jolts {:.0} mm/frame² at frame {f}", c * 1000.0) });
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// Each frame's standing joint of one foot (the ball before the ankle), or None: a joint stands while it's within
|
||||
/// REACH of the lowest it goes in the clip and moving along the ground slower than STILL. And the stretches of
|
||||
/// STANCE frames or more it stands, (first, last).
|
||||
fn stances(skel: &Skeleton, world: &[Posed], s: Side, fps: f32) -> Option<(Vec<(usize, usize)>, Vec<Option<usize>>)> {
|
||||
let foot = skel.joint(&format!("foot_{}", s.sx()))?;
|
||||
let ball = skel.joint(&format!("ball_{}", s.sx()));
|
||||
let n = world.len();
|
||||
let low = |j: usize| world.iter().map(|w| w.pos[j].y).fold(f32::MAX, f32::min);
|
||||
let speed = |j: usize, f: usize| {
|
||||
let (a, b) = (f.saturating_sub(1), (f + 1).min(n - 1));
|
||||
let d = world[b].pos[j] - world[a].pos[j];
|
||||
Vec3::new(d.x, 0.0, d.z).length() * fps / (b - a).max(1) as f32
|
||||
};
|
||||
let stands = |j: usize, lo: f32, f: usize| world[f].pos[j].y < lo + REACH && speed(j, f) < STILL;
|
||||
let (fl, bl) = (low(foot), ball.map(low));
|
||||
let on: Vec<Option<usize>> = (0..n)
|
||||
.map(|f| match ball {
|
||||
Some(b) if stands(b, bl.unwrap(), f) => Some(b),
|
||||
_ if stands(foot, fl, f) => Some(foot),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut runs = Vec::new();
|
||||
let mut start = None;
|
||||
for (f, o) in on.iter().chain([&None]).enumerate() {
|
||||
match (o, start) {
|
||||
(Some(_), None) => start = Some(f),
|
||||
(None, Some(a)) => {
|
||||
if f - a >= STANCE {
|
||||
runs.push((a, f - 1));
|
||||
}
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some((runs, on))
|
||||
}
|
||||
|
||||
/// The knee's sharpest give over a stance: a fold that rises and falls back within SNAP frames (at 30 fps) each side,
|
||||
/// or a snap straight that folds back as fast; its size (the smaller of the two sides) and frame.
|
||||
fn sharpest(flex: &[f32], k: f32) -> (f32, usize) {
|
||||
let w = ((SNAP as f32) * k).round().max(1.0) as usize;
|
||||
let mut best = (0.0f32, 0);
|
||||
for t in w..flex.len().saturating_sub(w) {
|
||||
let (before, after) = (&flex[t - w..t], &flex[t + 1..=t + w]);
|
||||
let ((lo_b, hi_b), (lo_a, hi_a)) = (bounds(before), bounds(after));
|
||||
let fold = (flex[t] - lo_b).min(flex[t] - lo_a);
|
||||
let snap = (hi_b - flex[t]).min(hi_a - flex[t]);
|
||||
let g = fold.max(snap);
|
||||
if g > best.0 {
|
||||
best = (g, t);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Buckles and skates, one fault per stance at most for each.
|
||||
pub(crate) fn stance(skel: &Skeleton, poses: &[Pose], world: &[Posed], fps: f32) -> Vec<Fault> {
|
||||
let k = per30(fps);
|
||||
let mut out = Vec::new();
|
||||
for s in Side::BOTH {
|
||||
let (Some((runs, on)), Some(calf)) = (stances(skel, world, s, fps), skel.joint(&format!("calf_{}", s.sx()))) else { continue };
|
||||
let knee = skel.joints[calf].name.clone();
|
||||
for (a, b) in runs {
|
||||
let flex: Vec<f32> = (a..=b).map(|f| angles_of(skel, calf, poses[f].turns[calf]).map_or(0.0, |x| x.flex)).collect();
|
||||
let (give, at) = sharpest(&flex, k);
|
||||
if give > GIVE {
|
||||
out.push(Fault { check: "buckle", joint: knee.clone(), from: a, to: b, peak: a + at, value: give, unit: "degrees", says: format!("{knee} gives {give:.0}° and back within {SNAP} frames while its foot stands, frame {}", a + at) });
|
||||
}
|
||||
// the foot: how far a standing joint drifts along the ground from where it first stood this stance
|
||||
let mut anchor: [Option<(usize, Vec3)>; 2] = [None, None];
|
||||
let (mut drift, mut when) = (0.0f32, a);
|
||||
for f in a..=b {
|
||||
let Some(j) = on[f] else { continue };
|
||||
let p = world[f].pos[j];
|
||||
let slot = anchor.iter_mut().find(|x| x.is_none_or(|x| x.0 == j)).unwrap();
|
||||
let from = slot.get_or_insert((j, p)).1;
|
||||
let d = Vec3::new(p.x - from.x, 0.0, p.z - from.z).length();
|
||||
if d > drift {
|
||||
(drift, when) = (d, f);
|
||||
}
|
||||
}
|
||||
if drift >= SLIDE {
|
||||
let foot = format!("foot_{}", s.sx());
|
||||
out.push(Fault { check: "skate", joint: foot.clone(), from: a, to: b, peak: when, value: drift, unit: "m", says: format!("{foot} slides {:.0} mm while it stands (frames {a}-{b}, furthest at {when})", drift * 1000.0) });
|
||||
}
|
||||
}
|
||||
// a foot gliding along the ground too fast to count as standing: its ball within HUG of the lowest it goes
|
||||
// for GLIDE frames (at 30 fps) or more, however fast, and carried SLIDE or more over them
|
||||
let Some(ball) = skel.joint(&format!("ball_{}", s.sx())) else { continue };
|
||||
let low = world.iter().map(|w| w.pos[ball].y).fold(f32::MAX, f32::min);
|
||||
let need = ((GLIDE as f32) * k).round() as usize;
|
||||
let mut start = None;
|
||||
for f in 0..=world.len() {
|
||||
let hugs = f < world.len() && world[f].pos[ball].y < low + HUG;
|
||||
match (hugs, start) {
|
||||
(true, None) => start = Some(f),
|
||||
(false, Some(a)) => {
|
||||
start = None;
|
||||
let b = f - 1;
|
||||
let (p, q) = (world[a].pos[ball], world[b].pos[ball]);
|
||||
let drift = Vec3::new(q.x - p.x, 0.0, q.z - p.z).length();
|
||||
let foot = format!("foot_{}", s.sx());
|
||||
if f - a >= need && drift >= SLIDE && !out.iter().any(|o: &Fault| o.check == "skate" && o.joint == foot && o.from <= b && a <= o.to) {
|
||||
out.push(Fault { check: "skate", joint: foot.clone(), from: a, to: b, peak: b, value: drift, unit: "m", says: format!("{foot} glides {:.0} mm along the ground (frames {a}-{b})", drift * 1000.0) });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
//! A clip's faults that only show in motion, which no still shows and a vision model reading stills misses (Shane,
|
||||
//! 2026-11-27: "its knees keep buckling when it walks", "a hand that grabbed a gun, its fingers are twisting up ...
|
||||
//! the thumb is clipping through the handle"). Every frame of the clip is posed (raea-sys-body's forward kinematics)
|
||||
//! and held to:
|
||||
//! - limit: a joint past its anatomical range (raea-sys-body's limits: a knee bent backwards, an elbow past straight);
|
||||
//! - finger: a finger joint twisted about its bone, bent sideways at a hinge, bent back past its range or folded past
|
||||
//! it (fingers.rs: the limits table has no fingers);
|
||||
//! - buckle: a knee folding fast while its foot stands on the ground;
|
||||
//! - skate: a foot that stands sliding along the ground;
|
||||
//! - jolt: a joint's (or the root's) turn changing speed more in a frame than a body does;
|
||||
//! - through: a finger, the thumb or the palm inside the thing the hand holds (held.rs).
|
||||
//!
|
||||
//! Each is said once per stretch of frames it lasts, with the frame it's worst on and by how much. What counts as too
|
||||
//! much is set below from anatomy and measured gait, written down so a learned critic (NT11) can replace it.
|
||||
|
||||
use glam::Vec3;
|
||||
use raea_sys_body::rig::{Posed, Skeleton};
|
||||
use raea_sys_body::shape::Thing;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
mod clip;
|
||||
/// The checks' version: a finding gone since a run of other checks went because the checks changed, not the motion,
|
||||
/// so a fix is only read between runs of the same checks (bump it with any change to what a check finds).
|
||||
pub const CHECKS: &str = "2026-11-27.3";
|
||||
|
||||
pub mod critic;
|
||||
mod fingers;
|
||||
pub mod grip;
|
||||
mod held;
|
||||
mod legs;
|
||||
pub mod plant;
|
||||
pub mod verdicts;
|
||||
|
||||
pub use clip::{Clip, clip_of};
|
||||
pub use legs::bounds;
|
||||
|
||||
/// A fault over a stretch of frames.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Fault {
|
||||
pub check: &'static str,
|
||||
/// the joint it's on (or "root")
|
||||
pub joint: String,
|
||||
pub from: usize,
|
||||
pub to: usize,
|
||||
/// the frame it's worst on, and how bad there
|
||||
pub peak: usize,
|
||||
pub value: f32,
|
||||
pub unit: &'static str,
|
||||
pub says: String,
|
||||
}
|
||||
|
||||
impl Fault {
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({"check": self.check, "joint": self.joint, "frames": [self.from, self.to + 1], "peak": self.peak, "value": (self.value * 1e3).round() / 1e3, "unit": self.unit, "says": self.says})
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame's reading of one joint: over the line by `value` on frame `f`.
|
||||
pub struct Hit {
|
||||
pub check: &'static str,
|
||||
pub joint: String,
|
||||
pub f: usize,
|
||||
pub value: f32,
|
||||
pub unit: &'static str,
|
||||
pub what: String,
|
||||
}
|
||||
|
||||
/// Frames this far apart still make one stretch.
|
||||
const GAP: usize = 2;
|
||||
|
||||
/// Hits joined into stretches: one per check and joint while the frames run on (GAP frames apart at most).
|
||||
pub fn stretches(mut hits: Vec<Hit>) -> Vec<Fault> {
|
||||
hits.sort_by(|a, b| (a.check, &a.joint, a.f).cmp(&(b.check, &b.joint, b.f)));
|
||||
let mut out: Vec<Fault> = Vec::new();
|
||||
for h in hits {
|
||||
if let Some(l) = out.last_mut()
|
||||
&& l.check == h.check
|
||||
&& l.joint == h.joint
|
||||
&& h.f <= l.to + GAP
|
||||
{
|
||||
l.to = h.f;
|
||||
if h.value > l.value {
|
||||
(l.peak, l.value, l.says) = (h.f, h.value, h.what);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.push(Fault { check: h.check, joint: h.joint, from: h.f, to: h.f, peak: h.f, value: h.value, unit: h.unit, says: h.what });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A JSON file read, or none when it's missing or isn't JSON (a judge's weights, the verdicts so far).
|
||||
pub(crate) fn read_json(path: &std::path::Path) -> Option<serde_json::Value> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// The faults of a clip, worst first within each check, the checks in the order a viewer notices them.
|
||||
pub fn check(c: &Clip) -> Vec<Fault> {
|
||||
let world = c.world();
|
||||
let mut hits = Vec::new();
|
||||
hits.extend(legs::limits(&c.skel, &c.poses));
|
||||
hits.extend(fingers::check(&c.skel, &c.poses));
|
||||
hits.extend(legs::jolts(&c.skel, &c.poses, c.fps));
|
||||
let mut out = stretches(hits);
|
||||
out.extend(legs::stance(&c.skel, &c.poses, &world, c.fps));
|
||||
if let Some(things) = &c.held {
|
||||
out.extend(stretches(held::through(&c.skel, &world, things)));
|
||||
}
|
||||
let order = |k: &str| ["through", "buckle", "skate", "finger", "limit", "jolt"].iter().position(|x| *x == k).unwrap_or(9);
|
||||
out.sort_by(|a, b| order(a.check).cmp(&order(b.check)).then(b.value.total_cmp(&a.value)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Where a joint's bone ends on a posed frame: its child's place, else its tail carried by its turn.
|
||||
pub fn tip(skel: &Skeleton, w: &Posed, i: usize) -> Vec3 {
|
||||
let j = &skel.joints[i];
|
||||
w.pos[i] + w.rot[i] * (j.tail - j.head)
|
||||
}
|
||||
|
||||
/// The things held, one a frame (None on a frame the hand holds nothing).
|
||||
pub type Held = Vec<Option<Thing>>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,172 +0,0 @@
|
||||
//! Faults of known size planted into a clip, to measure what `check` catches on real motion (NT10's recall): each
|
||||
//! kind as an animation tool gets it wrong.
|
||||
//! - buckle: a standing knee that gives and comes back over three frames, the body dipping with it so the foot stays
|
||||
//! planted (a solver's knee popping);
|
||||
//! - skate: the whole body carried along while a foot stands (root motion that doesn't match the steps);
|
||||
//! - jolt: one joint snapped round for one frame (a bad key);
|
||||
//! - limit: a knee bent backwards for a few frames;
|
||||
//! - finger: a finger's middle joint bent back or twisted for a stretch (a grip solved wrong);
|
||||
//! - through: a grip held so the thumb passes through it.
|
||||
|
||||
use glam::{Quat, Vec3};
|
||||
use raea_sys_body::limits::angles_of;
|
||||
use raea_sys_body::rig::{FINGERS, Side, Skeleton, hand_rest};
|
||||
use raea_sys_body::shape::{Solid, Thing};
|
||||
|
||||
use crate::{Clip, tip};
|
||||
|
||||
pub const KINDS: [&str; 6] = ["buckle", "skate", "jolt", "limit", "finger", "through"];
|
||||
|
||||
/// A small seeded generator (xorshift), so a run can be repeated.
|
||||
pub struct Rng(pub u64);
|
||||
|
||||
impl Rng {
|
||||
pub fn next(&mut self) -> f32 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 >> 40) as f32 / (1u64 << 24) as f32
|
||||
}
|
||||
pub fn range(&mut self, a: f32, b: f32) -> f32 {
|
||||
a + (b - a) * self.next()
|
||||
}
|
||||
pub fn pick(&mut self, n: usize) -> usize {
|
||||
((self.next() * n as f32) as usize).min(n.saturating_sub(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// What was planted: its kind, the joint and frame it's on, and its size.
|
||||
pub struct Planted {
|
||||
pub check: &'static str,
|
||||
pub joint: String,
|
||||
pub frame: usize,
|
||||
pub size: f32,
|
||||
pub says: String,
|
||||
}
|
||||
|
||||
/// a turn of `deg` of flex as the limits read it: about the joint's flex axis, found by how a degree about each of
|
||||
/// x, y and z reads (the axis isn't x on every rig: on a SOMA body a turn about x read a 27° bend as under 19°)
|
||||
pub fn bend(skel: &Skeleton, i: usize, deg: f32) -> Quat {
|
||||
let read = |q: Quat| angles_of(skel, i, q).map_or(0.0, |a| a.flex);
|
||||
let axis = Vec3::new(read(Quat::from_rotation_x(1f32.to_radians())), read(Quat::from_rotation_y(1f32.to_radians())), read(Quat::from_rotation_z(1f32.to_radians())));
|
||||
Quat::from_axis_angle(axis.normalize_or(Vec3::X), deg.to_radians())
|
||||
}
|
||||
|
||||
/// the frames a foot's ball is lowest and still: a stretch where it stands, (first, last), at least `len` frames
|
||||
fn standing(c: &Clip, s: Side, len: usize) -> Option<(usize, usize)> {
|
||||
let ball = c.skel.joint(&format!("ball_{}", s.sx()))?;
|
||||
let w = c.world();
|
||||
let low = w.iter().map(|w| w.pos[ball].y).fold(f32::MAX, f32::min);
|
||||
let ok: Vec<bool> = (0..w.len())
|
||||
.map(|f| {
|
||||
let g = (f + 1).min(w.len() - 1);
|
||||
let d = w[g].pos[ball] - w[f].pos[ball];
|
||||
w[f].pos[ball].y < low + 0.02 && Vec3::new(d.x, 0.0, d.z).length() * c.fps < 0.3
|
||||
})
|
||||
.collect();
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
let mut start = None;
|
||||
for (f, &o) in ok.iter().chain([&false]).enumerate() {
|
||||
match (o, start) {
|
||||
(true, None) => start = Some(f),
|
||||
(false, Some(a)) => {
|
||||
if f - a >= len && best.is_none_or(|b| f - a > b.1 - b.0 + 1) {
|
||||
best = Some((a, f - 1));
|
||||
}
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub fn plant(c: &Clip, kind: &str, rng: &mut Rng) -> Option<(Clip, Planted)> {
|
||||
let skel = &c.skel;
|
||||
let mut poses = c.poses.clone();
|
||||
let mut held = None;
|
||||
let n = poses.len();
|
||||
let s = if rng.next() < 0.5 { Side::L } else { Side::R };
|
||||
let planted = match kind {
|
||||
"buckle" => {
|
||||
let (a, b) = standing(c, s, 9)?;
|
||||
let t = (a + b) / 2;
|
||||
let (thigh, calf, ball) = (skel.joint(&format!("thigh_{}", s.sx()))?, skel.joint(&format!("calf_{}", s.sx()))?, skel.joint(&format!("ball_{}", s.sx()))?);
|
||||
let deg = rng.range(15.0, 35.0);
|
||||
for (f, share) in [(t - 1, 0.5), (t, 1.0), (t + 1, 0.5)] {
|
||||
let before = skel.fk(&poses[f]).pos[ball];
|
||||
let p = &mut poses[f];
|
||||
p.turns[calf] = (bend(skel, calf, deg * share) * p.turns[calf]).normalize();
|
||||
p.turns[thigh] = (bend(skel, thigh, deg * share * 0.5) * p.turns[thigh]).normalize();
|
||||
let after = skel.fk(p).pos[ball];
|
||||
p.root += before - after;
|
||||
}
|
||||
Planted { check: "buckle", joint: skel.joints[calf].name.clone(), frame: t, size: deg, says: format!("{} gives {deg:.0}° at frame {t}", skel.joints[calf].name) }
|
||||
}
|
||||
"skate" => {
|
||||
let (a, b) = standing(c, s, 8)?;
|
||||
let total = rng.range(0.10, 0.30);
|
||||
let dir = Vec3::new(rng.range(-1.0, 1.0), 0.0, rng.range(-1.0, 1.0)).normalize_or(Vec3::X);
|
||||
for (f, p) in poses.iter_mut().enumerate() {
|
||||
let along = ((f as f32 - a as f32) / (b - a) as f32).clamp(0.0, 1.0);
|
||||
p.root += dir * total * along;
|
||||
}
|
||||
Planted { check: "skate", joint: format!("foot_{}", s.sx()), frame: (a + b) / 2, size: total, says: format!("foot_{} carried {:.0} mm over frames {a}-{b}", s.sx(), total * 1000.0) }
|
||||
}
|
||||
"jolt" => {
|
||||
let names = ["spine_02", "neck_01", "head", "upperarm_l", "lowerarm_r", "thigh_r", "hand_l"];
|
||||
let i = skel.joint(names[rng.pick(names.len())])?;
|
||||
let t = 2 + rng.pick(n - 4);
|
||||
let deg = rng.range(20.0, 45.0);
|
||||
let axis = Vec3::new(rng.range(-1.0, 1.0), rng.range(-1.0, 1.0), rng.range(-1.0, 1.0)).normalize_or(Vec3::Y);
|
||||
poses[t].turns[i] = (Quat::from_axis_angle(axis, deg.to_radians()) * poses[t].turns[i]).normalize();
|
||||
Planted { check: "jolt", joint: skel.joints[i].name.clone(), frame: t, size: deg, says: format!("{} snapped {deg:.0}° for frame {t}", skel.joints[i].name) }
|
||||
}
|
||||
"limit" => {
|
||||
let calf = skel.joint(&format!("calf_{}", s.sx()))?;
|
||||
let t = 2 + rng.pick(n - 8);
|
||||
let deg = rng.range(25.0, 55.0);
|
||||
for p in &mut poses[t..t + 5] {
|
||||
p.turns[calf] = bend(skel, calf, -deg);
|
||||
}
|
||||
// its size: how far past the knee's range that is (on a SOMA body the range ends near -17°, not -8°)
|
||||
let past = raea_sys_body::limits::violations(skel, &poses[t + 2], 0.0).iter().find(|v| v.0 == calf).map_or(0.0, |v| v.1);
|
||||
Planted { check: "limit", joint: skel.joints[calf].name.clone(), frame: t + 2, size: past, says: format!("{} bent {deg:.0}° backwards ({past:.0}° past its range) over frames {t}-{}", skel.joints[calf].name, t + 4) }
|
||||
}
|
||||
"finger" => {
|
||||
let rest = hand_rest(skel, s)?;
|
||||
let f = FINGERS[1 + rng.pick(4)];
|
||||
let i = skel.finger(f, s)?[1];
|
||||
let j = &skel.joints[i];
|
||||
let bone = (j.tail - j.head).normalize();
|
||||
let palm = (rest.palm - bone * rest.palm.dot(bone)).normalize();
|
||||
let twist = rng.next() < 0.5;
|
||||
let deg = rng.range(35.0, 70.0);
|
||||
let q = if twist { Quat::from_axis_angle(bone, deg.to_radians()) } else { Quat::from_axis_angle(bone.cross(palm).normalize(), -deg.to_radians()) };
|
||||
let t = rng.pick(n - 10);
|
||||
for p in &mut poses[t..t + 10] {
|
||||
p.turns[i] = (p.turns[i] * q).normalize();
|
||||
}
|
||||
Planted { check: "finger", joint: j.name.clone(), frame: t + 5, size: deg, says: format!("{} {} {deg:.0}° over frames {t}-{}", j.name, if twist { "twisted" } else { "bent back" }, t + 9) }
|
||||
}
|
||||
"through" => {
|
||||
let thumb = skel.finger("thumb", s)?[1];
|
||||
let into = rng.range(0.006, 0.02);
|
||||
let r = 0.015;
|
||||
let mut things = Vec::with_capacity(n);
|
||||
for p in &poses {
|
||||
let w = skel.fk(p);
|
||||
let (a, b) = (w.pos[thumb], tip(skel, &w, thumb));
|
||||
let mid = a.lerp(b, 0.5);
|
||||
// a grip beside the thumb, its axis across the thumb, its surface `into` past the thumb's skin
|
||||
let side = (b - a).cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let at = mid + side * (r + 0.010 - into);
|
||||
things.push(Some(Thing { solid: Solid::Cylinder { half: 0.06, r }, at, turn: Quat::from_rotation_arc(Vec3::Y, (b - a).normalize_or(Vec3::Y)) }));
|
||||
}
|
||||
held = Some(things);
|
||||
Planted { check: "through", joint: skel.joints[thumb].name.clone(), frame: n / 2, size: into, says: format!("{}: a grip {:.0} mm into it", skel.joints[thumb].name, into * 1000.0) }
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((Clip { skel: skel.clone(), fps: c.fps, poses, held: held.or_else(|| c.held.clone()) }, planted))
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
use glam::{Quat, Vec3};
|
||||
use raea_sys_body::rig::{Pose, Side, Skeleton, hand_rest, mannequin};
|
||||
use raea_sys_body::shape::{Solid, Thing};
|
||||
|
||||
use crate::{Clip, Fault, check, clip_of};
|
||||
|
||||
fn clip(skel: &Skeleton, poses: Vec<Pose>, held: Option<crate::Held>) -> Clip {
|
||||
Clip { skel: skel.clone(), fps: 30.0, poses, held }
|
||||
}
|
||||
|
||||
fn kinds(f: &[Fault]) -> Vec<String> {
|
||||
f.iter().map(|f| format!("{}:{}", f.check, f.joint)).collect()
|
||||
}
|
||||
|
||||
use crate::plant::bend;
|
||||
|
||||
/// both legs bent like a squat by `a` degrees, the body moved so the left ball stays where it stands at rest
|
||||
fn squat(skel: &Skeleton, a: f32) -> Pose {
|
||||
let mut p = skel.rest();
|
||||
for s in Side::BOTH {
|
||||
let (t, c) = (skel.joint(&format!("thigh_{}", s.sx())).unwrap(), skel.joint(&format!("calf_{}", s.sx())).unwrap());
|
||||
p.turns[t] = bend(skel, t, a);
|
||||
p.turns[c] = bend(skel, c, 2.0 * a);
|
||||
}
|
||||
let ball = skel.joint("ball_l").unwrap();
|
||||
let (rest, now) = (skel.fk(&skel.rest()).pos[ball], skel.fk(&p).pos[ball]);
|
||||
p.root += rest - now;
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_standing_still_has_no_faults() {
|
||||
let skel = mannequin();
|
||||
let f = check(&clip(&skel, vec![skel.rest(); 12], None));
|
||||
assert!(f.is_empty(), "{:?}", kinds(&f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stance_that_folds_once_is_fine_and_one_that_folds_again_buckles() {
|
||||
let skel = mannequin();
|
||||
let fine: Vec<Pose> = [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 10.0, 8.0, 6.0, 4.0, 2.0, 0.0].iter().map(|&a| squat(&skel, a)).collect();
|
||||
let f = check(&clip(&skel, fine, None));
|
||||
assert!(f.iter().all(|f| f.check != "buckle" && f.check != "skate"), "{:?}", kinds(&f));
|
||||
let buckled: Vec<Pose> = [0.0, 4.0, 8.0, 12.0, 9.0, 5.0, 2.0, 10.0, 3.0, 0.0].iter().map(|&a| squat(&skel, a)).collect();
|
||||
let f = check(&clip(&skel, buckled, None));
|
||||
let b = f.iter().find(|f| f.check == "buckle").unwrap_or_else(|| panic!("no buckle: {:?}", kinds(&f)));
|
||||
assert_eq!(b.peak, 7, "{}", b.says);
|
||||
assert!(b.value > 10.0, "{}", b.says);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_standing_foot_that_slides_skates() {
|
||||
let skel = mannequin();
|
||||
let poses: Vec<Pose> = (0..10)
|
||||
.map(|k| {
|
||||
let mut p = skel.rest();
|
||||
p.root.x += 0.01 * k as f32;
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
let f = check(&clip(&skel, poses, None));
|
||||
let s: Vec<&Fault> = f.iter().filter(|f| f.check == "skate").collect();
|
||||
assert_eq!(s.len(), 2, "{:?}", kinds(&f));
|
||||
assert!((s[0].value - 0.09).abs() < 0.005, "{}", s[0].says);
|
||||
assert!(f.iter().all(|f| f.check != "jolt"), "steady motion isn't a jolt: {:?}", kinds(&f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_knee_bent_backwards_and_a_pop_are_said() {
|
||||
let skel = mannequin();
|
||||
let calf = skel.joint("calf_l").unwrap();
|
||||
let spine = skel.joint("spine_02").unwrap();
|
||||
let mut poses = vec![skel.rest(); 10];
|
||||
poses[5].turns[spine] = Quat::from_rotation_y(30f32.to_radians());
|
||||
for p in &mut poses[2..4] {
|
||||
p.turns[calf] = bend(&skel, calf, -30.0);
|
||||
}
|
||||
let f = check(&clip(&skel, poses, None));
|
||||
let limit = f.iter().find(|f| f.check == "limit" && f.joint == "calf_l").unwrap_or_else(|| panic!("{:?}", kinds(&f)));
|
||||
assert_eq!((limit.from, limit.to), (2, 3));
|
||||
assert!(f.iter().any(|f| f.check == "jolt" && f.joint == "spine_02" && f.peak == 5), "{:?}", kinds(&f));
|
||||
}
|
||||
|
||||
/// a finger joint turned about its bone's curl axis (positive folds it toward the palm) or about the bone itself
|
||||
fn finger_turn(skel: &Skeleton, i: usize, curl: f32, twist: f32) -> Quat {
|
||||
let j = &skel.joints[i];
|
||||
let bone = (j.tail - j.head).normalize();
|
||||
let palm = hand_rest(skel, Side::L).unwrap().palm;
|
||||
let palm = (palm - bone * palm.dot(bone)).normalize();
|
||||
// the curl after the twist (a turn read as swing x twist): twisted about its own bone, then folded
|
||||
Quat::from_axis_angle(bone.cross(palm).normalize(), curl.to_radians()) * Quat::from_axis_angle(bone, twist.to_radians())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingers_bent_back_or_twisted_are_faults_and_a_fist_is_not() {
|
||||
let skel = mannequin();
|
||||
let mid = skel.finger("index", Side::L).unwrap()[1];
|
||||
let curl = |deg: f32, tw: f32| {
|
||||
let mut p = skel.rest();
|
||||
for f in ["index", "middle", "ring", "pinky"] {
|
||||
for &i in &skel.finger(f, Side::L).unwrap() {
|
||||
p.turns[i] = finger_turn(&skel, i, deg, 0.0);
|
||||
}
|
||||
}
|
||||
p.turns[mid] = finger_turn(&skel, mid, deg, tw);
|
||||
p
|
||||
};
|
||||
let f = check(&clip(&skel, vec![curl(80.0, 0.0); 4], None));
|
||||
assert!(f.is_empty(), "a fist: {:?}", kinds(&f));
|
||||
let mut back = skel.rest();
|
||||
back.turns[mid] = finger_turn(&skel, mid, -40.0, 0.0);
|
||||
let f = check(&clip(&skel, vec![back; 4], None));
|
||||
assert!(f.iter().any(|f| f.check == "finger" && f.joint == "index_02_l" && f.says.contains("bent back")), "{:?}", f.iter().map(|f| &f.says).collect::<Vec<_>>());
|
||||
let f = check(&clip(&skel, vec![curl(60.0, 45.0); 4], None));
|
||||
assert!(f.iter().any(|f| f.check == "finger" && f.says.contains("twisted")), "{:?}", f.iter().map(|f| &f.says).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thumb_through_the_grip_is_said_and_a_grip_beside_it_is_not() {
|
||||
let skel = mannequin();
|
||||
let thumb = skel.finger("thumb", Side::L).unwrap()[1];
|
||||
let w = skel.fk(&skel.rest());
|
||||
let at = w.pos[thumb].lerp(crate::tip(&skel, &w, thumb), 0.5);
|
||||
let grip = Solid::Cylinder { half: 0.05, r: 0.012 };
|
||||
let through = vec![Some(Thing::new(grip, at)); 4];
|
||||
let f = check(&clip(&skel, vec![skel.rest(); 4], Some(through)));
|
||||
let t = f.iter().find(|f| f.check == "through" && f.joint == "thumb_02_l").unwrap_or_else(|| panic!("{:?}", kinds(&f)));
|
||||
assert!(t.value > 0.015, "{}", t.says);
|
||||
let beside = vec![Some(Thing::new(grip, at + Vec3::new(0.0, 0.0, 0.2))); 4];
|
||||
let f = check(&clip(&skel, vec![skel.rest(); 4], Some(beside)));
|
||||
assert!(f.is_empty(), "{:?}", kinds(&f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_reads_from_json() {
|
||||
let skel = mannequin();
|
||||
let joints: Vec<serde_json::Value> = skel
|
||||
.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: Vec<[f32; 4]> = skel.joints.iter().map(|_| [0.0, 0.0, 0.0, 1.0]).collect();
|
||||
let frames: Vec<serde_json::Value> = (0..5).map(|k| serde_json::json!({"root": [0.01 * k as f32, 0.0, 0.0], "turns": rest, "thing": {"at": [2.0, 0.0, 0.0]}})).collect();
|
||||
let v = serde_json::json!({"joints": joints, "fps": 30, "frames": frames, "thing": {"box": [0.1, 0.1, 0.1]}});
|
||||
let c = clip_of(&v).unwrap();
|
||||
assert_eq!(c.poses.len(), 5);
|
||||
assert!(c.held.as_ref().unwrap().iter().all(|t| t.is_some()));
|
||||
assert_eq!(c.skel.joints.len(), skel.joints.len());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn verdicts_move_a_line_for_that_joint_only() {
|
||||
use crate::verdicts::{Verdicts, key};
|
||||
let f = |joint: &str, value: f32| Fault { check: "skate", joint: joint.into(), from: 0, to: 9, peak: 4, value, unit: "m", says: String::new() };
|
||||
let mut v = Verdicts::default();
|
||||
// a crouch's drag of 9 cm called fine: 9 cm again is held back, 15 cm still stands, the other foot unmoved
|
||||
v.give(&f("LeftFoot", 0.09), false);
|
||||
assert_eq!(key(&f("LeftFoot", 0.09)), "skate:foot_l");
|
||||
assert!(!v.stands(&f("LeftFoot", 0.09)));
|
||||
assert!(v.stands(&f("LeftFoot", 0.15)));
|
||||
assert!(v.stands(&f("RightFoot", 0.09)));
|
||||
// a smaller one called real stands, and so does anything that size or more
|
||||
v.give(&f("LeftFoot", 0.085), true);
|
||||
assert!(v.stands(&f("LeftFoot", 0.09)));
|
||||
let back = Verdicts::of_json(&v.to_json());
|
||||
assert_eq!(back.keys, v.keys);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finding_gone_after_a_change_was_fixed() {
|
||||
use crate::verdicts::{fixed, record};
|
||||
let f = |check: &'static str, joint: &str, from: usize, value: f32| Fault { check, joint: joint.into(), from, to: from + 5, peak: from, value, unit: "deg", says: String::new() };
|
||||
let last = vec![record(&f("finger", "thumb_03_r", 200, 40.0)), record(&f("skate", "foot_l", 30, 0.09)), record(&f("buckle", "calf_l", 100, 15.0))];
|
||||
// the thumb fixed; the skate still there, moved a few frames; the buckle still there
|
||||
let now = vec![f("skate", "foot_l", 36, 0.08), f("buckle", "calf_l", 100, 15.0)];
|
||||
let got = fixed(&last, &now);
|
||||
assert_eq!(got.len(), 1, "{got:?}");
|
||||
assert!(got[0].0.starts_with("finger:") && got[0].1 == 40.0);
|
||||
assert!(fixed(&last, &[f("finger", "thumb_03_r", 205, 40.0), f("skate", "foot_l", 30, 0.09), f("buckle", "calf_l", 100, 15.0)]).is_empty(), "nothing changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verdict_on_the_finding_outranks_the_critic() {
|
||||
use crate::critic::{Critic, SAY, features};
|
||||
use crate::verdicts::Verdicts;
|
||||
let f = |v: f32| Fault { check: "finger", joint: "pinky_02_r".into(), from: 0, to: 3, peak: 0, value: v, unit: "deg", says: String::new() };
|
||||
// the critic taught that the pinky's small bends are fine, and over-learns it onto the big one
|
||||
let ex: Vec<_> = (0..12).map(|k| { let (x, t) = features(&f(10.0 + k as f32 * 0.4)); (x, t, 0.0) }).collect();
|
||||
let c = Critic::fit(&ex);
|
||||
assert!(c.score(&f(24.0)) < SAY);
|
||||
let mut v = Verdicts::default();
|
||||
v.give(&f(24.0), true);
|
||||
assert!(v.real_at(&f(24.0)) && v.real_at(&f(30.0)) && !v.real_at(&f(12.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shin_roll_its_foot_takes_back_is_no_limit_and_one_it_doesnt_is() {
|
||||
// a crouch's shin, then the same shin rolled half a turn about its bone: with the foot rolled back (the world pose
|
||||
// unchanged, as a solve's flipped roll leaves it) nothing is past its range; with the foot left, the roll is real
|
||||
let skel = mannequin();
|
||||
let (calf, foot) = (skel.joint("calf_l").unwrap(), skel.joint("foot_l").unwrap());
|
||||
let j = &skel.joints[calf];
|
||||
let roll = Quat::from_axis_angle((j.tail - j.head).normalize(), std::f32::consts::PI);
|
||||
let mut bent = skel.rest();
|
||||
bent.turns[calf] = bend(&skel, calf, 70.0);
|
||||
let mut undone = bent.clone();
|
||||
undone.turns[calf] = bent.turns[calf] * roll;
|
||||
undone.turns[foot] = roll.inverse() * bent.turns[foot];
|
||||
let (a, b) = (skel.fk(&bent), skel.fk(&undone));
|
||||
assert!(a.pos.iter().zip(&b.pos).all(|(x, y)| x.distance(*y) < 1e-4), "the roll moved a joint");
|
||||
let hits = crate::legs::limits(&skel, &[undone.clone()]);
|
||||
assert!(hits.is_empty(), "{:?}", hits.iter().map(|h| h.what.clone()).collect::<Vec<_>>());
|
||||
let mut kept = bent.clone();
|
||||
kept.turns[calf] = bent.turns[calf] * roll;
|
||||
assert!(!crate::legs::limits(&skel, &[kept]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hands_roll_stays_on_the_hand_and_a_change_of_checks_is_no_fix() {
|
||||
// a hand has five children: its roll moved to one finger would move the others, so it stays and is judged
|
||||
let skel = mannequin();
|
||||
let hand = skel.joint("hand_l").unwrap();
|
||||
assert!(skel.joints.iter().filter(|j| j.parent == Some(hand)).count() > 1, "the mannequin's hand has fingers");
|
||||
let j = &skel.joints[hand];
|
||||
let mut p = skel.rest();
|
||||
p.turns[hand] = Quat::from_axis_angle((j.tail - j.head).normalize(), 60f32.to_radians());
|
||||
let hits = crate::legs::limits(&skel, &[p]);
|
||||
assert!(hits.iter().any(|h| h.joint == j.name), "{:?}", hits.iter().map(|h| h.what.clone()).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
//! What the motion checks learn from verdicts: each finding's key is its check and its joint's role ("skate:foot_l",
|
||||
//! "finger:index_02_r", "buckle:calf_l"), and a verdict moves that key's line. `fine` at a size raises the line to just
|
||||
//! above it (a foot that drags in a crouch, a captured hand bent further than the table allows); `real` at a size
|
||||
//! lowers it to that size, never under what was called fine. A size is the finding's `value`: for a finger or a
|
||||
//! joint limit, degrees past its range (a pinky bent back 25° against a 10° range is 15), not the angle said. Kept as JSON beside the scene judge's model
|
||||
//! (raea's models folder, notice/motion.json; RAEA_NOTICE_MOTION names another file).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Fault;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Verdicts {
|
||||
/// key -> (the largest size called fine, the smallest called real)
|
||||
pub keys: BTreeMap<String, (Option<f32>, Option<f32>)>,
|
||||
}
|
||||
|
||||
/// A finding's key: its check and its joint by role (the game_engine rig's name), so a verdict on one body holds on
|
||||
/// another rig's.
|
||||
pub fn key(f: &Fault) -> String {
|
||||
format!("{}:{}", f.check, raea_sys_body::rig::role_name(&f.joint))
|
||||
}
|
||||
|
||||
impl Verdicts {
|
||||
pub fn of_json(v: &Value) -> Verdicts {
|
||||
let mut keys = BTreeMap::new();
|
||||
for (k, x) in v["keys"].as_object().into_iter().flatten() {
|
||||
let n = |s: &str| x[s].as_f64().map(|v| v as f32);
|
||||
keys.insert(k.clone(), (n("fine"), n("real")));
|
||||
}
|
||||
Verdicts { keys }
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
json!({"keys": self.keys.iter().map(|(k, (f, r))| (k.clone(), json!({"fine": f, "real": r}))).collect::<serde_json::Map<_, _>>()})
|
||||
}
|
||||
|
||||
pub fn load(path: &std::path::Path) -> Verdicts {
|
||||
Self::of_json(&crate::read_json(path).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// A verdict on a finding at its size.
|
||||
pub fn give(&mut self, f: &Fault, real: bool) {
|
||||
self.give_at(&key(f), f.value, real);
|
||||
}
|
||||
|
||||
/// A verdict on a key at a size.
|
||||
pub fn give_at(&mut self, k: &str, value: f32, real: bool) {
|
||||
let e = self.keys.entry(k.to_string()).or_default();
|
||||
if real {
|
||||
e.1 = Some(e.1.map_or(value, |r| r.min(value)));
|
||||
} else {
|
||||
e.0 = Some(e.0.map_or(value, |x| x.max(value)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a verdict called this key real at this size or smaller: then it stands whatever the critic says (a
|
||||
/// verdict on the finding itself outranks what the critic generalised from its neighbours).
|
||||
pub fn real_at(&self, f: &Fault) -> bool {
|
||||
self.keys.get(&key(f)).and_then(|e| e.1).is_some_and(|r| f.value >= r)
|
||||
}
|
||||
|
||||
/// Whether a finding still stands after the verdicts: one called real at its size or smaller stands; else one no
|
||||
/// bigger than the largest called fine (by a twentieth) is held back.
|
||||
pub fn stands(&self, f: &Fault) -> bool {
|
||||
let Some((fine, real)) = self.keys.get(&key(f)) else { return true };
|
||||
if real.is_some_and(|r| f.value >= r) {
|
||||
return true;
|
||||
}
|
||||
!fine.is_some_and(|x| f.value <= x * 1.05)
|
||||
}
|
||||
}
|
||||
|
||||
/// A finding as the next run reads it back: its key, its frames and its size.
|
||||
pub fn record(f: &Fault) -> Value {
|
||||
json!({"key": key(f), "from": f.from, "to": f.to, "value": f.value})
|
||||
}
|
||||
|
||||
/// Frames a finding may move by between runs and still be the same one.
|
||||
const SLOP: usize = 10;
|
||||
|
||||
/// What a fix shows. Of the last run's findings (`record`s), each gone now, no finding of its key within SLOP frames
|
||||
/// of its own, was fixed: a person or an agent changed the motion until it went, so it was real at its size. The
|
||||
/// caller compares runs of one character over the same frames.
|
||||
pub fn fixed(last: &[Value], now: &[Fault]) -> Vec<(String, f32, usize)> {
|
||||
last.iter()
|
||||
.filter_map(|r| {
|
||||
let (k, from, to, v) = (r["key"].as_str()?, r["from"].as_u64()? as usize, r["to"].as_u64()? as usize, r["value"].as_f64()? as f32);
|
||||
let still = now.iter().any(|f| key(f) == k && f.from <= to + SLOP && from <= f.to + SLOP);
|
||||
(!still).then(|| (k.to_string(), v, to.saturating_sub(from) + 1))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
[package]
|
||||
name = "raea-sys-notice"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Whether a viewer would notice a 3D scene's fault: where each camera of a shot sees it, how large it shows, and a small model that learns from what people mark real or fine (raea scene faults)"
|
||||
|
||||
[dependencies]
|
||||
raea-core-ease = { path = "../../core/ease" }
|
||||
raea-core-scene = { path = "../../core/scene" }
|
||||
# the models folder a trained judge is kept in
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
|
||||
serde_json = "1"
|
||||
@@ -1,170 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
//! What the judge learns from: verdicts kept beside each project, in review/faults.labels.jsonl, one row a verdict with
|
||||
//! the finding's features as they were (so training never re-runs a scene). Two kinds:
|
||||
//! - marked: a person or agent says a finding is real (`--real KEY`) or fine (`--fine KEY`, meant as it is);
|
||||
//! - fixed: a finding the last run reported where a camera saw it is gone, both its parts are still there and no
|
||||
//! finding names the part now, so someone moved one: it was real. A finding no camera of a shot saw teaches nothing
|
||||
//! from its fix there, and one whose part is still found under another check (a gap that became a mount) wasn't
|
||||
//! fixed, only renamed. The last run's findings are kept in review/faults.last.json for that.
|
||||
//!
|
||||
//! `raea scene faults train` gathers every project's labels under a folder and fits the model (model.rs).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// What marks a project's folder.
|
||||
const PROJECT_MARKS: [&str; 2] = ["brief.ts", "AGENTS.md"];
|
||||
|
||||
/// The project a composition belongs to: the nearest folder up holding brief.ts or AGENTS.md, else its own.
|
||||
pub fn project_of(tsx: &Path) -> PathBuf {
|
||||
let start = tsx.parent().unwrap_or(Path::new("."));
|
||||
start.ancestors().find(|d| PROJECT_MARKS.iter().any(|m| d.join(m).is_file())).unwrap_or(start).to_path_buf()
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// One verdict's row.
|
||||
pub fn row(key: &str, label: bool, by: &str, shot: &str, x: &[f32], toks: &[String]) -> Value {
|
||||
let at = now();
|
||||
json!({"key": key, "label": label as u8, "by": by, "shot": shot, "x": x, "toks": toks, "at": at})
|
||||
}
|
||||
|
||||
/// Rows appended to the project's labels.
|
||||
pub fn append(project: &Path, rows: &[Value]) -> Result<(), String> {
|
||||
if rows.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
use std::io::Write;
|
||||
let dir = project.join("review");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let p = dir.join("faults.labels.jsonl");
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&p).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
for r in rows {
|
||||
writeln!(f, "{r}").map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The last run's findings for `shot`: key, parts, features, words.
|
||||
pub fn last(project: &Path, shot: &str) -> Vec<Value> {
|
||||
let p = project.join("review").join("faults.last.json");
|
||||
std::fs::read_to_string(p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v[shot].as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// This run's findings kept as the last for `shot` (other shots' left as they were).
|
||||
pub fn keep_last(project: &Path, shot: &str, rows: Vec<Value>) -> Result<(), String> {
|
||||
let dir = project.join("review");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let p = dir.join("faults.last.json");
|
||||
let mut all = std::fs::read_to_string(&p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).filter(Value::is_object).unwrap_or(json!({}));
|
||||
all[shot] = Value::Array(rows);
|
||||
std::fs::write(&p, serde_json::to_string(&all).unwrap_or_default()).map_err(|e| format!("{}: {e}", p.display()))
|
||||
}
|
||||
|
||||
/// The part a finding's key is about ("floats:mug|table" is the mug's).
|
||||
fn part_of(key: &str) -> &str {
|
||||
key.split_once(':').and_then(|(_, r)| r.split('|').next()).unwrap_or("")
|
||||
}
|
||||
|
||||
/// The last run's findings, seen on this shot, now gone though both their parts are still in the scene and nothing
|
||||
/// else is found of the part: fixed, so real.
|
||||
pub fn fixed(last: &[Value], now_keys: &[String], parts: &[String]) -> Vec<Value> {
|
||||
let here = |n: &Value| n.as_str().is_none_or(|n| n.is_empty() || parts.iter().any(|p| p == n));
|
||||
let busy = |p: &Value| p.as_str().is_some_and(|p| now_keys.iter().any(|k| part_of(k) == p));
|
||||
let seen = |r: &Value| r["x"].get(1).and_then(Value::as_f64).is_some_and(|s| s > 0.0);
|
||||
last.iter()
|
||||
.filter(|r| r["key"].as_str().is_some_and(|k| !now_keys.iter().any(|n| n == k)))
|
||||
.filter(|r| here(&r["part"]) && here(&r["into"]) && !busy(&r["part"]) && seen(r))
|
||||
.map(|r| {
|
||||
let x: Vec<f32> = serde_json::from_value(r["x"].clone()).unwrap_or_default();
|
||||
let toks: Vec<String> = r["toks"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect();
|
||||
row(r["key"].as_str().unwrap_or(""), true, "fixed", r["shot"].as_str().unwrap_or(""), &x, &toks)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every labels file under `root` (node_modules, .git, target and out left out), at most `depth` folders down.
|
||||
pub fn files(root: &Path, depth: usize) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let p = root.join("review").join("faults.labels.jsonl");
|
||||
if p.is_file() {
|
||||
out.push(p);
|
||||
}
|
||||
if depth == 0 {
|
||||
return out;
|
||||
}
|
||||
let Ok(rd) = std::fs::read_dir(root) else { return out };
|
||||
for e in rd.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') || ["node_modules", "target", "out", "media", "assets", "review"].contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
out.extend(files(&e.path(), depth - 1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A file's verdicts as examples, the newest verdict on each finding winning.
|
||||
pub fn examples(file: &Path) -> Vec<(Vec<f32>, Vec<String>, f32)> {
|
||||
shots(file).into_iter().map(|(_, x, t, y)| (x, t, y)).collect()
|
||||
}
|
||||
|
||||
/// The verdicts as `examples` reads them, each with the shot it was given on (for a fit held out a shot at a time).
|
||||
pub fn shots(file: &Path) -> Vec<(String, Vec<f32>, Vec<String>, f32)> {
|
||||
// per shot and key the newest verdict, a person's over a vision model's (`by: "ask"`) whatever their order
|
||||
let mut by: std::collections::BTreeMap<String, (Vec<f32>, Vec<String>, f32, bool)> = Default::default();
|
||||
for line in std::fs::read_to_string(file).unwrap_or_default().lines() {
|
||||
let Ok(r) = serde_json::from_str::<Value>(line) else { continue };
|
||||
let x: Vec<f32> = serde_json::from_value(r["x"].clone()).unwrap_or_default();
|
||||
if x.len() != crate::features::NAMES.len() {
|
||||
continue;
|
||||
}
|
||||
let toks = r["toks"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect();
|
||||
let key = format!("{}|{}", r["shot"].as_str().unwrap_or(""), r["key"].as_str().unwrap_or(""));
|
||||
let asked = r["by"] == "ask";
|
||||
if asked && by.get(&key).is_some_and(|e| !e.3) {
|
||||
continue;
|
||||
}
|
||||
by.insert(key, (x, toks, r["label"].as_f64().unwrap_or(0.0) as f32, asked));
|
||||
}
|
||||
by.into_iter().map(|(k, (x, t, y, _))| (k.split('|').next().unwrap_or("").to_string(), x, t, y)).collect()
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
//! Whether a viewer would notice a 3D scene's fault (`raea scene faults`). The lint (raea-sys-contact) measures every
|
||||
//! part against every other wherever they meet, so it finds what no camera sees as readily as what every frame shows:
|
||||
//! on room 106 of the Halcyon (approved 11-27), 32 errors, most of them walls meeting the ceiling inside the slab.
|
||||
//! A list that long gets skimmed, and the clip that shows gets missed with the rest.
|
||||
//!
|
||||
//! This judges each finding as a viewer of the shot would: every frame's camera asked where the fault would show
|
||||
//! (sight.rs: in frame, facing it, not behind any part, against the scene's real triangles), how many pixels its gap,
|
||||
//! depth or patch covers there, and what the parts are (features.rs). A small logistic model (model.rs) turns that into
|
||||
//! the chance it's a fault. It starts from a written prior and learns from verdicts kept beside each project
|
||||
//! (labels.rs): findings people mark real or fine, and findings that went away because someone fixed them.
|
||||
|
||||
use raea_core_scene::Item;
|
||||
use serde_json::Value;
|
||||
|
||||
pub mod features;
|
||||
pub mod labels;
|
||||
pub mod model;
|
||||
pub mod sight;
|
||||
|
||||
pub use features::{Fault, fault, features};
|
||||
pub use model::{FAULT, Model};
|
||||
pub use sight::{Cam, Scene, Seen, camera, seen};
|
||||
|
||||
/// A finding judged: the fault, what the cameras saw of it, its features and words, and its chance of being a fault.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Judged {
|
||||
pub fault: Fault,
|
||||
pub seen: Seen,
|
||||
pub x: Vec<f32>,
|
||||
pub toks: Vec<String>,
|
||||
pub p: f32,
|
||||
}
|
||||
|
||||
/// Each fault the lint found on `frames[0]` judged over every frame's camera, the likeliest first. `w`, `h`: the
|
||||
/// picture's size in pixels.
|
||||
pub fn judge(found: &[Value], frames: &[Vec<Item>], w: u32, h: u32, model: &Model) -> Vec<Judged> {
|
||||
let Some(first) = frames.first() else { return Vec::new() };
|
||||
let scene = Scene::of(first);
|
||||
let cams: Vec<Cam> = frames.iter().filter_map(|f| camera(f)).collect();
|
||||
judge_in(found, &scene, &cams, w, h, model)
|
||||
}
|
||||
|
||||
/// judge, given the scene's triangles and the cameras.
|
||||
pub fn judge_in(found: &[Value], scene: &Scene, cams: &[Cam], w: u32, h: u32, model: &Model) -> Vec<Judged> {
|
||||
let mut out: Vec<Judged> = found
|
||||
.iter()
|
||||
.filter_map(fault)
|
||||
.map(|f| {
|
||||
let s = seen(&f.spots, f.area, cams, scene, w as f32, h as f32);
|
||||
let (x, toks) = features(&f, &s);
|
||||
let p = model.score(&x, &toks);
|
||||
Judged { fault: f, seen: s, x, toks, p }
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.p.total_cmp(&a.p));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,152 +0,0 @@
|
||||
//! The judge: a logistic model over a finding's features and the words of its parts' names, the chance a viewer would
|
||||
//! call it wrong. It starts from a prior written down here (seen, and large enough on screen, is a fault; hidden is
|
||||
//! not) and learns from every verdict people and fixes leave (labels.rs): a weight drifts from its prior only as far as
|
||||
//! the labels pull it, and a word's weight starts at nothing. Small enough to run on every lint in microseconds and to
|
||||
//! read whole.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::features::{N, NAMES};
|
||||
|
||||
/// The prior, NAMES' order: how the judge weighs a finding before any label.
|
||||
pub const PRIOR: [f32; N] = [
|
||||
-3.0, // bias: a finding no camera sees is no fault
|
||||
1.5, // seen on some frame
|
||||
1.0, // and on more of them
|
||||
1.4, // log2(1 + pixels): a millimetre gap at arm's length is a few pixels, at five metres under one
|
||||
0.0, // log2(1 + mm) in the world: what shows is what counts, the pixels say it
|
||||
0.0, // floats
|
||||
0.0, // sunk
|
||||
1.0, // in the air: a thing with weight touching nothing reads wrong at any size
|
||||
0.5, // clips
|
||||
0.0, // z-fight between two parts
|
||||
-1.0, // z-fight inside one model: doubled faces often share a material and draw alike
|
||||
-0.5, // tilted
|
||||
-2.5, // seated: a post in the ground, a frame in its wall
|
||||
-1.0, // both parts structural: a room's shell meeting itself
|
||||
-0.7, // soft: cloth folds into and lifts off what it lies on
|
||||
0.0, // small
|
||||
-1.5, // mounted with a gap under it: mostly what hangs (a picture, a shelf, a sconce)
|
||||
4.0, // ... and named as a thing that stands (a lamp, a phone, a cup): lifted against the wall beside it
|
||||
];
|
||||
|
||||
/// A finding's chance of being a fault at or over this is said as one.
|
||||
pub const FAULT: f32 = 0.5;
|
||||
/// A verdict its finding already scores this sure of, either way, stops teaching.
|
||||
const MARGIN: f32 = 0.9;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Model {
|
||||
pub w: [f32; N],
|
||||
pub tokens: BTreeMap<String, f32>,
|
||||
/// labels it was fitted on (0: the prior alone)
|
||||
pub labels: usize,
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
use raea_core_ease::sigmoid;
|
||||
|
||||
impl Model {
|
||||
pub fn prior() -> Model {
|
||||
Model { w: PRIOR, tokens: BTreeMap::new(), labels: 0, from: "the prior".into() }
|
||||
}
|
||||
|
||||
/// The model kept in raea's models folder (notice/faults.json, what `raea scene faults train` writes), else the prior.
|
||||
pub fn load() -> Model {
|
||||
let p = path();
|
||||
std::fs::read_to_string(&p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| Model::of_json(&v)).map(|mut m| {
|
||||
m.from = p.display().to_string();
|
||||
m
|
||||
}).unwrap_or_else(Model::prior)
|
||||
}
|
||||
|
||||
pub fn logit(&self, x: &[f32], toks: &[String]) -> f32 {
|
||||
let mut z: f32 = self.w.iter().zip(x).map(|(w, x)| w * x).sum();
|
||||
for t in toks {
|
||||
z += self.tokens.get(t).copied().unwrap_or(0.0);
|
||||
}
|
||||
z
|
||||
}
|
||||
|
||||
pub fn score(&self, x: &[f32], toks: &[String]) -> f32 {
|
||||
sigmoid(self.logit(x, toks))
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Value {
|
||||
let w: serde_json::Map<String, Value> = NAMES.iter().zip(self.w).map(|(n, w)| (n.to_string(), json!((w * 1e4).round() / 1e4))).collect();
|
||||
let t: serde_json::Map<String, Value> = self.tokens.iter().filter(|(_, w)| w.abs() >= 1e-3).map(|(k, w)| (k.clone(), json!((w * 1e4).round() / 1e4))).collect();
|
||||
json!({"weights": w, "tokens": t, "labels": self.labels})
|
||||
}
|
||||
|
||||
pub fn of_json(v: &Value) -> Option<Model> {
|
||||
let mut w = PRIOR;
|
||||
for (k, n) in NAMES.iter().enumerate() {
|
||||
if let Some(x) = v["weights"][n].as_f64() {
|
||||
w[k] = x as f32;
|
||||
}
|
||||
}
|
||||
let tokens = v["tokens"].as_object()?.iter().filter_map(|(k, x)| Some((k.clone(), x.as_f64()? as f32))).collect();
|
||||
Some(Model { w, tokens, labels: v["labels"].as_u64().unwrap_or(0) as usize, from: String::new() })
|
||||
}
|
||||
|
||||
/// Fitted to labelled findings (features, words, 1 for a fault, 0 for fine): logistic regression by gradient
|
||||
/// descent, each weight held toward its prior and each word's toward nothing, so a few labels nudge it and many
|
||||
/// move it.
|
||||
pub fn fit(examples: &[(Vec<f32>, Vec<String>, f32)]) -> Model {
|
||||
let mut m = Model::prior();
|
||||
m.labels = examples.len();
|
||||
if examples.is_empty() {
|
||||
return m;
|
||||
}
|
||||
let (hold_w, hold_t, rate, steps) = (0.5f32, 0.3f32, 0.3f32, 3000);
|
||||
let n = examples.len() as f32;
|
||||
for (_, toks, _) in examples {
|
||||
for t in toks {
|
||||
m.tokens.entry(t.clone()).or_insert(0.0);
|
||||
}
|
||||
}
|
||||
// verdicts all one way (every one real, say) say what's wrong but nothing about where the line between
|
||||
// wrong and fine sits: then only the words learn, and the weights stay at the prior. 15 real verdicts and no fine
|
||||
// ones on room 106 (11-27) otherwise raised every weight toward "fault" and flipped walls' fixtures, mounted as
|
||||
// they should be, to faults
|
||||
let both = examples.iter().any(|e| e.2 >= 0.5) && examples.iter().any(|e| e.2 < 0.5);
|
||||
for _ in 0..steps {
|
||||
let mut gw = [0f32; N];
|
||||
let mut gt: BTreeMap<&str, f32> = BTreeMap::new();
|
||||
for (x, toks, y) in examples {
|
||||
let p = m.score(x, toks);
|
||||
// one already on its side by a margin teaches no more (else agreeing verdicts push forever)
|
||||
if (*y >= 0.5 && p >= MARGIN) || (*y < 0.5 && p <= 1.0 - MARGIN) {
|
||||
continue;
|
||||
}
|
||||
let e = p - y;
|
||||
for k in 0..N {
|
||||
gw[k] += e * x[k];
|
||||
}
|
||||
for t in toks {
|
||||
*gt.entry(t).or_insert(0.0) += e;
|
||||
}
|
||||
}
|
||||
if both {
|
||||
for k in 0..N {
|
||||
m.w[k] -= rate * (gw[k] / n + hold_w * (m.w[k] - PRIOR[k]) / n);
|
||||
}
|
||||
}
|
||||
for (t, g) in gt {
|
||||
let w = m.tokens.get_mut(t).unwrap();
|
||||
*w -= rate * (g / n + hold_t * *w / n);
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the trained judge is kept: RAEA_NOTICE_MODEL when set (a trial fit kept apart), else the models folder.
|
||||
pub fn path() -> std::path::PathBuf {
|
||||
match std::env::var_os("RAEA_NOTICE_MODEL").filter(|v| !v.is_empty()) {
|
||||
Some(p) => p.into(),
|
||||
None => raea_io_home::models().join("notice").join("faults.json"),
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
//! Where a shot's cameras see a point: in frame, in front, not behind any part, and how many pixels a metre there
|
||||
//! covers. Every frame's camera is asked, against the scene's real triangles (a BVH over every part's), not boxes.
|
||||
|
||||
use bevy::math::{Mat4, Vec3, Vec4};
|
||||
use raea_core_scene::{Item, parts_of, vec3};
|
||||
use serde_json::Value;
|
||||
|
||||
/// One frame's camera: world to view, its eye, the focal scale (1 / tan of half the vertical field of view) and the
|
||||
/// fog's far edge.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Cam {
|
||||
pub view: Mat4,
|
||||
pub eye: Vec3,
|
||||
pub focal: f32,
|
||||
pub far: f32,
|
||||
}
|
||||
|
||||
/// The frame's camera (its first PerspectiveCamera: Camera3d's fov in degrees, its position and lookAt).
|
||||
pub fn camera(its: &[Item]) -> Option<Cam> {
|
||||
let c = its.iter().find(|i| i.kind == "camera")?;
|
||||
let p = vec3(&c.props, "position", [0.0, 0.0, 5.0]);
|
||||
let l = vec3(&c.props, "lookAt", [0.0, 0.0, 0.0]);
|
||||
let fov = c.props.get("fov").and_then(Value::as_f64).unwrap_or(50.0) as f32;
|
||||
let eye = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32);
|
||||
let at = Vec3::new(l[0] as f32, l[1] as f32, l[2] as f32);
|
||||
let far = its.iter().find(|i| i.kind == "fog").and_then(|f| f.props.get("far").and_then(Value::as_f64)).unwrap_or(f64::MAX) as f32;
|
||||
Some(Cam { view: look_at(eye, at), eye, focal: 1.0 / (fov.to_radians() * 0.5).tan(), far })
|
||||
}
|
||||
|
||||
fn look_at(eye: Vec3, at: Vec3) -> Mat4 {
|
||||
let f = (at - eye).normalize_or(Vec3::NEG_Z);
|
||||
let s = f.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let u = s.cross(f);
|
||||
Mat4::from_cols(Vec4::new(s.x, u.x, -f.x, 0.0), Vec4::new(s.y, u.y, -f.y, 0.0), Vec4::new(s.z, u.z, -f.z, 0.0), Vec4::new(-eye.dot(s), -eye.dot(u), eye.dot(f), 1.0))
|
||||
}
|
||||
|
||||
struct Node {
|
||||
lo: Vec3,
|
||||
hi: Vec3,
|
||||
/// a leaf's first triangle and count; an inner node's two children
|
||||
a: u32,
|
||||
b: u32,
|
||||
leaf: bool,
|
||||
}
|
||||
|
||||
/// Every part's triangles in a bounding-volume hierarchy, for rays.
|
||||
pub struct Scene {
|
||||
tris: Vec<[Vec3; 3]>,
|
||||
nodes: Vec<Node>,
|
||||
}
|
||||
|
||||
/// A leaf holds at most this many triangles.
|
||||
const LEAF: usize = 4;
|
||||
|
||||
impl Scene {
|
||||
/// The parts of a frame (every mesh and model, the excused ones too: a wall left out of the checks still hides).
|
||||
pub fn of(its: &[Item]) -> Scene {
|
||||
let (parts, ..) = parts_of(its, &vec![false; its.len()]);
|
||||
Scene::new(parts.into_iter().flat_map(|p| p.tris).collect())
|
||||
}
|
||||
|
||||
/// Its triangles' count.
|
||||
pub fn len(&self) -> usize {
|
||||
self.tris.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.tris.is_empty()
|
||||
}
|
||||
|
||||
/// The distance from `p` to the nearest surface, up to `look`: along the 26 directions of a cube's faces, edges and
|
||||
/// corners, each bisected to under a millimetre at a few centimetres. A fingertip's distance from what a hand holds.
|
||||
pub fn reach(&self, p: Vec3, look: f32) -> f32 {
|
||||
let mut best = look;
|
||||
for x in -1..=1i32 {
|
||||
for y in -1..=1i32 {
|
||||
for z in -1..=1i32 {
|
||||
if (x, y, z) == (0, 0, 0) {
|
||||
continue;
|
||||
}
|
||||
let d = Vec3::new(x as f32, y as f32, z as f32).normalize();
|
||||
if !self.blocked(p, p + d * best, 0.0) {
|
||||
continue;
|
||||
}
|
||||
let (mut lo, mut hi) = (0.0, best);
|
||||
for _ in 0..7 {
|
||||
let m = (lo + hi) / 2.0;
|
||||
if self.blocked(p, p + d * m, 0.0) { hi = m } else { lo = m }
|
||||
}
|
||||
best = hi;
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub fn new(tris: Vec<[Vec3; 3]>) -> Scene {
|
||||
let mut s = Scene { tris, nodes: Vec::new() };
|
||||
if !s.tris.is_empty() {
|
||||
let n = s.tris.len();
|
||||
s.build(0, n);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn build(&mut self, a: usize, b: usize) -> u32 {
|
||||
let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
let (mut clo, mut chi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
|
||||
for t in &self.tris[a..b] {
|
||||
for p in t {
|
||||
lo = lo.min(*p);
|
||||
hi = hi.max(*p);
|
||||
}
|
||||
let c = (t[0] + t[1] + t[2]) / 3.0;
|
||||
clo = clo.min(c);
|
||||
chi = chi.max(c);
|
||||
}
|
||||
let me = self.nodes.len();
|
||||
self.nodes.push(Node { lo, hi, a: a as u32, b: (b - a) as u32, leaf: true });
|
||||
if b - a <= LEAF {
|
||||
return me as u32;
|
||||
}
|
||||
let e = chi - clo;
|
||||
let k = if e.x >= e.y && e.x >= e.z { 0 } else if e.y >= e.z { 1 } else { 2 };
|
||||
let mid = (a + b) / 2;
|
||||
self.tris[a..b].select_nth_unstable_by(mid - a, |p, q| (p[0][k] + p[1][k] + p[2][k]).total_cmp(&(q[0][k] + q[1][k] + q[2][k])));
|
||||
let left = self.build(a, mid);
|
||||
let right = self.build(mid, b);
|
||||
self.nodes[me] = Node { lo, hi, a: left, b: right, leaf: false };
|
||||
me as u32
|
||||
}
|
||||
|
||||
/// Whether anything lies on the segment from `a` to `b` (its first `skip` metres and last millimetre left out).
|
||||
pub fn blocked(&self, a: Vec3, b: Vec3, skip: f32) -> bool {
|
||||
let len = (b - a).length();
|
||||
if self.nodes.is_empty() || len <= skip + 0.001 {
|
||||
return false;
|
||||
}
|
||||
let d = (b - a) / len;
|
||||
let inv = d.recip();
|
||||
let (t0, t1) = (skip, len - 0.001);
|
||||
let mut stack = vec![0u32];
|
||||
while let Some(i) = stack.pop() {
|
||||
let n = &self.nodes[i as usize];
|
||||
if !slab(a, inv, n.lo, n.hi, t0, t1) {
|
||||
continue;
|
||||
}
|
||||
if n.leaf {
|
||||
for t in &self.tris[n.a as usize..(n.a + n.b) as usize] {
|
||||
if hit(a, d, t).is_some_and(|t| t > t0 && t < t1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stack.push(n.a);
|
||||
stack.push(n.b);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn slab(o: Vec3, inv: Vec3, lo: Vec3, hi: Vec3, mut t0: f32, mut t1: f32) -> bool {
|
||||
for k in 0..3 {
|
||||
let (a, b) = ((lo[k] - o[k]) * inv[k], (hi[k] - o[k]) * inv[k]);
|
||||
let (a, b) = if a <= b { (a, b) } else { (b, a) };
|
||||
// a ray along a box's face (inv infinite, 0 * inf NaN) counts as inside on that axis
|
||||
if a.is_nan() || b.is_nan() {
|
||||
if o[k] < lo[k] || o[k] > hi[k] {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
t0 = t0.max(a);
|
||||
t1 = t1.min(b);
|
||||
if t0 > t1 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Möller-Trumbore: the distance along `d` from `o` to triangle `t`, either side facing.
|
||||
fn hit(o: Vec3, d: Vec3, t: &[Vec3; 3]) -> Option<f32> {
|
||||
let (e1, e2) = (t[1] - t[0], t[2] - t[0]);
|
||||
let p = d.cross(e2);
|
||||
let det = e1.dot(p);
|
||||
if det.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let s = o - t[0];
|
||||
let u = s.dot(p) / det;
|
||||
if !(0.0..=1.0).contains(&u) {
|
||||
return None;
|
||||
}
|
||||
let q = s.cross(e1);
|
||||
let v = d.dot(q) / det;
|
||||
if v < 0.0 || u + v > 1.0 {
|
||||
return None;
|
||||
}
|
||||
Some(e2.dot(q) / det)
|
||||
}
|
||||
|
||||
/// A point where a fault would show, and the way its surface faces when that's known (a z-fight's faces).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Spot {
|
||||
pub at: Vec3,
|
||||
pub facing: Option<Vec3>,
|
||||
/// what of the fault this spot carries: metres (a gap, a depth) or square metres (a z-fight's patch)
|
||||
pub size: f32,
|
||||
}
|
||||
|
||||
/// What the shot's cameras saw of a fault.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Seen {
|
||||
/// frames asked, and frames on which some spot showed
|
||||
pub frames: usize,
|
||||
pub shown: usize,
|
||||
/// the most pixels it covered on one frame: a length's pixels, or a patch's side (the square root of its pixels)
|
||||
pub px: f32,
|
||||
/// the nearest it came to the camera, metres (0 when never seen)
|
||||
pub near: f32,
|
||||
/// the camera it shows largest to (its index), and where its spots show there: x and y from -1 to 1, y up
|
||||
pub best: Option<usize>,
|
||||
pub marks: Vec<[f32; 2]>,
|
||||
}
|
||||
|
||||
/// Pixels a metre covers at view depth `z`, on a picture `h` pixels tall.
|
||||
fn px_per_m(c: &Cam, z: f32, h: f32) -> f32 {
|
||||
c.focal * h * 0.5 / z
|
||||
}
|
||||
|
||||
/// Each camera asked whether any spot shows (in frame with a margin, in front, nearer than the fog, facing it, not
|
||||
/// behind a part), and how large: a gap's or depth's metres as pixels, a patch's area as pixels squared summed over the
|
||||
/// spots that show.
|
||||
pub fn seen(spots: &[Spot], area: bool, cams: &[Cam], scene: &Scene, w: f32, h: f32) -> Seen {
|
||||
let mut s = Seen { frames: cams.len(), ..Seen::default() };
|
||||
for (ci, c) in cams.iter().enumerate() {
|
||||
let (mut px, mut any, mut near) = (0f32, false, f32::MAX);
|
||||
let mut marks = Vec::new();
|
||||
for p in spots {
|
||||
let q = c.view.transform_point3(p.at);
|
||||
let z = -q.z;
|
||||
if z <= 0.05 || z >= c.far {
|
||||
continue;
|
||||
}
|
||||
let (x, y) = (q.x / z * c.focal * h / w, q.y / z * c.focal);
|
||||
if x.abs() > 1.02 || y.abs() > 1.02 {
|
||||
continue;
|
||||
}
|
||||
if p.facing.is_some_and(|n| n.dot(c.eye - p.at) <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
// off the surface toward the eye first: the spot's own faces aren't in its way
|
||||
if scene.blocked(p.at, c.eye, 0.003) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
marks.push([x, y]);
|
||||
near = near.min(z);
|
||||
let k = px_per_m(c, z, h);
|
||||
px = if area { px + p.size * k * k } else { px.max(p.size * k) };
|
||||
}
|
||||
if any {
|
||||
s.shown += 1;
|
||||
let px = if area { px.sqrt() } else { px };
|
||||
if s.best.is_none() || px > s.px {
|
||||
(s.best, s.marks) = (Some(ci), marks);
|
||||
}
|
||||
s.px = s.px.max(px);
|
||||
s.near = if s.near == 0.0 { near } else { s.near.min(near) };
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
use super::*;
|
||||
use bevy::math::{Mat4, Vec3};
|
||||
use serde_json::json;
|
||||
|
||||
fn cam(eye: [f32; 3], at: [f32; 3], fov: f32) -> Cam {
|
||||
let props = json!({"position": eye, "lookAt": at, "fov": fov}).as_object().unwrap().clone();
|
||||
camera(&[Item { kind: "camera", props: std::sync::Arc::new(props), shape: None, at: None, material: None, world: Mat4::IDENTITY }]).unwrap()
|
||||
}
|
||||
|
||||
/// A box's twelve triangles.
|
||||
fn cube(c: Vec3, s: Vec3) -> Vec<[Vec3; 3]> {
|
||||
let h = s / 2.0;
|
||||
let p = |x: f32, y: f32, z: f32| c + Vec3::new(x * h.x, y * h.y, z * h.z);
|
||||
let quads = [
|
||||
[p(-1., -1., 1.), p(1., -1., 1.), p(1., 1., 1.), p(-1., 1., 1.)],
|
||||
[p(1., -1., -1.), p(-1., -1., -1.), p(-1., 1., -1.), p(1., 1., -1.)],
|
||||
[p(-1., 1., 1.), p(1., 1., 1.), p(1., 1., -1.), p(-1., 1., -1.)],
|
||||
[p(-1., -1., -1.), p(1., -1., -1.), p(1., -1., 1.), p(-1., -1., 1.)],
|
||||
[p(1., -1., 1.), p(1., -1., -1.), p(1., 1., -1.), p(1., 1., 1.)],
|
||||
[p(-1., -1., -1.), p(-1., -1., 1.), p(-1., 1., 1.), p(-1., 1., -1.)],
|
||||
];
|
||||
quads.iter().flat_map(|q| [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]).collect()
|
||||
}
|
||||
|
||||
/// A room: a floor slab, a wall at z = -2 and a table, with a mug on the table.
|
||||
fn room() -> Scene {
|
||||
let mut t = cube(Vec3::new(0.0, -0.05, 0.0), Vec3::new(6.0, 0.1, 6.0));
|
||||
t.extend(cube(Vec3::new(0.0, 1.25, -2.05), Vec3::new(6.0, 2.5, 0.1)));
|
||||
t.extend(cube(Vec3::new(0.0, 0.725, 0.0), Vec3::new(1.2, 0.05, 0.8)));
|
||||
Scene::new(t)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rays_stop_at_parts() {
|
||||
let s = room();
|
||||
// through the wall
|
||||
assert!(s.blocked(Vec3::new(0.0, 1.0, -3.0), Vec3::new(0.0, 1.0, 2.0), 0.003));
|
||||
// over the table, in the open
|
||||
assert!(!s.blocked(Vec3::new(0.0, 1.0, -1.5), Vec3::new(0.0, 1.0, 2.0), 0.003));
|
||||
// from the table's top straight up
|
||||
assert!(!s.blocked(Vec3::new(0.0, 0.751, 0.0), Vec3::new(0.0, 2.0, 0.0), 0.003));
|
||||
// from under the table, up through it
|
||||
assert!(s.blocked(Vec3::new(0.0, 0.5, 0.0), Vec3::new(0.0, 2.0, 0.0), 0.003));
|
||||
}
|
||||
|
||||
fn floats(name: &str, gap: f64, c: [f32; 3]) -> Value {
|
||||
let (lo, hi) = ([c[0] - 0.04, c[1], c[2] - 0.04], [c[0] + 0.04, c[1] + 0.1, c[2] + 0.04]);
|
||||
json!({"part": name, "check": "floats", "level": "error", "on": "table", "gap": gap, "at": [c[0], c[1] - gap as f32, c[2]], "box": {"min": lo, "max": hi}, "says": format!("{name} floats")})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gap_in_view_is_a_fault_and_one_out_of_it_is_not() {
|
||||
let s = room();
|
||||
let m = Model::prior();
|
||||
let near = [cam([0.0, 1.2, 1.0], [0.0, 0.75, 0.0], 40.0)];
|
||||
let far = [cam([0.0, 1.6, 5.0], [0.0, 0.75, 0.0], 40.0)];
|
||||
let behind = [cam([0.0, 1.2, -1.0], [0.0, 1.2, -3.0], 40.0)];
|
||||
let mug = [floats("mug", 0.004, [0.1, 0.754, 0.1])];
|
||||
let j = |c: &[Cam]| judge_in(&mug, &s, c, 1920, 1080, &m).remove(0);
|
||||
let (a, b, c) = (j(&near), j(&far), j(&behind));
|
||||
assert_eq!(a.seen.shown, 1);
|
||||
assert!(a.seen.px > 4.0, "{:?}", a.seen);
|
||||
assert!(a.p >= FAULT, "{}", a.p);
|
||||
// five metres off it covers under two pixels: still seen, less sure
|
||||
assert!(b.seen.px < a.seen.px / 3.0, "{:?}", b.seen);
|
||||
assert!(b.p < a.p);
|
||||
// the camera turned to the wall: not seen, no fault
|
||||
assert_eq!(c.seen.shown, 0);
|
||||
assert!(c.p < 0.1, "{}", c.p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zfight_inside_a_wall_is_hidden() {
|
||||
let s = room();
|
||||
let m = Model::prior();
|
||||
let cams = [cam([0.0, 1.4, 1.5], [0.0, 1.0, -2.0], 50.0)];
|
||||
// a carpet's edge running under the wall: its faces in the floor's plane, but inside the wall's foot
|
||||
let under = json!({"part": "carpet", "into": "walls", "check": "zfight", "level": "error", "area": 0.03, "spots": [[0.5, 0.0, -2.05, 0.0, 1.0, 0.0, 0.03]], "says": "x"});
|
||||
// a rug's face in the floor's, out in the room
|
||||
let open = json!({"part": "rug", "into": "floor", "check": "zfight", "level": "error", "area": 0.5, "spots": [[1.5, 0.0, -1.0, 0.0, 1.0, 0.0, 0.25], [1.2, 0.0, -1.2, 0.0, 1.0, 0.0, 0.25]], "says": "x"});
|
||||
let j = judge_in(&[under, open], &s, &cams, 1920, 1080, &m);
|
||||
let by = |n: &str| j.iter().find(|x| x.fault.part == n).unwrap();
|
||||
assert_eq!(by("carpet").seen.shown, 0);
|
||||
assert!(by("carpet").p < 0.1);
|
||||
assert_eq!(by("rug").seen.shown, 1);
|
||||
assert!(by("rug").p >= FAULT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdicts_teach_it_words() {
|
||||
// three maps in the air marked fine, three mugs in the air marked real, all seen alike
|
||||
let s = Seen { frames: 4, shown: 4, px: 40.0, near: 1.5, ..Seen::default() };
|
||||
let air = |name: &str| {
|
||||
let v = json!({"part": name, "check": "air", "level": "error", "box": {"min": [0, 1, 0], "max": [0.3, 1.4, 0.02]}, "says": "x"});
|
||||
features(&fault(&v).unwrap(), &s)
|
||||
};
|
||||
let mut ex = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let (x, t) = air("r106_map");
|
||||
ex.push((x, t, 0.0));
|
||||
let (x, t) = air("mug");
|
||||
ex.push((x, t, 1.0));
|
||||
}
|
||||
let m = Model::fit(&ex);
|
||||
let (xm, tm) = air("office_map");
|
||||
let (xg, tg) = air("mug_b");
|
||||
assert!(m.score(&xm, &tm) < 0.5, "{}", m.score(&xm, &tm));
|
||||
assert!(m.score(&xg, &tg) > 0.8, "{}", m.score(&xg, &tg));
|
||||
// and the model round-trips through its file's JSON
|
||||
let back = Model::of_json(&m.to_json()).unwrap();
|
||||
assert!((back.score(&xm, &tm) - m.score(&xm, &tm)).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixed_finding_is_a_real_one() {
|
||||
let mut seen = vec![0.0f32; 18];
|
||||
seen[1] = 1.0;
|
||||
let row = |key: &str, part: &str, into: &str, x: &[f32]| json!({"key": key, "part": part, "into": into, "x": x, "toks": [], "shot": "a"});
|
||||
let last = vec![
|
||||
row("floats:mug|table", "mug", "table", &seen),
|
||||
row("air:lamp|", "lamp", "", &seen),
|
||||
// no camera saw this one: its going teaches nothing
|
||||
row("floats:cup|table", "cup", "table", &[0.0f32; 18]),
|
||||
// a gap that became a mount isn't fixed, only renamed
|
||||
row("floats:socks|carpet", "socks", "carpet", &seen),
|
||||
];
|
||||
let parts: Vec<String> = ["mug", "table", "cup", "socks", "carpet"].map(String::from).to_vec();
|
||||
// the mug's gap is gone, both parts still there; the lamp's finding went with the lamp
|
||||
let rows = labels::fixed(&last, &["mounted:socks|carpet".into()], &parts);
|
||||
assert_eq!(rows.len(), 1, "{rows:?}");
|
||||
assert_eq!(rows[0]["key"], "floats:mug|table");
|
||||
assert_eq!(rows[0]["label"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_of_names() {
|
||||
assert_eq!(features::words("r106_table (its \"table_lam\")"), vec!["table", "lam"]);
|
||||
assert_eq!(features::words("/media/props/bed_kit.glb"), vec!["media", "props", "bed", "kit"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lamp_lifted_against_the_wall_is_a_fault_and_a_picture_is_not() {
|
||||
let s = room();
|
||||
let m = Model::prior();
|
||||
let cams = [cam([0.0, 1.4, 1.5], [0.0, 1.0, -2.0], 50.0)];
|
||||
let mounted = |name: &str, y: f32, gap: f64| json!({"part": name, "check": "mounted", "level": "ok", "on": "wall", "gap": gap, "under": "floor",
|
||||
"box": {"min": [0.4, y, -2.0], "max": [0.7, y + 0.4, -1.8]}, "says": "x"});
|
||||
let j = judge_in(&[mounted("r106_lamp_b", 0.27, 0.27), mounted("r106_picture", 1.2, 1.2)], &s, &cams, 1920, 1080, &m);
|
||||
let by = |n: &str| j.iter().find(|x| x.fault.part == n).unwrap();
|
||||
assert!(by("r106_lamp_b").p >= FAULT, "{}", by("r106_lamp_b").p);
|
||||
assert!(by("r106_picture").p < 0.2, "{}", by("r106_picture").p);
|
||||
// and mounted flush on what's under it (no gap) is no candidate
|
||||
assert!(fault(&json!({"part": "shelf", "check": "mounted", "level": "ok", "on": "wall", "says": "x"})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_verdict_outranks_a_vision_models() {
|
||||
let dir = std::env::temp_dir().join(format!("notice-ask-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("faults.labels.jsonl");
|
||||
let x = vec![0.0f32; crate::features::NAMES.len()];
|
||||
let rows = [crate::labels::row("air:map|", false, "marked", "shot-tv", &x, &[]), crate::labels::row("air:map|", true, "ask", "shot-tv", &x, &[]), crate::labels::row("air:mug|", true, "ask", "shot-tv", &x, &[])];
|
||||
std::fs::write(&file, rows.iter().map(|r| r.to_string()).collect::<Vec<_>>().join("\n")).unwrap();
|
||||
let mut ex = crate::labels::examples(&file);
|
||||
ex.sort_by(|a, b| a.2.total_cmp(&b.2));
|
||||
// the map: Shane's fine stands over the later ask; the mug: only the ask, so it counts
|
||||
assert_eq!(ex.iter().map(|e| e.2).collect::<Vec<_>>(), vec![0.0, 1.0]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdicts_all_one_way_teach_words_not_the_line() {
|
||||
use crate::model::{Model, PRIOR};
|
||||
let n = crate::features::NAMES.len();
|
||||
let mut x = vec![0.0f32; n];
|
||||
x[0] = 1.0;
|
||||
x[1] = 1.0;
|
||||
let ex: Vec<(Vec<f32>, Vec<String>, f32)> = (0..15).map(|_| (x.clone(), vec!["seated:carpet".to_string()], 1.0)).collect();
|
||||
let m = Model::fit(&ex);
|
||||
assert_eq!(m.w, PRIOR, "the weights stay at the prior");
|
||||
assert!(m.tokens["seated:carpet"] > 0.0, "the word learns");
|
||||
// a finding sharing no word scores as the prior did
|
||||
assert_eq!(m.score(&x, &["mounted:fixtures".to_string()]), Model::prior().score(&x, &["mounted:fixtures".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reach_is_the_distance_to_the_nearest_surface() {
|
||||
use bevy::math::Vec3;
|
||||
// a floor 2 m square at y = 0
|
||||
let (a, b, c, d) = (Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, 1.0));
|
||||
let floor = crate::Scene::new(vec![[a, b, c], [a, c, d]]);
|
||||
let r = floor.reach(Vec3::new(0.1, 0.02, 0.0), 0.06);
|
||||
assert!((r - 0.02).abs() < 0.002, "20 mm above the floor read as {r}");
|
||||
assert_eq!(floor.reach(Vec3::new(0.0, 0.5, 0.0), 0.06), 0.06, "nothing within the look");
|
||||
}
|
||||
@@ -11,7 +11,6 @@ description = "Gaussian splats (<Splat>): .ply, .splat and .spz clouds drawn as
|
||||
native = []
|
||||
|
||||
[dependencies]
|
||||
raea-core-ease = { path = "../../core/ease" }
|
||||
raea-sys-frame = { path = "../frame" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
|
||||
|
||||
@@ -53,7 +53,9 @@ pub(crate) struct Raw {
|
||||
|
||||
pub(crate) const SH_C0: f32 = 0.282_094_8;
|
||||
|
||||
pub(crate) use raea_core_ease::sigmoid;
|
||||
pub(crate) fn sigmoid(x: f32) -> f32 {
|
||||
1.0 / (1.0 + (-x).exp())
|
||||
}
|
||||
|
||||
pub(crate) fn read_cloud(path: &Path) -> Result<Cloud, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("splat {}: {e}", path.display()))?;
|
||||
|
||||
@@ -97,7 +97,7 @@ type Counted = HashMap<(&'static str, String, u64), i64>;
|
||||
fn counted(its: &[Item]) -> Counted {
|
||||
let mut m = Counted::new();
|
||||
for it in its {
|
||||
*m.entry((it.kind, base_ident(it).to_string(), spawn_sig(it))).or_default() += 1;
|
||||
*m.entry((it.kind, base_ident(it).to_string(), spawn_sig(it, false))).or_default() += 1;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
@@ -243,7 +243,7 @@ impl Snaps {
|
||||
if x < 0.0 || x > w || y < 0.0 || y > h {
|
||||
continue;
|
||||
}
|
||||
by.entry((called(it), raea_core_scene::spawn_sig(it))).or_default().push((k, r * v.focal / depth, [x, y]));
|
||||
by.entry((called(it), raea_core_scene::spawn_sig(it, false))).or_default().push((k, r * v.focal / depth, [x, y]));
|
||||
}
|
||||
for (stem, n) in links {
|
||||
let c = chains.entry(stem).or_insert((k, n, n));
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "raea-sys-toon"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "Toon surfaces and their ink outlines: three's MeshToonMaterial as a Bevy material, its shaders embedded where raea-sys-material had them"
|
||||
|
||||
[dependencies]
|
||||
raea-sys-frame = { path = "../frame" }
|
||||
raea-core-program = { path = "../../core/program" }
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }
|
||||
serde_json = "1"
|
||||
@@ -11,7 +11,11 @@
|
||||
//! keyed on a mesh, as the standard material's: col_r col_g col_b, emissive emissive_k, opacity; and the toon's own
|
||||
//! sh_r sh_g sh_b (an animated shadow colour), rim_k, spec_k, outline_w
|
||||
|
||||
use super::*;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use raea_core_program::ir::V;
|
||||
use raea_sys_frame::*;
|
||||
use bevy::light::{NotShadowCaster, NotShadowReceiver};
|
||||
use bevy::mesh::{MeshVertexBufferLayoutRef, VertexAttributeValues};
|
||||
use bevy::pbr::{ExtendedMaterial, MaterialExtension, MaterialPipeline, MaterialPipelineKey, MaterialPlugin};
|
||||
@@ -87,8 +91,11 @@ impl Material for OutlineMaterial {
|
||||
|
||||
/// The shaders and the two materials, on every engine (nothing is compiled until a toon part draws).
|
||||
pub fn install(app: &mut App) {
|
||||
bevy::asset::embedded_asset!(app, "toon.wesl");
|
||||
bevy::asset::embedded_asset!(app, "toon_outline.wesl");
|
||||
// embedded where raea-sys-material had them, the path a composition names (<ShaderConstants shader=...>)
|
||||
let embedded = app.world_mut().resource_mut::<bevy::asset::io::embedded::EmbeddedAssetRegistry>();
|
||||
for (name, src) in [("toon.wesl", include_bytes!("toon.wesl").as_slice()), ("toon_outline.wesl", include_bytes!("toon_outline.wesl").as_slice())] {
|
||||
embedded.insert_asset(std::path::PathBuf::new(), &std::path::Path::new("raea_sys_material").join(name), src);
|
||||
}
|
||||
app.add_plugins((MaterialPlugin::<ToonMaterial>::default(), MaterialPlugin::<OutlineMaterial>::default()));
|
||||
}
|
||||
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user