Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

DR3: one Finding; the clipping check, raea scene lint and raea check write it

shinyobjectz05abcdfc824a
diff --git a/Cargo.lock b/Cargo.lock
index c14bc51a..63d1fa47 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14797,6 +14797,7 @@ version = "0.1.0"
dependencies = [
"bevy",
"image",
+ "raea-core-facts",
"raea-core-program",
"raea-core-review",
"raea-core-scene",
@@ -15222,6 +15223,7 @@ name = "raea-sys-contact"
version = "0.1.0"
dependencies = [
"bevy",
+ "raea-core-facts",
"raea-core-meshcheck",
"raea-core-scene",
"raea-core-shape",
diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rs
index 6dabdbc8..54e66f5a 100644
--- a/apps/check/src/lib.rs
+++ b/apps/check/src/lib.rs
@@ -11,7 +11,7 @@
//! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form:
//! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.
use serde_json::{Value, json};
-use std::collections::BTreeMap;
+use raea_core_facts::{Finding, Level, finding};
use std::process::Command;
mod sound;
@@ -56,7 +56,7 @@ fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
-pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; P0-P3)";
+pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)";
/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.
#[derive(Clone, Debug, PartialEq)]
@@ -145,35 +145,27 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)
}
}
- report(&video, issues, passed, flag(args, "-o"))
+ report(&video, issues, Vec::new(), passed, flag(args, "-o"), fps)
}
-/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them.
-fn report(video: &str, mut issues: Vec<Issue>, passed: Vec<String>, out: Option<&str>) -> R<(String, bool)> {
+/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at
+/// `fps`), with `more` (a render's own), worst first then by time; written to -o as JSON when asked, and the report's
+/// text with the count last. True when an error is among them.
+fn report(video: &str, mut issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {
issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));
- let bad = issues.iter().any(|i| i.p <= 1);
+ let at = |t: f64| (t * fps).round() as i64;
+ let found = finding::ranked(issues.iter().map(|i| Finding::new(i.rule, Level::of_rank(i.p), &i.says, "raea check")).zip(&issues).map(|(f, i)| if let Some(t) = i.at { f.frames(at(t), at(t) + 1) } else { f }).chain(more).collect());
+ let bad = found.iter().any(|f| f.level == Level::Error);
if let Some(out) = out {
- let j = json!({
- "file": video,
- "issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(),
- "passed": passed,
- });
+ let j = json!({"file": video, "fps": fps, "findings": found, "passed": passed});
std::fs::write(out, serde_json::to_string_pretty(&j).unwrap()).map_err(|e| format!("{out}: {e}"))?;
}
- let mut by = BTreeMap::new();
- for i in &issues {
- *by.entry(i.p).or_insert(0) += 1;
+ let mut s = format!("raea check {video}\n");
+ for line in found.iter().map(Finding::line).chain(passed.iter().map(|p| format!("ok {p}"))) {
+ s.push_str(&line);
+ s.push('\n');
}
- let counts = by.iter().map(|(p, n)| format!("P{p} {n}")).collect::<Vec<_>>().join(", ");
- let mut s = format!("raea check {}: {}\n", video, if issues.is_empty() { "nothing to fix".to_string() } else { format!("{} to fix ({counts})", issues.len()) });
- for i in &issues {
- let at = i.at.map(|t| format!("{t:6.2} s")).unwrap_or_else(|| " ".into());
- s.push_str(&format!("P{} {:<9} {at} {}\n", i.p, i.rule, i.says));
- }
- for p in &passed {
- s.push_str(&format!("ok {p}\n"));
- }
- Ok((s.trim_end().to_string(), bad))
+ Ok((s + &finding::count(&found), bad))
}
struct Probe {
diff --git a/apps/check/src/quick.rs b/apps/check/src/quick.rs
index 2fef5bf1..1504fd6c 100644
--- a/apps/check/src/quick.rs
+++ b/apps/check/src/quick.rs
@@ -34,8 +34,8 @@ pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String,
why.push(line);
}
}
- let why = why.join("\n");
- Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true))
+ let f = raea_core_facts::Finding::new("render", raea_core_facts::Level::Error, why.join("\n"), "raea check --quick");
+ Ok((format!("raea check {file}: it doesn't render\n{}\n{}", f.line(), raea_core_facts::finding::count(&[f])), true))
};
let _ = std::fs::remove_dir_all(&tmp);
result
@@ -52,7 +52,9 @@ fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_co
let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));
text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);
taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);
- report(file, issues, passed, flag(args, "-o"))
+ // and what the render of the stills found (the 3D's clipping, DR3)
+ let more = serde_json::from_value(m["findings"].clone()).unwrap_or_default();
+ report(file, issues, more, passed, flag(args, "-o"), m["fps"].as_f64().unwrap_or(30.0))
}
#[cfg(test)]
diff --git a/apps/workspace/src/next.rs b/apps/workspace/src/next.rs
index c4794418..1f7ff128 100644
--- a/apps/workspace/src/next.rs
+++ b/apps/workspace/src/next.rs
@@ -27,13 +27,13 @@ fn name(p: &Path) -> String {
full.rsplit(['/', '\\']).next().unwrap_or_default().to_string()
}
-/// The P0 and P1 issues a check file holds, as its lines.
+/// The errors a check file holds (its findings, docs/direction.feature DR3), as their lines.
fn blocking(check: &Path) -> Vec<String> {
let Ok(j) = std::fs::read_to_string(check).map_err(drop).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(drop)) else { return vec![] };
let mut out = Vec::new();
- for i in j["issues"].as_array().into_iter().flatten() {
- if let (Some(p @ ("P0" | "P1")), Some(says)) = (i["p"].as_str(), i["says"].as_str()) {
- out.push(format!("{p} {says}"));
+ for f in j["findings"].as_array().into_iter().flatten() {
+ if let (Some("error"), Some(check), Some(says)) = (f["level"].as_str(), f["check"].as_str(), f["says"].as_str()) {
+ out.push(format!("{check}: {says}"));
}
}
out
diff --git a/apps/workspace/src/tests.rs b/apps/workspace/src/tests.rs
index f0f6c4f0..1b7ca4bc 100644
--- a/apps/workspace/src/tests.rs
+++ b/apps/workspace/src/tests.rs
@@ -52,9 +52,9 @@ fn next_walks_a_project_from_brief_to_show() {
std::fs::write(d.join("out/piece.mp4"), "").unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("check piece.mp4"));
std::thread::sleep(std::time::Duration::from_millis(20));
- std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P1","says":"text clipped at 2 s"}]}"#).unwrap();
- assert_eq!(next::steps(&d, &shaped, 0)[0], "polish piece.mp4: P1 text clipped at 2 s (`raea guide polish`)");
- std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P3","says":"minor"}]}"#).unwrap();
+ std::fs::write(d.join("out/piece.check.json"), r#"{"findings":[{"check":"clipped","level":"error","says":"text clipped at 2 s","by":"raea check"}]}"#).unwrap();
+ assert_eq!(next::steps(&d, &shaped, 0)[0], "polish piece.mp4: clipped: text clipped at 2 s (`raea guide polish`)");
+ std::fs::write(d.join("out/piece.check.json"), r#"{"findings":[{"check":"reading","level":"note","says":"minor","by":"raea check"}]}"#).unwrap();
assert!(next::steps(&d, &shaped, 0)[0].starts_with("show piece.mp4"));
let _ = std::fs::remove_dir_all(&d);
}
diff --git a/core/facts/src/components.rs b/core/facts/src/components.rs
index 089c8e8d..410a14e1 100644
--- a/core/facts/src/components.rs
+++ b/core/facts/src/components.rs
@@ -230,7 +230,7 @@ pub struct Line {
pub fn declarations() -> Vec<String> {
let cfg = Config::default();
macro_rules! decls { ($($t:ty),*) => { vec![$(format!("export {}", <$t as TS>::decl(&cfg))),*] }; }
- decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line)
+ decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line, crate::Level, crate::About, crate::Measure, crate::Finding)
}
#[cfg(test)]
diff --git a/core/facts/src/finding.rs b/core/facts/src/finding.rs
new file mode 100644
index 00000000..e5f99375
--- /dev/null
+++ b/core/facts/src/finding.rs
@@ -0,0 +1,175 @@
+//! One finding, for every command (docs/direction.feature DR3): what the clipping check, `raea scene lint`, `raea check`
+//! and the rest write, in one shape, so "everything found about this part" is one query and a count means the same
+//! thing whichever command printed it. raea check's ranks and lint's words map onto its three levels.
+
+use serde::{Deserialize, Serialize};
+use ts_rs::TS;
+
+/// How bad: an error stops a render's exit (unless `--despite`), a warn is shown, a note is said. Ordered worst first.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, TS)]
+#[serde(rename_all = "lowercase")]
+pub enum Level {
+ Error,
+ Warn,
+ Note,
+}
+
+impl Level {
+ /// raea check's ranks: P0 and P1 are errors, P2 a warn, P3 (and anything past it) a note.
+ pub fn of_rank(p: u8) -> Level {
+ match p {
+ 0 | 1 => Level::Error,
+ 2 => Level::Warn,
+ _ => Level::Note,
+ }
+ }
+
+ /// lint's and the older commands' words: "error", "warning" or "warn"; anything else is a note.
+ pub fn of_word(w: &str) -> Level {
+ match w {
+ "error" => Level::Error,
+ "warning" | "warn" => Level::Warn,
+ _ => Level::Note,
+ }
+ }
+
+ fn word(self) -> &'static str {
+ match self {
+ Level::Error => "error",
+ Level::Warn => "warn",
+ Level::Note => "note",
+ }
+ }
+}
+
+/// An entity a finding is about, by what names it across renders: its layer key (a Source's key, "file:line:col…")
+/// when it has one, and the name it goes by (a part's label, a text's words).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
+pub struct About {
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none", default)]
+ #[ts(optional)]
+ pub key: Option<String>,
+}
+
+/// The number a finding turns on: what was measured, its value and unit, and the limit it was held to.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Measure {
+ pub name: String,
+ pub value: f64,
+ pub unit: String,
+ #[serde(skip_serializing_if = "Option::is_none", default)]
+ #[ts(optional)]
+ pub limit: Option<f64>,
+}
+
+/// One thing found: by which check, how bad, about which entities, on which frames, in a sentence, with the number it
+/// turns on and how to fix it, and what found it (a command, or the ask a note's check was written for, DR6).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Finding {
+ pub check: String,
+ pub level: Level,
+ #[serde(default)]
+ pub about: Vec<About>,
+ /// from its first frame to the frame after its last; None when it is about the whole piece
+ #[serde(default)]
+ pub frames: Option<[i64; 2]>,
+ pub says: String,
+ #[serde(default)]
+ pub measure: Option<Measure>,
+ #[serde(default)]
+ pub fix: Option<String>,
+ pub by: String,
+}
+
+impl Finding {
+ pub fn new(check: &str, level: Level, says: impl Into<String>, by: &str) -> Finding {
+ Finding { check: check.into(), level, about: Vec::new(), frames: None, says: says.into(), measure: None, fix: None, by: by.into() }
+ }
+
+ pub fn about(mut self, name: impl Into<String>, key: Option<String>) -> Finding {
+ self.about.push(About { name: name.into(), key });
+ self
+ }
+
+ pub fn frames(mut self, from: i64, to: i64) -> Finding {
+ self.frames = Some([from, to]);
+ self
+ }
+
+ pub fn measure(mut self, name: &str, value: f64, unit: &str, limit: Option<f64>) -> Finding {
+ self.measure = Some(Measure { name: name.into(), value, unit: unit.into(), limit });
+ self
+ }
+
+ pub fn fix(mut self, fix: impl Into<String>) -> Finding {
+ self.fix = Some(fix.into());
+ self
+ }
+
+ /// One line: `error clips frames 120-139 seat, rider: the rider is 4 cm into the seat (fix: …)`.
+ pub fn line(&self) -> String {
+ let mut s = format!("{:<5} {}", self.level.word(), self.check);
+ if let Some([a, b]) = self.frames {
+ s.push_str(&if b <= a + 1 { format!(" frame {a}") } else { format!(" frames {a}-{}", b - 1) });
+ }
+ if !self.about.is_empty() {
+ s.push_str(" ");
+ s.push_str(&self.about.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", "));
+ }
+ s.push_str(": ");
+ s.push_str(&self.says);
+ if let Some(f) = &self.fix {
+ s.push_str(&format!(" (fix: {f})"));
+ }
+ s
+ }
+}
+
+/// Findings worst first, each level in the order found.
+pub fn ranked(mut fs: Vec<Finding>) -> Vec<Finding> {
+ fs.sort_by_key(|f| f.level);
+ fs
+}
+
+/// The count a command prints last: "2 errors, 1 warn, 3 notes".
+pub fn count(fs: &[Finding]) -> String {
+ let say = |l: Level| match fs.iter().filter(|f| f.level == l).count() {
+ 1 => format!("1 {}", l.word()),
+ k => format!("{k} {}s", l.word()),
+ };
+ [Level::Error, Level::Warn, Level::Note].map(say).join(", ")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_old_ranks_and_words_map_onto_three_levels() {
+ assert_eq!([0, 1, 2, 3].map(Level::of_rank), [Level::Error, Level::Error, Level::Warn, Level::Note]);
+ assert_eq!(["error", "warning", "warn", "info"].map(Level::of_word), [Level::Error, Level::Warn, Level::Warn, Level::Note]);
+ }
+
+ #[test]
+ fn a_finding_reads_as_one_line_and_as_json_and_back() {
+ let f = Finding::new("clips", Level::Error, "the rider is 4 cm into the seat", "raea render")
+ .about("rider", Some("scene.tsx:12:5".into()))
+ .about("seat", None)
+ .frames(120, 140)
+ .measure("depth", 0.04, "m", Some(0.005))
+ .fix("raise the rider 4 cm");
+ assert_eq!(f.line(), "error clips frames 120-139 rider, seat: the rider is 4 cm into the seat (fix: raise the rider 4 cm)");
+ let j = serde_json::to_value(&f).unwrap();
+ assert_eq!((j["level"].as_str(), j["about"][1].get("key")), (Some("error"), None));
+ assert_eq!(serde_json::from_value::<Finding>(j).unwrap(), f);
+ }
+
+ #[test]
+ fn findings_rank_worst_first_and_count() {
+ let fs = vec![Finding::new("a", Level::Note, "n", "x"), Finding::new("b", Level::Error, "e", "x"), Finding::new("c", Level::Warn, "w", "x")];
+ let fs = ranked(fs);
+ assert_eq!(fs.iter().map(|f| f.check.as_str()).collect::<Vec<_>>(), ["b", "c", "a"]);
+ assert_eq!(count(&fs), "1 error, 1 warn, 1 note");
+ }
+}
diff --git a/core/facts/src/lib.rs b/core/facts/src/lib.rs
index de4dfb0e..4b6490c0 100644
--- a/core/facts/src/lib.rs
+++ b/core/facts/src/lib.rs
@@ -9,6 +9,9 @@ pub use components::*;
pub mod words;
pub use words::transcript_words;
+pub mod finding;
+pub use finding::{About, Finding, Level, Measure};
+
/// A JSON value as text: a string as it is, anything else as its JSON (a list key may be a number, a stamp a string).
pub fn text_of(v: &serde_json::Value) -> String {
match v {
diff --git a/docs/direction.feature b/docs/direction.feature
index 2a31b80a..f0caae1a 100644
--- a/docs/direction.feature
+++ b/docs/direction.feature
@@ -222,9 +222,12 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
Scenario: DR3. One finding, for every command
Given the plan
| crate | file | lines | job |
- | raea-core-facts | core/facts/src/finding.rs | 160 | Finding, its JSON, its one-line text; the two old ranks mapped onto it |
+ | raea-core-facts | core/facts/src/finding.rs | 200 | Finding, its JSON, its one-line text; the two old ranks mapped onto it |
| raea-sys-contact | systems/contact/src/found.rs | 140 | the clipping check's and the lint's results as Findings about entities |
- | raea-app-direction | apps/direction/src/issue.rs | 150 | raea check's Issue as Finding (rule -> check, p -> level, at -> frames) |
+ | raea-app-check | apps/check/src/lib.rs | 240 | raea check's Issue as Finding in its report (rule -> check, p -> level, at -> frames) |
+ # Fixed in the code (DR3): the plan gave raea check's Issue -> Finding a file of 150 lines in apps/direction. It is
+ # six lines in apps/check's report, which writes check.json, and its crate had the room; a second crate would
+ # have converted raea check's output after the fact instead of raea check writing Findings.
| raea-app-direction | apps/direction/src/record.rs | 220 | the project's record: findings by render and by commit, read back |
| raea-app-direction | apps/direction/src/findings.rs | 160 | `raea findings` |
Then these write Findings and nothing else: the render's clipping check, `raea scene lint|light`, `raea check`
diff --git a/docs/manual/reference/cli/check.md b/docs/manual/reference/cli/check.md
index 4f4f903b..560da036 100644
--- a/docs/manual/reference/cli/check.md
+++ b/docs/manual/reference/cli/check.md
@@ -6,9 +6,10 @@ sources: ["apps/check/src/lib.rs", "apps/check/src/quick.rs"]
---
`raea check` has two speeds. On a composition with `--quick`, it renders three stills and measures the text:
-clipped, cramped, inside the safe areas, large enough to read. That takes about a second, so run it after every save.
-On an exported video, it measures everything the floor asks of a finished piece. Each finding is ranked P0 (broken)
-to P3 (polish), says where it is and how to fix it, and the command exits 1 while a P0 or P1 stands.
+clipped, cramped, inside the safe areas, large enough to read, and what the stills' render found (3D parts clipping).
+That takes about a second, so run it after every save. On an exported video, it measures everything the floor asks
+of a finished piece. Each finding is an error, a warn or a note (raea's one finding, as `raea scene lint` and a
+render's manifest have it), says on which frames and how to fix it, and the command exits 1 while an error stands.
```sh
raea check piece.tsx --quick --platform tiktok
@@ -20,7 +21,7 @@ What a full check can see depends on what you give it. The file alone gives loud
dead, frozen stretches and blotching in dark areas. The render's manifest adds text clipped off the frame, text under
the platform's buttons, captions held too briefly and caption contrast. The transcript adds cues away from their
word and music fighting the voice; the perception adds text over a face. A taste file adds the person's own rules,
-each a P1 when broken, since their rule beats the floor's default.
+each an error when broken, since their rule beats the floor's default.
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
@@ -28,7 +29,7 @@ each a P1 when broken, since their rule beats the floor's default.
```sh
raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)
-raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; P0-P3)
+raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
diff --git a/docs/manual/reference/cli/scene.md b/docs/manual/reference/cli/scene.md
index ce8e0e43..5c18ace6 100644
--- a/docs/manual/reference/cli/scene.md
+++ b/docs/manual/reference/cli/scene.md
@@ -33,7 +33,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
| --- | --- | --- |
| `--composition` | `ID` | Which composition to measure. `light` takes several, comma-separated, to compare the light across their cuts. |
| `--frame` | `N` | The frame to measure (0 by default; `light` also takes `last`). |
-| `--json` | – | Print the findings as JSON: each part's support, gap and position. |
+| `--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. |
| `--part` | `NAME` | With `light`: the part to meter, in place of the shot's subject. |
<!-- generated:end -->
diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.toml
index 40aaf6be..06d87dd5 100644
--- a/runtime/export/Cargo.toml
+++ b/runtime/export/Cargo.toml
@@ -26,6 +26,8 @@ raea-core-program = { path = "../../core/program" }
raea-core-scene = { path = "../../core/scene" }
raea-runtime-scene = { path = "../scene" }
raea-sys-contact = { path = "../../systems/contact" }
+# a render's findings, in one shape (docs/direction.feature DR3)
+raea-core-facts = { path = "../../core/facts" }
raea-sys-light-meter = { path = "../../systems/light-meter" }
# --clay: every standard surface grey (its clay switch)
raea-runtime-scene3d = { path = "../scene3d" }
diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs
index bc2ab62d..44dd442e 100644
--- a/runtime/export/src/fed.rs
+++ b/runtime/export/src/fed.rs
@@ -4,7 +4,7 @@ use super::*;
/// What `scene_program_checked` finds (on its own thread), for the fed render that draws that scene to write in its
/// manifest.
-pub(crate) static FED_CLIPPING: std::sync::Mutex<Option<std::thread::JoinHandle<Vec<Value>>>> = std::sync::Mutex::new(None);
+pub(crate) static FED_CLIPPING: std::sync::Mutex<Option<std::thread::JoinHandle<Vec<raea_core_facts::Finding>>>> = std::sync::Mutex::new(None);
/// RAEA_FRAME_LOG=FILE: a fed render (an .mp4 or .mov of a piece with 3D; not --frame or --at, which write none) writes
/// one line a frame (ms, tab-separated): frame, react (the frame's commit
diff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rs
index 36b61e96..a961bcdd 100644
--- a/runtime/export/src/lib.rs
+++ b/runtime/export/src/lib.rs
@@ -67,10 +67,10 @@ pub(crate) struct Sound {
/// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes.
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
-/// With --manifest, its file: the frames' boxes as drawn (Ctx.manifest), the 3D's clipping and the sounds heard.
-fn write_manifest(cx: &mut Ctx, (w, h, fps): (u32, u32, f64), clipping: Vec<Value>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {
+/// With --manifest, its file: the frames' boxes as drawn (Ctx.manifest), its findings (DR3) and the sounds heard.
+fn write_manifest(cx: &mut Ctx, (w, h, fps): (u32, u32, f64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {
let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };
- let m = json!({"width": w, "height": h, "fps": fps, "frames": frames, "clipping": clipping, "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps)});
+ let m = json!({"width": w, "height": h, "fps": fps, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps)});
std::fs::write(&path, m.to_string()).map_err(|e| format!("{}: {e}", path.display()))
}
diff --git a/runtime/export/src/scene.rs b/runtime/export/src/scene.rs
index f64167f3..f9bf047c 100644
--- a/runtime/export/src/scene.rs
+++ b/runtime/export/src/scene.rs
@@ -18,7 +18,7 @@ pub(crate) fn all_items(frames: &[(i64, Frame)]) -> Vec<Vec<raea_core_scene::Ite
/// raea_sys_contact::told on a render's frames: the parts that clip where the camera sees them, said on stderr
/// (RAEA_CLIP_CHECK=0 skips it).
-pub(crate) fn told(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> Vec<Value> {
+pub(crate) fn told(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
if std::env::var("RAEA_CLIP_CHECK").as_deref() == Ok("0") || frames.iter().all(|(_, f)| f.scene.is_empty()) {
return Vec::new();
}
@@ -57,22 +57,21 @@ pub fn cli(args: &[String]) -> Result<String, String> {
// and the Blender steps its models call for (a format raea can't load, triangles over budget for the distance)
let (more, unloadable) = raea_sys_contact::assets(&items(&frames[k].1));
found.extend(more);
- let errors = errors + unloadable;
- let shown: Vec<&Value> = found.iter().filter(|v| mode == "explain" || !matches!(v["level"].as_str(), Some("ok") | Some("note"))).collect();
- let text = if args.iter().any(|a| a == "--json") {
- serde_json::to_string_pretty(&json!({"frame": frame, "errors": errors, "found": shown})).unwrap_or_default()
- } else {
- let mut t: Vec<String> = shown.iter().map(|v| format!("{:<8} {}", v["level"].as_str().unwrap_or(""), v["says"].as_str().unwrap_or(""))).collect();
- let warnings = found.iter().filter(|v| v["level"] == "warning").count();
- t.push(format!("frame {frame}: {} parts, {errors} errors, {warnings} warnings", found.iter().filter(|v| v["check"] != "clips" && v["check"] != "tilted" && v["check"] != "skipped").count()));
- t.join("\n")
- };
- // errors fail a lint, with nothing after the findings (--json stays one document)
- if errors > 0 && mode == "lint" {
- println!("{text}");
- std::process::exit(1);
+ let (errors, json_out) = (errors + unloadable, args.iter().any(|a| a == "--json"));
+ let parts = found.iter().filter(|v| v["check"] != "clips" && v["check"] != "tilted" && v["check"] != "skipped").count();
+ if mode == "lint" {
+ // its faults as Findings (DR3), worst first, every one shown, the count last; errors fail it, with nothing after
+ let fs = raea_core_facts::finding::ranked(raea_sys_contact::lint_findings(&found, frame, "raea scene lint"));
+ let text = if json_out { serde_json::to_string_pretty(&json!({"frame": frame, "findings": fs})).unwrap_or_default() } else { fs.iter().map(raea_core_facts::Finding::line).chain([format!("frame {frame}: {parts} parts; {}", raea_core_facts::finding::count(&fs))]).collect::<Vec<_>>().join("\n") };
+ if errors > 0 {
+ println!("{text}");
+ std::process::exit(1);
+ }
+ return Ok(text);
}
- Ok(text)
+ // explain: every part's support
+ let t: Vec<String> = found.iter().map(|v| format!("{:<8} {}", v["level"].as_str().unwrap_or(""), v["says"].as_str().unwrap_or(""))).collect();
+ Ok(if json_out { serde_json::to_string_pretty(&json!({"frame": frame, "errors": errors, "found": found})).unwrap_or_default() } else { format!("{}\nframe {frame}: {parts} parts, {errors} errors", t.join("\n")) })
}
/// One composition's frames, stepped.
diff --git a/systems/contact/Cargo.toml b/systems/contact/Cargo.toml
index 3c977296..cc47636e 100644
--- a/systems/contact/Cargo.toml
+++ b/systems/contact/Cargo.toml
@@ -11,5 +11,7 @@ raea-core-scene = { path = "../../core/scene" }
raea-core-shape = { path = "../../core/shape" }
# the Blender step a model calls for (an unloadable format, triangles over budget for its distance): docs/blender.feature
raea-core-meshcheck = { path = "../../core/meshcheck" }
+# its results as Findings (docs/direction.feature DR3)
+raea-core-facts = { path = "../../core/facts" }
bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
serde_json = "1"
diff --git a/systems/contact/src/found.rs b/systems/contact/src/found.rs
new file mode 100644
index 00000000..a9ad4616
--- /dev/null
+++ b/systems/contact/src/found.rs
@@ -0,0 +1,91 @@
+//! The clipping check's and the lint's results as Findings (docs/direction.feature DR3): the parts each is about by
+//! name, the number it turns on, and the move that fixes it. The lint's own list keeps every part's support (what
+//! `raea scene explain` prints and a review frames its cameras by); only its faults are findings.
+
+use raea_core_facts::{Finding, Level};
+use serde_json::Value;
+
+fn text<'a>(v: &'a Value, k: &str) -> Option<&'a str> {
+ v.get(k).and_then(Value::as_str)
+}
+
+/// The lint's faults on `frame` as Findings: sunk, floats, air, tilted, clips, a model it can't load or that's over
+/// budget, and what it skipped (a note). A part that rests, is mounted or is the ground is no finding.
+pub fn lint_findings(found: &[Value], frame: i64, by: &str) -> Vec<Finding> {
+ found
+ .iter()
+ .filter(|v| text(v, "level").is_some_and(|l| l != "ok"))
+ .map(|v| {
+ let check = text(v, "check").unwrap_or("lint");
+ let mut f = Finding::new(check, Level::of_word(text(v, "level").unwrap_or("")), text(v, "says").unwrap_or_default(), by).frames(frame, frame + 1);
+ for k in ["part", "into", "on"] {
+ if let Some(name) = text(v, k) {
+ f = f.about(name, None);
+ }
+ }
+ let num = |k: &str| v.get(k).and_then(Value::as_f64);
+ if let Some(g) = num("gap").filter(|_| matches!(check, "sunk" | "floats")) {
+ f = f.measure("gap", g, "m", None);
+ } else if let Some(d) = num("depth") {
+ f = f.measure("depth", d, "m", None);
+ } else if let Some(d) = num("degrees") {
+ f = f.measure("lean", d, "degrees", None);
+ }
+ if let Some((y, dy)) = v.get("fix").and_then(|x| Some((x.get("y")?.as_f64()?, x.get("dy")?.as_f64()?))) {
+ f = f.fix(format!("move it {dy:+.4} m in y, to y = {y}"));
+ }
+ f
+ })
+ .collect()
+}
+
+/// The clipping check's overlaps (lib.rs `check`) as error Findings over the frames each holds on.
+pub fn clip_findings(found: &[Value], by: &str) -> Vec<Finding> {
+ found
+ .iter()
+ .map(|v| {
+ let at = |k: &str| v.get(k).and_then(Value::as_i64).unwrap_or(0);
+ let mut f = Finding::new("clips", Level::Error, text(v, "says").unwrap_or_default(), by).frames(at("from"), at("to"));
+ for k in ["part", "into"] {
+ if let Some(name) = text(v, k) {
+ f = f.about(name, None);
+ }
+ }
+ if let Some(d) = v.get("depth").and_then(Value::as_f64) {
+ f = f.measure("depth", d, "m", None);
+ }
+ if let (Some(axis), Some(step)) = (v.pointer("/move/axis").and_then(Value::as_str), v.pointer("/move/by").and_then(Value::as_f64)) {
+ f = f.fix(format!("move it {step:+.3} m along {axis}"));
+ }
+ f
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn a_lints_faults_are_findings_and_its_support_lines_are_not() {
+ let found = vec![
+ json!({"part": "rug", "check": "rests", "level": "ok", "says": "rug rests on floor", "on": "floor"}),
+ json!({"part": "lamp", "check": "floats", "level": "error", "says": "lamp floats 12 mm above desk", "on": "desk", "gap": 0.012, "fix": {"y": 0.75, "dy": -0.012}}),
+ json!({"part": "vase", "check": "tilted", "level": "warning", "on": "desk", "degrees": 7.5, "says": "vase leans 7.5° off level on desk"}),
+ ];
+ let fs = lint_findings(&found, 30, "raea scene lint");
+ assert_eq!(fs.len(), 2);
+ let lamp = &fs[0];
+ assert_eq!((lamp.level, lamp.frames, lamp.about.iter().map(|a| a.name.as_str()).collect::<Vec<_>>()), (Level::Error, Some([30, 31]), vec!["lamp", "desk"]));
+ assert_eq!((lamp.measure.as_ref().map(|m| m.value), lamp.fix.as_deref()), (Some(0.012), Some("move it -0.0120 m in y, to y = 0.75")));
+ assert_eq!((fs[1].level, fs[1].measure.as_ref().map(|m| m.unit.as_str())), (Level::Warn, Some("degrees")));
+ }
+
+ #[test]
+ fn an_overlap_is_an_error_about_both_parts_over_its_frames() {
+ let found = vec![json!({"from": 40, "to": 52, "part": "rider", "into": "seat", "depth": 0.04, "share": 0.2, "move": {"axis": "y", "by": 0.05}, "says": "rider passes 40 mm into seat"})];
+ let f = &clip_findings(&found, "raea render")[0];
+ assert_eq!(f.line(), "error clips frames 40-51 rider, seat: rider passes 40 mm into seat (fix: move it +0.050 m along y)");
+ }
+}
diff --git a/systems/contact/src/lib.rs b/systems/contact/src/lib.rs
index 87e9ad1d..1c4f9dc6 100644
--- a/systems/contact/src/lib.rs
+++ b/systems/contact/src/lib.rs
@@ -28,6 +28,9 @@ pub use lint::lint;
mod assets;
pub use assets::assets;
+mod found;
+pub use found::{clip_findings, lint_findings};
+
mod model;
pub use model::{bounds, facing, seat_facing};
@@ -395,12 +398,13 @@ fn clear_move(a: &[Solid], wa: &Mat4, b: &[Solid], wb: &Mat4, move_a: bool) -> (
if best.1 == f32::MAX { (1, reach) } else { best }
}
-/// `check`, each overlap said on stderr (what an agent driving raea reads) as it's returned for the manifest.
-pub fn told(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec<Value> {
+/// `check`'s overlaps as Findings (DR3), each said on stderr (what an agent driving raea reads) as it's returned for
+/// the manifest.
+pub fn told(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
let t = std::time::Instant::now();
- let found = check(all, frames, w, h, fps);
- for c in &found {
- eprintln!("raea: clipping: {}", c["says"].as_str().unwrap_or_default());
+ let found = clip_findings(&check(all, frames, w, h, fps), "raea render");
+ for f in &found {
+ eprintln!("raea: {}", f.line());
}
if std::env::var_os("RAEA_TIMES").is_some() {
eprintln!("raea times: the clipping check {:.0} ms", t.elapsed().as_secs_f64() * 1e3);