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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
MK3-MK18: raea make's gates, kits, shots and plan (docs/make.feature), checked end to end
shinyobjectz0deac6fe0a9f
diff --git a/Cargo.lock b/Cargo.lockindex 08945bc7..64552a68 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13876,9 +13876,13 @@ name = "raea-app-make"version = "0.1.0"dependencies = ["dunce",+ "image","raea-app-judge",+ "raea-core-ask","raea-core-brief","raea-core-facts",+ "raea-io-home",+ "resvg 0.48.1","serde_json",]@@ -14310,6 +14314,7 @@ version = "0.1.0"dependencies = ["serde","serde_json",+ "sha2 0.10.9","ts-rs",]diff --git a/apps/ask/src/record.rs b/apps/ask/src/record.rsindex 6499f73d..b4536a8e 100644--- a/apps/ask/src/record.rs+++ b/apps/ask/src/record.rs@@ -6,7 +6,6 @@//! question, so a verdict reads in its terms and `raea ask try` can reword it.use std::io::Write as _;-use std::io::{Read as _, Seek as _, SeekFrom};use std::path::{Path, PathBuf};use raea_core_ask::{Question, Reading};@@ -50,28 +49,8 @@ fn hex(digest: &[u8]) -> String {digest.iter().take(16).map(|b| format!("{b:02x}")).collect()}-/// What a file is, cheaply: its size and a hash of its first and last MB. A render is known again by its copy in the-/// feed, and a later render to the same path isn't taken for it.-pub fn ident(path: &Path) -> Option<String> {- const MB: u64 = 1 << 20;- let mut f = std::fs::File::open(path).ok()?;- let len = f.metadata().ok()?.len();- let mut h = Sha256::new();- let mut part = vec![0u8; len.min(MB) as usize];- f.read_exact(&mut part).ok()?;- h.update(&part);- if len > 2 * MB {- f.seek(SeekFrom::Start(len - MB)).ok()?;- f.read_exact(&mut part).ok()?;- h.update(&part);- }- Some(format!("{len}-{}", hex(&h.finalize())))-}--/// The size an ident names, to pass over files that can't be it without reading them.-pub fn ident_len(ident: &str) -> Option<u64> {- ident.split_once('-')?.0.parse().ok()-}+/// What a file is, cheaply, and the size an ident names (raea-core-ask, so `raea make status` reads the same).+pub use raea_core_ask::ident::{ident, ident_len};/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.pub fn write_whole(file: &str, text: &str) -> Result<(), String> {diff --git a/apps/ask/src/verbs.rs b/apps/ask/src/verbs.rsindex 21e8b581..507304a9 100644--- a/apps/ask/src/verbs.rs+++ b/apps/ask/src/verbs.rs@@ -18,7 +18,7 @@ use crate::prepare::{self, Piece};use crate::runner::{self, Entry, Event, Opts};use crate::{calibrate, record};-pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";+pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];diff --git a/apps/check/make/src/lib.rs b/apps/check/make/src/lib.rsindex 6e671405..e21b33a5 100644--- a/apps/check/make/src/lib.rs+++ b/apps/check/make/src/lib.rs@@ -48,11 +48,12 @@ pub fn may_block(guard: &Path, items: &str) -> bool {/// What the agent is told when its turn may not end, or None to let it end: no job here, the job is done, the job/// didn't load (never block on raea's own failure), or the same items have blocked it three times already.+/// Each turn's status also brings the job's task in plan.org up to date (`--plan`, docs/make.feature MK3).pub fn stop(v: &Value) -> Option<String> {let cwd = PathBuf::from(v["cwd"].as_str()?);let brief = brief_with_job(&cwd)?;let exe = std::env::current_exe().ok()?;- let out = std::process::Command::new(exe).args(["make", "status"]).arg(brief.parent()?).arg("--json").env("RAEA_RECORD", "off").output().ok()?;+ let out = std::process::Command::new(exe).args(["make", "status"]).arg(brief.parent()?).args(["--json", "--plan"]).env("RAEA_RECORD", "off").output().ok()?;let s: Value = serde_json::from_slice(&out.stdout).ok()?;let home = raea_io_home::user_home()?;let session = v["session_id"].as_str().unwrap_or("");diff --git a/apps/judge/src/agent.rs b/apps/judge/src/agent.rsindex 8729af24..50d6de73 100644--- a/apps/judge/src/agent.rs+++ b/apps/judge/src/agent.rs@@ -9,13 +9,58 @@ use std::path::Path;use serde_json::{Map, Value, json};-use crate::rubric::SCORES;+use crate::rubric::{BAR, scores};pub const BY: [&str; 2] = ["kimi", "claude"];-/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer.-pub fn prompt(dir: &Path, brief: &Value, target: Option<&Path>) -> String {- let words = ["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ");+/// The judge prompt: the sheets by name, the brief's words, and the JSON to answer. A `raea make` job's kind asks its+/// own categories and the bar (docs/make.feature MK5); none asks the rubric raea judge has always asked.+pub fn prompt(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> String {+ match kind {+ None => prompt_default(dir, brief, target),+ Some(k) => prompt_kind(k, dir, brief, target),+ }+}++fn brief_words(brief: &Value) -> String {+ ["look", "logline", "notDoing"].iter().filter_map(|k| brief.get(*k).map(|v| format!("{k}: {}", v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))).collect::<Vec<_>>().join("; ")+}++fn prompt_kind(kind: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> String {+ let words = brief_words(brief);+ let target = target.map(|t| format!(" The reference, what it must read as, is {}.", t.display())).unwrap_or_default();+ let d = dir.display();+ let sheets = match kind {+ "shot" => format!("This round's sheet: {d}/framing.png. Each row is one shot: its first, middle and last frame, left to right, each stamped with its name and time. Open it."),+ _ => format!(+ "This round's sheets: {d}/colour.png and {d}/clay.png, each six tiles, left to right, top to bottom: hero, front, right, top, iso, low (0.3 m off the floor). Clay is every surface light grey and matte. Open both{}.",+ if kind == "kit" { "; the scene is the kit's lineup, its props side by side with a scale bar" } else { "" }+ ),+ };+ let blind = if kind == "shot" {+ String::new()+ } else {+ format!("PART 1, BLIND: open {d}/hero-colour.png first, one frame. In one sentence: what is this, what era? List five objects you can name. Is it a photograph or a render, and which three tells decided it?\n\n")+ };+ let cats: String = scores(Some(kind)).iter().map(|(k, on, ask)| format!("- {k}{}: {}\n", if *on == "clay" { " (judged on CLAY)" } else { "" }, ask.split_once(": ").map(|(_, r)| r).unwrap_or(ask))).collect();+ let json_scores = scores(Some(kind)).iter().map(|(k, _, _)| format!("\"{k}\": 0")).collect::<Vec<_>>().join(", ");+ format!(+ "You review a {kind} from images only, as the person who will use it would. You have never seen how it was built and you never will. \+Judge what is in the pixels; do not guess at intentions. Only look at images; change no file.\n\n{blind}\+PART 2, SCORED. The brief: \"{words}\".{target} {sheets}\n\n\+Score each 0-10 (5 = a believable draft; 7 = a production base an artist would accept; 9 = indistinguishable from real). Halves are allowed.\n{cats}\n\+{BAR} Each defect field is one short sentence; \"blocking\" means someone using this would notice it where it will be seen. \+Name exactly what gives it away (not \"the phone looks fake\" but \"the handset is fused to the cradle with no gap\").\n\n\+End your answer with only this JSON, nothing after it:\n\+{{\"blind\": {{\"place\": \"\", \"objects\": [], \"photo\": \"yes|no\", \"tells\": []}}, \+\"scores\": {{{json_scores}}}, \+\"defects\": [{{\"tile\": \"\", \"where\": \"\", \"wrong\": \"\", \"real\": \"\", \"fix\": \"\", \"level\": \"blocking|detail\"}}], \+\"show_as_is\": \"\"}}"+ )+}++fn prompt_default(dir: &Path, brief: &Value, target: Option<&Path>) -> String {+ let words = brief_words(brief);let target = target.map(|t| format!(" The target picture, what it must read as, is {}.", t.display())).unwrap_or_default();format!("You review a 3D scene from images only, as the person who will use it would. You have never seen how it was built and you never will. \@@ -57,13 +102,13 @@ pub fn last_verdict(text: &str) -> Option<Value> {None}-/// The verdict read into the judge's own shape: scores (0-10, the seven categories), defects (present, level, named+/// The verdict read into the judge's own shape: scores (0-10, the kind's categories), defects (present, level, named/// by what is wrong), the blind read's photo (1 a photo, 0 a render) and the agent's own words.-pub fn read(v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {- let mut scores = Map::new();- for (k, _, _) in SCORES {+pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {+ let mut out = Map::new();+ for &(k, _, _) in scores(kind) {if let Some(x) = v["scores"][k].as_f64().filter(|x| (0.0..=10.0).contains(x)) {- scores.insert(k.into(), json!(x));+ out.insert(k.into(), json!(x));}}let defects = v["defects"].as_array().into_iter().flatten().filter(|d| d["wrong"].as_str().is_some_and(|w| !w.trim().is_empty())).map(|d| {@@ -77,15 +122,15 @@ pub fn read(v: &Value) -> (Map<String, Value>, Vec<Value>, Value) {Some(p) if p.starts_with('n') => json!(0.0),_ => Value::Null,};- (scores, defects, photo)+ (out, defects, photo)}/// One fresh judging session by `by` over DIR's sheets: its verdict JSON. Its steps stream (kimi's stream-json), each/// said on stderr as it comes, so a watcher sees it working through a judgement that can take minutes.-pub fn ask(by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {+pub fn ask(kind: Option<&str>, by: &str, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {use std::io::BufRead as _;let dir = dunce::canonicalize(&dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;- let p = prompt(&dir, brief, target);+ let p = prompt(kind, &dir, brief, target);let mut cmd = match by {"kimi" => {let mut c = std::process::Command::new("kimi");diff --git a/apps/judge/src/eye.rs b/apps/judge/src/eye.rsindex e34a98ef..1155b7b5 100644--- a/apps/judge/src/eye.rs+++ b/apps/judge/src/eye.rs@@ -10,15 +10,26 @@ use std::path::PathBuf;use serde_json::{Map, Value, json};-use crate::rubric::{SCORES, pass};+use crate::rubric::{pass_for, scores};fn home() -> PathBuf {raea_io_home::env_path("RAEA_JUDGE_DIR", ".raea/judge")}-/// The calibration in force, if one was made.-pub fn calibration() -> Option<Value> {- serde_json::from_str(&std::fs::read_to_string(home().join("calibration.json")).ok()?).ok()+/// A kind's calibration file: calibration.json for the default rubric, calibration.KIND.json for a `raea make` kind's+/// (docs/make.feature MK6), each fitted on that kind's rounds alone.+fn file_of(kind: Option<&str>) -> PathBuf {+ home().join(kind.map_or_else(|| "calibration.json".to_string(), |k| format!("calibration.{k}.json")))+}++/// The calibration in force for a kind, if one was made.+pub fn calibration(kind: Option<&str>) -> Option<Value> {+ serde_json::from_str(&std::fs::read_to_string(file_of(kind)).ok()?).ok()+}++/// A row's or a verdict's kind: none for the default rubric.+fn kind_in(v: &Value) -> Option<&str> {+ v["kind"].as_str()}/// The judge's scores mapped through the calibration's lines, kept to 0-10.@@ -33,15 +44,17 @@ pub fn apply(c: &Value, scores: &mut Map<String, Value>) {pub fn record(args: &[String]) -> Result<String, String> {let dir = args.get(2).map(PathBuf::from).ok_or("raea judge eye DIR CATEGORY=SCORE... [--pass yes|no]")?;let verdict: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("judge.json")).map_err(|_| format!("judge eye: no {}: judge the round first (raea judge {})", dir.join("judge.json").display(), dir.display()))?).map_err(|e| e.to_string())?;+ let kind = kind_in(&verdict);+ let cats = scores(kind);// an agent's reading as the eye (`--by kimi`): a fresh session's scores, and its pass by the same rule in codeif let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {- let v = crate::agent::ask(by, &dir, &json!({}), None)?;- let (eye, defects, _) = crate::agent::read(&v);- if eye.len() < SCORES.len() {- return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), SCORES.len()));+ let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;+ let (eye, defects, _) = crate::agent::read(kind, &v);+ if eye.len() < cats.len() {+ return Err(format!("judge eye: {by} scored only {} of {} categories", eye.len(), cats.len()));}- let eye_pass = pass(&eye, &defects).0;- let row = json!({"dir": verdict["dir"], "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});+ let eye_pass = pass_for(kind, &eye, &defects).0;+ let row = json!({"dir": verdict["dir"], "kind": kind, "by": by, "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass, "eye_defects": defects});append(&row)?;let shown: Vec<String> = eye.iter().map(|(k, v)| format!("{k} {v}")).collect();return Ok(format!("APPLIED {by}'s eye on {} recorded ({}): {}; raea judge calibrate fits clef to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }, shown.join(", ")));@@ -56,8 +69,8 @@ pub fn record(args: &[String]) -> Result<String, String> {continue;}let (k, v) = args[i].split_once('=').ok_or_else(|| format!("judge eye: {:?} isn't CATEGORY=SCORE", args[i]))?;- if !SCORES.iter().any(|s| s.0 == k) {- return Err(format!("judge eye: no category {k}: {}", SCORES.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));+ if !cats.iter().any(|s| s.0 == k) {+ return Err(format!("judge eye: no category {k}: {}", cats.iter().map(|s| s.0).collect::<Vec<_>>().join(", ")));}let x: f64 = v.parse().ok().filter(|x| (0.0..=10.0).contains(x)).ok_or_else(|| format!("judge eye: {k} is a score 0-10, got {v:?}"))?;eye.insert(k.into(), json!(x));@@ -67,8 +80,8 @@ pub fn record(args: &[String]) -> Result<String, String> {return Err("judge eye: give your scores, e.g. composition=6 form=5 assembly=7 materials=4 light=6 detail=5 world=6".into());}// his pass: as he says it, else the same rule on his scores with the judge's defects- let eye_pass = said_pass.unwrap_or_else(|| pass(&eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);- let row = json!({"dir": verdict["dir"], "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});+ let eye_pass = said_pass.unwrap_or_else(|| pass_for(kind, &eye, verdict["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0);+ let row = json!({"dir": verdict["dir"], "kind": kind, "by": "shane", "judge": verdict["raw"], "judge_pass": verdict["pass"], "defects": verdict["defects"], "eye": eye, "eye_pass": eye_pass});append(&row)?;Ok(format!("APPLIED your eye on {} recorded ({}): raea judge calibrate fits the judge to it", dir.display(), if eye_pass { "a pass" } else { "not yet" }))}@@ -94,10 +107,11 @@ fn fit(xy: &[(f64, f64)]) -> (f64, f64) {(a, my - a * mx)}-/// The fit over rows of {judge, eye, defects, eye_pass}: per-category maps and errors, and the pass agreement.-pub fn fit_rows(rows: &[Value]) -> Value {+/// The fit over a kind's rows of {judge, eye, defects, eye_pass} (none: the default rubric's): per-category maps and+/// errors, and the pass agreement.+pub fn fit_rows_for(kind: Option<&str>, rows: &[Value]) -> Value {let mut maps = Map::new();- for (k, _, _) in SCORES {+ for &(k, _, _) in scores(kind) {let xy: Vec<(f64, f64)> = rows.iter().filter_map(|r| Some((r["judge"][k].as_f64()?, r["eye"][k].as_f64()?))).collect();if xy.len() < 2 {continue;@@ -112,7 +126,7 @@ pub fn fit_rows(rows: &[Value]) -> Value {for r in rows {let mut s = r["judge"].as_object().cloned().unwrap_or_default();apply(&cal, &mut s);- let p = pass(&s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;+ let p = pass_for(kind, &s, r["defects"].as_array().map(Vec::as_slice).unwrap_or(&[])).0;if Value::Bool(p) == r["eye_pass"] {agree += 1;}@@ -126,16 +140,20 @@ pub fn fit_rows(rows: &[Value]) -> Value {}pub fn calibrate(args: &[String]) -> Result<String, String> {- let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();+ let kind = crate::kind_of(args)?;+ let kind = kind.as_deref();+ let rows: Vec<Value> = std::fs::read_to_string(home().join("eye.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|r: &Value| kind_in(r) == kind).collect();if rows.is_empty() {- return Err("judge calibrate: no rounds with your eye yet (raea judge eye DIR form=5 ...)".into());+ let k = kind.map(|k| format!(" of a {k}")).unwrap_or_default();+ return Err(format!("judge calibrate: no rounds{k} with your eye yet (raea judge eye DIR form=5 ...)"));}- let mut cal = fit_rows(&rows);+ let mut cal = fit_rows_for(kind, &rows);+ cal["kind"] = json!(kind);let mut eyes: Vec<String> = rows.iter().map(whose).map(str::to_string).collect();eyes.sort();eyes.dedup();cal["eyes"] = json!(eyes);- std::fs::write(home().join("calibration.json"), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;+ std::fs::write(file_of(kind), serde_json::to_string_pretty(&cal).unwrap_or_default()).map_err(|e| e.to_string())?;if args.iter().any(|a| a == "--json") {return Ok(serde_json::to_string_pretty(&cal).unwrap_or_default());}diff --git a/apps/judge/src/lib.rs b/apps/judge/src/lib.rsindex a2bebd5f..f72f310c 100644--- a/apps/judge/src/lib.rs+++ b/apps/judge/src/lib.rs@@ -2,15 +2,24 @@//! fresh every round and blind to the code, with the pass decided here in code. Until it is calibrated against Shane's//! eye (`raea judge eye`, `raea judge calibrate`, eye.rs) its verdict is advice: `gating` says which.//!-//! raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]+//! raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry]//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --by kimi: an agent's reading as the eye)-//! raea judge calibrate [--json]+//! raea judge calibrate [--kind scene|kit|shot] [--json]+//!+//! `--kind` asks a `raea make` job's own rubric (docs/make.feature MK5): a scene's, a kit's or a shot list's categories,+//! with the bar AnyKit's critic is given; each kind is calibrated on its own rounds (MK6).//!//! DIR/judge.json is the verdict; DIR's parent's judge.log.jsonl holds every round's, so "done" (two passes in a row,//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.mod agent;mod eye;++/// Whether the judge's score gates a `raea make` kind's jobs: its calibration (`raea judge calibrate --kind KIND`)+/// agreed with the person's eye (docs/make.feature MK6).+pub fn kind_gates(kind: &str) -> bool {+ eye::calibration(Some(kind)).is_some_and(|c| c["gate"] == true)+}pub mod rubric;pub use agent::BY;@@ -21,7 +30,16 @@ use raea_core_facts::{Finding, Level, finding};use raea_runtime_bundle::flag;use serde_json::{Value, json};-pub const USAGE: &str = "raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; the pass decided in code; clef advises until calibrated against your eye or an agent's)";+pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a raea make job's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)";++/// `--kind`, checked: one of the rubric's kinds, or none (the default rubric).+pub fn kind_of(args: &[String]) -> Result<Option<String>, String> {+ match flag(args, "--kind") {+ None => Ok(None),+ Some(k) if rubric::KINDS.contains(&k.as_str()) => Ok(Some(k)),+ Some(k) => Err(format!("judge: --kind {k}: the kinds are {}", rubric::KINDS.join(", "))),+ }+}/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),/// with the rubric's questions as written and each sheet as a JPEG still.@@ -76,10 +94,14 @@ pub fn cli(args: &[String]) -> Result<String, String> {None => return Err(USAGE.into()),}let dir = PathBuf::from(&args[1]);- let (colour, clay, hero) = (dir.join("colour.png"), dir.join("clay.png"), dir.join("hero-colour.png"));- for f in [&colour, &clay] {+ let kind = kind_of(args)?;+ let kind = kind.as_deref();+ let hero = dir.join("hero-colour.png");+ let sheets: Vec<(&str, PathBuf)> = rubric::sheets(kind).iter().map(|(s, f)| (*s, dir.join(f))).collect();+ for (_, f) in &sheets {if !f.is_file() {- return Err(format!("judge: no {} (make the sheets with raea render EDIT.tsx --review {})", f.display(), dir.display()));+ let make = if kind == Some("shot") { format!("raea make framing --out {}", dir.display()) } else { format!("raea render EDIT.tsx --review {}", dir.display()) };+ return Err(format!("judge: no {} (make the sheets with {make})", f.display()));}}let brief = brief_of(flag(args, "--brief").as_deref())?;@@ -88,21 +110,21 @@ pub fn cli(args: &[String]) -> Result<String, String> {let by = flag(args, "--by").unwrap_or_else(|| "clef".into());if by != "clef" {if dry {- return Ok(agent::prompt(&dir, &brief, target.as_deref()));+ return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));}- let v = agent::ask(&by, &dir, &brief, target.as_deref())?;- let (scores, defects, photo) = agent::read(&v);- return finish(args, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));+ let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;+ let (scores, defects, photo) = agent::read(kind, &v);+ return finish(args, kind, &dir, scores.clone(), scores, defects, photo, 0.0, &by, false, json!({"blind": v["blind"], "show_as_is": v["show_as_is"]}));}let mut calls = Vec::new();- for (sheet, img) in [("colour", &colour), ("clay", &clay)] {+ for (sheet, img) in &sheets {let mut images = vec![img.clone()];- if sheet == "colour" {+ if *sheet == "colour" {images.extend(target.clone());}- calls.push((sheet, rubric::state(sheet, &brief), rubric::questions(sheet), images));+ calls.push((*sheet, rubric::state_for(kind, sheet, &brief), rubric::questions_for(kind, sheet), images));}- if hero.is_file() {+ if hero.is_file() && kind != Some("shot") {calls.push(("blind", "One frame. Judge only what is in the pixels.".into(), rubric::blind(), vec![hero.clone()]));}if dry {@@ -120,7 +142,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));continue;}- let (s, d) = rubric::read(&answers);+ let (s, d) = rubric::read_for(kind, &answers);scores.extend(s);defects.extend(d.into_iter().map(|mut x| {x["sheet"] = json!(sheet);@@ -128,12 +150,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {}));}let raw = scores.clone();- let cal = eye::calibration();+ let cal = eye::calibration(kind);if let Some(c) = &cal {eye::apply(c, &mut scores);}let gating = cal.as_ref().is_some_and(|c| c["gate"] == true);- finish(args, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))+ finish(args, kind, &dir, scores, raw, defects, photo, cost, "clef", !gating, json!({"calibrated": cal.is_some()}))}/// The defects a judge saw, as raea's one Finding (docs/direction.feature DR3): a blocking one an error and a detail a@@ -164,13 +186,13 @@ pub fn findings(defects: &[Value], by: &str, advice: bool) -> Vec<Finding> {/// The verdict decided in code, written (DIR/judge.json for clef, DIR/judge.BY.json for an agent; every round in the/// log), and said. `advice` marks a judge not yet trusted to gate (clef before calibration).#[allow(clippy::too_many_arguments)]-fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {- let (pass, why) = rubric::pass(&scores, &defects);+fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::Map<String, Value>, raw: serde_json::Map<String, Value>, defects: Vec<Value>, photo: Value, cost: f64, by: &str, advice: bool, extra: Value) -> Result<String, String> {+ let (pass, why) = rubric::pass_for(kind, &scores, &defects);let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();let mean = if vals.is_empty() { 0.0 } else { (vals.iter().sum::<f64>() / vals.len() as f64 * 100.0).round() / 100.0 };let model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { format!("{by} cli") };let found = findings(&defects, by, advice);- let mut verdict = json!({"dir": dir.display().to_string(), "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,+ let mut verdict = json!({"dir": dir.display().to_string(), "kind": kind, "by": by, "scores": scores, "raw": raw, "mean": mean, "defects": defects, "photo": photo,"pass": pass, "why": why, "gating": !advice, "cost": cost, "model": model, "findings": found, "count": finding::count(&found)});if let (Some(v), Some(e)) = (verdict.as_object_mut(), extra.as_object()) {v.extend(e.clone());@@ -181,7 +203,7 @@ fn finish(args: &[String], dir: &Path, scores: serde_json::Map<String, Value>, rverdict["progress"] = progress(&rounds);let file = if by == "clef" { "judge.json".to_string() } else { format!("judge.{by}.json") };std::fs::write(dir.join(file), serde_json::to_string_pretty(&verdict).unwrap_or_default()).map_err(|e| e.to_string())?;- let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();+ let lines: Vec<String> = rounds.iter().map(|r| serde_json::to_string(&json!({"dir": r["dir"], "kind": r["kind"], "by": r["by"], "pass": r["pass"], "mean": r["mean"], "defects": r["defects"]})).unwrap_or_default()).collect();std::fs::write(&log, lines.join("\n") + "\n").map_err(|e| e.to_string())?;if cost > 0.0 {let _ = std::process::Command::new("antsy").args(["spend", &format!("{cost:.6}"), "raea judge (clef-omni)"]).output();diff --git a/apps/judge/src/rubric.rs b/apps/judge/src/rubric.rsindex 348b401d..c2442f3c 100644--- a/apps/judge/src/rubric.rs+++ b/apps/judge/src/rubric.rs@@ -18,8 +18,11 @@ fn levels(what: &str) -> Value {])}-/// (id, the sheet it is judged on, the question)-pub const SCORES: [(&str, &str, &str); 7] = [+/// A category: (id, the sheet it is judged on, the question).+pub type Score = (&'static str, &'static str, &'static str);++/// (id, the sheet it is judged on, the question): the rubric raea judge has always asked, when no `--kind` is given.+pub const SCORES: [Score; 7] = [("composition", "colour", "Composition: the camera, framing and layout; every major object's position and scale against the brief's space."),("form", "clay", "Form, judged on these grey clay tiles: silhouettes read at a glance, parts have real thickness, nothing blobby or melted, no primitive standing in for a thing, repeated things vary."),("assembly", "clay", "Assembly, judged on these grey clay tiles: nothing floats, sinks, pokes through or rests on the wrong thing; joints touch; the low tile shows the feet resting."),@@ -29,6 +32,64 @@ pub const SCORES: [(&str, &str, &str); 7] = [("world", "colour", "World: one coherent real place matching the brief; nothing off-era, no real brands, nothing invented beyond the brief."),];+/// The job kinds with a rubric of their own (docs/make.feature MK5): `raea judge DIR --kind scene|kit|shot`.+pub const KINDS: [&str; 3] = ["scene", "kit", "shot"];++/// A scene made to a plan (AnyScene's categories): judged on the six-camera sheets.+pub const SCENE: [Score; 8] = [+ ("layout", "clay", "Layout, judged on these grey clay tiles: every major object where the plan and the reference put it, at its real size, with room to move between them."),+ ("props", "clay", "Props, judged on these grey clay tiles: each object's form reads at a glance, with real thickness; nothing blobby or a primitive standing in; nothing floats, sinks or pokes through."),+ ("signage", "colour", "Screens and signage: every screen, sign, label and printed thing reads, belongs to one invented world, and shows no real brand."),+ ("materials", "colour", "Materials: every surface reads as its real material with wear where use puts it; nothing a flat default colour; glass is glass."),+ ("light", "colour", "Light: motivated by the place's own sources; exposure and contrast believable; emissive things glow without lighting the room wrong."),+ ("atmosphere", "colour", "Atmosphere: the air, haze, dust or weather the place would have, matching the plan's dials; not empty and clinical."),+ ("plausibility", "colour", "Plausibility: one coherent real place a person could stand in; nothing off-era, nothing that couldn't be there."),+ ("composition", "colour", "Composition: the hero camera's framing and the place's layout read as the reference's."),+];++/// A kit (AnyKit's categories): judged on the six-camera sheets of its lineup.+pub const KIT: [Score; 8] = [+ ("cohesion", "colour", "Cohesion: every prop belongs to one set: the same era, palette, materials, wear and maker; none is an outlier."),+ ("fidelity", "colour", "Reference fidelity: the props read as the style references' world, at normal viewing distance."),+ ("brief", "colour", "Brief: the kit holds the props the brief asked for, each recognisable as what it is meant to be."),+ ("mesh", "clay", "Mesh, judged on these grey clay tiles: crisp silhouettes, real thickness, no melted or blobby forms, no holes or spikes."),+ ("texture", "colour", "Texture: real materials with wear where use puts it; no smeared, stretched or flat default surfaces; glass is glass."),+ ("assembly", "clay", "Assembly, judged on these grey clay tiles: every part of each prop is connected to its body; handles, legs and lids attached."),+ ("scale", "clay", "Scale, judged on these grey clay tiles: each prop's size is right beside the others and the scale bar."),+ ("labels", "colour", "Labels: printed text and logos read, belong to the one invented maker, and no real brand shows."),+];++/// A shot list (AnyShot's categories): judged on the framing sheet, each shot's first, middle and last frame.+pub const SHOT: [Score; 6] = [+ ("framing", "colour", "Framing: each shot frames its subject as its description says, at every one of its frames."),+ ("move", "colour", "Move: the camera's change from first to last frame is the move the description names, at a believable size."),+ ("focus", "colour", "Focus: what the description says is sharp is sharp; nothing important lost in blur."),+ ("clearance", "colour", "Clearance: the camera is never inside or against a wall or object; nothing blocks the frame."),+ ("continuity", "colour", "Continuity: the shots read as one place at one time: the same light, weather and dressing across them."),+ ("grade", "colour", "Grade: the look matches the plan's look dial, with believable exposure and colour."),+];++/// The categories asked for a kind: its own rubric, or the default one.+pub fn scores(kind: Option<&str>) -> &'static [Score] {+ match kind {+ Some("scene") => &SCENE,+ Some("kit") => &KIT,+ Some("shot") => &SHOT,+ _ => &SCORES,+ }+}++/// What a kind's critic is told the bar is (AnyKit's own words, docs/make.feature MK5).+pub const BAR: &str = "The bar is a production base an artist then refines, judged at normal viewing distance: take no points off for choices that differ from the reference, don't nitpick, and name at most five fixes, most damaging first.";++/// The sheets a kind is judged on: the six-camera colour and clay sheets, or a shot list's framing sheet alone.+pub fn sheets(kind: Option<&str>) -> &'static [(&'static str, &'static str)] {+ match kind {+ Some("shot") => &[("colour", "framing.png")],+ _ => &[("colour", "colour.png"), ("clay", "clay.png")],+ }+}+/// (id, sheet, the yes/no question, blocking when yes)pub const DEFECTS: [(&str, &str, &str, bool); 12] = [("floating", "clay", "Does any object float above the surface it should rest on, with a visible gap under it?", true),@@ -47,26 +108,50 @@ pub const DEFECTS: [(&str, &str, &str, bool); 12] = [/// The paragraph clef reads before the sheet: what it is looking at, and the brief's words (no code, no log, no line).pub fn state(sheet: &str, brief: &Value) -> String {+ state_for(None, sheet, brief)+}++/// state, for a kind: a kind's critic also reads what it is looking at in its terms, and the bar.+pub fn state_for(kind: Option<&str>, sheet: &str, brief: &Value) -> String {+ let what = match kind {+ Some("shot") => "The image is a framing sheet: each row is one shot, its first, middle and last frame left to right, each stamped with the shot's name and time. Judge each shot as its description would.".to_string(),+ _ => {+ let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";+ let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };+ let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };+ let kit = if kind == Some("kit") { " The scene is a kit: a lineup of props made to belong together, with a scale bar." } else { "" };+ format!("{what}{target}{kit}")+ }+ };+ // the default rubric's words stay as calibrated: "the scene"+ let it = match kind { None | Some("scene") => "the scene", Some("kit") => "the kit", _ => "the shots" };+ let mut s = format!("{what} Judge only what is in the pixels, as the person who will use {it} would.");let look = brief["look"].as_str().unwrap_or("");let logline = brief["logline"].as_str().unwrap_or("");let not: Vec<&str> = brief["notDoing"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();- let tiles = "six tiles of one 3D scene, left to right and top to bottom: hero (the shot's own camera), front, right, top, iso, and low (a camera 0.3 m off the floor)";- let what = if sheet == "clay" { format!("The image is {tiles}, rendered in clay: every surface plain grey, so only form and assembly show.") } else { format!("The image is {tiles}, in full colour.") };- let target = if sheet == "colour" { " A second image, when given, is the target picture the scene should read as." } else { "" };- let mut s = format!("{what}{target} Judge only what is in the pixels, as the person who will use the scene would.");if !logline.is_empty() || !look.is_empty() {s.push_str(&format!(" The brief: {logline} Look: {look}."));}if !not.is_empty() {- s.push_str(&format!(" The scene must not contain: {}.", not.join("; ")));+ let it = it[..1].to_uppercase() + &it[1..];+ s.push_str(&format!(" {it} must not contain: {}.", not.join("; ")));+ }+ if kind.is_some() {+ s.push(' ');+ s.push_str(BAR);}s}/// The questions for one sheet, by id.pub fn questions(sheet: &str) -> Value {+ questions_for(None, sheet)+}++/// questions, for a kind's rubric.+pub fn questions_for(kind: Option<&str>, sheet: &str) -> Value {let mut q = serde_json::Map::new();- for (id, on, ask) in SCORES {+ for &(id, on, ask) in scores(kind) {if on == sheet {q.insert(format!("score_{id}"), json!({"type": "score", "instructions": ask, "criteria": levels(id)}));}@@ -86,9 +171,14 @@ pub fn blind() -> Value {/// clef's answers read into scores (0-10) and defects (probability of yes, blocking ones flagged).pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {+ read_for(None, answers)+}++/// read, for a kind's rubric.+pub fn read_for(kind: Option<&str>, answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {let mut scores = serde_json::Map::new();let mut defects = Vec::new();- for (id, _, _) in SCORES {+ for &(id, _, _) in self::scores(kind) {if let Some(a) = answers.get(format!("score_{id}")) {let level = a["score"].as_f64().unwrap_or(0.0);scores.insert(id.into(), json!((level * 2.0 * 100.0).round() / 100.0));@@ -106,6 +196,12 @@ pub fn read(answers: &Value) -> (serde_json::Map<String, Value>, Vec<Value>) {/// The loop's pass, in code: no blocking defect present, the lowest score 6 or more and the mean 7 or more (raea's/// 0-10 scale; the prompt pack's line). Scores mapped by a calibration first, when there is one.pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {+ pass_for(None, scores, defects)+}++/// pass, for a kind's rubric: every one of its categories scored.+pub fn pass_for(kind: Option<&str>, scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool, Vec<String>) {+ let want = self::scores(kind).len();let vals: Vec<f64> = scores.values().filter_map(Value::as_f64).collect();let mut why = Vec::new();let blocking = blocking(defects);@@ -114,8 +210,8 @@ pub fn pass(scores: &serde_json::Map<String, Value>, defects: &[Value]) -> (bool}let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);let mean = if vals.is_empty() { 0.0 } else { vals.iter().sum::<f64>() / vals.len() as f64 };- if vals.len() < SCORES.len() {- why.push(format!("only {} of {} categories scored", vals.len(), SCORES.len()));+ if vals.len() < want {+ why.push(format!("only {} of {want} categories scored", vals.len()));}if min < 6.0 {let low: Vec<String> = scores.iter().filter(|(_, v)| v.as_f64().is_some_and(|x| x < 6.0)).map(|(k, _)| k.clone()).collect();diff --git a/apps/judge/src/tests.rs b/apps/judge/src/tests.rsindex c1be5563..7e1b7679 100644--- a/apps/judge/src/tests.rs+++ b/apps/judge/src/tests.rs@@ -37,15 +37,15 @@ fn calibration_maps_a_lenient_judge_onto_the_eye() {// the judge says 8 to everything the eye gives 5, and 9 to what the eye gives 8let row = |j: f64, e: f64, p: bool| json!({"judge": scores(j), "eye": scores(e), "eye_pass": p, "defects": []});let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { row(8.0, 5.0, false) } else { row(9.0, 8.0, true) }).collect();- let cal = eye::fit_rows(&rows);+ let cal = eye::fit_rows_for(None, &rows);assert_eq!(cal["agreement"], 1.0);assert_eq!(cal["gate"], true);assert!((cal["maps"]["form"]["a"].as_f64().unwrap() - 3.0).abs() < 1e-6);- let few = eye::fit_rows(&rows[..4]);+ let few = eye::fit_rows_for(None, &rows[..4]);assert_eq!(few["gate"], false, "too few rounds to gate");// an eye that failed everything agrees with a judge that fails everything, which proves nothinglet fails: Vec<Value> = (0..12).map(|_| row(3.0, 2.0, false)).collect();- let all_fail = eye::fit_rows(&fails);+ let all_fail = eye::fit_rows_for(None, &fails);assert_eq!(all_fail["agreement"], 1.0);assert_eq!(all_fail["gate"], false, "no pass among the eye's rounds");}@@ -60,7 +60,7 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {{"tile": "low", "wrong": "", "level": "detail"}],"show_as_is": "no"}"#;let v = crate::agent::last_verdict(text).unwrap();- let (scores, defects, photo) = crate::agent::read(&v);+ let (scores, defects, photo) = crate::agent::read(None, &v);assert_eq!(scores.len(), 7, "only the seven categories, each 0-10");assert_eq!(scores["form"], serde_json::json!(5.5));assert_eq!(defects.len(), 1, "a defect with nothing wrong named is dropped");@@ -75,3 +75,52 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {assert!(f.says.starts_with("iso sheet: "), "{}", f.says);assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);}++#[test]+fn each_make_kind_has_its_own_rubric_and_the_default_is_unchanged() {+ // docs/make.feature MK5: a kit's categories, a shot list's on the framing sheet alone, the bar said to each+ let kit = rubric::questions_for(Some("kit"), "clay");+ for k in ["score_mesh", "score_assembly", "score_scale"] {+ assert!(kit.get(k).is_some(), "{k} in {kit}");+ }+ assert!(kit.get("score_cohesion").is_none(), "cohesion is judged in colour");+ assert_eq!(rubric::sheets(Some("shot")), &[("colour", "framing.png")]);+ assert_eq!(rubric::sheets(None).len(), 2);+ let shot = rubric::questions_for(Some("shot"), "colour");+ assert!(shot.get("score_clearance").is_some() && shot.get("score_composition").is_none());+ assert!(rubric::state_for(Some("kit"), "colour", &json!({})).contains(rubric::BAR));+ assert!(rubric::state_for(Some("shot"), "colour", &json!({})).contains("framing sheet"));+ // the default's words are what it was calibrated on+ let d = rubric::state("clay", &json!({"notDoing": ["cats"]}));+ assert!(d.contains("as the person who will use the scene would") && d.contains("The scene must not contain: cats.") && !d.contains(rubric::BAR), "{d}");+ // every kind scored in full to pass+ let all = |k: Option<&str>, v: f64| -> serde_json::Map<String, Value> { rubric::scores(k).iter().map(|s| (s.0.to_string(), json!(v))).collect() };+ assert!(rubric::pass_for(Some("kit"), &all(Some("kit"), 8.0), &[]).0);+ let (ok, why) = rubric::pass_for(Some("kit"), &all(None, 8.0), &[]);+ assert!(!ok && why.iter().any(|w| w.contains("of 8 categories")), "{why:?}");+ assert!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "film".into()]).is_err());+ assert_eq!(kind_of(&["judge".into(), "d".into(), "--kind".into(), "shot".into()]).unwrap().as_deref(), Some("shot"));+}++#[test]+fn an_agent_critic_is_asked_its_kinds_categories() {+ let p = crate::agent::prompt(Some("shot"), std::path::Path::new("/r/r1"), &json!({"look": "dusk"}), None);+ assert!(p.contains("/r/r1/framing.png") && p.contains("\"clearance\": 0") && p.contains(rubric::BAR) && !p.contains("PART 1, BLIND"), "{p}");+ let k = crate::agent::prompt(Some("kit"), std::path::Path::new("/r/r1"), &json!({}), None);+ assert!(k.contains("\"cohesion\": 0") && k.contains("scale bar") && k.contains("(judged on CLAY)"));+ let d = crate::agent::prompt(None, std::path::Path::new("/r/r1"), &json!({}), None);+ assert!(d.contains("\"composition\": 0") && !d.contains(rubric::BAR));+ let v = json!({"scores": {"cohesion": 7, "fidelity": 8, "composition": 9}});+ let (s, _, _) = crate::agent::read(Some("kit"), &v);+ assert_eq!(s.len(), 2, "only the kit's categories");+}++#[test]+fn a_kind_is_calibrated_on_its_own_categories() {+ // docs/make.feature MK6+ let s = |j: f64| -> serde_json::Map<String, Value> { rubric::KIT.iter().map(|c| (c.0.to_string(), json!(j))).collect() };+ let rows: Vec<Value> = (0..12).map(|i| if i % 2 == 0 { json!({"kind": "kit", "judge": s(8.0), "eye": s(5.0), "eye_pass": false, "defects": []}) } else { json!({"kind": "kit", "judge": s(9.0), "eye": s(8.0), "eye_pass": true, "defects": []}) }).collect();+ let cal = eye::fit_rows_for(Some("kit"), &rows);+ assert_eq!(cal["gate"], true);+ assert!(cal["maps"]["cohesion"].is_object() && cal["maps"]["form"].is_null());+}diff --git a/apps/make/Cargo.toml b/apps/make/Cargo.tomlindex 2cf265f4..573c11e8 100644--- a/apps/make/Cargo.toml+++ b/apps/make/Cargo.toml@@ -13,6 +13,13 @@ raea-core-brief = { path = "../../core/brief" }raea-core-facts = { path = "../../core/facts" }# the judge's rounds, passes and blocking defects, read as it keeps themraea-app-judge = { path = "../judge" }+# the make questions, their calibrations and a sheet's ident, as raea ask keeps them (MK4)+raea-core-ask = { path = "../../core/ask" }+# raea ask's ledger folder+raea-io-home = { path = "../../io/home" }+# the contact sheets: tiles composited, labels drawn in the system's fonts+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }+resvg = { version = "=0.48.1", default-features = false, features = ["text", "system-fonts"] }dunce = "1"serde_json = "1"diff --git a/apps/make/src/asked.rs b/apps/make/src/asked.rsnew file mode 100644index 00000000..f6b0dba6--- /dev/null+++ b/apps/make/src/asked.rs@@ -0,0 +1,111 @@+//! The second tier of the gate (docs/make.feature MK4): the `make` set of `raea ask` questions (core/ask+//! library/make.json), asked of the job's newest sheets. A question gates once it is calibrated on the person's labels+//! (`raea ask calibrate`: 16 problem, 16 clean, an AUC of 0.8); until then what it says is advice in the status. An+//! answer counts for a sheet only when its call was about exactly that sheet's bytes (the ledger's `ident`), so a sheet+//! rendered again must be asked again.++use std::collections::{BTreeMap, HashMap};+use std::path::{Path, PathBuf};++use raea_core_ask::{Calibration, Question};+use serde_json::{Value, json};++/// The ledger as status reads it: every call's ident by id, every answer, and the person's calibrations.+#[derive(Default)]+pub struct Ledger {+ pub idents: HashMap<String, String>,+ pub answers: Vec<Value>,+ pub calibrations: BTreeMap<String, Calibration>,+}++impl Ledger {+ /// `raea ask`'s record (RAEA_ASK_DIR, else ~/.raea/ask), read once.+ pub fn read() -> Ledger {+ let dir = raea_io_home::env_path("RAEA_ASK_DIR", ".raea/ask");+ let rows = |f: &str| -> Vec<Value> { std::fs::read_to_string(dir.join(f)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect() };+ let idents = rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c["ident"].as_str()?.to_string()))).collect();+ let answers = rows("answers.jsonl").into_iter().filter(|a| a["question"].as_str().is_some_and(|q| q.starts_with("make."))).collect();+ let calibrations = std::fs::read_to_string(dir.join("calibration.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();+ Ledger { idents, answers, calibrations }+ }+}++/// The `make` set's questions with the person's calibrations in place of raea's (as `raea ask` applies them).+pub fn questions(ledger: &Ledger) -> Vec<Question> {+ let mut qs = raea_core_ask::library::set("make", None).unwrap_or_default();+ for q in &mut qs {+ if let Some(c) = ledger.calibrations.get(&q.version()) {+ q.calibration = Some(c.clone());+ }+ }+ qs+}++/// The sheet a question is asked of: its id's second word (make.clay.floating is asked of a clay sheet).+pub fn sheet_of(q: &Question) -> &str {+ q.id.split('.').nth(1).unwrap_or("")+}++/// The command that asks a sheet its questions.+pub fn command(sheet: &Path, qs: &[&Question]) -> String {+ let std: Vec<String> = qs.iter().map(|q| format!("--std {}", q.id)).collect();+ format!("raea ask {} {}", sheet.display(), std.join(" "))+}++/// Each sheet's gate, and the advice: what uncalibrated questions flagged. `sheets` are (kind, file): clay, colour,+/// refs, framing. `notes` is NOTES.md: a flagged question answered there by its id holds nothing.+pub fn gates(sheets: &[(&str, PathBuf)], ledger: &Ledger, notes: &str) -> (Vec<Value>, Vec<String>) {+ let qs = questions(ledger);+ let mut gates = Vec::new();+ let mut advice = Vec::new();+ for (kind, file) in sheets {+ let mine: Vec<&Question> = qs.iter().filter(|q| sheet_of(q) == *kind).collect();+ if mine.is_empty() {+ continue;+ }+ let rel = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+ let Some(ident) = raea_core_ask::ident::ident(file) else { continue };+ // the newest answer to each question about these exact bytes+ let mut latest: BTreeMap<&str, &Value> = BTreeMap::new();+ for a in &ledger.answers {+ let about = a["call"].as_str().and_then(|c| ledger.idents.get(c)).is_some_and(|i| *i == ident);+ let Some(q) = a["question"].as_str() else { continue };+ if about && latest.get(q).is_none_or(|b| at(a) >= at(b)) {+ latest.insert(q, a);+ }+ }+ let mut open = Vec::new();+ let mut unasked = Vec::new();+ for q in &mine {+ let a = latest.get(q.id.as_str());+ let flagged = a.is_some_and(|a| a["flagged"] == true);+ let p = a.and_then(|a| a["problem"].as_f64()).map(|p| format!(" (p {p:.2})")).unwrap_or_default();+ if q.calibrated() {+ match a {+ None => unasked.push(*q),+ Some(_) if flagged && !notes.contains(&q.id) => open.push(format!("{} flagged{p}: {}", q.id, q.fix.as_deref().unwrap_or("fix it, or answer it in NOTES.md by its id"))),+ _ => {}+ }+ } else if flagged {+ advice.push(format!("{rel}: {} says yes{p}, advice until calibrated: {}", q.id, q.fix.as_deref().unwrap_or("")));+ }+ }+ if !unasked.is_empty() {+ open.push(format!("not asked of this {kind} sheet yet: {}", command(file, &unasked)));+ }+ let calibrated = mine.iter().filter(|q| q.calibrated()).count();+ let says = match (open.is_empty(), calibrated) {+ (true, 0) => format!("advice only: none of its {} questions is calibrated yet (raea ask calibrate)", mine.len()),+ (true, n) => format!("{n} calibrated question{} clear", if n == 1 { "" } else { "s" }),+ (false, _) => open.join("; "),+ };+ let mut g = json!({"gate": "ask", "of": rel, "clear": open.is_empty(), "says": says});+ g["ask"] = json!(command(file, &mine));+ gates.push(g);+ }+ (gates, advice)+}++fn at(a: &Value) -> u64 {+ a["at"].as_str().and_then(|s| s.parse().ok()).or_else(|| a["at"].as_u64()).unwrap_or(0)+}diff --git a/apps/make/src/floor.rs b/apps/make/src/floor.rsnew file mode 100644index 00000000..8dfd30bf--- /dev/null+++ b/apps/make/src/floor.rs@@ -0,0 +1,155 @@+//! The plan stop (docs/make.feature MK18, from AnyScene's endpoint/floorplan.py, MIT): before anything is generated,+//! the plan drawn so a person can approve it. A floor plan from above (every object's footprint at its `at`, turned by+//! its `rot`, labelled; invented ones dashed, so what came from the reference and what was added are told apart), a+//! grey-box blockout of the same plan rendered from the entrance and through `raea render --review`, and the+//! reference beside the blockout on one comparison sheet.+//!+//! raea make plan [DIR] -> review/plan/floor-plan.png, blockout.tsx, blockout.png, comparison.png, colour/clay sheets++use std::path::{Path, PathBuf};++use raea_core_brief::make::{Make, Object, Origin};++use crate::sheet::{Tile, esc, sheet, svg_png};+use crate::shots::raea;++/// An object's footprint, metres: [width, depth] (its box, else a square about as wide as it's tall).+pub fn footprint(o: &Object) -> [f64; 2] {+ if let Some([w, d, _]) = o.dims {+ return [w, d];+ }+ let s = o.max.unwrap_or_else(|| o.h.unwrap_or(0.5) * 0.6).max(0.05);+ [s, s]+}++fn height(o: &Object) -> f64 {+ o.dims.map(|d| d[2]).or(o.h).unwrap_or(0.05).max(0.01)+}++/// The placed objects and the floor they span: (objects with an `at`, [x0, z0, x1, z1] with half a metre around).+pub fn extent(m: &Make) -> (Vec<&Object>, [f64; 4]) {+ let placed: Vec<&Object> = m.objects.iter().filter(|o| o.at.is_some()).collect();+ let mut b = [0.0f64, 0.0, 1.0, 1.0];+ for o in &placed {+ let at = o.at.unwrap();+ let [w, d] = footprint(o);+ let r = 0.5 * (w * w + d * d).sqrt();+ b = [b[0].min(at[0] - r), b[1].min(at[2] - r), b[2].max(at[0] + r), b[3].max(at[2] + r)];+ }+ (placed, [b[0] - 0.5, b[1] - 0.5, b[2] + 0.5, b[3] + 0.5])+}++/// The floor plan as SVG: the entrance (z = 0) at the bottom, a metre grid, each footprint turned and labelled.+pub fn floor_svg(m: &Make) -> Result<String, String> {+ let (placed, [x0, z0, x1, z1]) = extent(m);+ if placed.is_empty() {+ return Err("raea make plan: no object has an `at` (where it stands, in metres: x right, z away from the entrance)".into());+ }+ let px = (1400.0 / (x1 - x0).max(z1 - z0)).min(260.0);+ let (w, h) = (((x1 - x0) * px).ceil() as u32 + 40, ((z1 - z0) * px).ceil() as u32 + 130);+ // text sized to the plan, so it still reads once the plan is a third of a comparison sheet+ let t = (w as f64 * 0.02).max(16.0);+ // plan x right, z away from the entrance: up the page+ let sx = |x: f64| 20.0 + (x - x0) * px;+ let sy = |z: f64| 70.0 + (z1 - z) * px;+ let mut s = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><rect width=\"100%\" height=\"100%\" fill=\"#f4f2ee\"/>");+ s += &format!("<text x=\"20\" y=\"{:.0}\" font-size=\"{:.0}\" font-weight=\"bold\" fill=\"#222\">Floor plan: {} objects (solid: from the reference; dashed: invented)</text>", t * 1.6, t * 1.1, placed.len());+ let mut g = x0.ceil();+ while g <= x1 {+ s += &format!("<line x1=\"{0:.1}\" y1=\"{1:.1}\" x2=\"{0:.1}\" y2=\"{2:.1}\" stroke=\"#dedad2\" stroke-width=\"1\"/>", sx(g), sy(z1), sy(z0));+ g += 1.0;+ }+ let mut g = z0.ceil();+ while g <= z1 {+ s += &format!("<line x1=\"{1:.1}\" y1=\"{0:.1}\" x2=\"{2:.1}\" y2=\"{0:.1}\" stroke=\"#dedad2\" stroke-width=\"1\"/>", sy(g), sx(x0), sx(x1));+ g += 1.0;+ }+ // the entrance: the front edge, and where the camera looks in from+ s += &format!("<line x1=\"{0:.1}\" y1=\"{1:.1}\" x2=\"{2:.1}\" y2=\"{1:.1}\" stroke=\"#3a7bd5\" stroke-width=\"4\"/>", sx(x0), sy(z0), sx(x1));+ s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#3a7bd5\" text-anchor=\"middle\">entrance: the camera looks in from here</text>", (sx(x0) + sx(x1)) / 2.0, sy(z0) + t * 1.3, t * 0.9);+ for o in &placed {+ let at = o.at.unwrap();+ let [fw, fd] = footprint(o);+ let invented = o.source == Some(Origin::Invented);+ let dash = if invented { " stroke-dasharray=\"8 5\"" } else { "" };+ let fill = if o.hero == Some(true) { "#f2c46d" } else if invented { "#ece8f4" } else { "#d9e4d2" };+ s += &format!(+ "<g transform=\"translate({:.1} {:.1}) rotate({:.1})\"><rect x=\"{:.1}\" y=\"{:.1}\" width=\"{:.1}\" height=\"{:.1}\" fill=\"{fill}\" stroke=\"#333\" stroke-width=\"2\"{dash}/><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"{:.1}\" stroke=\"#333\" stroke-width=\"2\"/></g>",+ sx(at[0]),+ sy(at[2]),+ -o.rot.unwrap_or(0.0),+ -fw * px / 2.0,+ -fd * px / 2.0,+ fw * px,+ fd * px,+ fd * px / 2.0+ );+ s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#111\" text-anchor=\"middle\">{}</text>", sx(at[0]), sy(at[2]) - t * 0.25, t, esc(&o.label));+ s += &format!("<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{:.0}\" fill=\"#555\" text-anchor=\"middle\">{:.2} m</text>", sx(at[0]), sy(at[2]) + t * 0.9, t * 0.8, height(o));+ }+ s += &format!("<line x1=\"20\" y1=\"{0}\" x2=\"{1:.1}\" y2=\"{0}\" stroke=\"#111\" stroke-width=\"5\"/><text x=\"20\" y=\"{2:.0}\" font-size=\"{3:.0}\" fill=\"#111\">1 m</text>", h - 18, 20.0 + px, h as f64 - 26.0, t * 0.9);+ s += "</svg>";+ Ok(s)+}++/// The blockout: a grey box for each placed object at its place and turn on a floor, seen from the entrance.+pub fn blockout_tsx(m: &Make) -> String {+ let (placed, [x0, z0, x1, z1]) = extent(m);+ let mut boxes = String::new();+ for o in &placed {+ let at = o.at.unwrap();+ let [w, d] = footprint(o);+ let h = height(o);+ let colour = if o.source == Some(Origin::Invented) { "#b4b0bd" } else { "#bdbdb8" };+ let a = -o.rot.unwrap_or(0.0).to_radians() / 2.0;+ boxes += &format!(+ " <Mesh3d transform={{Transform.fromXyz({:.3}, {:.3}, {:.3}).withRotation([0, {:.5}, 0, {:.5}])}}>\n <Cuboid half_size={{[{:.3}, {:.3}, {:.3}]}} />\n <StandardMaterial base_color=\"{colour}\" perceptual_roughness={{0.9}} />\n </Mesh3d>\n",+ at[0],+ at[1] + h / 2.0,+ at[2],+ a.sin(),+ a.cos(),+ w / 2.0,+ h / 2.0,+ d / 2.0+ );+ }+ let (cx, cz) = ((x0 + x1) / 2.0, (z0 + z1) / 2.0);+ let (fw, fd) = ((x1 - x0) / 2.0, (z1 - z0) / 2.0);+ format!(+ "// written by raea make plan: the plan as grey boxes, seen from the entrance (approve it before anything is made)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n\nfunction Blockout() {{\n return (\n <AbsoluteFill style={{{{ background: \"#cfd3d6\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, 1.6, {ez:.3}).lookingAt([{cx:.3}, 0.9, {cz:.3}])}} projection={{{{ Perspective: {{ fov: (50 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{350}} />\n <DirectionalLight transform={{Transform.fromXyz({lx:.3}, 6, -2).lookingAt([{cx:.3}, 0, {cz:.3}])}} illuminance={{8000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, -0.01, {cz:.3})}}>\n <Cuboid half_size={{[{fw:.3}, 0.01, {fd:.3}]}} />\n <StandardMaterial base_color=\"#e6e3dc\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n{boxes} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"blockout\" component={{Blockout}} width={{1280}} height={{720}} fps={{30}} durationInFrames={{1}} />);\n",+ ez = z0 - 0.4,+ lx = cx + 2.0,+ )+}++pub fn plan_dir(dir: &Path) -> PathBuf {+ dir.join("review/plan")+}++/// The plan stop's pictures: floor plan, blockout (and its review sheets), and the comparison with reference 0.+pub fn draw_plan(dir: &Path, m: &Make, review: bool) -> Result<String, String> {+ let out = plan_dir(dir);+ std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;+ let floor = out.join("floor-plan.png");+ svg_png(&floor_svg(m)?)?.save(&floor).map_err(|e| format!("{}: {e}", floor.display()))?;+ let tsx = out.join("blockout.tsx");+ std::fs::write(&tsx, blockout_tsx(m)).map_err(|e| format!("{}: {e}", tsx.display()))?;+ let shot = out.join("blockout.png");+ raea(&["render".into(), tsx.display().to_string(), "-o".into(), shot.display().to_string(), "--frame".into(), "0".into()], &[])?;+ let mut said = vec![format!("wrote {}", floor.display()), format!("wrote {}", shot.display())];+ if review {+ raea(&["render".into(), tsx.display().to_string(), "--review".into(), out.display().to_string()], &[])?;+ said.push(format!("review sheets of the blockout in {}", out.display()));+ }+ let mut row = Vec::new();+ if let Some(r) = m.references.first() {+ row.push(Tile { img: dir.join(r), label: "reference".into() });+ }+ row.push(Tile { img: shot, label: "blockout from the entrance".into() });+ row.push(Tile { img: floor, label: "floor plan".into() });+ let cmp = out.join("comparison.png");+ sheet("Plan: the reference, the blockout from the entrance, the floor plan", &[row], 640, &cmp)?;+ said.push(format!("wrote {}: approve the plan (positions, sizes, what's invented) before any generation", cmp.display()));+ Ok(said.join("\n"))+}diff --git a/apps/make/src/kit.rs b/apps/make/src/kit.rsnew file mode 100644index 00000000..09dc6d43--- /dev/null+++ b/apps/make/src/kit.rs@@ -0,0 +1,300 @@+//! A kit's steps (docs/make.feature MK10-MK12, from AnyKit): every object's reference made in one style from the+//! style images, checked on one sheet before any 3D; each reference to both generators (Tripo H3.1 and Meshy, on fal)+//! and the pick made on clay renders (kitout.rs draws the pick sheets); the pick fitted to its real size with a+//! quarter-triangle LOD beside it, each with a sidecar saying how it was made.+//!+//! raea make refs [DIR] [--only ID,...] [--model M] [--dry]+//! raea make sheet refs [DIR]+//! raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry]+//! raea make pick ID GENERATOR "why"+//! raea make prep [DIR] [--only ID,...]++use std::path::{Path, PathBuf};++use raea_core_brief::make::{Make, Object};+use serde_json::{Value, json};++use crate::sheet::{Tile, sheet};+use crate::shots::raea;++/// What every reference prompt ends with: one object, whole, on a plain ground, in even light (the scan template).+pub const SCAN: &str = "One object only, whole and centred, on a plain light grey background, soft even studio light, a three-quarter view from slightly above. Its own printed labels only, from the one maker named; no real brands, no text overlays.";+/// The two generators every reference goes to (MK11).+pub const TRIPO: &str = "tripo:H3.1";+pub const MESHY: &str = "fal:meshy/v7.1/image-to-3d";+/// Face limits: a hero, a small prop.+const HERO_FACES: u32 = 150_000;+const PROP_FACES: u32 = 60_000;++/// The objects named in `--only` (all when it's empty).+pub fn objects<'a>(m: &'a Make, only: &[String]) -> Vec<&'a Object> {+ m.objects.iter().filter(|o| only.is_empty() || only.contains(&o.id)).collect()+}++/// The prompt a reference is made from: the plan's style paragraph, the object's own words, the scan template.+pub fn ref_prompt(m: &Make, o: &Object) -> String {+ let style = m.style.as_deref().unwrap_or("").trim().trim_end_matches('.');+ let what = o.prompt.as_deref().unwrap_or(&o.label).trim().trim_end_matches('.');+ format!("{style}. {what}. {SCAN}")+}++/// `--h`, `--dims` or nothing: how gen check fits an object to its real size.+pub fn size_args(o: &Object) -> Vec<String> {+ if let Some([w, d, h]) = o.dims {+ return vec!["--dims".into(), format!("{w},{d},{h}")];+ }+ if let Some(h) = o.h {+ return vec!["--h".into(), h.to_string()];+ }+ Vec::new()+}++/// How `raea gen check -o` fits one generator's model to the object's size: its height (`--h`, which is what scales;+/// a boxy object's is the third of its dims) and, for a boxy one, a quarter turn when the model's long side lies+/// across (x) where the plan's lies front to back (z), or the other way: generators don't agree on which way is front.+/// `measured` is the raw model's [w, h, d] (`raea gen check --json`'s measured.size).+pub fn fit_args(o: &Object, measured: Option<[f64; 3]>) -> Vec<String> {+ let mut a = size_args(o);+ if let Some([w, d, h]) = o.dims {+ a.extend(["--h".into(), h.to_string()]);+ if let Some([mw, _, md]) = measured {+ let long = |x: f64, z: f64| if x > z * 1.2 { Some(true) } else if z > x * 1.2 { Some(false) } else { None };+ if let (Some(want), Some(got)) = (long(w, d), long(mw, md)) {+ if want != got {+ a.extend(["--turn".into(), "90".into()]);+ }+ }+ }+ }+ a+}++/// The raw model's size [w, h, d], measured by `raea gen check --json`.+pub fn measured_size(model: &Path) -> Option<[f64; 3]> {+ let out = raea(&["gen".into(), "check".into(), model.display().to_string(), "--json".into()], &[]).ok()?;+ let v = json_of(&out)?;+ let s = v["measured"]["size"].as_array()?;+ Some([s.first()?.as_f64()?, s.get(1)?.as_f64()?, s.get(2)?.as_f64()?])+}++/// The file a single-shot `raea gen` wrote: its JSON's `out.out`, a path or the first of a list.+pub fn gen_file(out: &str) -> Option<PathBuf> {+ let v: Value = serde_json::from_str(out.trim()).ok()?;+ let o = &v["out"]["out"];+ o.as_str().or_else(|| o.as_array()?.first()?.as_str()).map(PathBuf::from)+}++fn cents(out: &str) -> f64 {+ json_of(out).and_then(|v| v["cents"].as_f64()).unwrap_or(0.0)+}++/// raea gen's JSON from its output (anything printed before it skipped).+fn json_of(out: &str) -> Option<Value> {+ serde_json::from_str(out[out.find('{')?..].trim()).ok()+}++/// A `--plan` or `gen plan` quote in a line: what each paid step runs on, and the total.+pub fn quote(out: &str) -> String {+ let Some(v) = json_of(out) else { return out.split_whitespace().collect::<Vec<_>>().join(" ") };+ let on: Vec<&str> = v["steps"].as_array().into_iter().flatten().filter_map(|s| s["runs_on"].as_str()).filter(|r| *r != "load").collect();+ format!("{} (about {}¢)", if on.is_empty() { "nothing paid".to_string() } else { on.join(" + ") }, v["cents"].as_f64().unwrap_or(0.0))+}++pub fn refs_dir(dir: &Path) -> PathBuf {+ dir.join("out/kit/refs")+}++/// Every object's reference, made from the style images (`references`) in the plan's style; then the sheet.+pub fn refs(dir: &Path, m: &Make, only: &[String], model: Option<&str>, dry: bool) -> Result<String, String> {+ if m.references.is_empty() {+ return Err("raea make refs: the plan has no `references` (the style images every reference is made from)".into());+ }+ let mut said = Vec::new();+ let mut spent = 0.0;+ for o in objects(m, only) {+ let work = refs_dir(dir).join("gen").join(&o.id);+ let mut args: Vec<String> = vec!["gen".into(), "image".into(), ref_prompt(m, o)];+ for r in &m.references {+ args.extend(["--image".into(), dir.join(r).display().to_string()]);+ }+ args.extend(["--aspect".into(), "1:1".into(), "-o".into(), work.display().to_string()]);+ if let Some(md) = model {+ args.extend(["--model".into(), md.to_string()]);+ }+ if dry {+ args.push("--plan".into());+ let out = raea(&args, &[])?;+ spent += cents(&out);+ said.push(format!("{}: {}", o.id, quote(&out)));+ continue;+ }+ eprintln!("raea make refs: {}", o.id);+ let out = raea(&args, &[])?;+ spent += cents(&out);+ let made = gen_file(&out).ok_or_else(|| format!("{}: raea gen image wrote no file: {}", o.id, out.trim()))?;+ let to = refs_dir(dir).join(format!("{}.png", o.id));+ std::fs::copy(&made, &to).map_err(|e| format!("{}: {e}", to.display()))?;+ said.push(format!("{}: {}", o.id, to.display()));+ }+ if dry {+ return Ok(format!("would make {} reference{} for about ${:.2} (nothing spent):\n{}", said.len(), if said.len() == 1 { "" } else { "s" }, spent / 100.0, said.join("\n")));+ }+ let sheet = sheet_refs(dir, m)?;+ Ok(format!("{}\n{sheet}\nspent about ${:.2}", said.join("\n"), spent / 100.0))+}++/// The reference sheet: the style images first, then every object's reference, labelled with its id and size.+pub fn sheet_refs(dir: &Path, m: &Make) -> Result<String, String> {+ let style: Vec<Tile> = m.references.iter().enumerate().map(|(i, r)| Tile { img: dir.join(r), label: format!("style {}", i + 1) }).collect();+ let refs: Vec<Tile> = m+ .objects+ .iter()+ .map(|o| {+ let size = o.h.map(|h| format!("{h} m tall")).or(o.dims.map(|d| format!("{} x {} x {} m", d[0], d[1], d[2]))).or(o.max.map(|x| format!("{x} m long"))).unwrap_or_default();+ Tile { img: refs_dir(dir).join(format!("{}.png", o.id)), label: format!("{} {size}", o.id) }+ })+ .collect();+ let mut rows = vec![style];+ rows.extend(refs.chunks(4).map(|c| c.iter().map(|t| Tile { img: t.img.clone(), label: t.label.clone() }).collect()));+ let file = dir.join("review/refs.png");+ sheet("Reference sheet: the style, then every object's reference", &rows, 320, &file)?;+ Ok(format!("wrote {}: regenerate an outlier before any 3D (raea make refs --only ID); ask it: raea ask {} --std make.refs.outlier --std make.refs.two_objects --std make.refs.brands", file.display(), file.display()))+}++/// The flow that sends one reference to both generators, each at its face limit.+pub fn gen_flow(m: &Make, o: &Object, reference: &Path, tripo: &str, meshy: &str) -> Value {+ let faces = if o.hero == Some(true) { HERO_FACES } else { PROP_FACES };+ let prompt = o.prompt.clone().unwrap_or_else(|| o.label.clone());+ let _ = m;+ json!({"flow": 1, "steps": {+ "ref": {"op": "media.load", "in": {"path": reference.display().to_string()}},+ "tripo": {"op": "mesh.generate", "model": tripo, "in": {"prompt": prompt, "image": "@ref", "x_face_limit": faces}},+ "meshy": {"op": "mesh.generate", "model": meshy, "in": {"prompt": prompt, "image": "@ref"}}+ }, "out": ["tripo", "meshy"]})+}++pub fn gen_dir(dir: &Path, id: &str) -> PathBuf {+ dir.join("out/kit/gen").join(id)+}++/// Every reference to both generators: out/kit/gen/ID/tripo.glb and meshy.glb.+pub fn generate(dir: &Path, m: &Make, only: &[String], tripo: &str, meshy: &str, dry: bool) -> Result<String, String> {+ let mut said = Vec::new();+ let mut spent = 0.0;+ for o in objects(m, only) {+ let reference = refs_dir(dir).join(format!("{}.png", o.id));+ if !reference.is_file() {+ return Err(format!("raea make gen: no reference for {} ({}): raea make refs --only {}", o.id, reference.display(), o.id));+ }+ let to = gen_dir(dir, &o.id);+ // both models already there: a rerun (after a stop, or for the pieces still missing) doesn't pay twice+ if !dry && to.join("tripo.glb").is_file() && to.join("meshy.glb").is_file() {+ said.push(format!("{}: already made ({})", o.id, to.display()));+ continue;+ }+ std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;+ if !dry {+ eprintln!("raea make gen: {} on {tripo} and {meshy} (a few minutes each)", o.id);+ }+ let flow = to.join("flow.json");+ std::fs::write(&flow, serde_json::to_string_pretty(&gen_flow(m, o, &reference, tripo, meshy)).unwrap_or_default()).map_err(|e| e.to_string())?;+ // quoted first: the run is capped at its own quote (a little over, for rounding), never gen's default cap+ let plan = raea(&["gen".into(), "plan".into(), flow.display().to_string()], &[])?;+ let out = if dry {+ plan+ } else {+ let cap = (cents(&plan) * 1.1).ceil().max(1.0) as u64;+ raea(&["gen".into(), "run".into(), flow.display().to_string(), "-o".into(), to.display().to_string(), "--max-cents".into(), cap.to_string()], &[])?+ };+ spent += cents(&out);+ said.push(if dry { format!("{}: {}", o.id, quote(&out)) } else { format!("{}: {}", o.id, to.display()) });+ }+ let tail = if dry { format!("about ${:.2} in all; nothing spent", spent / 100.0) } else { format!("spent about ${:.2}; next: raea make pick-sheet", spent / 100.0) };+ Ok(format!("{}\n{tail}", said.join("\n")))+}++/// The model a pick's generator ran (from its flow.json), for the sidecar.+fn pick_model(dir: &Path, id: &str, generator: &str) -> String {+ let flow: Option<Value> = std::fs::read_to_string(gen_dir(dir, id).join("flow.json")).ok().and_then(|t| serde_json::from_str(&t).ok());+ flow.and_then(|f| f["steps"][generator]["model"].as_str().map(String::from)).unwrap_or_else(|| generator.to_string())+}++pub fn picks_file(dir: &Path) -> PathBuf {+ dir.join("out/kit/picks.json")+}++/// The picks so far, by object id: {generator, why}.+pub fn picks(dir: &Path) -> serde_json::Map<String, Value> {+ std::fs::read_to_string(picks_file(dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()+}++/// One object's pick and why, recorded (MK11).+pub fn choose(dir: &Path, m: &Make, id: &str, generator: &str, why: &str) -> Result<String, String> {+ if !m.objects.iter().any(|o| o.id == id) {+ return Err(format!("raea make pick: no object `{id}` in the plan"));+ }+ let glb = gen_dir(dir, id).join(format!("{generator}.glb"));+ if !glb.is_file() {+ return Err(format!("raea make pick: no {} (the generators are tripo and meshy: raea make gen --only {id})", glb.display()));+ }+ if why.trim().is_empty() {+ return Err("raea make pick: say why in one line (\"sharper dial numerals; Tripo fused the handset to the cradle\")".into());+ }+ let mut p = picks(dir);+ p.insert(id.into(), json!({"generator": generator, "why": why.trim()}));+ let f = picks_file(dir);+ std::fs::write(&f, serde_json::to_string_pretty(&p).unwrap_or_default()).map_err(|e| format!("{}: {e}", f.display()))?;+ Ok(format!("picked {generator} for {id}: {}", why.trim()))+}++/// The triangles gen check measured.+fn triangles(glb: &Path) -> Result<u64, String> {+ let out = raea(&["gen".into(), "check".into(), glb.display().to_string(), "--json".into()], &[]).or_else(|e| if e.contains('{') { Ok(e) } else { Err(e) })?;+ let v: Value = serde_json::from_str(out.trim()).map_err(|e| format!("gen check {}: {e}", glb.display()))?;+ v["measured"]["triangles"].as_u64().ok_or_else(|| format!("gen check couldn't read {}", glb.display()))+}++/// Each pick fitted to its real size (front -Y, bottom-centre, metres) and a quarter-triangle LOD1 beside it, each+/// with a sidecar saying how it was made (MK12).+pub fn prep(dir: &Path, m: &Make, only: &[String]) -> Result<String, String> {+ let p = picks(dir);+ let mut said = Vec::new();+ for o in objects(m, only) {+ let Some(pick) = p.get(&o.id) else {+ said.push(format!("{}: no pick yet (raea make pick {} tripo|meshy \"why\")", o.id, o.id));+ continue;+ };+ let generator = pick["generator"].as_str().unwrap_or("tripo");+ let src = gen_dir(dir, &o.id).join(format!("{generator}.glb"));+ let to = dir.join("out/kit").join(&o.id);+ std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;+ let full = to.join(format!("{}.glb", o.id));+ let mut args = vec!["gen".into(), "check".into(), src.display().to_string()];+ args.extend(fit_args(o, measured_size(&src)));+ args.extend(["-o".into(), full.display().to_string()]);+ // gen check exits non-zero on a finding it can't fix; the fitted copy is still written, and its findings said+ let _ = raea(&args, &[]);+ if !full.is_file() {+ return Err(format!("{}: gen check wrote no fitted copy of {}", o.id, src.display()));+ }+ let tris = triangles(&full)?;+ let lod = to.join(format!("{}_lod1.glb", o.id));+ let quarter = (tris / 4).max(500);+ let model = pick_model(dir, &o.id, generator);+ // the sidecar the Blender scripts carry along (source, licence, credit) and how it was made: ours, generated+ let made = |what: &str, tris: u64| {+ json!({"source": format!("generated by raea make: {model} from out/kit/refs/{}.png", o.id), "license": "ours (generated for this project)", "credit": "",+ "made": {"by": "raea make (docs/make.feature)", "route": "gen", "generator": generator, "model": model, "why": pick["why"], "prompt": o.prompt, "reference": format!("out/kit/refs/{}.png", o.id),+ "style": m.style, "what": what, "triangles": tris, "source": if o.source.is_some() { json!(o.source) } else { Value::Null }}})+ };+ std::fs::write(full.with_extension("glb.json"), serde_json::to_string_pretty(&made("fitted to its real size", tris)).unwrap_or_default()).map_err(|e| e.to_string())?;+ raea(&["blender".into(), "run".into(), "blender/decimate.py".into(), full.display().to_string(), lod.display().to_string(), quarter.to_string()], &[])?;+ // decimate.py wrote the LOD's sidecar from the model's, with its step; it says what it is, over the copy+ let side = lod.with_extension("glb.json");+ let mut v: Value = std::fs::read_to_string(&side).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_else(|| made("", 0));+ v["made"] = made("LOD1: a quarter of the fitted model's triangles", quarter)["made"].clone();+ std::fs::write(&side, serde_json::to_string_pretty(&v).unwrap_or_default()).map_err(|e| e.to_string())?;+ said.push(format!("{}: {} ({tris} triangles) and its LOD1 ({quarter})", o.id, full.display()));+ }+ Ok(said.join("\n"))+}diff --git a/apps/make/src/kitout.rs b/apps/make/src/kitout.rsnew file mode 100644index 00000000..d33ce44a--- /dev/null+++ b/apps/make/src/kitout.rs@@ -0,0 +1,216 @@+//! The kit's sheets and its landing (docs/make.feature MK11, MK13): the pick sheet (each object's reference beside+//! both generators' models, each in colour and in clay, drawn in raea), and the kit landed as a component set (one+//! component per object, its model and LOD imported beside it, so it travels as one folder), a `<Lineup>` of them all+//! with a scale bar, a thumb each, and kit.json.+//!+//! raea make pick-sheet [DIR] [--only ID,...]+//! raea make kit [DIR] [--name KIT] [--to FOLDER]++use std::path::{Path, PathBuf};++use raea_core_brief::make::{Make, Object};+use serde_json::{Value, json};++use crate::kit::{gen_dir, objects, picks};+use crate::sheet::{Tile, sheet};+use crate::shots::raea;++/// The tallest side an object will have once fitted, metres (for framing it): its height, its box, or its longest side.+pub fn tall(o: &Object) -> f64 {+ o.h.or(o.dims.map(|d| d[2])).or(o.max).unwrap_or(0.5).max(0.02)+}++/// The size a model is framed to: its biggest side (a stapler is framed by its length, not its height).+pub fn frame_size(o: &Object) -> f64 {+ o.dims.map(|[w, d, h]| w.max(d).max(h)).unwrap_or_else(|| tall(o))+}++/// A composition showing one model alone, fitted (bottom-centred at the origin, metres), on a pale floor in a+/// three-quarter view from slightly above, framed to its height.+pub fn viewer(model: &Path, h: f64) -> String {+ let d = h * 3.2 + 0.06;+ let m = model.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();+ format!(+ "// written by raea make (pick sheet, kit thumbs): one model, framed to its height\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ Model }} from \"raea/3d\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\nimport model from \"./{m}\";\n\nfunction View() {{\n return (\n <AbsoluteFill style={{{{ background: \"#d9d6d0\" }}}}>\n <Camera3d transform={{Transform.fromXyz({x:.3}, {y:.3}, {z:.3}).lookingAt([0, {cy:.3}, 0])}} projection={{{{ Perspective: {{ fov: (30 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{300}} />\n <DirectionalLight transform={{Transform.fromXyz(2, 5, 3).lookingAt([0, 0, 0])}} illuminance={{9000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz(0, -0.005, 0)}}>\n <Cuboid half_size={{[{g:.2}, 0.005, {g:.2}]}} />\n <StandardMaterial base_color=\"#cfccc6\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n <Model src={{model}} />\n </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"view\" component={{View}} width={{768}} height={{768}} fps={{30}} durationInFrames={{1}} />);\n",+ x = d * 0.62,+ y = h * 0.55 + d * 0.32,+ z = d * 0.78,+ cy = h * 0.45,+ g = (h * 4.0).max(1.0),+ )+}++/// One model drawn in colour and in clay: (colour.png, clay.png) beside it.+pub fn draw(model: &Path, h: f64) -> Result<(PathBuf, PathBuf), String> {+ let dir = model.parent().ok_or("a model's folder")?;+ let stem = model.file_stem().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();+ let tsx = dir.join(format!("{stem}.view.tsx"));+ std::fs::write(&tsx, viewer(model, h)).map_err(|e| format!("{}: {e}", tsx.display()))?;+ let (colour, clay) = (dir.join(format!("{stem}.colour.png")), dir.join(format!("{stem}.clay.png")));+ raea(&["render".into(), tsx.display().to_string(), "-o".into(), colour.display().to_string(), "--frame".into(), "0".into()], &[])?;+ raea(&["render".into(), tsx.display().to_string(), "-o".into(), clay.display().to_string(), "--frame".into(), "0".into(), "--clay".into()], &[])?;+ Ok((colour, clay))+}++/// The pick sheet: a row an object, its reference, then each generator's model fitted to size, in colour and in clay.+pub fn pick_sheet(dir: &Path, m: &Make, only: &[String]) -> Result<String, String> {+ let mut rows = Vec::new();+ for o in objects(m, only) {+ let g = gen_dir(dir, &o.id);+ let mut row = vec![Tile { img: crate::kit::refs_dir(dir).join(format!("{}.png", o.id)), label: format!("{} reference", o.id) }];+ for generator in ["tripo", "meshy"] {+ let raw = g.join(format!("{generator}.glb"));+ if !raw.is_file() {+ row.push(Tile { img: g.join("none.png"), label: format!("{generator}: not made") });+ continue;+ }+ // fitted to its real size first, so both are framed alike+ let fit = g.join(format!("{generator}.fit.glb"));+ let mut args = vec!["gen".into(), "check".into(), raw.display().to_string()];+ args.extend(crate::kit::fit_args(o, crate::kit::measured_size(&raw)));+ args.extend(["-o".into(), fit.display().to_string()]);+ let _ = raea(&args, &[]);+ let shown = if fit.is_file() { fit } else { raw };+ let (colour, clay) = draw(&shown, frame_size(o))?;+ row.push(Tile { img: colour, label: generator.to_string() });+ row.push(Tile { img: clay, label: format!("{generator} clay") });+ }+ rows.push(row);+ }+ if rows.is_empty() {+ return Err("raea make pick-sheet: no objects in the plan (or none named)".into());+ }+ let file = dir.join("review/picks.png");+ sheet("Pick sheet: reference | Tripo | Tripo clay | Meshy | Meshy clay", &rows, 300, &file)?;+ Ok(format!("wrote {}: judge each on its clay (fused parts, blobs, fidelity to the reference), then: raea make pick ID tripo|meshy \"why\"", file.display()))+}++/// A component's name from an object id: rotary_phone -> RotaryPhone.+pub fn component_name(id: &str) -> String {+ id.split(['_', '-']).filter(|w| !w.is_empty()).map(|w| w[..1].to_uppercase() + &w[1..]).collect()+}++/// One object's component: its model imported beside it, its LOD for far away, placed by the props a composition gives.+pub fn component(o: &Object, why: &str) -> String {+ let n = component_name(&o.id);+ format!(+ "// raea component add: {label}, {h} m, from the kit's style (raea make kit; {why})\nimport {{ Model }} from \"raea/3d\";\nimport full from \"./{id}.glb\";\nimport far from \"./{id}_lod1.glb\";\n\ntype Props = {{\n position?: [number, number, number];\n rotation?: [number, number, number];\n /** the quarter-triangle model, for when it's small on screen */\n lod?: boolean;\n}};\n\n/** {label}: fitted to its real size, its bottom at the origin, its front toward +z. */\nexport default function {n}({{ position = [0, 0, 0], rotation = [0, 0, 0], lod = false }}: Props) {{\n return <Model src={{lod ? far : full}} position={{position}} rotation={{rotation}} />;\n}}\n",+ label = o.label,+ h = tall(o),+ id = o.id,+ why = why.replace('\n', " "),+ )+}++/// The lineup: every component side by side in the plan's order, gaps between, a label each lying in front of the pieces and a+/// scale bar (the longest round length the set covers), seen from a little right of centre and above.+pub fn lineup(m: &Make, kit: &str) -> String {+ let mut imports = String::new();+ let mut parts = String::new();+ let mut x = 0.0;+ let foot = |o: &Object| o.dims.map(|d| (d[0], d[1])).unwrap_or((tall(o) * 0.8, tall(o) * 0.8));+ let widths: Vec<f64> = m.objects.iter().map(|o| foot(o).0).collect();+ let gap = (widths.iter().cloned().fold(0.0, f64::max) * 0.6).clamp(0.03, 0.3);+ let total: f64 = widths.iter().sum::<f64>() + gap * (m.objects.len().saturating_sub(1)) as f64;+ let highest = m.objects.iter().map(tall).fold(0.02, f64::max);+ let deepest = m.objects.iter().map(|o| foot(o).1).fold(0.02, f64::max);+ // labels lie on the floor in front of every piece, so none hides one; the bar in front of them+ let fs = (total * 0.035).clamp(0.01, 0.06);+ let lz = deepest / 2.0 + fs * 1.9;+ let (bar, bar_label) = scale_bar(total);+ let bz = lz + fs * 2.8;+ for (o, w) in m.objects.iter().zip(&widths) {+ let n = component_name(&o.id);+ imports.push_str(&format!("import {n} from \"./{n}\";\n"));+ let cx = x + w / 2.0 - total / 2.0;+ parts.push_str(&format!(" <{n} position={{[{cx:.3}, 0, 0]}} />\n <Mesh3d transform={{Transform.fromXyz({cx:.3}, 0.002, {lz:.3}).withRotation(FLAT)}}>\n <Text3D size={{{fs:.3}}} depth={{0.001}} read={{false}}>{{{label:?}}}</Text3D>\n <StandardMaterial base_color=\"#2a2a2a\" />\n </Mesh3d>\n", label = o.label));+ x += w + gap;+ }+ // framed to the set: wide enough for every piece, tall enough for the highest and the bar in front, from a little+ // to the right and above, so a long piece shows its length+ let d = (total * 1.45).max(highest * 4.2).max(bz * 3.0).max(0.35);+ let (cx, cy, cz) = (d * 0.34, highest * 0.5 + d * 0.36, d * 0.88 + bz * 0.5);+ format!(+ "// raea make kit: the {kit} kit's lineup, every piece at its real size beside a {bar_label} bar (the kit's cover)\nimport {{ AbsoluteFill, Composition, registerRoot }} from \"raea\";\nimport {{ Text3D }} from \"raea/3d\";\nimport {{ StandardMaterial }} from \"raea/pbr\";\nimport {{ Cuboid, Mesh3d }} from \"raea/mesh\";\nimport {{ AmbientLight, DirectionalLight }} from \"raea/light\";\nimport {{ Transform }} from \"raea/transform\";\nimport {{ Camera3d }} from \"raea/camera\";\n{imports}\n// lying flat on the floor, reading toward the camera\nconst FLAT: [number, number, number, number] = [-0.7071068, 0, 0, 0.7071068];\n\nexport function Lineup() {{\n return (\n <AbsoluteFill style={{{{ background: \"#d6d2ca\" }}}}>\n <Camera3d transform={{Transform.fromXyz({cx:.3}, {cy:.3}, {cz:.3}).lookingAt([0, {ty:.3}, {tz:.3}])}} projection={{{{ Perspective: {{ fov: (30 * Math.PI) / 180 }} }}}} />\n <AmbientLight brightness={{300}} />\n <DirectionalLight transform={{Transform.fromXyz(2, 6, 4).lookingAt([0, 0, 0])}} illuminance={{9000}} shadow_maps_enabled />\n <Mesh3d transform={{Transform.fromXyz(0, -0.005, 0)}}>\n <Cuboid half_size={{[{g:.2}, 0.005, {g:.2}]}} />\n <StandardMaterial base_color=\"#d6d2ca\" perceptual_roughness={{0.95}} />\n </Mesh3d>\n <Mesh3d transform={{Transform.fromXyz({bx:.3}, 0.002, {bz:.3})}}>\n <Cuboid half_size={{[{bh:.3}, 0.002, {bt:.4}]}} />\n <StandardMaterial base_color=\"#202020\" />\n </Mesh3d>\n <Mesh3d transform={{Transform.fromXyz({bx:.3}, 0.002, {blz:.3}).withRotation(FLAT)}}>\n <Text3D size={{{fs:.3}}} depth={{0.001}} read={{false}}>{bar_label}</Text3D>\n <StandardMaterial base_color=\"#202020\" />\n </Mesh3d>\n{parts} </AbsoluteFill>\n );\n}}\n\nregisterRoot(() => <Composition id=\"lineup\" component={{Lineup}} width={{1920}} height={{1080}} fps={{30}} durationInFrames={{1}} />);\n",+ ty = highest * 0.35,+ tz = bz * 0.45,+ // a floor past every edge of the frame (the review's views leave a ground slab out of their framing)+ g = (total * 3.0).max(2.0),+ bh = bar / 2.0,+ bt = fs * 0.25,+ bx = -total / 2.0 + bar / 2.0,+ blz = bz + fs * 1.3,+ )+}++/// The scale bar for a set this wide: the longest round length that fits under it, and its label.+pub fn scale_bar(width: f64) -> (f64, &'static str) {+ [(1.0, "1 m"), (0.5, "50 cm"), (0.25, "25 cm"), (0.1, "10 cm"), (0.05, "5 cm")].into_iter().find(|(l, _)| *l <= width.max(0.05)).unwrap_or((0.05, "5 cm"))+}++/// Where a kit lands: `--to`, else the workspace's shared/components/KIT (every project imports it as+/// @shared/components/KIT), else the project's components/KIT.+pub fn kit_dir(dir: &Path, kit: &str, to: Option<&str>) -> PathBuf {+ if let Some(t) = to {+ return PathBuf::from(t);+ }+ if let Some(ws) = raea_core_facts::record::up(dir, ".raea/workspace") {+ let shared = if !ws.join("shared").is_dir() && ws.join("components").is_dir() { ws.join("components") } else { ws.join("shared/components") };+ return shared.join(kit);+ }+ let project = raea_core_facts::record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());+ project.join("components").join(kit)+}++fn copy(a: &Path, b: &Path) -> Result<(), String> {+ std::fs::copy(a, b).map(|_| ()).map_err(|e| format!("{} -> {}: {e}", a.display(), b.display()))+}++/// The kit landed: each prepped object's model, LOD and sidecars, its component and thumb; the lineup and its cover+/// render; kit.json. Objects not prepped yet are named, not skipped silently.+pub fn land(dir: &Path, m: &Make, name: Option<&str>, to: Option<&str>) -> Result<String, String> {+ let kit = name.map(str::to_string).unwrap_or_else(|| dir.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or("kit".into()));+ let dest = kit_dir(dir, &kit, to);+ std::fs::create_dir_all(dest.join("thumbs")).map_err(|e| format!("{}: {e}", dest.display()))?;+ let p = picks(dir);+ let (mut items, mut missing) = (Vec::new(), Vec::new());+ for o in &m.objects {+ let from = dir.join("out/kit").join(&o.id);+ let (full, lod) = (from.join(format!("{}.glb", o.id)), from.join(format!("{}_lod1.glb", o.id)));+ if !full.is_file() || !lod.is_file() {+ missing.push(o.id.clone());+ continue;+ }+ for f in [&full, &lod] {+ let name = f.file_name().unwrap();+ copy(f, &dest.join(name))?;+ let side = f.with_extension("glb.json");+ if side.is_file() {+ copy(&side, &dest.join(format!("{}.json", name.to_string_lossy())))?;+ }+ }+ let why = p.get(&o.id).and_then(|v| v["why"].as_str()).unwrap_or("");+ let n = component_name(&o.id);+ std::fs::write(dest.join(format!("{n}.tsx")), component(o, why)).map_err(|e| e.to_string())?;+ let (colour, _) = draw(&full, frame_size(o))?;+ copy(&colour, &dest.join("thumbs").join(format!("{}.png", o.id)))?;+ std::fs::create_dir_all(dir.join("out/kit/thumbs")).map_err(|e| e.to_string())?;+ copy(&colour, &dir.join("out/kit/thumbs").join(format!("{}.png", o.id)))?;+ items.push(json!({"id": o.id, "label": o.label, "component": format!("{n}.tsx"), "model": format!("{}.glb", o.id), "lod1": format!("{}_lod1.glb", o.id),+ "thumb": format!("thumbs/{}.png", o.id), "h": tall(o), "pick": p.get(&o.id).cloned().unwrap_or(Value::Null)}));+ }+ if !missing.is_empty() {+ return Err(format!("raea make kit: not prepped yet: {} (raea make prep --only {})", missing.join(", "), missing.join(",")));+ }+ let lineup_tsx = dest.join("lineup.tsx");+ std::fs::write(&lineup_tsx, lineup(m, &kit)).map_err(|e| e.to_string())?;+ let cover = dest.join("cover.png");+ raea(&["render".into(), lineup_tsx.display().to_string(), "-o".into(), cover.display().to_string(), "--frame".into(), "0".into()], &[])?;+ let doc = json!({"kit": kit, "style": m.style, "references": m.references, "items": items, "lineup": "lineup.tsx", "cover": "cover.png", "landed": dest.display().to_string(), "made": {"by": "raea make kit (docs/make.feature MK13)"}});+ let text = serde_json::to_string_pretty(&doc).unwrap_or_default();+ std::fs::write(dest.join("kit.json"), &text).map_err(|e| e.to_string())?;+ // the job's own record of it, what `raea make status` counts (core/brief deliverables)+ std::fs::write(dir.join("out/kit/kit.json"), &text).map_err(|e| e.to_string())?;+ copy(&cover, &dir.join("out/kit/lineup.png"))?;+ Ok(format!("landed the {kit} kit ({} pieces) in {}: components, lineup.tsx, cover.png, thumbs/, kit.json", items.len(), dest.display()))+}diff --git a/apps/make/src/lib.rs b/apps/make/src/lib.rsindex f82f00ac..b07fedb1 100644--- a/apps/make/src/lib.rs+++ b/apps/make/src/lib.rs@@ -2,8 +2,16 @@//! review loop (docs/make.feature). `status` decides, in code, what's missing and whether the agent may stop; the Stop//! hook (apps/check hook.rs) asks it at the end of every turn.//!-//! raea make status [DIR] [--json]+//! raea make status [DIR] [--json] [--plan] (--plan: the gates as check lines in plan.org, MK3)+//! raea make plan|refs|sheet refs|gen|pick-sheet|pick|prep|kit|framing|lenschart ... (the steps, USAGE)+pub mod asked;+pub mod floor;+pub mod kit;+pub mod kitout;+pub mod plan;+pub mod sheet;+pub mod shots;pub mod status;use std::path::{Path, PathBuf};@@ -11,7 +19,17 @@ use std::path::{Path, PathBuf};use raea_core_brief::make::Make;use serde_json::Value;-pub const USAGE: &str = "raea make status [DIR] [--json] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate, the judge's rounds, and whether it's done, decided in code; the agent's Stop hook holds it there)";+pub const USAGE: &str = "raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)+ raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)+ raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)+ raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)+ raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry] (each reference to both generators, Tripo H3.1 and Meshy on fal: out/kit/gen/ID/)+ raea make pick-sheet [DIR] [--only ID,...] (review/picks.png: reference | Tripo | Tripo clay | Meshy | Meshy clay, fitted to size)+ raea make pick ID tripo|meshy \"why\" [DIR] (the pick and its reason, out/kit/picks.json)+ raea make prep [DIR] [--only ID,...] (each pick fitted to its real size, a quarter-triangle _lod1 beside it, .glb.json sidecars)+ raea make kit [DIR] [--name KIT] [--to FOLDER] (the kit as a component set: shared/components/KIT, lineup.tsx, cover.png, thumbs, kit.json)+ raea make framing [DIR] [--only NAME,...] [--out DIR] (a shot list: each shot's first, middle and last frame on framing.png, stamped)+ raea make lenschart SHOT [DIR] [--out DIR] (a shot's first frame at 18, 24, 35, 50, 85 and 135 mm on lens-SHOT.png)";/// The brief.ts the job is read from: DIR's own, else the nearest above it inside its raea project.pub fn brief_path(dir: &Path) -> Option<PathBuf> {@@ -50,11 +68,15 @@ pub fn read_make(brief: &Path) -> Result<Option<Make>, String> {}/// The judge's rounds beside the brief (review/judge.log.jsonl, as `raea judge` keeps them), the newest round's-/// judge.json, and when the log was last written.+/// verdict (judge.json, or judge.BY.json for an agent critic), and when the log was last written.fn judged(dir: &Path) -> (Vec<Value>, Option<Value>, Option<std::time::SystemTime>) {let log = dir.join("review").join("judge.log.jsonl");let rounds: Vec<Value> = std::fs::read_to_string(&log).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect();- let verdict = rounds.last().and_then(|r| r["dir"].as_str()).and_then(|d| std::fs::read_to_string(Path::new(d).join("judge.json")).ok()).and_then(|t| serde_json::from_str(&t).ok());+ let verdict = rounds.last().and_then(|r| {+ let d = status::round_dir(dir, r)?;+ let file = r["by"].as_str().filter(|b| *b != "clef").map_or_else(|| "judge.json".to_string(), |b| format!("judge.{b}.json"));+ serde_json::from_str(&std::fs::read_to_string(d.join(file)).ok()?).ok()+ });let at = std::fs::metadata(&log).and_then(|m| m.modified()).ok();(rounds, verdict, at)}@@ -65,7 +87,8 @@ pub fn status_of(brief: &Path, make: &Make) -> Value {let project = raea_core_facts::record::up(dir, ".raea/project");let record = project.as_deref().map(raea_core_facts::record::read).unwrap_or_default();let (rounds, verdict, judged_at) = judged(dir);- let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at };+ let ledger = asked::Ledger::read();+ let job = status::Job { make, dir, project: project.as_deref(), record: &record, rounds: &rounds, verdict: verdict.as_ref(), judged_at, ledger: &ledger, score_gates: raea_app_judge::kind_gates(status::kind_name(make.kind)) };let mut s = status::status(&job);s["brief"] = Value::String(brief.display().to_string());s@@ -78,20 +101,107 @@ pub fn status_in(dir: &Path) -> Result<Option<Value>, String> {Ok(Some(status_of(&brief, &make)))}+/// The flags that take a value: what follows them isn't a positional argument.+const VALUED: [&str; 7] = ["--only", "--model", "--tripo", "--meshy", "--name", "--to", "--out"];++fn flag<'a>(args: &'a [String], k: &str) -> Option<&'a str> {+ args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).map(String::as_str)+}++/// The positional arguments after the verb (words), flags and their values left out.+pub fn positional(args: &[String], skip: usize) -> Vec<String> {+ let mut out = Vec::new();+ let mut i = skip;+ while i < args.len() {+ if VALUED.contains(&args[i].as_str()) {+ i += 2;+ continue;+ }+ if !args[i].starts_with("--") {+ out.push(args[i].clone());+ }+ i += 1;+ }+ out+}++fn list(args: &[String], k: &str) -> Vec<String> {+ flag(args, k).map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default()+}++/// The job's brief and plan from a folder.+fn job(dir: &Path) -> Result<(PathBuf, Make), String> {+ let brief = brief_path(dir).ok_or_else(|| format!("raea make: no brief.ts at or above {} in its project", dir.display()))?;+ let make = read_make(&brief)?.ok_or_else(|| format!("raea make: {} has no `make` (scene(), kit() or shot() from raea/brief)", brief.display()))?;+ Ok((brief, make))+}++/// The steps: each reads the plan from DIR's brief.ts and works beside it.+fn step(verb: &str, args: &[String]) -> Result<String, String> {+ let skip = if verb == "sheet" { 3 } else { 2 };+ let pos = positional(args, skip);+ let (words, dir_at) = match verb {+ "pick" => (3, 3),+ "lenschart" => (1, 1),+ _ => (0, 0),+ };+ if pos.len() < words {+ return Err(USAGE.into());+ }+ let dir = pos.get(dir_at).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));+ let (brief, m) = job(&dir)?;+ let here = brief.parent().unwrap_or(Path::new(".")).to_path_buf();+ let only = list(args, "--only");+ let dry = args.iter().any(|a| a == "--dry");+ let out_or = |d: PathBuf| flag(args, "--out").map(PathBuf::from).unwrap_or(d);+ match verb {+ "plan" => floor::draw_plan(&here, &m, !args.iter().any(|a| a == "--no-review")),+ "refs" => kit::refs(&here, &m, &only, flag(args, "--model"), dry),+ "sheet" => match args.get(2).map(String::as_str) {+ Some("refs") => kit::sheet_refs(&here, &m),+ Some("picks") => kitout::pick_sheet(&here, &m, &only),+ Some("framing") => shots::framing(&here, &m, &only, &out_or(here.join("review"))),+ _ => Err("raea make sheet refs|picks|framing [DIR]".into()),+ },+ "gen" => kit::generate(&here, &m, &only, flag(args, "--tripo").unwrap_or(kit::TRIPO), flag(args, "--meshy").unwrap_or(kit::MESHY), dry),+ "pick-sheet" => kitout::pick_sheet(&here, &m, &only),+ "pick" => kit::choose(&here, &m, &pos[0], &pos[1], &pos[2]),+ "prep" => kit::prep(&here, &m, &only),+ "kit" => kitout::land(&here, &m, flag(args, "--name"), flag(args, "--to")),+ "framing" => shots::framing(&here, &m, &only, &out_or(here.join("review"))),+ "lenschart" => shots::lenschart(&here, &m, &pos[0], &out_or(here.join("review"))),+ _ => Err(USAGE.into()),+ }+}+pub fn cli(args: &[String]) -> Result<String, String> {match args.get(1).map(String::as_str) {Some("status") => {}+ Some(v @ ("plan" | "refs" | "sheet" | "gen" | "pick-sheet" | "pick" | "prep" | "kit" | "framing" | "lenschart")) => return step(v, args),_ => return Err(USAGE.into()),}- let dir = args.iter().skip(2).find(|a| !a.starts_with("--")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));- let brief = brief_path(&dir).ok_or_else(|| format!("raea make: no brief.ts at or above {} in its project", dir.display()))?;- let make = read_make(&brief)?.ok_or_else(|| format!("raea make: {} has no `make` (scene(), kit() or shot() from raea/brief)", brief.display()))?;- let s = status_of(&brief, &make);+ let dir = positional(args, 2).first().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));+ let (brief, make) = job(&dir)?;+ let mut s = status_of(&brief, &make);+ if args.iter().any(|a| a == "--plan") {+ let dir = brief.parent().unwrap_or(Path::new("."));+ let root = raea_core_facts::record::up(dir, ".raea/project").unwrap_or_else(|| dir.to_path_buf());+ let kind = s["kind"].as_str().unwrap_or("make").to_string();+ let (file, task) = plan::write(&root, &brief, &kind, &s)?;+ s["planOrg"] = Value::String(file.display().to_string());+ s["planTask"] = Value::String(task);+ }if args.iter().any(|a| a == "--json") {return Ok(serde_json::to_string_pretty(&s).unwrap_or_default());}- Ok(status::text(&s))+ let mut t = status::text(&s);+ if let (Some(p), Some(task)) = (s["planOrg"].as_str(), s["planTask"].as_str()) {+ t.push_str(&format!("\nplan.org: the gates are check lines under task {task} in {p}"));+ }+ Ok(t)}#[cfg(test)]mod tests;+#[cfg(test)]+mod tests_steps;diff --git a/apps/make/src/plan.rs b/apps/make/src/plan.rsnew file mode 100644index 00000000..1322b605--- /dev/null+++ b/apps/make/src/plan.rs@@ -0,0 +1,89 @@+//! The job's gates in the project's plan.org (docs/make.feature MK3; docs/plan.feature PL1): one task, its :ID: from the+//! brief's path, each gate and each missing thing a check line under it with a progress cookie, so the person, the app+//! and raea cloud read the same list the Stop hook holds the agent to. MAKING while it isn't done, REVIEW once it is+//! (the person closes it); a task the person marked DONE or DROPPED keeps their mark, and their own lines under it stay.++use std::path::Path;++use serde_json::Value;++/// The task's id: t- and eight letters and digits (PL1b), the same for the same brief.+pub fn task_id(brief_rel: &str) -> String {+ let h = brief_rel.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));+ format!("t-mk{:06x}", h & 0xff_ffff)+}++fn is_check(line: &str) -> bool {+ let t = line.trim_start();+ let rest = t.strip_prefix("- ").or_else(|| t.strip_prefix("+ "));+ rest.is_some_and(|r| r.starts_with("[ ]") || r.starts_with("[X]") || r.starts_with("[x]") || r.starts_with("[-]"))+}++fn short(s: &str) -> String {+ let s = s.replace('\n', " ");+ if s.chars().count() > 140 { format!("{}…", s.chars().take(139).collect::<String>()) } else { s }+}++/// The check lines for a status: what's missing, then each gate.+pub fn checks(status: &Value) -> Vec<(bool, String)> {+ let mut out: Vec<(bool, String)> = Vec::new();+ for m in status["missing"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ out.push((false, format!("missing: {}", short(m))));+ }+ for g in status["gates"].as_array().into_iter().flatten() {+ let of = g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default();+ out.push((g["clear"] == true, format!("{}{of}: {}", g["gate"].as_str().unwrap_or("gate"), short(g["says"].as_str().unwrap_or("")))));+ }+ out+}++/// plan.org's text with the job's task brought up to date (made at the end when it isn't there).+pub fn update(text: &str, title: &str, brief_rel: &str, kind: &str, status: &Value) -> String {+ let id = task_id(brief_rel);+ let lines: Vec<&str> = text.lines().collect();+ let done = status["done"] == true;+ let cs = checks(status);+ let cookie = format!("[{}/{}]", cs.iter().filter(|c| c.0).count(), cs.len());+ let check_lines: Vec<String> = cs.iter().map(|(d, t)| format!("- [{}] {t}", if *d { "X" } else { " " })).collect();+ let id_line = lines.iter().position(|l| l.trim() == format!(":ID: {id}") || l.trim() == format!(":ID: {id}"));+ let Some(id_at) = id_line else {+ let mut out = if text.trim().is_empty() { format!("#+TITLE: {title}\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n") } else { text.trim_end().to_string() + "\n" };+ out.push_str(&format!("\n* {} make: {kind} ({brief_rel}) {cookie}\n:PROPERTIES:\n:ID: {id}\n:KIND: make\n:VERB: {kind}\n:END:\n", if done { "REVIEW" } else { "MAKING" }));+ out.push_str(&(check_lines.join("\n") + "\n"));+ return out;+ };+ let head = (0..id_at).rev().find(|&i| lines[i].starts_with('*')).unwrap_or(0);+ let stars = lines[head].chars().take_while(|c| *c == '*').count();+ let end = (id_at + 1..lines.len()).find(|&i| lines[i].starts_with('*') && lines[i].chars().take_while(|c| *c == '*').count() <= stars).unwrap_or(lines.len());+ let drawer_end = (id_at..end).find(|&i| lines[i].trim() == ":END:").unwrap_or(id_at);+ // the headline: its keyword brought up to date unless the person closed it, its cookie replaced+ let words: Vec<&str> = lines[head][stars..].split_whitespace().collect();+ let kw = words.first().copied().unwrap_or("");+ let closed = kw == "DONE" || kw == "DROPPED";+ let rest: Vec<&str> = words.iter().skip(if ["TODO", "MAKING", "REVIEW", "DONE", "DROPPED"].contains(&kw) { 1 } else { 0 }).copied().filter(|w| !(w.starts_with('[') && w.ends_with(']') && w.contains('/'))).collect();+ let kw = if closed { kw } else if done { "REVIEW" } else { "MAKING" };+ let headline = format!("{} {kw} {} {cookie}", "*".repeat(stars), rest.join(" "));+ let theirs: Vec<&str> = lines[drawer_end + 1..end].iter().copied().filter(|l| !is_check(l)).collect();+ let mut out: Vec<String> = lines[..head].iter().map(|l| l.to_string()).collect();+ out.push(headline);+ out.extend(lines[head + 1..=drawer_end].iter().map(|l| l.to_string()));+ out.extend(check_lines);+ out.extend(theirs.iter().map(|l| l.to_string()));+ out.extend(lines[end..].iter().map(|l| l.to_string()));+ out.join("\n") + "\n"+}++/// Writes the job's task into plan.org at the top of `root` (the project's folder, else the brief's): the file and the+/// task's id.+pub fn write(root: &Path, brief: &Path, kind: &str, status: &Value) -> Result<(std::path::PathBuf, String), String> {+ let file = root.join("plan.org");+ let rel = brief.strip_prefix(root).unwrap_or(brief).to_string_lossy().replace('\\', "/");+ let title = root.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "plan".into());+ let text = std::fs::read_to_string(&file).unwrap_or_default();+ let next = update(&text, &title, &rel, kind, status);+ if next != text {+ let tmp = file.with_extension("org.tmp");+ std::fs::write(&tmp, &next).and_then(|_| std::fs::rename(&tmp, &file)).map_err(|e| format!("{}: {e}", file.display()))?;+ }+ Ok((file, task_id(&rel)))+}diff --git a/apps/make/src/sheet.rs b/apps/make/src/sheet.rsnew file mode 100644index 00000000..21ca5221--- /dev/null+++ b/apps/make/src/sheet.rs@@ -0,0 +1,86 @@+//! The contact sheets a gate looks at (docs/make.feature MK10, MK11, MK15): pictures in rows, each labelled under it,+//! a title over them, on one PNG a person, `raea ask` and the critic read at once. Labels are drawn by resvg in the+//! system's own fonts; an SVG drawn whole (the floor plan, MK18) goes through `svg_png`.++use std::path::{Path, PathBuf};+use std::sync::{Arc, OnceLock};++use image::{Rgba, RgbaImage, imageops};+use resvg::{tiny_skia, usvg};++/// One picture on a sheet and what it is.+pub struct Tile {+ pub img: PathBuf,+ pub label: String,+}++const LABEL_H: u32 = 30;+const TITLE_H: u32 = 44;+const GAP: u32 = 6;++fn options() -> usvg::Options<'static> {+ static DB: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();+ let db = DB.get_or_init(|| {+ let mut db = usvg::fontdb::Database::new();+ db.load_system_fonts();+ Arc::new(db)+ });+ usvg::Options { fontdb: db.clone(), font_family: "Helvetica".into(), ..usvg::Options::default() }+}++/// SVG text escaped.+pub fn esc(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)+}++/// An SVG document drawn at its own size.+pub fn svg_png(svg: &str) -> Result<RgbaImage, String> {+ let tree = usvg::Tree::from_str(svg, &options()).map_err(|e| format!("svg: {e}"))?;+ let size = tree.size().to_int_size();+ let mut pix = tiny_skia::Pixmap::new(size.width(), size.height()).ok_or("svg: empty size")?;+ resvg::render(&tree, tiny_skia::Transform::default(), &mut pix.as_mut());+ // tiny-skia keeps premultiplied alpha; image wants it straight+ let mut img = RgbaImage::new(size.width(), size.height());+ for (p, c) in img.pixels_mut().zip(pix.pixels()) {+ let d = c.demultiply();+ *p = Rgba([d.red(), d.green(), d.blue(), d.alpha()]);+ }+ Ok(img)+}++/// Rows of tiles, each `tile_w` wide (its height from the first picture's shape; any other shape fitted inside it), a label under each and the title+/// over them all, written to `out`. A tile whose picture won't open is drawn grey, its label saying so.+pub fn sheet(title: &str, rows: &[Vec<Tile>], tile_w: u32, out: &Path) -> Result<(), String> {+ let first = rows.iter().flatten().find_map(|t| image::open(&t.img).ok()).ok_or_else(|| format!("{title}: no picture to put on the sheet"))?;+ let th = ((tile_w as f64) * first.height() as f64 / first.width().max(1) as f64).round().max(1.0) as u32;+ let cols = rows.iter().map(Vec::len).max().unwrap_or(1).max(1) as u32;+ let (w, h) = (GAP + cols * (tile_w + GAP), TITLE_H + rows.len() as u32 * (th + LABEL_H + GAP));+ let mut img = RgbaImage::from_pixel(w, h, Rgba([18, 18, 20, 255]));+ let mut text = format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{w}\" height=\"{h}\"><text x=\"{GAP}\" y=\"30\" font-size=\"22\" font-weight=\"bold\" fill=\"#ffffff\">{}</text>", esc(title));+ for (r, row) in rows.iter().enumerate() {+ for (c, t) in row.iter().enumerate() {+ let (x, y) = (GAP + c as u32 * (tile_w + GAP), TITLE_H + r as u32 * (th + LABEL_H + GAP));+ let label = match image::open(&t.img) {+ Ok(p) => {+ // fitted inside the tile, its own shape kept, centred+ let k = (tile_w as f64 / p.width().max(1) as f64).min(th as f64 / p.height().max(1) as f64);+ let (pw, ph) = (((p.width() as f64 * k).round() as u32).max(1), ((p.height() as f64 * k).round() as u32).max(1));+ let small = imageops::resize(&p.to_rgba8(), pw, ph, imageops::FilterType::Triangle);+ imageops::overlay(&mut img, &small, (x + (tile_w - pw.min(tile_w)) / 2) as i64, (y + (th - ph.min(th)) / 2) as i64);+ t.label.clone()+ }+ Err(_) => {+ imageops::overlay(&mut img, &RgbaImage::from_pixel(tile_w, th, Rgba([70, 70, 70, 255])), x as i64, y as i64);+ format!("{} (missing)", t.label)+ }+ };+ text.push_str(&format!("<text x=\"{}\" y=\"{}\" font-size=\"17\" fill=\"#e8e8e8\">{}</text>", x + 4, y + th + 21, esc(&label)));+ }+ }+ text.push_str("</svg>");+ imageops::overlay(&mut img, &svg_png(&text)?, 0, 0);+ if let Some(d) = out.parent() {+ std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;+ }+ img.save(out).map_err(|e| format!("{}: {e}", out.display()))+}diff --git a/apps/make/src/shots.rs b/apps/make/src/shots.rsnew file mode 100644index 00000000..919dea40--- /dev/null+++ b/apps/make/src/shots.rs@@ -0,0 +1,112 @@+//! Blocking a shot list (docs/make.feature MK15): `raea make framing` renders each shot's first, middle and last+//! frame and puts them on one sheet, a row a shot, each stamped with its name and time, so the person, `raea ask`+//! (make.framing.*) and the critic (`raea judge --kind shot`) see every shot's start and end at once; `raea make+//! lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm (RAEA_LENS, core/review) to choose its+//! lens before it's moved.++use std::path::{Path, PathBuf};++use raea_core_brief::make::{Make, Shot};++use crate::sheet::{Tile, sheet};++/// The focal lengths a lens chart shows.+pub const LENSES: [u32; 6] = [18, 24, 35, 50, 85, 135];++/// raea itself, run on `args` with `env`: its output, or what it said when it failed.+pub fn raea(args: &[String], env: &[(&str, String)]) -> Result<String, String> {+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let mut c = std::process::Command::new(exe);+ c.args(args);+ for (k, v) in env {+ c.env(k, v);+ }+ // stderr passes through as it comes (a generation's progress, a render's frames), so whoever watches sees it+ // working, and is kept for the error+ let mut child = c.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn().map_err(|e| e.to_string())?;+ let err = child.stderr.take().map(|e| {+ std::thread::spawn(move || {+ use std::io::BufRead;+ let mut kept = Vec::new();+ for line in std::io::BufReader::new(e).lines().map_while(Result::ok) {+ eprintln!(" {line}");+ kept.push(line);+ }+ kept+ })+ });+ let out = child.wait_with_output().map_err(|e| e.to_string())?;+ let err = err.and_then(|t| t.join().ok()).unwrap_or_default();+ let text = String::from_utf8_lossy(&out.stdout).to_string();+ if out.status.success() {+ Ok(text)+ } else {+ Err(format!("raea {}: {}", args.first().map(String::as_str).unwrap_or(""), err.iter().rev().find(|l| !l.trim().is_empty()).map_or(text.trim(), String::as_str)))+ }+}++/// A shot's frames: its first, middle and last, from its seconds at its frame rate.+pub fn frames_of(s: &Shot) -> Vec<i64> {+ let n = ((s.seconds.unwrap_or(0.0) * s.fps.unwrap_or(30.0)).round() as i64).max(1);+ if s.still == Some(true) || n == 1 {+ return vec![0];+ }+ let mut v = vec![0, (n - 1) / 2, n - 1];+ v.dedup();+ v+}++fn composition(dir: &Path, s: &Shot) -> Result<PathBuf, String> {+ let c = s.composition.as_deref().ok_or_else(|| format!("shot `{}` has no composition (the .tsx that renders it)", s.name))?;+ Ok(dir.join(c))+}++/// The framing sheet of the plan's shots (or those named in `only`), written to `out` (OUT/framing.png).+pub fn framing(dir: &Path, m: &Make, only: &[String], out: &Path) -> Result<String, String> {+ let shots: Vec<&Shot> = m.shots.iter().filter(|s| only.is_empty() || only.contains(&s.name)).collect();+ if shots.is_empty() {+ return Err("raea make framing: no shots in the plan (or none named)".into());+ }+ let work = out.join("framing-frames");+ let mut rows = Vec::new();+ for s in &shots {+ let tsx = composition(dir, s)?;+ let fr = frames_of(s);+ let to = work.join(&s.name);+ let _ = std::fs::remove_dir_all(&to);+ std::fs::create_dir_all(&to).map_err(|e| format!("{}: {e}", to.display()))?;+ let at = fr.iter().map(|f| f.to_string()).collect::<Vec<_>>().join(",");+ raea(&["render".into(), tsx.display().to_string(), "-o".into(), to.display().to_string(), "--at".into(), at], &[])?;+ let fps = s.fps.unwrap_or(30.0);+ rows.push(fr.iter().enumerate().map(|(i, f)| Tile { img: to.join(format!("frame-{i:05}.png")), label: format!("{} t={:.1}s (frame {f})", s.name, *f as f64 / fps) }).collect());+ }+ let file = out.join("framing.png");+ sheet("Framing: each shot's first, middle and last frame", &rows, 480, &file)?;+ Ok(format!("wrote {} ({} shot{}); ask it: raea ask {} --set make (the framing questions apply); judge it: raea judge {} --kind shot", file.display(), shots.len(), if shots.len() == 1 { "" } else { "s" }, file.display(), out.display()))+}++/// One shot's first frame at every lens of the chart, on one sheet (OUT/lens-SHOT.png).+pub fn lenschart(dir: &Path, m: &Make, name: &str, out: &Path) -> Result<String, String> {+ let s = m.shots.iter().find(|s| s.name == name).ok_or_else(|| format!("raea make lenschart: no shot `{name}` in the plan"))?;+ let tsx = composition(dir, s)?;+ let work = out.join("lens-frames").join(name);+ std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;+ let mut tiles = Vec::new();+ for mm in LENSES {+ let png = work.join(format!("{mm}mm.png"));+ raea(&["render".into(), tsx.display().to_string(), "-o".into(), png.display().to_string(), "--frame".into(), "0".into()], &[("RAEA_LENS", mm.to_string())])?;+ tiles.push(Tile { img: png, label: format!("{mm} mm ({:.0}° vertical)", fov_of(mm as f64)) });+ }+ let rows: Vec<Vec<Tile>> = {+ let mut it = tiles.into_iter();+ vec![it.by_ref().take(3).collect(), it.collect()]+ };+ let file = out.join(format!("lens-{name}.png"));+ sheet(&format!("Lens chart: {name}, its first frame"), &rows, 480, &file)?;+ Ok(format!("wrote {}: pick the lens, then set the shot's `lens` (raea/camera lens(mm) for its fov)", file.display()))+}++/// The vertical field of view of a focal length on full frame (as core/review's RAEA_LENS sets it).+pub fn fov_of(mm: f64) -> f64 {+ 2.0 * (12.0 / mm).atan().to_degrees()+}diff --git a/apps/make/src/status.rs b/apps/make/src/status.rsindex aa848776..ed551223 100644--- a/apps/make/src/status.rs+++ b/apps/make/src/status.rs@@ -25,6 +25,46 @@ pub struct Job<'a> {pub verdict: Option<&'a Value>,/// when the judge last wrote its logpub judged_at: Option<SystemTime>,+ /// `raea ask`'s ledger, for the make questions' gate (asked.rs)+ pub ledger: &'a crate::asked::Ledger,+ /// `raea judge calibrate --kind KIND` agreed with the person's eye for this kind: its score gates too (MK6)+ pub score_gates: bool,+}++/// A round's folder: as the judge wrote it when absolute, else the folder of that name beside the log (review/), since+/// `raea judge DIR` keeps its log in DIR's parent and DIR was written relative to wherever it ran.+pub fn round_dir(dir: &Path, round: &Value) -> Option<PathBuf> {+ let d = Path::new(round["dir"].as_str()?);+ if d.is_absolute() {+ return Some(d.to_path_buf());+ }+ Some(dir.join("review").join(d.file_name()?))+}++/// The sheets the make questions are asked of: the newest round's (its framing sheet for a shot list, its colour and+/// clay sheets otherwise) and a kit's reference sheet.+pub fn sheets(job: &Job) -> Vec<(&'static str, PathBuf)> {+ let mut out = Vec::new();+ if let Some(r) = job.rounds.last().and_then(|r| round_dir(job.dir, r)) {+ if job.make.kind == make::Kind::Shot {+ out.push(("framing", r.join("framing.png")));+ } else {+ out.push(("clay", r.join("clay.png")));+ out.push(("colour", r.join("colour.png")));+ }+ }+ if job.make.kind == make::Kind::Kit {+ out.push(("refs", job.dir.join("review/refs.png")));+ }+ out.into_iter().filter(|(_, f)| f.is_file()).collect()+}++pub(crate) fn kind_name(k: make::Kind) -> &'static str {+ match k {+ make::Kind::Scene => "scene",+ make::Kind::Kit => "kit",+ make::Kind::Shot => "shot",+ }}fn mtime(p: &Path) -> Option<SystemTime> {@@ -96,7 +136,13 @@ fn checks(job: &Job) -> Vec<Value> {/// fixed (the round passed) or answered in NOTES.md by its name. Its score gates once the judge is calibrated.fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {let Some(last) = job.rounds.last() else {- return vec![gate("critic", None, false, "no round yet: raea render EDIT.tsx --review review/r1, then raea judge review/r1 --by claude".into())];+ let kind = kind_name(job.make.kind);+ let what = match job.make.kind {+ make::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",+ make::Kind::Shot => "raea make framing --out review/r1",+ make::Kind::Scene => "raea render EDIT.tsx --review review/r1",+ };+ return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];};let mut out = Vec::new();let fresh = match (job.judged_at, newest) {@@ -105,10 +151,17 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {_ => false,};out.push(gate("critic", None, fresh, if fresh { format!("round {} judged after the newest deliverable", job.rounds.len()) } else { "the newest deliverable came after the last round: review and judge it again".into() }));+ // the kind's own rubric (MK5): a round judged on another's doesn't count+ let kind = kind_name(job.make.kind);+ if last["kind"].as_str() != Some(kind) {+ let dir = last["dir"].as_str().unwrap_or("review/rN");+ out.push(gate("rubric", None, false, format!("the last round wasn't judged on the {kind} rubric: raea judge {dir} --kind {kind} --by claude")));+ }let blocking: Vec<&str> = raea_app_judge::rubric::blocking(last["defects"].as_array().map(Vec::as_slice).unwrap_or_default());let open: Vec<&str> = if last["pass"] == true { Vec::new() } else { blocking.into_iter().filter(|d| !notes.contains(d)).collect() };out.push(gate("defects", None, open.is_empty(), if open.is_empty() { "no blocking defect left unanswered".into() } else { format!("blocking, neither fixed nor answered in NOTES.md: {}", open.join(", ")) }));- if job.verdict.is_some_and(|v| v["gating"] == true) {+ // the score gates once the judge is calibrated for this kind; before that, fixed-or-answered is enough (MK6)+ if job.score_gates {let p = raea_app_judge::progress(job.rounds);let done = p["done"] == true;out.push(gate("score", None, done, format!("the calibrated judge: {} passes in a row, two needed", p["passesInARow"])));@@ -132,6 +185,8 @@ pub fn status(job: &Job) -> Value {}let mut gates = checks(job);gates.extend(critic(job, newest, ¬es));+ let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, ¬es);+ gates.extend(asks);let cap = job.make.rounds.unwrap_or(make::ROUNDS) as usize;let capped = job.rounds.len() >= cap;let stalled = stalled(job.rounds);@@ -152,6 +207,7 @@ pub fn status(job: &Job) -> Value {"gates": gates,"judge": {"rounds": job.rounds.len(), "cap": cap, "passesInARow": advice["passesInARow"], "changeApproach": advice["stall"], "again": advice["again"]},"plan": make::doctor(job.make),+ "advice": said,"why": why,})}@@ -171,6 +227,10 @@ pub fn text(s: &Value) -> String {t.push("missing:".into());t.extend(list("missing").iter().map(|m| format!(" {}", m.as_str().unwrap_or(""))));}+ if !list("advice").is_empty() {+ t.push("advice (raea ask, not calibrated yet):".into());+ t.extend(list("advice").iter().map(|m| format!(" {}", m.as_str().unwrap_or(""))));+ }t.push("gates:".into());for g in list("gates") {let of = g["of"].as_str().map(|o| format!(" {o}")).unwrap_or_default();diff --git a/apps/make/src/tests.rs b/apps/make/src/tests.rsindex 9c39c209..23c6fa47 100644--- a/apps/make/src/tests.rs+++ b/apps/make/src/tests.rs@@ -5,6 +5,7 @@ use raea_core_brief::{make::Make, read};use raea_core_facts::record::Entry;use serde_json::{Value, json};+use crate::asked::Ledger;use crate::status::{Job, status, stalled};fn dir(name: &str) -> PathBuf {@@ -25,18 +26,22 @@ fn kit() -> Make {}fn delivered(d: &PathBuf) {- for f in ["out/kit/phone/phone.glb", "out/kit/phone/phone_lod1.glb", "out/kit/thumbs/phone.png", "out/kit/lineup.png", "out/kit/kit.json"] {+ for f in ["out/kit/phone/phone.glb", "out/kit/phone/phone_lod1.glb", "out/kit/thumbs/phone.png", "out/kit/lineup.png", "out/kit/kit.json", "review/refs.png"] {put(d, f, "x");}put(d, "NOTES.md", "# Notes\n\n## What the skill got wrong\n- nothing yet\n");}fn round(pass: bool, mean: f64, defects: Value) -> Value {- json!({"dir": "review/r1", "pass": pass, "mean": mean, "defects": defects})+ json!({"dir": "review/r1", "kind": "kit", "pass": pass, "mean": mean, "defects": defects})}fn run(make: &Make, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>) -> Value {- status(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at })+ run_with(make, d, record, rounds, judged_at, &Ledger::default())+}++fn run_with(make: &Make, d: &PathBuf, record: &[Entry], rounds: &[Value], judged_at: Option<SystemTime>, ledger: &Ledger) -> Value {+ status(&Job { make, dir: d, project: None, record, rounds, verdict: None, judged_at, ledger, score_gates: false })}fn later() -> Option<SystemTime> {@@ -80,8 +85,13 @@ fn a_blocking_defect_must_be_fixed_or_answered_in_the_notes() {assert_eq!(s["done"], false);assert!(s["gates"].to_string().contains("floating"));put(&d, "NOTES.md", "## What the skill got wrong\n- floating: the handset rests in its cradle; the judge read its shadow as a gap\n");- let s = run(&kit(), &d, &[], &[round(false, 6.0, defects)], later());+ let s = run(&kit(), &d, &[], &[round(false, 6.0, defects.clone())], later());assert_eq!(s["done"], true, "{s:#}");+ // once the judge is calibrated for kits, its score gates too: two passes in a row (MK6)+ let (rounds, ledger) = ([round(false, 6.0, defects)], Ledger::default());+ let s = status(&Job { make: &kit(), dir: &d, project: None, record: &[], rounds: &rounds, verdict: None, judged_at: later(), ledger: &ledger, score_gates: true });+ assert_eq!(s["done"], false, "{s:#}");+ assert!(s["gates"].to_string().contains("two needed"), "{s:#}");}#[test]@@ -132,3 +142,81 @@ fn a_scene_wants_three_stills() {let s = run(&make, &d, &[], &[], None);assert!(s["missing"].to_string().contains("holds 1 picture"), "{s:#}");}++#[test]+fn a_round_judged_on_another_kinds_rubric_does_not_count() {+ // docs/make.feature MK5: a kit is judged on the kit's rubric+ let d = dir("rubric");+ delivered(&d);+ let old = json!({"dir": "review/r1", "pass": true, "mean": 8.0, "defects": []});+ let s = run(&kit(), &d, &[], &[old], later());+ assert_eq!(s["done"], false);+ assert!(s["gates"].to_string().contains("--kind kit"), "{s:#}");+}++#[test]+fn a_calibrated_ask_question_gates_and_an_uncalibrated_one_advises() {+ // docs/make.feature MK4+ let d = dir("ask");+ delivered(&d);+ put(&d, "review/r1/clay.png", "clay sheet bytes");+ put(&d, "review/r1/colour.png", "colour sheet bytes");+ let rounds = [round(true, 7.5, json!([]))];+ let floating = raea_core_ask::library::find("make.clay.floating", None).unwrap();+ let mut ledger = Ledger::default();+ // nothing calibrated: every question is advice, and the job is done+ let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);+ assert_eq!(s["done"], true, "{s:#}");+ assert!(s["gates"].to_string().contains("advice only"), "{s:#}");+ // floating calibrated on the person's labels: it must be asked of this exact clay sheet+ ledger.calibrations.insert(floating.version(), serde_json::from_value(json!({"auc": 0.9, "n": 40, "positives": 16, "threshold": 0.4, "date": "2026-11-23", "by": "you"})).unwrap());+ let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);+ assert_eq!(s["done"], false);+ let gates = s["gates"].to_string();+ assert!(gates.contains("not asked of this clay sheet") && gates.contains("--std make.clay.floating"), "{gates}");+ // asked, and it flagged: open until fixed or answered by its id in NOTES.md+ let ident = raea_core_ask::ident::ident(&d.join("review/r1/clay.png")).unwrap();+ ledger.idents.insert("c-1".into(), ident);+ ledger.answers.push(json!({"id": "a-1", "at": "100", "call": "c-1", "question": "make.clay.floating", "flagged": true, "problem": 0.8}));+ let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);+ assert_eq!(s["done"], false);+ assert!(s["gates"].to_string().contains("make.clay.floating flagged (p 0.80)"), "{s:#}");+ put(&d, "NOTES.md", "## What the skill got wrong\n- make.clay.floating: the handset's shadow, not a gap; checked on the low tile\n");+ let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);+ assert_eq!(s["done"], true, "{s:#}");+ // the sheet rendered again: the old answer was about other bytes, so it's asked again+ put(&d, "review/r1/clay.png", "a new clay sheet");+ let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);+ assert!(s["gates"].to_string().contains("not asked of this clay sheet"), "{s:#}");+ // an uncalibrated question that flags is said as advice, holding nothing+ let ident = raea_core_ask::ident::ident(&d.join("review/r1/colour.png")).unwrap();+ ledger.idents.insert("c-2".into(), ident);+ ledger.answers.push(json!({"id": "a-2", "at": "101", "call": "c-2", "question": "make.colour.plastic", "flagged": true, "problem": 0.7}));+ let s = run_with(&kit(), &d, &[], &rounds, later(), &ledger);+ assert!(s["advice"].to_string().contains("make.colour.plastic says yes"), "{s:#}");+}++#[test]+fn the_gates_are_check_lines_under_the_jobs_task_in_plan_org() {+ // docs/make.feature MK3+ let not_done = json!({"done": false, "missing": ["out/kit/lineup.png"], "gates": [{"gate": "critic", "clear": false, "says": "no round yet"}, {"gate": "checks", "of": "kit.tsx", "clear": true, "says": "clean"}]});+ let t = crate::plan::update("", "desk", "brief.ts", "kit", ¬_done);+ let id = crate::plan::task_id("brief.ts");+ assert!(id.len() == 10 && id.starts_with("t-") && id[2..].chars().all(|c| c.is_ascii_alphanumeric()), "{id}");+ assert!(t.starts_with("#+TITLE: desk\n#+TODO: TODO MAKING REVIEW | DONE DROPPED\n"), "{t}");+ assert!(t.contains("* MAKING make: kit (brief.ts) [1/3]") && t.contains(&format!(":ID: {id}")), "{t}");+ assert!(t.contains("- [ ] missing: out/kit/lineup.png") && t.contains("- [X] checks kit.tsx: clean"), "{t}");+ // the person's own line under it stays; the checks are brought up to date; done is REVIEW+ let mut mine = t.replace("- [X] checks kit.tsx: clean\n", "- [X] checks kit.tsx: clean\nShane: keep the phone's cord\n");+ mine = format!("{mine}* TODO another task\n");+ let done = json!({"done": true, "missing": [], "gates": [{"gate": "critic", "clear": true, "says": "round 2 judged"}]});+ let t2 = crate::plan::update(&mine, "desk", "brief.ts", "kit", &done);+ assert!(t2.contains("* REVIEW make: kit (brief.ts) [1/1]") && t2.contains("Shane: keep the phone's cord") && t2.contains("* TODO another task"), "{t2}");+ assert!(!t2.contains("missing:"), "{t2}");+ assert_eq!(t2.matches(":ID: ").count(), 1);+ // a task the person closed keeps their mark+ let closed = t2.replace("* REVIEW make", "* DONE make");+ assert!(crate::plan::update(&closed, "desk", "brief.ts", "kit", ¬_done).contains("* DONE make: kit (brief.ts) [1/3]"));+ // once written, writing the same again changes nothing+ assert_eq!(crate::plan::update(&t2, "desk", "brief.ts", "kit", &done), t2);+}diff --git a/apps/make/src/tests_steps.rs b/apps/make/src/tests_steps.rsnew file mode 100644index 00000000..da528f8f--- /dev/null+++ b/apps/make/src/tests_steps.rs@@ -0,0 +1,205 @@+//! The steps' own work, without a render or a paid call: sheets, prompts, flows, picks, components, the floor plan.++use std::path::PathBuf;++use image::{Rgba, RgbaImage};+use raea_core_brief::{make::Make, read};++use crate::sheet::{Tile, sheet};++fn dir(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("raea-make-steps-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++fn png(p: &PathBuf, w: u32, h: u32, c: [u8; 3]) {+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ RgbaImage::from_pixel(w, h, Rgba([c[0], c[1], c[2], 255])).save(p).unwrap();+}++fn kit() -> Make {+ read("make", r#"{"kind": "kit", "references": ["media/style.png"], "style": "1970s flight desk, cream enamel, maker Aurora Instruments.", "objects": [+ {"id": "rotary_phone", "label": "Rotary phone", "h": 0.12, "prompt": "a rotary desk phone, worn bakelite", "hero": true},+ {"id": "clock", "label": "Wall clock", "dims": [0.3, 0.05, 0.3]}]}"#)+ .unwrap()+}++// MK10, MK11, MK15: a sheet is its tiles in rows, labelled, any shape fitted without stretching, a missing one grey+#[test]+fn a_sheet_holds_its_tiles_in_rows_with_labels() {+ let d = dir("sheet");+ let (a, b, wide) = (d.join("a.png"), d.join("b.png"), d.join("wide.png"));+ png(&a, 200, 100, [200, 30, 30]);+ png(&b, 200, 100, [30, 200, 30]);+ png(&wide, 400, 100, [30, 30, 200]);+ let out = d.join("review/sheet.png");+ let rows = vec![+ vec![Tile { img: a.clone(), label: "red <a&b>".into() }, Tile { img: b, label: "green".into() }],+ vec![Tile { img: wide, label: "wide".into() }, Tile { img: d.join("gone.png"), label: "gone".into() }],+ ];+ sheet("Test sheet", &rows, 300, &out).unwrap();+ let img = image::open(&out).unwrap().to_rgba8();+ // two columns of 300 and three gaps of 6; the tile is 150 tall (from the first's 2:1), title 44, label 30, gap 6+ assert_eq!((img.width(), img.height()), (618, 44 + 2 * (150 + 30 + 6)));+ // the first tile is red in its middle; the wide one is letterboxed (fitted 300x75, centred), not stretched+ assert_eq!(img.get_pixel(6 + 150, 44 + 75).0[..3], [200, 30, 30]);+ let row2 = 44 + 150 + 30 + 6;+ assert_eq!(img.get_pixel(6 + 150, row2 + 75).0[..3], [30, 30, 200]);+ assert_ne!(img.get_pixel(6 + 150, row2 + 10).0[..3], [30, 30, 200]);+ // the missing one is grey+ assert_eq!(img.get_pixel(6 + 300 + 6 + 150, row2 + 75).0[..3], [70, 70, 70]);+ // a label was drawn under the first tile (light pixels on the dark ground)+ let lit = (0..300).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(6 + x, 44 + 150 + y).0[0] > 150).count();+ assert!(lit > 40, "no label drawn ({lit} lit pixels)");+ assert!(sheet("empty", &[vec![Tile { img: d.join("none.png"), label: "x".into() }]], 100, &d.join("e.png")).is_err());+}++// MK10: a reference prompt is the plan's style, the object's words and the scan template, never a brand+#[test]+fn a_reference_prompt_is_style_object_and_scan() {+ let m = kit();+ let p = crate::kit::ref_prompt(&m, &m.objects[0]);+ assert!(p.starts_with("1970s flight desk, cream enamel, maker Aurora Instruments. a rotary desk phone, worn bakelite. One object only"), "{p}");+ assert!(p.contains("no real brands"));+ // an object with no prompt is described by its label+ assert!(crate::kit::ref_prompt(&m, &m.objects[1]).contains(". Wall clock. "));+ assert_eq!(crate::kit::size_args(&m.objects[0]), ["--h", "0.12"]);+ assert_eq!(crate::kit::size_args(&m.objects[1]), ["--dims", "0.3,0.05,0.3"]);+}++// MK11: one reference to both generators, the hero at 150k faces; the single-shot gen's file read from its JSON+#[test]+fn both_generators_get_each_reference() {+ let m = kit();+ let f = crate::kit::gen_flow(&m, &m.objects[0], std::path::Path::new("/r/rotary_phone.png"), crate::kit::TRIPO, crate::kit::MESHY);+ assert_eq!(f["out"], serde_json::json!(["tripo", "meshy"]));+ assert_eq!(f["steps"]["tripo"]["model"], "tripo:H3.1");+ assert_eq!(f["steps"]["tripo"]["in"]["x_face_limit"], 150000);+ assert_eq!(f["steps"]["meshy"]["model"], "fal:meshy/v7.1/image-to-3d");+ assert_eq!(f["steps"]["meshy"]["in"]["image"], "@ref");+ let small = crate::kit::gen_flow(&m, &m.objects[1], std::path::Path::new("/r/clock.png"), crate::kit::TRIPO, crate::kit::MESHY);+ assert_eq!(small["steps"]["tripo"]["in"]["x_face_limit"], 60000);+ assert_eq!(crate::kit::gen_file(r#"{"out": {"out": "/g/out.png"}, "cents": 4}"#), Some(PathBuf::from("/g/out.png")));+ assert_eq!(crate::kit::gen_file(r#"{"out": {"out": ["/g/a.png", "/g/b.png"]}}"#), Some(PathBuf::from("/g/a.png")));+ assert_eq!(crate::kit::gen_file("not json"), None);+}++// MK11: a pick names a model that exists and says why; it's kept by object+#[test]+fn a_pick_needs_its_model_and_a_reason() {+ let d = dir("pick");+ let m = kit();+ assert!(crate::kit::choose(&d, &m, "rotary_phone", "tripo", "sharper").unwrap_err().contains("raea make gen --only rotary_phone"));+ std::fs::create_dir_all(crate::kit::gen_dir(&d, "rotary_phone")).unwrap();+ std::fs::write(crate::kit::gen_dir(&d, "rotary_phone").join("meshy.glb"), "x").unwrap();+ assert!(crate::kit::choose(&d, &m, "rotary_phone", "meshy", " ").unwrap_err().contains("say why"));+ assert!(crate::kit::choose(&d, &m, "lamp", "meshy", "x").unwrap_err().contains("no object `lamp`"));+ crate::kit::choose(&d, &m, "rotary_phone", "meshy", "Tripo fused the handset to the cradle").unwrap();+ assert_eq!(crate::kit::picks(&d)["rotary_phone"]["generator"], "meshy");+ // prep names what isn't picked yet rather than skipping it+ let said = crate::kit::prep(&d, &m, &["clock".to_string()]).unwrap();+ assert!(said.contains("clock: no pick yet"), "{said}");+}++// MK13: each object a component importing its own model and LOD beside it; the lineup imports them all with a 1 m bar+#[test]+fn the_kit_lands_as_components_and_a_lineup() {+ let m = kit();+ assert_eq!(crate::kitout::component_name("rotary_phone"), "RotaryPhone");+ let c = crate::kitout::component(&m.objects[0], "sharper numerals");+ assert!(c.starts_with("// raea component add: Rotary phone, 0.12 m"), "{c}");+ assert!(c.contains("import full from \"./rotary_phone.glb\";") && c.contains("import far from \"./rotary_phone_lod1.glb\";"));+ assert!(c.contains("export default function RotaryPhone("));+ let l = crate::kitout::lineup(&m, "desk");+ assert!(l.contains("import RotaryPhone from \"./RotaryPhone\";") && l.contains("import Clock from \"./Clock\";"));+ assert!(l.contains("</Text3D>") && l.contains("registerRoot("));+ // the bar is the longest round length the set covers+ assert_eq!(crate::kitout::scale_bar(0.52), (0.5, "50 cm"));+ assert_eq!(crate::kitout::scale_bar(1.7), (1.0, "1 m"));+ assert_eq!(crate::kitout::scale_bar(0.02), (0.05, "5 cm"));+ // the viewer frames a model by its height+ let v = crate::kitout::viewer(std::path::Path::new("/k/tripo.fit.glb"), 0.12);+ assert!(v.contains("import model from \"./tripo.fit.glb\";") && v.contains("<Model src={model} />"));+ // where it lands: the workspace's shared/components, else the project's components+ let d = dir("land");+ let job = d.join("projects/p/kit");+ std::fs::create_dir_all(&job).unwrap();+ std::fs::create_dir_all(d.join("projects/p/.raea")).unwrap();+ std::fs::write(d.join("projects/p/.raea/project"), "{}").unwrap();+ let real = dunce::canonicalize(&d).unwrap();+ assert_eq!(crate::kitout::kit_dir(&job, "desk", None), real.join("projects/p/components/desk"));+ std::fs::create_dir_all(d.join(".raea")).unwrap();+ std::fs::write(d.join(".raea/workspace"), "{}").unwrap();+ std::fs::create_dir_all(d.join("shared")).unwrap();+ assert_eq!(crate::kitout::kit_dir(&job, "desk", None), real.join("shared/components/desk"));+ assert_eq!(crate::kitout::kit_dir(&job, "desk", Some("/x")), PathBuf::from("/x"));+}++// MK15: a shot's frames are its first, middle and last (a still: its first); the lens chart's angles+#[test]+fn a_shot_frames_its_start_middle_and_end() {+ let m: Make = read("make", r#"{"kind": "shot", "shots": [{"name": "push", "seconds": 4, "composition": "push.tsx"}, {"name": "hold", "still": true}, {"name": "fast", "seconds": 2, "fps": 24}]}"#).unwrap();+ assert_eq!(crate::shots::frames_of(&m.shots[0]), vec![0, 59, 119]);+ assert_eq!(crate::shots::frames_of(&m.shots[1]), vec![0]);+ assert_eq!(crate::shots::frames_of(&m.shots[2]), vec![0, 23, 47]);+ assert!((crate::shots::fov_of(50.0) - 26.99).abs() < 0.01);+ // a shot with no composition can't be framed, and says what's needed+ let d = dir("framing");+ assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));+ assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));+}++// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance+#[test]+fn the_plan_draws_a_floor_plan_and_a_blockout() {+ let m: Make = read("make", r#"{"kind": "scene", "references": ["media/ref.png"], "objects": [+ {"id": "desk", "label": "Desk", "dims": [1.6, 0.8, 0.75], "at": [2, 0, 3], "rot": 90, "source": "reference", "hero": true},+ {"id": "plant", "label": "Plant", "h": 1.2, "at": [0.5, 0, 4], "source": "invented"},+ {"id": "pen", "label": "Pen", "max": 0.14}]}"#)+ .unwrap();+ let (placed, b) = crate::floor::extent(&m);+ assert_eq!(placed.len(), 2);+ assert!(b[0] < 0.0 && b[3] > 4.5, "{b:?}");+ let svg = crate::floor::floor_svg(&m).unwrap();+ assert_eq!(svg.matches("stroke-dasharray").count(), 1);+ assert!(svg.contains(">Desk<") && svg.contains(">Plant<") && !svg.contains(">Pen<"));+ // the entrance runs along the front edge (the plan's nearest z), where the blockout's camera stands+ assert!(svg.contains("entrance: the camera looks in from here"));+ let img = crate::sheet::svg_png(&svg).unwrap();+ assert!(img.width() > 400 && img.height() > 400);+ let t = crate::floor::blockout_tsx(&m);+ assert_eq!(t.matches("<Cuboid").count(), 3, "the floor and two boxes");+ assert!(t.contains("half_size={[0.800, 0.375, 0.400]}"), "{t}");+ let none: Make = read("make", r#"{"kind": "scene", "objects": [{"id": "pen", "label": "Pen"}]}"#).unwrap();+ assert!(crate::floor::floor_svg(&none).unwrap_err().contains("no object has an `at`"));+}++// the CLI's positional words skip flags and their values+#[test]+fn positional_words_skip_flags() {+ let a: Vec<String> = ["make", "pick", "phone", "--only", "a,b", "tripo", "--dry", "why not", "proj"].iter().map(|s| s.to_string()).collect();+ assert_eq!(crate::positional(&a, 2), ["phone", "tripo", "why not", "proj"]);+}++#[test]+fn a_quote_reads_as_one_line() {+ let out = "raea: planning\n{\"steps\":[{\"op\":\"media.load\",\"runs_on\":\"load\",\"cents\":0},{\"op\":\"image\",\"runs_on\":\"made:nano_banana_2\",\"cents\":6}],\"cents\":6,\"cap_cents\":100}";+ assert_eq!(crate::kit::quote(out), "made:nano_banana_2 (about 6¢)");+ assert_eq!(crate::kit::quote("not json at all"), "not json at all");+}++#[test]+fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {+ use raea_core_brief::make::Object;+ let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();+ // long across (x) where the plan's is front to back (z): a quarter turn+ assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);+ // already front to back, or about square: no turn+ assert_eq!(crate::kit::fit_args(&stapler, Some([0.27, 0.12, 0.84])), ["--dims", "0.05,0.17,0.07", "--h", "0.07"]);+ assert_eq!(crate::kit::fit_args(&stapler, None), ["--dims", "0.05,0.17,0.07", "--h", "0.07"]);+ let clock: Object = serde_json::from_value(serde_json::json!({"id": "clock", "label": "Clock", "h": 0.14})).unwrap();+ assert_eq!(crate::kit::fit_args(&clock, Some([1.0, 1.0, 0.5])), ["--h", "0.14"]);+ assert!((crate::kitout::frame_size(&stapler) - 0.17).abs() < 1e-9);+}diff --git a/apps/scene/src/lib.rs b/apps/scene/src/lib.rsindex 31c99025..2d4c5e58 100644--- a/apps/scene/src/lib.rs+++ b/apps/scene/src/lib.rs@@ -10,7 +10,7 @@ use raea_runtime_export::{frame_of, items};mod light;mod stage;-pub const USAGE: &str = "raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--json]";+pub const USAGE: &str = "raea scene lint|explain|light|stage 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,diff --git a/apps/scene/src/stage.rs b/apps/scene/src/stage.rsindex b8b3e433..6be96a77 100644--- a/apps/scene/src/stage.rs+++ b/apps/scene/src/stage.rs@@ -4,6 +4,7 @@//! them. Errors fail it, as they fail a render, so it's the cheap look before one. It lays out no page, so what the//! page holds waits for a render: its words over the parts (type-over-part), a Label's part as the shot's subject, and//! a frame its words or pictures fill, which reads empty here and is said as a warning, not failed (SG11).+//! `--clearance M` holds the camera M metres off every solid part on every frame (0.45 for a carried camera, MK16).use serde_json::json;@@ -12,7 +13,7 @@ use raea_runtime_bundle::{bundle_composition, comp_opts, flag};use raea_runtime_export::{all_items, scene_frames_to};pub(crate) fn cli(args: &[String]) -> Result<String, String> {- let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]";+ let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--clearance M] [--json]";let Some(edit) = args.get(2) else { return Err(usage.into()) };let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;let dir = tsx.parent().unwrap().to_path_buf();@@ -26,7 +27,15 @@ pub(crate) fn cli(args: &[String]) -> Result<String, String> {let frames: Vec<_> = frames.into_iter().filter(|(f, _)| *f >= from && to.is_none_or(|t| *f <= t)).collect();let (Some(first), Some(last)) = (frames.first().map(|f| f.0), frames.last().map(|f| f.0)) else { return Err(format!("no frames from {from}")) };let nums: Vec<i64> = frames.iter().map(|(f, _)| *f).collect();- let mut fs = raea_sys_stage::check(&all_items(&frames), &nums, w, h, fps, "raea scene stage");+ let items = all_items(&frames);+ let mut fs = raea_sys_stage::check(&items, &nums, w, h, fps, "raea scene stage");+ // the camera held off every solid part, when asked: the number after the flag, else a carried camera's 0.45 m+ if let Some(v) = flag(args, "--clearance") {+ let min = v.parse::<f32>().ok().filter(|m| *m >= 0.0).ok_or_else(|| format!("--clearance takes metres (0.45 for a carried camera), got {v:?}"))?;+ let mut c = raea_sys_stage::clearance(&items, &nums, w, h, fps, min, "raea scene stage");+ c.append(&mut fs);+ fs = c;+ }for f in fs.iter_mut().filter(|f| f.check == "frame-empty" && f.level == Level::Error) {f.level = Level::Warn;f.says.push_str(" (no page is laid out here: if its words or pictures fill these frames, a render passes them)");diff --git a/core/ask/Cargo.toml b/core/ask/Cargo.tomlindex 72894f95..d6d0a576 100644--- a/core/ask/Cargo.toml+++ b/core/ask/Cargo.toml@@ -9,5 +9,7 @@ description = "Questions for the decision model (clef-omni): their types, how an[dependencies]serde = { version = "1", features = ["derive"] }serde_json = "1"+# a file's ident (ident.rs), the one the ledger keeps+sha2 = "0.10"# the TypeScript declarations are generated from these types, so the two can't driftts-rs = "12"diff --git a/core/ask/library/make.json b/core/ask/library/make.jsonnew file mode 100644index 00000000..846acad4--- /dev/null+++ b/core/ask/library/make.json@@ -0,0 +1,20 @@+[+ {"id": "make.clay.floating", "ask": "These are grey clay renders of one 3D scene or prop from several cameras. Does any object float above the surface it should rest on, with a visible gap under it?", "sees": "stills", "hears": false, "label_words": ["floating", "floats", "hovering", "gap under"], "fix": "settle it onto what's under it at its contact points (raea scene lint gives the dy)"},+ {"id": "make.clay.intersecting", "ask": "These are grey clay renders of one 3D scene or prop from several cameras. Does any object pass through another object, a wall or the floor?", "sees": "stills", "hears": false, "label_words": ["intersecting", "passes through", "clipping", "poking through"], "fix": "move it clear (raea scene lint names the pair and the depth)"},+ {"id": "make.clay.blobby", "ask": "These are grey clay renders. Is any object a blobby, melted or lumpy shape where the real thing has crisp form?", "sees": "stills", "hears": false, "label_words": ["blobby", "melted", "lumpy", "mushy"], "fix": "regenerate it from a cleaner reference, or pick the other generator"},+ {"id": "make.clay.stand_in", "ask": "These are grey clay renders. Is any object just a plain box, ball or cylinder standing in for a more detailed real thing?", "sees": "stills", "hears": false, "label_words": ["placeholder", "stand-in", "just a box", "primitive"], "fix": "build or generate the real thing"},+ {"id": "make.clay.disconnected", "ask": "These are grey clay renders. Is any object made of parts that don't connect: a handle, a leg or a lid hanging in the air beside the body it belongs to?", "sees": "stills", "hears": false, "label_words": ["disconnected", "detached", "not attached", "hanging in the air"], "fix": "regenerate it, or join the parts by script and check it again"},+ {"id": "make.clay.clones", "ask": "These are grey clay renders. Are several copies of one thing identical and evenly spaced in an obviously artificial way?", "sees": "stills", "hears": false, "label_words": ["clones", "identical", "copy paste", "repeated"], "fix": "vary each copy's rotation, scale and wear, or swap some for siblings"},+ {"id": "make.colour.flat_colour", "ask": "These are renders of one 3D scene or prop from several cameras. Is any large surface a flat, uniform default colour with no texture, variation or wear?", "sees": "stills", "hears": false, "label_words": ["flat colour", "flat color", "untextured", "default grey"], "fix": "give it its real material, with wear where use puts it"},+ {"id": "make.colour.plastic", "ask": "These are renders of one 3D scene or prop. Do the surfaces look like shiny uniform plastic or CG rather than their real materials?", "sees": "stills", "hears": false, "label_words": ["plastic", "cg", "fake", "shiny"], "fix": "roughness and colour variation from real material maps; no uniform gloss"},+ {"id": "make.colour.opaque_glass", "ask": "These are renders of one 3D scene or prop. Is anything that should be glass (a window, a bottle, a lens, a screen cover) solid and opaque instead of see-through?", "sees": "stills", "hears": false, "label_words": ["opaque glass", "glass isn't", "not see-through", "solid glass"], "fix": "mask the glass by colour and make it transmissive, keeping labels opaque"},+ {"id": "make.colour.garbled_text", "ask": "These are renders of one 3D scene or prop. Is any visible text garbled, tiled or unreadable where it should read, such as a hero object's label or a sign?", "sees": "stills", "hears": false, "label_words": ["garbled", "unreadable", "gibberish", "nonsense text"], "fix": "replace the label with real text from one invented maker"},+ {"id": "make.colour.brands", "ask": "These are renders of one 3D scene or prop. Is a real brand name or logo visible?", "sees": "stills", "hears": false, "label_words": ["brand", "logo", "trademark"], "fix": "debrand: flatten the logo's texels and normals, or replace it with the invented maker's"},+ {"id": "make.colour.too_dark", "ask": "These are renders of one 3D scene. Is the scene so dark that important objects are hard to see?", "sees": "stills", "hears": false, "label_words": ["too dark", "can't see", "underexposed"], "fix": "light it from its own sources; raise exposure"},+ {"id": "make.colour.too_bright", "ask": "These are renders of one 3D scene. Is it washed out, with large areas blown to white?", "sees": "stills", "hears": false, "label_words": ["washed out", "blown out", "overexposed", "too bright"], "fix": "lower exposure or the brightest light"},+ {"id": "make.refs.outlier", "ask": "This sheet shows reference pictures for one set of props that must belong together. Is any picture in a different style from the others: another era, palette, material, lighting or rendering look?", "sees": "stills", "hears": false, "label_words": ["outlier", "doesn't match", "different style", "off style"], "fix": "regenerate that reference with the style images and the plan's style paragraph"},+ {"id": "make.refs.two_objects", "ask": "This sheet shows one reference picture per prop. Does any picture show more than one object, or an object cropped by the edge of its picture?", "sees": "stills", "hears": false, "label_words": ["two objects", "cropped", "cut off", "more than one"], "fix": "regenerate it as one whole object, centred, on a plain background"},+ {"id": "make.refs.brands", "ask": "This sheet shows reference pictures for props. Does any picture show a real brand name or logo?", "sees": "stills", "hears": false, "label_words": ["brand", "logo", "trademark"], "fix": "regenerate it with the invented maker named in the prompt"},+ {"id": "make.framing.through_wall", "ask": "These are frames of camera moves through a 3D scene. Is the camera inside or passing through a wall, a piece of furniture or another solid, so part of the frame is blocked or cut open?", "sees": "stills", "hears": false, "label_words": ["through the wall", "inside the wall", "clipping", "camera in"], "fix": "move the path's keys clear (raea scene stage --clearance 0.45 names the frames)"},+ {"id": "make.framing.subject_lost", "ask": "These are frames of camera moves, each shot's start, middle and end. Does any shot lose its subject: cut off, out of frame or hidden at one of its frames?", "sees": "stills", "hears": false, "label_words": ["lost the subject", "out of frame", "cut off", "can't see the"], "fix": "re-aim the move or retime its keys so the subject stays framed"}+]diff --git a/core/ask/src/ident.rs b/core/ask/src/ident.rsnew file mode 100644index 00000000..d857727c--- /dev/null+++ b/core/ask/src/ident.rs@@ -0,0 +1,30 @@+//! What a file is, cheaply: its size and a hash of its first and last MB. The ledger keeps it on every call+//! (apps/ask record.rs), so a render is known again by its copy in the feed, a later render to the same path isn't+//! taken for it, and `raea make status` knows an answer was about exactly the sheet on disk now (docs/make.feature MK4).++use std::io::{Read as _, Seek as _, SeekFrom};+use std::path::Path;++use sha2::{Digest, Sha256};++pub fn ident(path: &Path) -> Option<String> {+ const MB: u64 = 1 << 20;+ let mut f = std::fs::File::open(path).ok()?;+ let len = f.metadata().ok()?.len();+ let mut h = Sha256::new();+ let mut part = vec![0u8; len.min(MB) as usize];+ f.read_exact(&mut part).ok()?;+ h.update(&part);+ if len > 2 * MB {+ f.seek(SeekFrom::Start(len - MB)).ok()?;+ f.read_exact(&mut part).ok()?;+ h.update(&part);+ }+ let hex: String = h.finalize().iter().take(16).map(|b| format!("{b:02x}")).collect();+ Some(format!("{len}-{hex}"))+}++/// The size an ident names, to pass over files that can't be it without reading them.+pub fn ident_len(ident: &str) -> Option<u64> {+ ident.split_once('-')?.0.parse().ok()+}diff --git a/core/ask/src/lib.rs b/core/ask/src/lib.rsindex fd9c3b48..1236b44d 100644--- a/core/ask/src/lib.rs+++ b/core/ask/src/lib.rs@@ -2,6 +2,7 @@//! question and how its answer reads, the sets that come standard, and the model's limits. Its TypeScript declarations//! are generated from these types (`declarations`): sdk/raea/src/ask.gen.ts, checked by a test.+pub mod ident;pub mod library;pub mod limits;pub mod question;diff --git a/core/ask/src/library.rs b/core/ask/src/library.rsindex ac0a5ae5..509cf7a7 100644--- a/core/ask/src/library.rs+++ b/core/ask/src/library.rs@@ -1,12 +1,14 @@//! The questions that come standard (docs/ask.feature AK1), each set named: `rubric` (the craft rubric's own questions,//! read from sdk/guides/craft/rubric.md, so there's one copy), `av` (picture with sound), `defects` (the fingerprint's-//! axes with no labels yet), `platform` (the check packs' questions with their calibration) and `decide` (picks and-//! comparisons). The JSON sets ship inside raea; the rubric is read from the guide the caller hands in.+//! axes with no labels yet), `platform` (the check packs' questions with their calibration), `decide` (picks and+//! comparisons) and `make` (the review loop's gate questions, asked of a job's sheets: docs/make.feature MK4; each id+//! says its sheet, make.clay.*, make.colour.*, make.refs.*, make.framing.*). The JSON sets ship inside raea; the+//! rubric is read from the guide the caller hands in.use crate::question::{Kind, Question};/// Every set, in the order `raea ask list` shows them.-pub const SETS: [&str; 5] = ["rubric", "av", "defects", "platform", "decide"];+pub const SETS: [&str; 6] = ["rubric", "av", "defects", "platform", "decide", "make"];fn embedded(name: &str) -> Option<&'static str> {Some(match name {@@ -14,6 +16,7 @@ fn embedded(name: &str) -> Option<&'static str> {"defects" => include_str!("../library/defects.json"),"platform" => include_str!("../library/platform.json"),"decide" => include_str!("../library/decide.json"),+ "make" => include_str!("../library/make.json"),_ => return None,})}diff --git a/core/brief/src/make.rs b/core/brief/src/make.rsindex eac46fd3..45f8ef9b 100644--- a/core/brief/src/make.rs+++ b/core/brief/src/make.rs@@ -176,6 +176,10 @@ pub struct Shot {pub handheld: Option<String>,/// a still rather than a movepub still: Option<bool>,+ /// the composition that renders it (relative to the brief): `raea make framing` and `lenschart` draw it+ pub composition: Option<String>,+ /// its frame rate, for the frames `seconds` spans (30 when left out)+ pub fps: Option<f64>,}/// Each kind's dials: what may be set, and what an unset one is read from the references as.@@ -204,7 +208,8 @@ pub fn deliverables(m: &Make) -> Vec<String> {.iter().flat_map(|o| [format!("out/kit/{0}/{0}.glb", o.id), format!("out/kit/{0}/{0}_lod1.glb", o.id), format!("out/kit/thumbs/{}.png", o.id)]).collect();- v.extend(["out/kit/lineup.png".into(), "out/kit/kit.json".into()]);+ // the reference sheet every reference was checked on before any 3D (MK10)+ v.extend(["out/kit/lineup.png".into(), "out/kit/kit.json".into(), "review/refs.png".into()]);v}// a shot is a still or a move, so either file answers; apps/make reads `a|b`@@ -252,6 +257,9 @@ pub fn doctor(m: &Make) -> Vec<String> {if !s.name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {out.push(format!("shot `{}`: names are [a-z0-9_], the file it lands as", s.name));}+ if s.composition.is_none() {+ out.push(format!("shot `{}` has no composition: the .tsx that renders it, for its framing sheet and lens chart", s.name));+ }}out}diff --git a/core/review/src/lib.rs b/core/review/src/lib.rsindex 642b7e14..f71355dc 100644--- a/core/review/src/lib.rs+++ b/core/review/src/lib.rs@@ -78,10 +78,16 @@ pub fn boxes_of(found: &[Value]) -> Vec<Box3> {}).filter(|(lo, hi)| (0..3).all(|k| hi[k].is_finite() && lo[k].is_finite() && hi[k] >= lo[k])).collect()}-/// The parts' box from scene lint's findings, flat wide parts (a ground slab) left out when anything else stands.+/// The parts' box from scene lint's findings, ground slabs left out when anything else stands: a flat part wider+/// than 5 m, or a thin one (under a twentieth of its span) lying at the bottom of the scene, the floor a few props+/// stand on. A raised slab (a table top, a shelf) stays.pub fn parts_box(found: &[Value]) -> Option<Box3> {let boxes = boxes_of(found);- let flat_wide = |(lo, hi): &([f64; 3], [f64; 3])| hi[1] - lo[1] < 0.25 && (hi[0] - lo[0]).max(hi[2] - lo[2]) > 5.0;+ let bottom = boxes.iter().map(|(lo, _)| lo[1]).fold(f64::INFINITY, f64::min);+ let flat_wide = |(lo, hi): &([f64; 3], [f64; 3])| {+ let (h, span) = (hi[1] - lo[1], (hi[0] - lo[0]).max(hi[2] - lo[2]));+ h < 0.25 && (span > 5.0 || (h < 0.05 * span && hi[1] <= bottom + 0.05))+ };let standing: Vec<Box3> = boxes.iter().copied().filter(|b| !flat_wide(b)).collect();whole(if standing.is_empty() { &boxes } else { &standing })}@@ -113,11 +119,27 @@ fn wanted() -> Option<&'static ([f64; 3], [f64; 3], Option<f64>)> {.as_ref()}+/// RAEA_LENS="mm": the scene's own camera kept where it is, with that focal length's field of view on a full-frame+/// sensor (a lens chart, docs/make.feature MK15).+fn lens() -> Option<f64> {+ static LENS: OnceLock<Option<f64>> = OnceLock::new();+ *LENS.get_or_init(|| std::env::var("RAEA_LENS").ok()?.trim().parse::<f64>().ok().filter(|mm| *mm > 0.0).map(fov_of_lens))+}++/// The vertical field of view (degrees) of a focal length (mm) on a 36 x 24 mm sensor.+pub fn fov_of_lens(mm: f64) -> f64 {+ 2.0 * (12.0 / mm).atan().to_degrees()+}+/// A review's fixed camera in place of the scene's own: every frame's camera item is moved there, or one is added when-/// the scene has none. With RAEA_CAMERA unset, nothing changes.+/// the scene has none; or, with RAEA_LENS, the scene's own camera given that lens. With both unset, nothing changes.pub fn camera_override(out: &mut Vec<Item>) {if let Some((eye, at, fov)) = wanted() {place_camera(out, *eye, *at, *fov);+ } else if let Some(fov) = lens()+ && let Some(c) = out.iter_mut().find(|i| i.kind == "camera")+ {+ Arc::make_mut(&mut c.props).insert("fov".into(), json!(fov));}}@@ -157,9 +179,16 @@ mod tests {let r = 3f64.sqrt();assert!(d * (fov / 2.0).to_radians().sin() >= r * 0.99, "{d} {r}");assert_eq!(cams[4].1[1], 0.3);+ // a 50 mm lens on full frame: about 27 degrees vertical (MK15's lens chart)+ assert!((fov_of_lens(50.0) - 26.99).abs() < 0.01);assert_eq!(passed(&["render", "e.tsx", "-o", "x", "--review", "d", "--clay", "--composition", "A"].map(String::from)), vec!["--composition", "A"]);let found = vec![json!({"box": {"min": [-50, -0.1, -50], "max": [50, 0, 50]}}), json!({"box": {"min": [0, 0, 0], "max": [1, 1, 1]}})];assert_eq!(parts_box(&found), Some(([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])));+ // a small floor under a few props (a kit's lineup) is a ground slab too; a raised table top isn't+ let kit = vec![json!({"box": {"min": [-0.6, -0.01, -0.6], "max": [0.6, 0, 0.6]}}), json!({"box": {"min": [-0.2, 0, -0.05], "max": [0.2, 0.14, 0.05]}})];+ assert_eq!(parts_box(&kit), Some(([-0.2, 0.0, -0.05], [0.2, 0.14, 0.05])));+ let table = vec![json!({"box": {"min": [-0.8, 0.72, -0.4], "max": [0.8, 0.75, 0.4]}}), json!({"box": {"min": [-0.7, 0, -0.3], "max": [-0.65, 0.72, -0.25]}})];+ assert_eq!(parts_box(&table), Some(([-0.8, 0.0, -0.4], [0.8, 0.75, 0.4])));// a room with a ceiling is seen from inside: every camera within its walls and under its ceilinglet room = vec![json!({"box": {"min": [-5, 0, -5], "max": [5, 0.1, 5]}}), json!({"box": {"min": [-5, 2.9, -5], "max": [5, 3, 5]}}), json!({"box": {"min": [0, 0, 0], "max": [1, 1, 1]}})];let (lo, hi) = whole(&boxes_of(&room)).unwrap();diff --git a/core/scene/src/parts.rs b/core/scene/src/parts.rsindex 15c6f417..56dd8bac 100644--- a/core/scene/src/parts.rs+++ b/core/scene/src/parts.rs@@ -132,6 +132,7 @@ pub fn label(it: &Item, piece: &str) -> String {}/// A part's triangles in the world, with the node each came from.+#[derive(Clone)]pub struct Part {pub label: String,pub tris: Vec<[Vec3; 3]>,diff --git a/docs/make.feature b/docs/make.featureindex 9d10a5f8..6214c159 100644--- a/docs/make.feature+++ b/docs/make.feature@@ -112,43 +112,47 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revieScenario: MK7. Grounding at contact pointsGiven a part whose box bottom isn't where it touches down (splayed feet, a handle, an origin offset)- Then `raea scene lint` casts rays down from its lowest vertices, ignoring itself, volumes and decals, and reports- `floating_contact` with the gap and its `{dy}` fix; hanging kinds (signs, pendants, lamps on cords) only with- --all; a fix only ever settles a part down+ Then `raea scene lint` casts rays down from its lowest vertices (its feet), ignoring itself, volumes and decals,+ and reports `floats` (the gap, and a `{y, dy}` fix that settles it down) or `sunk` (a fix that raises it);+ a part whose feet reach nothing reads as mounted (a wall or ceiling holds it) or as a warning in the air, so+ signs, pendants and lamps on cords aren't errors; a stool whose box clips a table's edge rests by its feetScenario: MK8. The clip check, for every level- Then the triangle check FLOOR3 used (projects/floor3 tools/clips.ts) is `raea scene lint --clips`: intersections- with depth, z-fighting faces, flicker inside one model, and nothing within 3 mm (floating)+ Then `raea scene lint` (raea-sys-contact) reports clips with their depth and the move that clears them+ (`{part, axis, by}`), and faces z-fighting: two parts' faces in one plane over each other (an error from+ 1 cm², a warning under), and doubled faces inside one model (a warning), on every lint, no flag neededScenario: MK9. Re-drop after every move- Then a part moved sideways by a fix is settled onto what's under its new place in the same pass, and stools drop- from below the table top, so nothing hovers at table height+ Then a part moved sideways by a clip's fix is settled onto what's under its new place in the same pass (the fix+ carries its `dy`), and a stool under a table rests on the floor by its feet, so nothing hovers at table heightRule: kits (MK10-MK13)@needs:MK1Scenario: MK10. References made in one style, checked on one sheet- Then each object's reference is `raea gen image --edit` with the style images as input, the plan's style- paragraph and the scan template, and `raea make sheet refs` puts them all on one sheet before any 3D+ Then `raea make refs` makes each object's reference with `raea gen image` with the style images as input, the+ plan's style paragraph and the scan template (`--dry` quotes it), and writes review/refs.png (`raea make sheet+ refs` again): the style images, then every reference labelled with its size, before any 3DAnd outliers (another style, a real brand, cropped, two objects) are regenerated first: the cheapest place to fixcohesion@needs:MK10Scenario: MK11. Both generators, picked on clay- Then every reference goes to Tripo H3.1 (face limit 150k heroes, 60k small) and Meshy, and `raea gen pick ID...`- renders reference | Tripo beauty | Tripo clay | Meshy beauty | Meshy clay under one light, and records the- pick and a one-line why (the earlier ~150 props: Meshy ~70%, small items and printed labels; Tripo the big+ Then `raea make gen` sends every reference to Tripo H3.1 (face limit 150k heroes, 60k small) and Meshy (fal),+ `raea make pick-sheet` fits both to size and renders reference | Tripo | Tripo clay | Meshy | Meshy clay under+ one light (review/picks.png), and `raea make pick ID tripo|meshy "why"` records the pick and its one-line why (the earlier ~150 props: Meshy ~70%, small items and printed labels; Tripo the bighard-surface heroes)@needs:MK11Scenario: MK12. Prep and LOD- Then `raea gen check -o` fits each pick (front -Y, real metres, bottom-centre, textures at 2K or less) and- `--lod1` writes a quarter-triangle copy, each with its .glb.json saying how it was made+ Then `raea make prep` fits each pick with `raea gen check -o` (front +z, real metres, bottom-centre) and writes a+ quarter-triangle ID_lod1.glb (blender/decimate.py), each with its .glb.json saying how it was made@needs:MK12Scenario: MK13. A kit is a component set- Then a finished kit is shared/components/<kit>/ (one component per object with its fixture), with a `<Lineup>`- composition (scale bar, labels), thumbnails and kit.json, so `raea component add` puts it in any scene+ Then `raea make kit` lands it in shared/components/<kit>/ (one component per object importing its model and LOD+ from beside it: compositions import .glb files as their path), with lineup.tsx (a 1 m bar, labels), cover.png,+ thumbnails and kit.json, and the job's own out/kit/ record that `raea make status` countsRule: shots (MK14-MK17)@@ -159,39 +163,46 @@ Feature: Make: scenes, kits and shots built to a frozen plan and held to a revie@needs:MK14Scenario: MK15. Blocking: framing sheets and a lens chart- Then `raea render --framing` stamps each shot at t = 0, 0.5 and 1 on one sheet, and `--lenschart SHOT` its first- frame at 18, 24, 35, 50, 85 and 135 mm+ Then `raea make framing` renders each shot's first, middle and last frame (`raea render --at`) onto+ review/framing.png, a row a shot stamped with its name and time, and `raea make lenschart SHOT` its first frame+ at 18, 24, 35, 50, 85 and 135 mm (RAEA_LENS keeps the scene's camera and sets its lens)@needs:MK14Scenario: MK16. Clearance on every frame- Then `raea scene stage --clearance 0.45` finds every frame where the camera is nearer a solid than that, leaving- out volumes, particles, decals, glass panes meant to be passed and anything under 5 cm+ Then `raea scene stage --clearance 0.45` finds every run of frames where the camera is nearer a solid than that+ (a box first, a model's triangles when its box comes close; inside a part said so), leaving out volumes,+ particles, decals, see-through parts (glass) and anything under 5 cm@needs:MK14Scenario: MK17. Shots from words and from a floor plan- Then the shot-language guide maps a crew's words to moves (push in, truck, reveal, rack focus, walkthrough at- 0.4-0.6 m/s and 1.5-1.7 m), and a floor plan with a drawn path is registered to an ortho top render and its- path becomes `path` keys; grade looks (clean, cinematic, gritty, vintage) are raea/post presets+ Then the shot-language guide (bevy/shots) maps a crew's words to moves (push in, truck, reveal, rack focus,+ walkthrough at 0.4-0.6 m/s and 1.5-1.7 m); a path drawn on `raea make plan`'s floor plan (its metres, x right,+ z away from the entrance) is `walkPath(points)`: an even walking pace at eye height, corners rounded; grade looks+ (clean, cinematic, gritty, vintage) are `gradeLook()` presets in raea/post_processRule: the plan, drawn (MK18)@needs:MK0Scenario: MK18. `raea make plan`: a floor plan, a grey box and a comparison- Then it draws floor-plan.png (labelled footprints, invented ones dashed, lights, the reference camera's cone),- renders a grey box of the plan from the reference camera (raea/room and boxes, `raea render --review`) and- puts the reference beside it, for the person to approve before anything is generated+ Then it draws review/plan/floor-plan.png (every placed object's footprint turned by its rot and labelled with its+ height, invented ones dashed, a metre grid, the entrance the camera looks in from), renders a grey box of the+ plan from the entrance (blockout.tsx, and `raea render --review` sheets of it) and puts the reference, the+ blockout and the floor plan on comparison.png, for the person to approve before anything is generatedRule: raea cloud (MK19-MK20)@needs:MK2Scenario: MK19. Three skills on raea cloud- Then raea cloud has "Scene from references" (stops: plan, spend, picks, finals), "Kit from style" (plan,- reference sheet, spend, lineup) and "Shots of a scene" (shot list, framing, finals), each stop's checks calling- `raea make status --json` on the box+ Then raea cloud has "Scene from references" (plan, spend, first cut, deliver), "Kit from style" (reference+ sheet, spend, deliver) and "Shots of a scene" (framing, deliver) as skill templates (GET|POST+ /v1/skills/templates), each with a workflow whose agent steps are checked by a `raea make status` line: run as+ `raea make status --json` on the box in the project's folder, "says done" holding on its done and "raea make+ status: critic, review/refs.png" on each named gate and file@needs:MK19Scenario: MK20. Retry-safe jobs and a live view- Then a project is keyed by a hash of its inputs: the same ask returns the finished project, attaches to the- running one or resumes it without paying again for what's already generated- And every picture the agent opens goes to the live watch with a preview, and a heartbeat every 20 s repeats the- milestones so far for anyone who joins late+ Then a project is keyed by a hash of its inputs (or the caller's Idempotency-Key; plan.org's :INPUTS:): the same+ ask from the API, the studio, a form or a webhook returns the finished project, attaches to the running one or+ resumes a failed one without paying again; one a person stopped doesn't hold the ask+ And every picture the agent opens goes to the live watch as a raea.seen event (its path, and a preview when the+ bytes are under 600 KB), and a raea.heartbeat every 20 s repeats the milestones so far for anyone who joins latediff --git a/docs/manual/reference/cli/ask.md b/docs/manual/reference/cli/ask.mdindex 1235ceef..dae4e896 100644--- a/docs/manual/reference/cli/ask.md+++ b/docs/manual/reference/cli/ask.md@@ -8,8 +8,8 @@ sources: ["apps/ask/src/verbs.rs", "apps/ask/src/prepare.rs", "apps/ask/src/runn`raea ask` puts questions about a video, a sound or a picture to clef-omni, the decision model raea's checks use, andprints each answer in words with its probability, the window it looked at and what it cost. Ask in your own words, oruse the standard questions: the craft rubric's (`rubric`), picture and sound together (`av`), the defects the-fingerprint can't judge yet (`defects`), the platform checks (`platform`) and picking between versions (`decide`).-`raea ask list` lists them all.+fingerprint can't judge yet (`defects`), the platform checks (`platform`), picking between versions (`decide`) and the+review loop's gate questions about a [`raea make`](make.md) job's sheets (`make`). `raea ask list` lists them all.Before it spends anything it reads what it can about the piece: what the file holds, the project's brief (the nearest`brief.ts` above the file, or `--brief`) and whether anyone speaks (`--words`, `--voice`). A question that doesn't@@ -63,7 +63,7 @@ raea ask try "Is the voice hard to hear over the music?" --like own-does-the-mus## Usage```sh-raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)+raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide, make); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)```Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.diff --git a/docs/manual/reference/cli/judge.md b/docs/manual/reference/cli/judge.mdindex 8a2c6486..411cdb5b 100644--- a/docs/manual/reference/cli/judge.md+++ b/docs/manual/reference/cli/judge.md@@ -2,7 +2,7 @@title: "raea judge"summary: "Judge a 3D scene's review sheets blind, by a model on a frozen rubric or a fresh agent session, with the pass decided in code."order: 43-sources: ["apps/judge/src/lib.rs"]+sources: ["apps/judge/src/lib.rs", "apps/judge/src/rubric.rs", "apps/judge/src/agent.rs", "apps/judge/src/eye.rs"]---`raea judge` reads the sheets [`raea render --review`](render.md) makes (`colour.png`, `clay.png`) and has them@@ -10,10 +10,19 @@ judged without the code or the conversation that made them: by clef-omni on a frfresh Kimi or Claude session on the judge prompt. The scores come back as data, and whether the scene passes isdecided in code from them. clef only advises until it has been calibrated against a person's or an agent's eye.+`--kind scene|kit|shot` judges on that kind's own rubric, for a job [`raea make`](make.md) holds: a scene on layout,+props, signage, materials, light, atmosphere, plausibility and composition; a kit on cohesion, reference fidelity,+the brief, mesh, texture, assembly, scale and labels; a shot on framing, move, focus, clearance, continuity and grade+(read from `framing.png`, which `raea make framing` writes). Form categories (layout, props, mesh, assembly, scale) are+judged on the clay sheet. The bar is a production base: don't nitpick, at most five fixes, each to do in a script.+The verdict and the log line say the kind, and `raea judge calibrate --kind KIND` fits that kind's calibration on its+own.+```shraea render scene.tsx --review review/raea judge review/ --brief brief.tsraea judge review/ --by claude --target reference.png --json+raea judge review/r3 --kind kit --by claude --brief brief.ts # a kit job's round, on the kit rubricraea judge eye review/ composition=4 light=3 --pass yes # record your own scores, for calibrationraea judge calibrate```@@ -23,7 +32,7 @@ raea judge calibrate## Usage```sh-raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; the pass decided in code; clef advises until calibrated against your eye or an agent's)+raea judge DIR [--kind scene|kit|shot] [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; --kind asks a raea make job's own rubric (a shot list's framing.png); the pass decided in code; clef advises until calibrated against your eye or an agent's, each kind on its own)```Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.@@ -36,6 +45,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu| `--by` | `clef\|kimi\|claude` | Who judges: clef-omni on the rubric (default), or a fresh Kimi or Claude session. With `judge eye`, the agent whose eye is recorded. || `--dry` | – | Print what the judge would be asked, with its images, without asking. || `--json` | – | Print the verdict as JSON: each score, the defects found and the pass. |+| `--kind` | `scene\|kit\|shot` | The rubric: `scene`, `kit` or `shot` (the make loop's categories), instead of the film rubric. || `--pass` | `yes\|no` | With `judge eye`: whether you'd pass it, recorded with your scores. || `--target` | `T.png` | A reference image the colour sheet is judged against. |diff --git a/docs/manual/reference/cli/make.md b/docs/manual/reference/cli/make.mdindex 064bbc38..accc646a 100644--- a/docs/manual/reference/cli/make.md+++ b/docs/manual/reference/cli/make.md@@ -1,8 +1,8 @@---title: "raea make"-summary: "Whether a scene, kit or shot made to its plan is done: what's missing, each gate, the judge's rounds, decided in code; the agent's Stop hook holds it there."+summary: "A scene, kit or shot made to its plan: the plan stop, the kit's references, generators, pick, prep and landing, a shot list's framing and lens charts, and whether it's done, decided in code; the agent's Stop hook holds it there."order: 44-sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "core/brief/src/make.rs", "apps/check/src/make_gate.rs"]+sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "apps/make/src/asked.rs", "apps/make/src/plan.rs", "apps/make/src/kit.rs", "apps/make/src/kitout.rs", "apps/make/src/shots.rs", "apps/make/src/floor.rs", "apps/make/src/sheet.rs", "core/brief/src/make.rs", "apps/check/make/src/lib.rs"]---`raea make status` reads the job on a project's brief.ts (`make: scene({...})`, `kit({...})` or `shot({...})` from@@ -12,9 +12,17 @@ sources: ["apps/make/src/lib.rs", "apps/make/src/status.rs", "core/brief/src/makand kit.json; a shot's still or move per shot), or the plan's own `deliverables`;- NOTES.md, ending with a "What the skill got wrong" section;- each composition the plan names has a render or check newer than it that found no error (the project's record);-- a fresh critic (`raea judge`) has judged a round newer than the newest deliverable, and each blocking defect it- named is fixed or answered in NOTES.md by its name; once the judge is calibrated against your eye, two passes in a- row as well.+- a fresh critic (`raea judge --kind KIND`) has judged a round newer than the newest deliverable on the job's own+ kind's rubric, and each blocking defect it named is fixed or answered in NOTES.md by its name; once the judge is+ calibrated against your eye, two passes in a row as well;+- each `raea ask` question of the make set that's calibrated (`raea ask calibrate`) has been asked of the job's+ latest sheets (clay and colour, the reference sheet for a kit, the framing sheet for a shot) and didn't flag, or is+ answered in NOTES.md. A question not calibrated yet is advice: status lists what it flagged and doesn't wait on it.+ An answer counts for the sheet it was asked of, matched by the file's bytes, so a sheet rendered again is asked+ again.++`--plan` writes the gates as check lines under the job's own task in the project's plan.org, keeping the person's+mark (DONE, DROPPED) and their own lines; the Stop hook runs it so.A job is done when all of that holds, and also at its round cap (8 by default) or when three rounds in a row haven'tbeaten the best before them: then it's delivered short, with what's missing listed. raea's Stop hook (`raea hook`)@@ -26,20 +34,76 @@ raea make statusraea make status ~/Documents/raea/acme/projects/flight-desk-kit --json```+## The steps++Each step reads the plan from the brief.ts at or above DIR and works beside it.++- **The plan stop** (any kind with placed objects): `raea make plan` draws `review/plan/floor-plan.png` (every+ object's footprint at its `at`, turned by its `rot`, labelled with its height; invented ones dashed), renders a+ grey-box blockout of the plan from the entrance (`blockout.png`, and its review sheets unless `--no-review`), and+ puts the first reference, the blockout and the floor plan on `comparison.png`.+- **A kit**, in order:+ - `raea make refs` makes each object's reference from the plan's style images, in its style paragraph, with the+ scan template (one object, whole, on plain grey, even light), then the reference sheet `review/refs.png`.+ `--only` remakes some, `--dry` quotes it and spends nothing.+ - `raea make gen` sends each reference to Tripo H3.1 (150 000 faces for a hero, 60 000 for a prop) and Meshy on+ fal, into `out/kit/gen/ID/` (`--tripo`, `--meshy` to change either; `--dry` quotes it).+ - `raea make pick-sheet` fits both models to the object's real size and draws each in colour and in clay beside+ the reference: `review/picks.png`. `raea make pick ID tripo|meshy "why"` records the pick in out/kit/picks.json.+ - `raea make prep` fits each pick to its real size with `raea gen check`, makes a quarter-triangle `ID_lod1.glb`+ beside it (`raea blender run blender/decimate.py`), and writes a `.glb.json` sidecar for each.+ - `raea make kit` lands the kit as a component set: the workspace's `shared/components/KIT/` (else the project's+ `components/KIT/`, or `--to`), one component per object importing its model and LOD from beside it, `lineup.tsx`+ with a 1 m bar, `cover.png`, `thumbs/` and `kit.json`; and the job's own `out/kit/` record that status counts.+- **A shot list**: `raea make framing` renders every shot's first, middle and last frame (from its `seconds` at its+ `fps`, 30 when left out) with `raea render --at` and puts them on `review/framing.png`, a row a shot, stamped with+ its name and time. `raea make lenschart SHOT` renders a shot's first frame at 18, 24, 35, 50, 85 and 135 mm+ (RAEA_LENS) onto `review/lens-SHOT.png`. Each shot needs its `composition`.++```sh+raea make plan+raea make refs --dry && raea make refs+raea make gen --only rotary_phone+raea make pick rotary_phone meshy "Tripo fused the handset to the cradle"+raea make prep && raea make kit --name flight-desk+raea make framing --only counter_push+raea make lenschart counter_push+```+<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->## Usage```sh-raea make status [DIR] [--json] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate, the judge's rounds, and whether it's done, decided in code; the agent's Stop hook holds it there)+raea make status [DIR] [--json] [--plan] (a scene, kit or shot held to its plan, `make` on brief.ts: what's missing, each gate (renders and checks, raea ask's calibrated questions, the critic on the kind's rubric), the judge's rounds, and whether it's done, decided in code; --plan writes the gates as check lines under the job's task in plan.org; the agent's Stop hook holds it there)+raea make plan [DIR] [--no-review] (the plan stop: review/plan/floor-plan.png, a grey-box blockout from the entrance and its review sheets, comparison.png beside reference 0)+raea make refs [DIR] [--only ID,...] [--model M] [--dry] (a kit: every object's reference from the style images, in the plan's style, then review/refs.png; --dry quotes it)+raea make sheet refs [DIR] (review/refs.png again: the style images, then every reference)+raea make gen [DIR] [--only ID,...] [--tripo M] [--meshy M] [--dry] (each reference to both generators, Tripo H3.1 and Meshy on fal: out/kit/gen/ID/)+raea make pick-sheet [DIR] [--only ID,...] (review/picks.png: reference | Tripo | Tripo clay | Meshy | Meshy clay, fitted to size)+raea make pick ID tripo|meshy "why" [DIR] (the pick and its reason, out/kit/picks.json)+raea make prep [DIR] [--only ID,...] (each pick fitted to its real size, a quarter-triangle _lod1 beside it, .glb.json sidecars)+raea make kit [DIR] [--name KIT] [--to FOLDER] (the kit as a component set: shared/components/KIT, lineup.tsx, cover.png, thumbs, kit.json)+raea make framing [DIR] [--only NAME,...] [--out DIR] (a shot list: each shot's first, middle and last frame on framing.png, stamped)+raea make lenschart SHOT [DIR] [--out DIR] (a shot's first frame at 18, 24, 35, 50, 85 and 135 mm on lens-SHOT.png)```-Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.+Headless: it needs nothing running and opens no window. Takes up to 5 arguments besides its flags.## Flags| Flag | Takes | What it does || --- | --- | --- |+| `--dry` | – | Quote the generation (refs, gen) and make nothing. || `--json` | – | Print the status as JSON: missing, gates, judge, done, short and why. |+| `--meshy` | `M` | The Meshy model for `gen` (default `fal:meshy/v7.1/image-to-3d`). |+| `--model` | `M` | The image model for `refs` (default raea gen image's). |+| `--name` | `KIT` | The kit's folder name for `kit` (default the brief's directory name). |+| `--no-review` | – | `plan` without the blockout's `raea render --review` sheets. |+| `--only` | `ID,...` | Only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. |+| `--out` | `DIR` | Where the sheet or chart is written (default the job's review/). |+| `--plan` | – | Also write the gates as check lines under the job's task in plan.org. |+| `--to` | `FOLDER` | Where `kit` lands the components (default the workspace's shared/components/KIT). |+| `--tripo` | `M` | The Tripo model for `gen` (default `tripo:H3.1`). |<!-- generated:end -->diff --git a/docs/manual/reference/cli/scene.md b/docs/manual/reference/cli/scene.mdindex 9700f518..5f40212c 100644--- a/docs/manual/reference/cli/scene.md+++ b/docs/manual/reference/cli/scene.md@@ -1,18 +1,25 @@---title: "raea scene"summary: "Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, and hold every frame to the stage checks a render runs."-order: 46-sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.rs", "systems/stage/src/lib.rs"]+order: 47+sources: ["apps/scene/src/lib.rs", "apps/scene/src/light.rs", "apps/scene/src/stage.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-parts that float, sink into what they stand on, clip into each other or tilt, and exits 1 on an error. `explain`+parts that float, sink into what they stand on, clip into each other or tilt, and exits 1 on an error. A float or+sink is measured at the part's feet (rays down from its lowest points), not its box, so a stool whose box clips a+table's edge but whose feet are on the floor rests. A clip comes with the move that clears it (the part, the axis,+how far) and, when the move is sideways, where it settles once moved. Faces of two parts lying in one plane over each+other (a rug's top in the floor's, which flickers as the camera moves) are an error from 1 cm² up. `explain`says what every part rests on. `light` meters the light on the shot's subject; given several compositions, itcompares their first and last frames across each cut. `stage` steps every frame and holds it to the checks `raearender` runs at its end (docs/stage-guards.feature): 3D words too small or turned too far to read, a reveal thatnever starts or never finishes, a part whose size jumps in one frame, a camera that lurches or goes in and back out,frames with almost nothing on screen. It exits 1 on an error, as the render would, without drawing a frame, so it's-the cheap look before one. RichText `read={false}` leaves a sign nobody is meant to read out of it.+the cheap look before one. RichText `read={false}` leaves a sign nobody is meant to read out of it. `--clearance M`+also holds the camera M metres off every solid part on every frame (0.45 for a carried camera, less for a rig): each+part it comes closer to, the frames and the nearest it gets, or that it's inside the part. Glass, decals, volumes and+parts under 5 cm are passed over.```shraea scene lint room.tsx@@ -20,6 +27,7 @@ raea scene explain room.tsx --frame 90 --jsonraea scene light room.tsx --part heroraea scene light film.tsx --composition shot1,shot2,shot3 # the light across the cutsraea scene stage film.tsx --from 1800 --to 2400 # the stage checks on 20 s of it+raea scene stage walk.tsx --clearance 0.45 # and the camera kept off the set```<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->@@ -28,7 +36,7 @@ raea scene stage film.tsx --from 1800 --to 2400 # the stage check```shraea 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|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)+raea scene lint|explain|light|stage 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 2 arguments besides its flags.@@ -38,6 +46,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments| Flag | Takes | What it does || --- | --- | --- || `--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. |+| `--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). || `--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`). || `--from` | `N` | With `stage`: 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. |diff --git a/docs/manual/reference/sdk/ask.md b/docs/manual/reference/sdk/ask.mdindex 2f5133b2..a4e372c8 100644--- a/docs/manual/reference/sdk/ask.md+++ b/docs/manual/reference/sdk/ask.md@@ -95,7 +95,7 @@ One file and what to ask of it: a line of `raea ask --batch`.| --- | --- | --- || `file` (required) | `string` | the video, sound or picture asked about || `questions` | `(string \| Question)[]` | questions in your own words (yes or no) or written out |-| `set` | `string \| string[]` | standard sets by name: rubric, av, defects, platform, decide |+| `set` | `string \| string[]` | standard sets by name: rubric, av, defects, platform, decide, make || `std` | `string[]` | standard questions by id (`raea ask list` lists them) || `window` | `Window` | the seconds to look at, for every question here (else each question's own, else the whole file) || `with` | `string[]` | files set beside it: to pick between, or a before and after |diff --git a/docs/manual/reference/sdk/brief.md b/docs/manual/reference/sdk/brief.mdindex acaab026..6018bdc9 100644--- a/docs/manual/reference/sdk/brief.md+++ b/docs/manual/reference/sdk/brief.md@@ -30,10 +30,10 @@ See [Workspaces and projects](../../concepts/workspaces.md) for where each spec<!-- generated:begin by tools/manual-ref/sdk.ts from the SDK's exports and doc comments; edit outside this block -->```ts-import { brief, fingerprint, parts, script } from "raea/brief"+import { brief, fingerprint, kit, parts } from "raea/brief"```-`raea/brief` exports 5 functions, 24 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).+`raea/brief` exports 8 functions, 34 types. Source: [sdk/raea/src/brief.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/brief.ts).## Functions@@ -54,6 +54,15 @@ A fingerprint (fingerprint.ts): its axes and the encoders its heads were trainedfunction fingerprint(f: Fingerprint): Fingerprint```+### `kit`++A kit: props in one style at real size (`style` is the paragraph every reference carries: era, palette, materials,+wear and one fictional maker). Done is a GLB, a LOD1 and a thumbnail per object, a lineup and kit.json.++```ts+function kit(m: Omit<Make, "kind">): Make+```+### `parts`An object's parts (NAME.parts.ts), written before any geometry: each by name, its level, count and material.@@ -62,6 +71,16 @@ An object's parts (NAME.parts.ts), written before any geometry: each by name, itfunction parts(p: Parts): Parts```+### `scene`++A job made to a frozen plan and held to the review loop: `make: scene({...})` on brief.ts. Every+object has its real size and whether it came from the reference or was invented; `raea make status` decides when+it's done, and the agent's Stop hook holds it there.++```ts+function scene(m: Omit<Make, "kind">): Make+```+### `script`A storyboard or a screenplay (script.ts): scenes, beats, lines, camera and cut.@@ -70,6 +89,14 @@ A storyboard or a screenplay (script.ts): scenes, beats, lines, camera and cut.function script(s: Script): Script```+### `shot`++Shots of a built scene, each named for the file it lands as and described in a crew's words.++```ts+function shot(m: Omit<Make, "kind">): Make+```+### `taste`Taste (taste.ts): standing rules, the person's, a workspace's or a project's. A rule raea can hold the work to@@ -172,6 +199,66 @@ type Level = "primary" | "secondary" | "tertiary"type Line = { /** * a character, or "narrator" */ who: string, says: string, /** * a screenplay's parenthetical ("quietly") */ how?: string, }```+### `Make`++```ts+type Make = { kind: MakeKind, /** * the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit */ references?: Array<string>, /** * one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker */ style?: string, /…+```++### `MakeDial`++```ts+type MakeDial = MakeDialValue | { value: MakeDialValue, source?: MakeSource, /** * what the value meant for this job, in one line */ means?: string, }+```++### `MakeDialValue`++```ts+type MakeDialValue = number | string+```++### `MakeKind`++```ts+type MakeKind = "scene" | "kit" | "shot"+```++### `MakeObject`++```ts+type MakeObject = { /** * snake_case, unique in the job */ id: string, label: string, /** * real height in metres */ h?: number, /** * [width, depth, height] in metres, for boxy things (generators invent depth) */ dims?: [number, number, number], /** * largest extent in metres, for things that lie flat (tools, pap…+```++### `MakeOrigin`++```ts+type MakeOrigin = "reference" | "invented"+```++### `MakePick`++```ts+type MakePick = { /** * "tripo-h31", "meshy", ... */ generator: string, /** * one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle") */ why: string, }+```++### `MakeRoute`++```ts+type MakeRoute = "solid" | "rule" | "gen" | "library" | "picture"+```++### `MakeShot`++```ts+type MakeShot = { /** * [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4) */ name: string, /** * in a crew's words: "slow push along the counter, rack focus to the register" */ description?: string, /** * static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path */ move?: string, seco…+```++### `MakeSource`++```ts+type MakeSource = "customer" | "reference"+```+### `Modality`What an axis's head reads: the frames (SigLIP 2), how they change, their look, the sound (CLAP) or its events (YAMNet).diff --git a/docs/manual/reference/sdk/camera.md b/docs/manual/reference/sdk/camera.mdindex b6b6e793..6dec2f5d 100644--- a/docs/manual/reference/sdk/camera.md+++ b/docs/manual/reference/sdk/camera.md@@ -22,7 +22,7 @@ const Shot = () => <Camera3d transform={Transform.fromXyz(-2, 2.5, 5).lookingAt(import { Camera3d, cameraPath, Canvas3D, checkMatchmove } from "raea/camera"```-`raea/camera` exports 6 components, 1 hook, 4 functions, 1 value, 15 types. Bevy's counterpart: `bevy_camera`. Source: [sdk/raea/src/camera.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/camera.ts).+`raea/camera` exports 6 components, 1 hook, 9 functions, 4 values, 19 types. Bevy's counterpart: `bevy_camera`. Source: [sdk/raea/src/camera.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/camera.ts).## Components@@ -143,6 +143,36 @@ Checks a Matchmove's props; throws a TypeError or RangeError naming the prop.function checkMatchmove(p: MatchmoveProps): void```+### `focusAt`++The focal distance (metres from the camera) at a frame: a DepthOfField's focal_distance.++```ts+function focusAt(f: Focus, path: CameraPath, frame: number): number+```++### `handheld`++A walking operator's motion on a path: the camera bobs with each step (1.8 Hz) and sways with each stride (0.9 Hz),+rolls a little with the sway, reframes slowly, and its aim follows the path's on a spring, so it lags a turn and+settles after it. Deterministic: the same path, fps and seed give the same frames. Nothing moves faster than 1.9 Hz.++```tsx+const walk = handheld(shotMove({ kind: "dolly", from: [0, 1.6, 6], look: [0, 1.5, 0], by: 4, frames: 300 }), { fps: 30 });+```++```ts+function handheld(path: CameraPath, o?: { profile?: HandheldProfile; fps?: number; seed?: number; amount?: number; }): CameraPath+```++### `lens`++The vertical field of view (degrees) of a focal length on a full-frame (36 x 24 mm) sensor.++```ts+function lens(mm: number): number+```+### `matchmoveIndex`The solve's frame at a time in the clip: the latest at or before it, clamped to the solve.@@ -160,12 +190,48 @@ zoom) and the frame's window in it, in frame pixels.function matchmoveView(footage: { width: number; height: number; }, frame: { width: number; height: number; }, crop?: number | [number, number], zoom?: number): { width: number; height: number; x: number; y: number; }```+### `shotMove`++A crew's move as a camera path. Each eases out of its start and into its end, and never lurches.++```tsx+const push = shotMove({ kind: "dolly", from: [0, 1.6, 4], look: [0, 1.2, 0], by: 1.5, frames: 120, fov: lens(35) });+<Camera3d {...push.camera(useCurrentFrame())} />+```++```ts+function shotMove(m: ShotMove): CameraPath+```++### `walkPath`++A path drawn on the floor plan (`raea make plan`'s floor-plan.png: x right, z away from the entrance, metres) as a+camera walking it: at eye height, at an even walking pace (0.4-0.6 m/s reads as a person; 0.5 by default), easing+only where it starts and stops, its corners rounded (`turn` metres either side) so it turns as a walker does rather+than stopping; looking `ahead` metres along the way, or at `look` throughout. Give it to `handheld` for the step.++```ts+function walkPath(points: readonly [number, number][], o?: { speed?: number; eye?: number; fps?: number; ahead?: number; look?: CameraVec3; start?: number; fov?: number; turn?: number; }): CameraPath+```+## Values### `LABEL_MIN`The least capital height a Label takes, in px at 1080 lines (SG10's floor for words that read).+### `LENSES`++The focal lengths a lens chart shows.++### `STEP_HZ`++A walker's steps, and the sway at half of it (one foot then the other). Every motion here is at or under STEP.++### `WALK`++A walkthrough's pace and eye height, as AnyShot's shot language keeps them: a person walking a set slowly.+## Types### `Camera3dProps`@@ -229,6 +295,20 @@ Bevy: `bevy_camera::clear_color::ClearColorConfig`.type ClearColorConfig = "Default" | "None" | { Custom: Srgba | LinearRgba }```+### `Focus`++Where the lens is focused.++```ts+type Focus = | { kind: "point"; at: CameraVec3 } | { kind: "track"; target: (frame: number) => CameraVec3 } /** from one subject to the other over `over` frames starting at `at`, held on each before and after */ | { kind: "rack"; from: CameraVec3; to: CameraVec3; at: number; over: number }+```++### `HandheldProfile`++```ts+type HandheldProfile = "walk" | "subtle"+```+### `LabelCamera`The camera a Label projects through: the props its Camera3d is given.@@ -308,6 +388,12 @@ Each frame's state under a <Matchmove>, for the 3D inside it.| `camera` (required) | `MatchmoveCamera` | the solve's camera for this frame || `project` (required) | `(p: Vec3) => [number, number, number]` | where a point of the solved world lands in the composition, in pixels ([x, y], and its distance in front of the camera; behind it when that's 0 or less) |+### `MoveKind`++```ts+type MoveKind = "static" | "dolly" | "truck" | "pedestal" | "crane" | "pan" | "tilt" | "orbit" | "dollyZoom" | "path"+```+### `Projection`Bevy's Projection enum, as it reflects: fov in radians (Bevy's default PI/4).@@ -316,4 +402,12 @@ Bevy's Projection enum, as it reflects: fov in radians (Bevy's default PI/4).type Projection = | { Perspective: { fov?: number; near?: number; far?: number } } | { Orthographic: { near?: number; far?: number; scaling_mode?: { FixedVertical: { viewport_height: number } } } }```+### `ShotMove`++A move: where the camera starts, what it looks at, and how it moves over `frames` from frame `at`.++```ts+type ShotMove = { kind: MoveKind; /** The camera's start. */ from: CameraVec3; /** What it looks at (the subject). */ look: CameraVec3; /** The frame it starts moving (0 if left out). */ at?: number; /** How many frames it moves for. */ frames: number; /** Metres: dolly in (negative: out), truck right (negative:…+```+<!-- generated:end -->diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.mdindex cb7a2ba9..83b74d91 100644--- a/docs/manual/reference/sdk/index.md+++ b/docs/manual/reference/sdk/index.md@@ -33,7 +33,7 @@ The composition, the app, and the specs and notes an agent writes.| --- | --- | --- || [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 64 functions, 11 values, 108 types || [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 4 functions, 3 classes, 17 values, 17 types |-| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 5 functions, 24 types |+| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 8 functions, 34 types || [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |## Time and motion@@ -70,12 +70,12 @@ Bevy's 3D: cameras, lights, materials, meshes and the frame after it's drawn.| Import | What it's for | Exports || --- | --- | --- || [`raea/3d`](3d.md) | raea's scene layer: models, physics, splats, matchmoves, instancing, custom shader passes and 3D text. | 70 components, 4 hooks, 26 functions, 3 classes, 12 values, 126 types |-| [`raea/camera`](camera.md) | Cameras and the views they make: Camera3d, the Canvas3D a 2D scene draws in, HDR and matchmoved cameras. | 6 components, 1 hook, 4 functions, 1 value, 15 types |+| [`raea/camera`](camera.md) | Cameras and the views they make: Camera3d, the Canvas3D a 2D scene draws in, HDR and matchmoved cameras. | 6 components, 1 hook, 9 functions, 4 values, 19 types || [`raea/light`](light.md) | Bevy's lights in Bevy's units, environments, skies and daylight. | 15 components, 9 functions, 2 values, 15 types || [`raea/pbr`](pbr.md) | Materials and volumes: StandardMaterial, extended and toon materials, custom shaders, decals, fog and fire. | 23 components, 1 function, 1 value, 37 types || [`raea/mesh`](mesh.md) | Shapes and solids: Mesh3d and Mesh2d, Bevy's primitives, buffer meshes, instancing and exact solids. | 16 components, 1 function, 2 classes, 10 values, 26 types || [`raea/transform`](transform.md) | Where things are: Bevy's Transform and Quat, and nesting. | 2 functions, 2 values, 4 types |-| [`raea/post_process`](post_process.md) | What's done to the frame after it's drawn: tone mapping, bloom, depth of field, motion blur, grading and outlines. | 12 components, 14 types |+| [`raea/post_process`](post_process.md) | What's done to the frame after it's drawn: tone mapping, bloom, depth of field, motion blur, grading and outlines. | 12 components, 1 function, 1 value, 15 types || [`raea/picking`](picking.md) | What the pointer is over: the nearest part under it, and the ray it casts. | 2 functions, 3 types || [`raea/gizmos`](gizmos.md) | Lines drawn for looking: Bevy's gizmos and debug overlays. | 2 components, 1 function, 3 types |diff --git a/docs/manual/reference/sdk/post_process.md b/docs/manual/reference/sdk/post_process.mdindex e5338684..1d17d86a 100644--- a/docs/manual/reference/sdk/post_process.md+++ b/docs/manual/reference/sdk/post_process.md@@ -29,7 +29,7 @@ const Glow = () => (import { AntiAliasing, Bloom, Compute, DepthOfField } from "raea/post_process"```-`raea/post_process` exports 12 components, 14 types. Bevy's counterpart: `bevy_post_process, bevy_anti_alias`. Source: [sdk/raea/src/post_process.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/post_process.ts).+`raea/post_process` exports 12 components, 1 function, 1 value, 15 types. Bevy's counterpart: `bevy_post_process, bevy_anti_alias`. Source: [sdk/raea/src/post_process.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/post_process.ts).## Components@@ -134,6 +134,20 @@ Bevy: `bevy_render::view::Tonemapping`, `bevy_camera::camera::Exposure`.Takes [`ToneMappingProps`](3d.md#tonemappingprops)'s props.+## Functions++### `gradeLook`++A grade look's props, with your changes over it: `<Grade {...gradeLook("cinematic", { vignette: 0.1 })} />`.++```ts+function gradeLook(look: GradeLook, over?: GradeProps): GradeProps+```++## Values++### `GRADES`+## Types### `AntiAliasingProps`@@ -214,6 +228,12 @@ A shader over the whole frame. Its source defines| `at` | `"before-tonemap" \| "after-tonemap"` | "after-tonemap" (display colours; the default) or "before-tonemap" (the HDR frame, after bloom) || `prepass` | `boolean \| { depth?: boolean; normal?: boolean }` | the camera's depth and normal prepasses, for depth(uv) and normal(uv) (turns its multisampling off) |+### `GradeLook`++```ts+type GradeLook = "clean" | "cinematic" | "gritty" | "vintage"+```+### `GradeProps`| Field | Type | What it is |diff --git a/runtime/bundle/src/rewrite.rs b/runtime/bundle/src/rewrite.rsindex 3b7ed23a..8d7a041e 100644--- a/runtime/bundle/src/rewrite.rs+++ b/runtime/bundle/src/rewrite.rs@@ -35,7 +35,9 @@ pub fn drop_tsconfigs(dir: &Path, depth: usize) {}}-pub const MEDIA_EXTS: [&str; 10] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif"];+/// Files a composition imports as their path (`import chair from "./chair.glb"`): media, and models, so a component+/// carries its own (a kit's, `raea make kit`) wherever it's imported from.+pub const MEDIA_EXTS: [&str; 12] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];/// The edit's source with its imports pointed at the bundle's copy of the SDK (its package name, a subpath such as /3d,/// or a relative path into raea/motion/src), and media imported as modules turned into their paths (spec: "Mediadiff --git a/runtime/bundle/src/tests.rs b/runtime/bundle/src/tests.rsindex bbbaa61d..04ce3d52 100644--- a/runtime/bundle/src/tests.rs+++ b/runtime/bundle/src/tests.rs@@ -114,3 +114,18 @@ fn an_edit_s_sources_leave_out_hidden_folders_and_packages() {assert_eq!(got, vec![PathBuf::from("a.tsx"), PathBuf::from("parts/b.ts")]);let _ = std::fs::remove_dir_all(&d);}++// MK13: a component imports its own model beside it, as media is imported: the path, wherever it's imported from+#[test]+fn a_model_imports_as_its_path() {+ let d = std::env::temp_dir().join(format!("raea-bundle-glb-{}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ std::fs::write(d.join("phone.glb"), b"glTF").unwrap();+ let m = &raea_io_home::home().join("sdk/raea/src");+ let out = rewrite_into("import model from \"./phone.glb\";\n", &d, m, "../motion", None).unwrap();+ let abs = dunce::canonicalize(d.join("phone.glb")).unwrap();+ assert!(out.contains(&format!("const model = {:?}", abs.display().to_string())), "{out}");+ let err = rewrite_into("import gone from \"./gone.glb\";\n", &d, m, "../motion", None).unwrap_err();+ assert!(err.contains("gone.glb doesn't exist"), "{err}");+ let _ = std::fs::remove_dir_all(&d);+}diff --git a/sdk/guides/craft/bevy.md b/sdk/guides/craft/bevy.mdindex f055997b..da7b6f6e 100644--- a/sdk/guides/craft/bevy.md+++ b/sdk/guides/craft/bevy.md@@ -22,6 +22,8 @@ pieces; then write the file. Each file's example is a complete composition you c| people: bodies posed by goals (a hand on the mouse, sat, looking at the screen), motion capture, walking round the furniture to a spot | `bevy/characters` || interiors: rooms, cabinets along walls, windows and bays, chairs turned to tables, layout checks, wall decor, the garden outside, daylight, sounds placed in the scene | `bevy/rooms` || a whole scene to build and make believable: the brief, which tool makes which object, build order, review sheets, the judge, when to stop | `bevy/scenes` |+| a kit of props in one style: references from style images, a reference sheet, Tripo and Meshy picked on clay, LODs, landed as components with a lineup | `bevy/kits` |+| shots of a built set from a crew's words: moves, walkthroughs from the floor plan, handheld, focus pulls, lens charts, framing sheets, camera clearance, grade looks | `bevy/shots` || the words to paste for a whole scene: the brief template, the builder prompt, the judge prompt | `bevy/prompts` || a Godot project: its scenes and resources scripted from TypeScript, run headless, recorded as frames to use as footage | `bevy/godot` || shapes: boxes to modelled solids, blended organic bodies (`sdf`), trees, terrain, rocks and plants (`grow`), 3D letters, lines and curves drawn on (`Line3d`, `Tube`) | `bevy/meshes` |diff --git a/sdk/guides/craft/bevy/NOTICE b/sdk/guides/craft/bevy/NOTICEindex 84a6ac96..d34b774e 100644--- a/sdk/guides/craft/bevy/NOTICE+++ b/sdk/guides/craft/bevy/NOTICE@@ -9,3 +9,9 @@ examples/3d/solari.rs and its implementation (v0.20, MIT OR Apache-2.0); JMS55's(Solari)"; GPU Gems 1 ch. 1, "Effective Water Simulation from Physical Models"; Tessendorf's "Simulating OceanWater"; an ocean simulation and rendering survey; Neopallium/bevy_water and mate-h/bevy_fft; and Bevy Elements'water research note.++The make loop (bevy/scenes section 0 and its gates, bevy/kits, bevy/shots; apps/make, docs/make.feature) follows+apekshik's AnyScene, AnyKit and AnyShot (MIT: github.com/apekshik/anyscene, anykit and anyshot): the plan stop and floor plan,+the reference sheet and two-generator pick on clay, the per-kind critic rubrics and their "production base, at most+five fixes" bar, the Stop hook that holds an agent to its deliverables, contact-point grounding, the camera rig's+walk profile, clearance and shot language. raea's code and words are its own; the method and its numbers are theirs.diff --git a/sdk/guides/craft/bevy/kits.md b/sdk/guides/craft/bevy/kits.mdnew file mode 100644index 00000000..50d09a27--- /dev/null+++ b/sdk/guides/craft/bevy/kits.md@@ -0,0 +1,56 @@+# Kits: props in one style, at real size, made and checked as a set++A kit is a set of objects that belong together (a 1970s flight desk's phone, clock, ashtray and lamp) and land as+components any project can import. It holds together because every reference comes from the same style images and+paragraph, every model is picked on clay from two generators, and the whole set is checked on one sheet before+anything costs much. This is AnyKit's loop (MIT), each step on a `raea make` verb; `raea make status` holds you to it+and the Stop hook won't let you end before it says done.++## What to do++1. **The plan.** `make: kit({ references: ["media/style.png"], style, objects, dials })` on brief.ts (`raea/brief`).+ - `style` is one paragraph every reference carries: era, palette, materials, wear, and one fictional maker+ ("Aurora Instruments"). Never a real brand.+ - Each object: `id` (snake_case), `label`, one size (`h` metres tall, `dims` [w, d, h] for boxy things, `max` for+ things lying flat), `prompt` (one object, its condition and materials), `hero: true` for the ones seen close.+ - `raea spec brief.ts --as make` prints the plan and what it still lacks.+2. **References, then the reference sheet.** `raea make refs --dry` quotes it; `raea make refs` makes each object's+ reference from the style images, in the style paragraph, with the scan template (one object, whole, plain grey+ ground, even light), then writes `review/refs.png` (style images first, then every reference with its size).+ - Look at the sheet as a set. One that's off (another era, another palette, two objects, a logo) is regenerated+ now: `raea make refs --only ID`. Ask it: the command the sheet step prints (`make.refs.*`).+3. **Both generators.** `raea make gen --dry` quotes it; `raea make gen` sends each reference to Tripo H3.1 (150k+ faces for a hero, 60k for a prop) and Meshy on fal, into `out/kit/gen/ID/`.+4. **Pick on clay.** `raea make pick-sheet` writes `review/picks.png`: the reference, then each model fitted to its+ real size, in colour and in clay. Judge on the clay: fused parts, blobs where there should be edges, and fidelity+ to the reference's shape. `raea make pick ID tripo|meshy "why"` records the pick and its reason.+5. **Prep.** `raea make prep` fits each pick to its real size (front toward +z, bottom-centred, metres) with+ `raea gen check`, makes a quarter-triangle `_lod1` beside it (`blender/decimate.py`), and writes a `.glb.json`+ sidecar for each saying how it was made (generator, why, prompt, reference, style).+6. **Land it.** `raea make kit --name KIT` puts the kit in the workspace's `shared/components/KIT/` (else the+ project's `components/KIT/`): one component per object (`RotaryPhone.tsx`, importing its model and LOD from+ beside it, `lod` for when it's small on screen), `lineup.tsx` (every piece at its real size beside a 1 m bar),+ `cover.png`, `thumbs/` and `kit.json`. Import it as `@shared/components/KIT/RotaryPhone`.+7. **Review and judge.** `raea render shared/components/KIT/lineup.tsx --review review/rN`, then+ `raea judge review/rN --kind kit --by claude --brief brief.ts --json`. The kit rubric: cohesion, reference+ fidelity, the brief, mesh (clay), texture, assembly (clay), scale (clay), labels. Fix its blocking defects or+ answer them in NOTES.md, and keep going until `raea make status` says done.++Cost: a six-piece kit is about $8-10 (references about $0.25 each, Tripo H3.1 and Meshy about $0.60-0.80 each).+`--dry` on refs and gen says the price first; ask before going over $10.++## Why++- One style paragraph and the same style images in every reference is what keeps a kit of one world. References+ made one at a time from text alone drift in era and palette, and an outlier caught on the sheet costs a picture,+ not a model.+- Generators fail differently: Tripo fuses a handset to its cradle, Meshy softens numerals. Two models and a pick on+ clay beat any one, and the reason written down is what the next kit learns from.+- Fitting to real size on the way in is what makes a kit drop into a scene without nudging.++## Common mistakes++- Picking on the colour render: texture hides a blob. Pick on the clay.+- A real brand in a prompt or the style ("Bakelite by Western Electric"). Name the one fictional maker.+- Skipping the reference sheet because each reference looks fine alone: judge them together.+- Landing a kit before `raea make prep`: `raea make kit` names what isn't prepped rather than landing half.diff --git a/sdk/guides/craft/bevy/scenes.md b/sdk/guides/craft/bevy/scenes.mdindex 4d3a0fce..17810e4e 100644--- a/sdk/guides/craft/bevy/scenes.md+++ b/sdk/guides/craft/bevy/scenes.md@@ -7,7 +7,24 @@ hayashimon, KOBATAKA), each step on a raea verb.## What to do-The brief template, the builder prompt and the judge prompt to paste are in `bevy/prompts`.+The brief template, the builder prompt and the judge prompt to paste are in `bevy/prompts`. A kit of props is+`bevy/kits`; shooting a finished set is `bevy/shots`.++### 0. The job: `make` on brief.ts, held by `raea make status`++- Put the job on the brief: `make: scene({ references, style, dials, objects })` from `raea/brief`. Each object has+ one size (`h`, `dims` or `max`), a `route`, `source: "reference" | "invented"` and, in a scene, `at` and `rot`+ (metres from the floor's front-left corner; rot 0 faces the entrance). Dials you don't set are read from the+ reference, so set only the ones the person asked for (`source: "customer"`).+- `raea make status` decides in code whether you're done: the deliverables on disk, every gate, the judge's rounds.+ The Stop hook asks it at the end of every turn, and you can't stop while it says "not done" (the loop gives way at+ the 8-round cap, on a stall, or when the same thing is missing three turns running). `--plan` writes the gates as+ check lines under the job's task in plan.org.+- `raea make plan` is the stop before anything costs money: `review/plan/floor-plan.png` (every footprint, invented+ ones dashed), a grey-box blockout seen from the entrance with its review sheets, and `comparison.png` beside the+ reference. Show it, fix positions and sizes, and only then generate.+- NOTES.md beside the brief ends with `## What the skill got wrong`: what the guides or tools led you into. Status+ checks it's there once the work is.### 1. The brief: a picture, a size, and what not to add@@ -113,26 +130,38 @@ check names a script (`bevy/blender`). It never places, lights, frames, materialyou checked.- Change one thing per material per round. Re-run the stage's checks after every fix.-### The judge--- `raea judge review/rN --brief brief.ts --target media/ref/target.png --json` sends the sheets to clef-omni with a- frozen rubric, and only the sheets and the brief's words: never the code or your log.-- It returns 0-10 scores for composition, form, assembly, materials, light, detail and world, plus every defect as- `{tile, where, wrong, real, fix, level}`.-- Code decides the pass. The thresholds are not in the prompt, and you do not tune toward them.-- In Claude Code you can also judge with a fresh subagent every round, given only the sheets, the brief and the- previous verdict.-- The judge doesn't gate until it has been calibrated against Shane's eye (`raea judge eye` and- `raea judge calibrate`). Until then its scores are advice.+### The judge, and the gates++Three tiers, each gating once it has earned it (`raea make status` lists them):++1. **Measured checks always gate:** `raea scene lint` (floats and sinks at the feet, clips with the move that clears+ them, faces z-fighting in one plane), `raea gen check` on every generated model, `raea scene stage --clearance 0.45` on+ a moving camera, and the deliverables' counts.+2. **`raea ask` questions gate one at a time, once calibrated.** The make set (`raea ask SHEET --set make`, or the+ command status prints) asks yes/no about one sheet: floating, intersecting, blobby, a stand-in, flat colour,+ plastic, opaque glass, garbled hero text, a real brand, too dark or bright; on a reference sheet, an outlier, two+ objects, a brand; on a framing sheet, a camera through a wall or a subject lost. Every answer lands in the ask+ ledger, matched to the sheet's bytes, so a re-rendered sheet needs asking again. A question gates once+ `raea ask calibrate` passes it (16 problem and 16 clean labels, held-out AUC 0.8); until then it's advice in the+ status.+3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --by claude --brief brief.ts --target+ media/ref/target.png --json` (or clef, kimi) scores the kind's rubric (scene: layout, props, signage, materials,+ light, atmosphere, plausibility, composition; layout and props judged on clay), on a production bar: don't+ nitpick, at most five fixes. It sees the sheets and the brief's words only, never the code or your log. Code+ decides the pass; the thresholds aren't in the prompt. A round judged on another kind's rubric doesn't count.+ Fix every blocking defect it names, or answer it in NOTES.md (its words, then what you checked). Its score gates+ once `raea judge calibrate --kind scene` agrees with Shane's eye (`raea judge eye`).### Stopping-- **Done:** two fresh judges in a row pass the scene.-- **Stall:** the score hasn't risen a full point in 2 rounds, or the same defect has been named twice. Stop tweaking- and change the approach for that part: another route (solid, field, Tripo HD, Tripo Smart Mesh), a rebuilt light- plan, or a moved camera. A defect that comes back after two fixes belongs to the method, not the dose.-- **Stalled:** the big change didn't move it. Show the latest sheet and the open defects.-- **Cap:** 8 judge rounds a scene, 3 per object system. At the cap, deliver and list what is still wrong.+`raea make status` says it; you don't decide it.++- **Done:** every deliverable on disk, every gate clear, and two fresh critic passes in a row on the latest renders.+- **Stall:** three rounds without beating the best score, or the same defect named twice. Stop tweaking and change+ the approach for that part: another route (solid, field, Tripo HD, Meshy), a rebuilt light plan, or a moved camera.+ A defect that comes back after two fixes belongs to the method, not the dose.+- **Cap:** 8 critic rounds a job. At the cap or a stall the job is delivered short: status lists what's still+ missing, and the Stop hook lets you end with it said.## Whydiff --git a/sdk/guides/craft/bevy/shots.md b/sdk/guides/craft/bevy/shots.mdnew file mode 100644index 00000000..e35de921--- /dev/null+++ b/sdk/guides/craft/bevy/shots.md@@ -0,0 +1,66 @@+# Shots: a built set filmed from plain directions++A shot list in a crew's words ("slow push on the counter, handheld, 35 mm") becomes camera paths that can't lurch,+checked on a framing sheet and for clearance before anything is rendered long. This is AnyShot's loop (MIT) on raea's+camera: `raea/camera` for the moves, `raea make framing` and `lenschart` for the sheets, `raea scene stage+--clearance` for the camera's path through the set. `raea make status` holds the job; the Stop hook won't let you end+before it says done.++## What to do++1. **The plan.** `make: shot({ shots: [...] })` on brief.ts. Each shot: `name` (the file it lands as),+ `description` in a crew's words, `move`, `seconds`, `lens` (mm), `handheld`, `still`, `composition` (the .tsx that+ renders it), `fps`.+2. **Moves from words** (`shotMove` from `raea/camera`; every one is a camera path, keyed in time):++ | The crew says | Move | Notes |+ |---|---|---|+ | push in, dolly in, move in | `dolly` toward the subject | stops 0.3 m short of it |+ | pull out, dolly out, reveal | `dolly` away | starts close, ends wide |+ | track left/right, crab, slide | `truck` | the look moves with it |+ | boom up/down, rise, sink | `pedestal` | straight up or down |+ | crane up over | `crane` | rises while the look holds on the subject |+ | pan, look across | `pan` | turns in place, keyed along the arc |+ | tilt up/down | `tilt` | turns in place vertically |+ | orbit, circle, arc | `orbit` | around the subject, keyed every 10 degrees or less |+ | vertigo, dolly zoom | `dollyZoom` | the lens is solved every frame to hold the subject's size |+ | walk through, follow the path | `walkPath` from the floor plan | 0.4-0.6 m/s at 1.5-1.7 m eye height |+ | lock off, hold | `static` | |++ - **Walkthroughs:** draw the path on `raea make plan`'s floor plan (x right, z away from the entrance, metres)+ and give the points to `walkPath(points, { speed: 0.5, eye: 1.6 })`. It keeps an even pace and rounds the+ corners, easing only at the start and end.+ - **Handheld:** `handheld(path, { profile: "walk" })` adds a walking operator: steps at 1.8 Hz, the aim on a+ spring that lags and settles, slow small reframes, nothing above 1.9 Hz. `"subtle"` for a held, standing camera.+ - **Focus:** `focusAt(focus, path, frame)` gives DepthOfField's `focal_distance`: `{ kind: "point", at }`,+ `{ kind: "track", target: (frame) => [x, y, z] }`, or `{ kind: "rack", from, to, at, over }`, which pulls from one+ subject to the other over `over` frames with holds either side.+ - A move is `shotMove({ kind, from, look, frames, by, angle, fov })`: `by` in metres (dolly in, truck right,+ pedestal or crane up; negative the other way), `angle` in degrees (pan right, tilt up, orbit counter-clockwise).+ - **Lens:** `lens(mm)` is the vertical field of view in degrees for a full-frame focal length. 24-35 mm for a+ walkthrough, 50 for a person's eye, 85-135 to compress a detail.+3. **Choose the lens.** `raea make lenschart SHOT` renders the shot's first frame at 18, 24, 35, 50, 85 and 135 mm+ (`review/lens-SHOT.png`). Pick from it and set the shot's `lens`.+4. **Block it.** `raea make framing` renders every shot's first, middle and last frame onto `review/framing.png`,+ stamped with the name and time. Look at every row: the subject in frame at the start and the end, nothing through+ a wall. Ask it (`raea ask review/framing.png --std make.framing.through_wall --std make.framing.subject_lost`) and+ judge it (`raea judge review --kind shot --by claude`: framing, move, focus, clearance, continuity, grade).+5. **Clearance.** `raea scene stage SHOT.tsx --clearance 0.45` holds the camera 0.45 m (a carried camera) off every solid part on every frame+ (`--clearance 0.15` for a camera on a rig). Glass, decals, volumes and parts under 5 cm are passed over.+6. **Grade.** `<Grade {...gradeLook("cinematic")} />` from `raea/post_process`: clean, cinematic, gritty or vintage,+ each a starting point to change (`gradeLook("vintage", { vignette: 0.2 })`).+7. **Finals** go to `out/shots/NAME.mp4` (or `.png` for a still), long ones on the render farm.++## Why++- A framing sheet catches in one picture what a full render shows after minutes: a subject leaving frame at the end,+ a move that starts inside a wall.+- Clearance is measured on the scene, not seen: a camera 20 cm from a door frame draws the frame's inside for a few+ frames that no one notices until the final.+- Keyed paths are paced by time, so a pan doesn't speed up at its middle and a walk doesn't stop at every corner.++## Common mistakes++- A walkthrough at 1.2 m/s: it reads as a drone. A person looking around walks 0.4-0.6 m/s.+- Handheld noise from random numbers per frame: it jitters. Use `handheld`, which has nothing above 1.9 Hz.+- A shot without its `composition`: `raea make framing` can't draw it, and `raea spec brief.ts --as make` says so.diff --git a/sdk/raea/conformance/camera-moves.test.ts b/sdk/raea/conformance/camera-moves.test.tsnew file mode 100644index 00000000..716823d8--- /dev/null+++ b/sdk/raea/conformance/camera-moves.test.ts@@ -0,0 +1,159 @@+// A crew's camera moves, focus and the handheld walk (docs/make.feature MK14): each move ends where its words say, a+// pan and an orbit follow their arc, a dolly zoom holds the subject's size, a rack holds on each subject either side,+// and the walk has nothing above 1.9 Hz.+import { describe, expect, test } from "bun:test";+import { focusAt, handheld, lens, shotMove, STEP_HZ, walkPath, WALK, type CameraVec3 } from "../src/camera";+import { GRADES, gradeLook } from "../src/post_process";++const dist = (a: CameraVec3, b: CameraVec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+const near = (a: CameraVec3, b: CameraVec3, tol = 1e-6) => expect(dist(a, b)).toBeLessThan(tol);+const base = { from: [0, 1.6, 5] as CameraVec3, look: [0, 1.2, 0] as CameraVec3, frames: 100 };++describe("moves", () => {+ test("each ends where its words say", () => {+ near(shotMove({ ...base, kind: "static" }).at(50).pos, base.from);+ const d = shotMove({ ...base, kind: "dolly", by: 2 }).at(100);+ expect(dist(d.pos, base.look)).toBeCloseTo(dist(base.from, base.look) - 2, 6);+ near(d.look, base.look);+ // never through the subject+ expect(dist(shotMove({ ...base, kind: "dolly", by: 50 }).at(100).pos, base.look)).toBeCloseTo(0.3, 6);+ const t = shotMove({ ...base, kind: "truck", by: 1 }).at(100);+ expect(t.pos[0]).toBeCloseTo(1, 6);+ expect(t.look[0]).toBeCloseTo(1, 6);+ const p = shotMove({ ...base, kind: "pedestal", by: 0.5 }).at(100);+ expect(p.pos[1]).toBeCloseTo(2.1, 6);+ expect(p.look[1]).toBeCloseTo(1.7, 6);+ const c = shotMove({ ...base, kind: "crane", by: 1 }).at(100);+ expect(c.pos[1]).toBeCloseTo(2.6, 6);+ near(c.look, base.look);+ });++ test("a pan and an orbit follow their arc and a tilt turns up", () => {+ const pan = shotMove({ ...base, kind: "pan", angle: 90 });+ // the look stays on the circle around the camera, and ends 90 degrees right+ const r = dist(base.look, base.from);+ for (const f of [0, 25, 50, 75, 100]) expect(dist(pan.at(f).look, base.from)).toBeCloseTo(r, 1);+ expect(pan.at(100).look[0]).toBeGreaterThan(4.5);+ const orbit = shotMove({ ...base, kind: "orbit", angle: 180 });+ for (const f of [0, 33, 66, 100]) expect(dist(orbit.at(f).pos, base.look)).toBeCloseTo(r, 1);+ expect(orbit.at(100).pos[2]).toBeLessThan(-4.5);+ near(orbit.at(60).look, base.look, 1e-9);+ const tilt = shotMove({ ...base, kind: "tilt", angle: 20 });+ expect(tilt.at(100).look[1]).toBeGreaterThan(base.look[1] + 1);+ });++ test("a dolly zoom holds the subject's frame height", () => {+ const dz = shotMove({ ...base, kind: "dollyZoom", by: 3, fov: lens(35) });+ const held = (f: number) => {+ const p = dz.at(f);+ return Math.tan((p.fov * Math.PI) / 360) * dist(p.pos, p.look);+ };+ for (const f of [0, 30, 60, 100]) expect(held(f)).toBeCloseTo(held(0), 6);+ expect(dz.at(100).fov).toBeGreaterThan(dz.at(0).fov * 1.8);+ expect(dz.camera(50).projection).toHaveProperty("Perspective");+ });++ test("a path is its keys, and a lens is its field of view", () => {+ const p = shotMove({ kind: "path", from: base.from, look: base.look, frames: 0, keys: [{ at: 0, pos: [0, 1, 4], look: [0, 1, 0] }, { at: 60, pos: [2, 1, 3], look: [0, 1, 0] }] });+ near(p.at(60).pos, [2, 1, 3]);+ expect(lens(50)).toBeCloseTo(26.99, 1);+ expect(() => lens(0)).toThrow();+ });+});++describe("focus", () => {+ test("a rack holds on each subject either side", () => {+ const path = shotMove({ ...base, kind: "static" });+ const near1: CameraVec3 = [0, 1.6, 3], far1: CameraVec3 = [0, 1.6, -3];+ const rack = { kind: "rack" as const, from: near1, to: far1, at: 40, over: 20 };+ expect(focusAt(rack, path, 0)).toBeCloseTo(2, 6);+ expect(focusAt(rack, path, 40)).toBeCloseTo(2, 6);+ expect(focusAt(rack, path, 50)).toBeCloseTo(5, 6);+ expect(focusAt(rack, path, 60)).toBeCloseTo(8, 6);+ expect(focusAt(rack, path, 99)).toBeCloseTo(8, 6);+ expect(focusAt({ kind: "point", at: base.look }, path, 10)).toBeCloseTo(dist(base.from, base.look), 6);+ });+});++describe("handheld walk", () => {+ const fps = 30, frames = 20 * fps;+ const walk = handheld(shotMove({ kind: "dolly", from: [0, 1.6, 12], look: [0, 1.5, 0], by: 8, frames }), { fps });+ const still = shotMove({ kind: "dolly", from: [0, 1.6, 12], look: [0, 1.5, 0], by: 8, frames });++ // the share of a signal's energy above `hz` (a plain DFT over the samples)+ function above(x: number[], hz: number): number {+ const n = x.length, mean = x.reduce((a, b) => a + b, 0) / n;+ let hi = 0, all = 0;+ for (let k = 1; k < n / 2; k++) {+ let re = 0, im = 0;+ for (let i = 0; i < n; i++) {+ const a = (2 * Math.PI * k * i) / n;+ re += (x[i] - mean) * Math.cos(a);+ im -= (x[i] - mean) * Math.sin(a);+ }+ const e = re * re + im * im;+ all += e;+ if ((k * fps) / n > hz) hi += e;+ }+ return all > 0 ? hi / all : 0;+ }++ test("it moves like a walking operator and has nothing above 1.9 Hz", () => {+ const off = (c: 0 | 1 | 2, w: "pos" | "look") => Array.from({ length: frames }, (_, f) => walk.at(f)[w][c] - still.at(f)[w][c]);+ const bob = off(1, "pos");+ // it moves: a centimetre or so of bob+ expect(Math.max(...bob) - Math.min(...bob)).toBeGreaterThan(0.01);+ expect(Math.max(...bob.map(Math.abs))).toBeLessThan(0.05);+ for (const s of [off(0, "pos"), bob, off(0, "look"), off(1, "look")]) expect(above(s, 1.9)).toBeLessThan(0.01);+ expect(STEP_HZ).toBeLessThan(1.9);+ });++ test("it's the same every time, and its aim lags and settles", () => {+ const again = handheld(shotMove({ kind: "dolly", from: [0, 1.6, 12], look: [0, 1.5, 0], by: 8, frames }), { fps });+ near(again.at(123).pos, walk.at(123).pos, 1e-12);+ const pan = shotMove({ kind: "pan", from: [0, 1.6, 0], look: [0, 1.6, -5], angle: 60, frames: 30 });+ const op = handheld(pan, { fps, amount: 0 });+ // mid-turn the operator's aim is behind the path's; a second after it ends it has caught up+ expect(dist(op.at(15).look, pan.at(15).look)).toBeGreaterThan(0.05);+ expect(dist(op.at(90).look, pan.at(90).look)).toBeLessThan(0.05);+ });+});++// MK17: a path drawn on the floor plan walks at a person's pace and eye height, turning where it was drawn+describe("walkPath", () => {+ test("at eye height and an even walking pace, turning corners without stopping", () => {+ const p = walkPath([[0, 0], [0, 3], [2, 3]], { fps: 30 });+ expect(p.at(0).pos).toEqual([0, WALK.eye, 0]);+ expect(p.at(p.end).pos.map((v) => +v.toFixed(3))).toEqual([2, 1.6, 3]);+ // about 5 m (the corner rounded) at 0.5 m/s: about 10 s+ expect(p.end).toBeGreaterThan(280);+ expect(p.end).toBeLessThan(300);+ // at the start it looks 2 m along the first leg+ expect(p.at(0).look.map((v) => +v.toFixed(3))).toEqual([0, 1.6, 2]);+ // after the first second, until the last, it walks at 0.5 m/s give or take a fifth: through the corner too+ const speed = (f: number) => { const a = p.at(f).pos, b = p.at(f + 1).pos; return Math.hypot(b[0] - a[0], b[2] - a[2]) * 30; };+ for (let f = 30; f < p.end - 30; f += 5) expect(Math.abs(speed(f) - 0.5)).toBeLessThan(0.1);+ // and it stays at eye height+ expect(Math.abs(p.at(150).pos[1] - 1.6)).toBeLessThan(1e-9);+ expect(p.check()).toEqual([]);+ });+ test("a fixed look point, and what's refused", () => {+ expect(walkPath([[0, 0], [1, 0]], { look: [5, 1, 5] }).at(10).look).toEqual([5, 1, 5]);+ expect(() => walkPath([[0, 0]])).toThrow("at least two points");+ expect(() => walkPath([[0, 0], [1, 0]], { speed: 0 })).toThrow("above 0");+ });+});++// MK17: grade looks are GradeProps to spread; your changes go over them, sections merged+describe("grade looks", () => {+ test("four looks, merged with changes", () => {+ expect(Object.keys(GRADES)).toEqual(["clean", "cinematic", "gritty", "vintage"]);+ expect(GRADES.vintage.shadows?.lift).toBeGreaterThan(0);+ expect(GRADES.gritty.saturation).toBeLessThan(0.8);+ const g = gradeLook("cinematic", { vignette: 0.1, midtones: { gamma: 1.05 } });+ expect(g.vignette).toBe(0.1);+ expect(g.midtones).toEqual({ contrast: 1.08, gamma: 1.05 });+ expect(GRADES.cinematic.midtones).toEqual({ contrast: 1.08 });+ expect(() => gradeLook("noir" as never)).toThrow("clean, cinematic, gritty, vintage");+ });+});diff --git a/sdk/raea/src/ask.gen.ts b/sdk/raea/src/ask.gen.tsindex 4e2fa3a9..55481605 100644--- a/sdk/raea/src/ask.gen.ts+++ b/sdk/raea/src/ask.gen.ts@@ -79,4 +79,4 @@ date: string,*/by: string, };-export const SETS = ["rubric", "av", "defects", "platform", "decide"] as const;+export const SETS = ["rubric", "av", "defects", "platform", "decide", "make"] as const;diff --git a/sdk/raea/src/ask.ts b/sdk/raea/src/ask.tsindex 03e57eed..127200f9 100644--- a/sdk/raea/src/ask.ts+++ b/sdk/raea/src/ask.ts@@ -23,7 +23,7 @@ export interface AskEntry {file: string;/** questions in your own words (yes or no) or written out */questions?: (string | Question)[];- /** standard sets by name: rubric, av, defects, platform, decide */+ /** standard sets by name: rubric, av, defects, platform, decide, make */set?: string | string[];/** standard questions by id (`raea ask list` lists them) */std?: string[];diff --git a/sdk/raea/src/brief.gen.ts b/sdk/raea/src/brief.gen.tsindex 72b48644..eafd0e6e 100644--- a/sdk/raea/src/brief.gen.ts+++ b/sdk/raea/src/brief.gen.ts@@ -305,4 +305,12 @@ handheld?: string,/*** a still rather than a move*/-still?: boolean, };+still?: boolean,+/**+ * the composition that renders it (relative to the brief): `raea make framing` and `lenschart` draw it+ */+composition?: string,+/**+ * its frame rate, for the frames `seconds` spans (30 when left out)+ */+fps?: number, };diff --git a/sdk/raea/src/camera.ts b/sdk/raea/src/camera.tsindex 396e2768..f1af6579 100644--- a/sdk/raea/src/camera.ts+++ b/sdk/raea/src/camera.ts@@ -8,5 +8,7 @@ export { Camera3d, Hdr, type Camera3dProps, type CameraViewport, type ClearColorexport { TextureView } from "@raea/render/bevy3d";// a camera path paced by time, so it can't lurch at a key (docs/stage-guards.feature SG7)export { cameraPath, type CameraKey, type CameraPath, type CameraPose, type CameraVec3 } from "@raea/render/camera/path";+// a crew's moves, focus and a handheld walk, each a camera path (docs/make.feature MK14)+export { shotMove, focusAt, handheld, walkPath, WALK, lens, LENSES, STEP_HZ, type ShotMove, type MoveKind, type Focus, type HandheldProfile } from "@raea/render/camera/moves";// page type that names a 3D part, placed through the shot's camera (docs/stage-guards.feature SG8)export { Label, LABEL_MIN, type LabelProps, type LabelCamera } from "@raea/render/3d/label";diff --git a/sdk/raea/src/post_process.ts b/sdk/raea/src/post_process.tsindex ae5700bb..2dc0d081 100644--- a/sdk/raea/src/post_process.ts+++ b/sdk/raea/src/post_process.ts@@ -2,3 +2,5 @@// into it at M5; until then the old subpaths and this one export the same values.// raea/post_process (bevy_post_process, bevy_anti_alias): what's done to the frame after it's drawn.export { Bloom, ToneMapping, Grade, DepthOfField, MotionBlur, Fisheye, LensDistortion, AntiAliasing, Outline, Look, FramePass, type FramePassProps, Compute, type ComputeProps, type BloomProps, type ToneMappingProps, type GradeProps, type GradeSection, type DepthOfFieldProps, type MotionBlurProps, type FisheyeProps, type LensDistortionProps, type LensCommon, type AntiAliasingProps, type OutlineProps, type LookProps } from "./3d";+// grade looks for shots (docs/make.feature MK17): clean, cinematic, gritty, vintage+export { GRADES, gradeLook, type GradeLook } from "@raea/render/3d/grades";diff --git a/sdk/render/package.json b/sdk/render/package.jsonindex 3c55cd45..c2397554 100644--- a/sdk/render/package.json+++ b/sdk/render/package.json@@ -23,9 +23,11 @@"./bevy-own": "./src/bevy-own.gen.tsx","./feathers": "./src/feathers.ts","./camera/path": "./src/camera/path.ts",+ "./camera/moves": "./src/camera/moves.ts","./3d/clock": "./src/3d/clock.ts","./3d/line": "./src/3d/line.tsx",- "./3d/label": "./src/3d/label.tsx"+ "./3d/label": "./src/3d/label.tsx",+ "./3d/grades": "./src/3d/grades.ts"},"raea": {"plugins": {diff --git a/sdk/render/src/3d/grades.ts b/sdk/render/src/3d/grades.tsnew file mode 100644index 00000000..3e9c8921--- /dev/null+++ b/sdk/render/src/3d/grades.ts@@ -0,0 +1,50 @@+// Grade looks for shots (docs/make.feature MK17, from AnyShot's grade presets): a few named starting points for+// <Grade>, each a plain GradeProps you can spread and change. clean: as shot, a touch of contrast. cinematic: slightly+// warm, softer blacks, held highlights, a light vignette. gritty: cool, desaturated, hard mids, a heavy vignette.+// vintage: warm and faded (lifted blacks, rolled highlights), less colour, fringes at the edges.+import type { GradeProps } from "./effects";++export type GradeLook = "clean" | "cinematic" | "gritty" | "vintage";++export const GRADES: Record<GradeLook, GradeProps> = {+ clean: { saturation: 1.02, midtones: { contrast: 1.04 } },+ cinematic: {+ temperature: 0.02,+ saturation: 0.92,+ shadows: { saturation: 0.85, lift: 0.01 },+ midtones: { contrast: 1.08 },+ highlights: { gain: 0.96 },+ vignette: 0.25,+ aberration: 0.002,+ },+ gritty: {+ temperature: -0.03,+ saturation: 0.72,+ shadows: { gamma: 1.12, saturation: 0.7 },+ midtones: { contrast: 1.22 },+ highlights: { gain: 1.02 },+ vignette: 0.42,+ aberration: 0.003,+ },+ vintage: {+ temperature: 0.08,+ tint: 0.015,+ saturation: 0.78,+ shadows: { lift: 0.035, contrast: 0.9 },+ midtones: { contrast: 0.96 },+ highlights: { gain: 0.93 },+ vignette: 0.35,+ aberration: 0.004,+ },+};++/** A grade look's props, with your changes over it: `<Grade {...gradeLook("cinematic", { vignette: 0.1 })} />`. */+export function gradeLook(look: GradeLook, over: GradeProps = {}): GradeProps {+ const base = GRADES[look];+ if (!base) throw new Error(`gradeLook: no look "${look}" (clean, cinematic, gritty, vintage).`);+ const merged: GradeProps = { ...base, ...over };+ for (const k of ["shadows", "midtones", "highlights"] as const) {+ if (base[k] || over[k]) merged[k] = { ...base[k], ...over[k] };+ }+ return merged;+}diff --git a/sdk/render/src/camera/moves.ts b/sdk/render/src/camera/moves.tsnew file mode 100644index 00000000..78b5d195--- /dev/null+++ b/sdk/render/src/camera/moves.ts@@ -0,0 +1,272 @@+// A crew's camera moves, focus and a handheld walk (docs/make.feature MK14, from AnyShot's camera language and camrig's+// walk profile, MIT). Each move is a CameraPath (path.ts), so it is paced by time and can't lurch: a pan or an orbit+// is keyed along its arc, a dolly zoom solves its lens every frame to hold the subject's size. Focus gives the+// DepthOfField's focal_distance at a frame (point, track, or a rack from one subject to another with holds either+// side). `handheld` adds a walking operator's motion to any path: steps at 1.8 Hz, the aim on a spring that lags and+// settles, slow small reframes, and nothing above 1.9 Hz, so it reads as a person and never as noise.+import { Transform, type Projection, type TransformBuilt } from "../bevy3d/core";+import { cameraPath, type CameraKey, type CameraPath, type CameraPose, type CameraVec3 } from "./path";++export type MoveKind = "static" | "dolly" | "truck" | "pedestal" | "crane" | "pan" | "tilt" | "orbit" | "dollyZoom" | "path";++/** A move: where the camera starts, what it looks at, and how it moves over `frames` from frame `at`. */+export type ShotMove = {+ kind: MoveKind;+ /** The camera's start. */+ from: CameraVec3;+ /** What it looks at (the subject). */+ look: CameraVec3;+ /** The frame it starts moving (0 if left out). */+ at?: number;+ /** How many frames it moves for. */+ frames: number;+ /** Metres: dolly in (negative: out), truck right (negative: left), pedestal or crane up (negative: down), or a dolly+ * zoom's push in. */+ by?: number;+ /** Degrees: pan right, tilt up, orbit counter-clockwise seen from above (negative: the other way). */+ angle?: number;+ /** The vertical field of view in degrees at the start (38 if left out); see `lens` for a focal length. */+ fov?: number;+ /** The path's own keys, for `path`. */+ keys?: CameraKey[];+};++const UP: CameraVec3 = [0, 1, 0];+const add = (a: CameraVec3, b: CameraVec3): CameraVec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+const sub = (a: CameraVec3, b: CameraVec3): CameraVec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const mul = (a: CameraVec3, s: number): CameraVec3 => [a[0] * s, a[1] * s, a[2] * s];+const dot = (a: CameraVec3, b: CameraVec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const len = (a: CameraVec3) => Math.hypot(a[0], a[1], a[2]);+const norm = (a: CameraVec3): CameraVec3 => mul(a, 1 / Math.max(1e-9, len(a)));+const cross = (a: CameraVec3, b: CameraVec3): CameraVec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+/** `v` turned by `deg` about the unit axis `k` (Rodrigues). */+function turn(v: CameraVec3, k: CameraVec3, deg: number): CameraVec3 {+ const t = (deg * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);+ return add(add(mul(v, c), mul(cross(k, v), s)), mul(k, dot(k, v) * (1 - c)));+}++/** The vertical field of view (degrees) of a focal length on a full-frame (36 x 24 mm) sensor. */+export function lens(mm: number): number {+ if (!(mm > 0)) throw new Error(`lens: ${mm} mm. Give a focal length in millimetres, more than 0.`);+ return (2 * Math.atan(12 / mm) * 180) / Math.PI;+}++/** The focal lengths a lens chart shows (docs/make.feature MK15). */+export const LENSES = [18, 24, 35, 50, 85, 135] as const;++/** A path whose poses come from a function, with cameraPath's camera() and an empty check. */+function poses(start: number, end: number, at: (f: number) => CameraPose, check: () => string[] = () => []): CameraPath {+ return {+ start,+ end,+ at,+ check,+ camera(frame: number): { transform: TransformBuilt; projection: Projection } {+ const { pos, look, fov } = at(frame);+ return { transform: Transform.fromXyz(...pos).lookingAt(look), projection: { Perspective: { fov: (fov * Math.PI) / 180 } } };+ },+ };+}++/** Keys along an arc: `n` steps of `angle` degrees in all, each pose from `pose(deg)`. */+function arc(t0: number, frames: number, angle: number, fov: number, pose: (deg: number) => { pos: CameraVec3; look: CameraVec3 }): CameraKey[] {+ const n = Math.max(1, Math.ceil(Math.abs(angle) / 10));+ return Array.from({ length: n + 1 }, (_, i) => ({ at: t0 + (frames * i) / n, ...pose((angle * i) / n), fov }));+}++/**+ * A crew's move as a camera path. Each eases out of its start and into its end, and never lurches.+ *+ * ```tsx+ * const push = shotMove({ kind: "dolly", from: [0, 1.6, 4], look: [0, 1.2, 0], by: 1.5, frames: 120, fov: lens(35) });+ * <Camera3d {...push.camera(useCurrentFrame())} />+ * ```+ */+export function shotMove(m: ShotMove): CameraPath {+ const t0 = m.at ?? 0, fov = m.fov ?? 38, t1 = t0 + m.frames;+ if (m.kind !== "static" && m.kind !== "path" && !(m.frames > 0)) throw new Error(`shotMove: ${m.kind} over ${m.frames} frames. Give frames, more than 0.`);+ const view = sub(m.look, m.from);+ const dir = norm(view);+ const right = norm(cross(dir, UP));+ const by = m.by ?? 0, angle = m.angle ?? 0;+ const two = (pos: CameraVec3, look: CameraVec3) => cameraPath([{ at: t0, pos: m.from, look: m.look, fov }, { at: t1, pos, look, fov }]);+ switch (m.kind) {+ case "static":+ return cameraPath([{ at: t0, pos: m.from, look: m.look, fov }]);+ case "dolly": {+ // never through the subject: it stops 30 cm short+ const d = Math.min(by, len(view) - 0.3);+ return two(add(m.from, mul(dir, d)), m.look);+ }+ case "truck":+ return two(add(m.from, mul(right, by)), add(m.look, mul(right, by)));+ case "pedestal":+ return two(add(m.from, [0, by, 0]), add(m.look, [0, by, 0]));+ case "crane":+ // the camera rises, held on its subject (it tilts as it goes)+ return two(add(m.from, [0, by, 0]), m.look);+ case "pan":+ return cameraPath(arc(t0, m.frames, -angle, fov, (deg) => ({ pos: m.from, look: add(m.from, turn(view, UP, deg)) })));+ case "tilt":+ return cameraPath(arc(t0, m.frames, angle, fov, (deg) => ({ pos: m.from, look: add(m.from, turn(view, right, deg)) })));+ case "orbit":+ return cameraPath(arc(t0, m.frames, angle, fov, (deg) => ({ pos: add(m.look, turn(mul(view, -1), UP, deg)), look: m.look })));+ case "dollyZoom": {+ // the subject's frame height held: tan(fov/2) * distance stays what it was at the start+ const d = Math.min(by, len(view) - 0.3);+ const base = cameraPath([{ at: t0, pos: m.from, look: m.look, fov }, { at: t1, pos: add(m.from, mul(dir, d)), look: m.look, fov }]);+ const height = Math.tan((fov * Math.PI) / 360) * len(view);+ return poses(base.start, base.end, (f) => {+ const p = base.at(f);+ const dist = Math.max(0.05, len(sub(p.look, p.pos)));+ return { ...p, fov: (2 * Math.atan(height / dist) * 180) / Math.PI };+ });+ }+ case "path":+ if (!m.keys?.length) throw new Error("shotMove: a path needs its keys ({ at, pos, look }).");+ return cameraPath(m.keys);+ }+}++/** Where the lens is focused. */+export type Focus =+ | { kind: "point"; at: CameraVec3 }+ | { kind: "track"; target: (frame: number) => CameraVec3 }+ /** from one subject to the other over `over` frames starting at `at`, held on each before and after */+ | { kind: "rack"; from: CameraVec3; to: CameraVec3; at: number; over: number };++/** The focal distance (metres from the camera) at a frame: a DepthOfField's focal_distance. */+export function focusAt(f: Focus, path: CameraPath, frame: number): number {+ const cam = path.at(frame).pos;+ const d = (p: CameraVec3) => Math.max(0.05, len(sub(p, cam)));+ switch (f.kind) {+ case "point":+ return d(f.at);+ case "track":+ return d(f.target(frame));+ case "rack": {+ const s = Math.min(1, Math.max(0, (frame - f.at) / Math.max(1, f.over)));+ const e = s * s * (3 - 2 * s);+ return d(f.from) + (d(f.to) - d(f.from)) * e;+ }+ }+}++export type HandheldProfile = "walk" | "subtle";++/** What a profile moves, at amount 1 (metres and degrees), and how fast its aim catches up (Hz). */+const PROFILES: Record<HandheldProfile, { bob: number; sway: number; roll: number; reframe: number; spring: number }> = {+ walk: { bob: 0.012, sway: 0.009, roll: 0.5, reframe: 0.7, spring: 1.2 },+ subtle: { bob: 0.002, sway: 0.003, roll: 0.15, reframe: 0.35, spring: 0.8 },+};+/** A walker's steps, and the sway at half of it (one foot then the other). Every motion here is at or under STEP. */+export const STEP_HZ = 1.8;++/**+ * A walking operator's motion on a path: the camera bobs with each step (1.8 Hz) and sways with each stride (0.9 Hz),+ * rolls a little with the sway, reframes slowly, and its aim follows the path's on a spring, so it lags a turn and+ * settles after it. Deterministic: the same path, fps and seed give the same frames. Nothing moves faster than 1.9 Hz.+ *+ * ```tsx+ * const walk = handheld(shotMove({ kind: "dolly", from: [0, 1.6, 6], look: [0, 1.5, 0], by: 4, frames: 300 }), { fps: 30 });+ * ```+ */+export function handheld(path: CameraPath, o: { profile?: HandheldProfile; fps?: number; seed?: number; amount?: number } = {}): CameraPath {+ const p = PROFILES[o.profile ?? "walk"];+ if (!p) throw new Error(`handheld: profile ${o.profile}. Give "walk" or "subtle".`);+ const fps = o.fps ?? 30, amount = o.amount ?? 1, seed = o.seed ?? 1;+ const ph = (k: number) => ((Math.sin(seed * 12.9898 + k * 78.233) * 43758.5453) % 1) * 2 * Math.PI;+ // the aim on a critically damped spring, stepped once a frame from the start (kept, so a frame costs one lookup)+ const aims: CameraVec3[] = [];+ const omega = 2 * Math.PI * p.spring;+ const aimAt = (frame: number): CameraVec3 => {+ const k = Math.max(0, Math.floor(frame - path.start));+ if (!aims.length) aims.push(path.at(path.start).look);+ let vel: CameraVec3 = [0, 0, 0];+ for (let i = aims.length; i <= k + 1; i++) {+ const target = path.at(path.start + i).look, cur = aims[i - 1], dt = 1 / fps;+ const prev = aims[i - 2] ?? cur;+ vel = mul(sub(cur, prev), fps);+ const acc = sub(mul(sub(target, cur), omega * omega), mul(vel, 2 * omega));+ aims.push(add(cur, mul(add(vel, mul(acc, dt)), dt)));+ }+ const a = aims[k], b = aims[k + 1], t = frame - path.start - k;+ return add(a, mul(sub(b, a), Math.min(1, Math.max(0, t))));+ };+ const at = (frame: number): CameraPose => {+ const base = path.at(frame);+ const s = Math.max(0, frame - path.start) / fps;+ const look = aimAt(frame);+ const dir = norm(sub(look, base.pos)), right = norm(cross(dir, UP)), up = cross(right, dir);+ const w = 2 * Math.PI;+ const bob = p.bob * amount * Math.sin(w * STEP_HZ * s + ph(1));+ const sway = p.sway * amount * Math.sin(w * (STEP_HZ / 2) * s + ph(2));+ const yaw = p.reframe * amount * (0.6 * Math.sin(w * 0.13 * s + ph(3)) + 0.4 * Math.sin(w * 0.29 * s + ph(4)));+ const pitch = p.reframe * amount * 0.6 * (0.6 * Math.sin(w * 0.11 * s + ph(5)) + 0.4 * Math.sin(w * 0.23 * s + ph(6)));+ const roll = p.roll * amount * Math.sin(w * (STEP_HZ / 2) * s + ph(2));+ const pos = add(add(base.pos, mul(up, bob)), mul(right, sway));+ let view = sub(look, base.pos);+ view = turn(view, UP, yaw);+ view = turn(view, right, pitch);+ // roll as a sideways lean of the look point is what Camera3d's lookingAt can carry (its up stays world up), so a+ // small roll reads as the frame's horizon swaying with the stride+ const lean = mul(right, Math.tan((roll * Math.PI) / 180) * 0.02 * len(view));+ return { pos, look: add(add(pos, view), lean), fov: base.fov };+ };+ return poses(path.start, path.end, at, () => path.check());+}++/** A walkthrough's pace and eye height, as AnyShot's shot language keeps them: a person walking a set slowly. */+export const WALK = { speed: 0.5, eye: 1.6 } as const;++/**+ * A path drawn on the floor plan (`raea make plan`'s floor-plan.png: x right, z away from the entrance, metres) as a+ * camera walking it: at eye height, at an even walking pace (0.4-0.6 m/s reads as a person; 0.5 by default), easing+ * only where it starts and stops, its corners rounded (`turn` metres either side) so it turns as a walker does rather+ * than stopping; looking `ahead` metres along the way, or at `look` throughout. Give it to `handheld` for the step.+ */+export function walkPath(points: readonly [number, number][], o: { speed?: number; eye?: number; fps?: number; ahead?: number; look?: CameraVec3; start?: number; fov?: number; turn?: number } = {}): CameraPath {+ if (points.length < 2) throw new Error("walkPath: draw at least two points on the plan ([x, z] in metres).");+ const speed = o.speed ?? WALK.speed;+ if (speed <= 0) throw new Error("walkPath: speed is metres a second, above 0 (0.4-0.6 reads as walking).");+ const eye = o.eye ?? WALK.eye;+ const fps = o.fps ?? 30;+ const ahead = o.ahead ?? 2;+ const raw: CameraVec3[] = points.map(([x, z]) => [x, eye, z]);+ // the corners rounded: each inner point replaced by a curve from `turn` before it to `turn` after (a quadratic+ // through the corner), so the walker's heading turns over half a metre instead of on the spot+ const line: CameraVec3[] = [raw[0]];+ for (let i = 1; i < raw.length - 1; i++) {+ const [a, p, b] = [raw[i - 1], raw[i], raw[i + 1]];+ const r = Math.min(o.turn ?? 0.5, len(sub(p, a)) / 2, len(sub(b, p)) / 2);+ const p0 = add(p, mul(sub(a, p), r / Math.max(len(sub(a, p)), 1e-9)));+ const p2 = add(p, mul(sub(b, p), r / Math.max(len(sub(b, p)), 1e-9)));+ for (let k = 0; k <= 8; k++) {+ const t = k / 8;+ line.push(add(add(mul(p0, (1 - t) * (1 - t)), mul(p, 2 * (1 - t) * t)), mul(p2, t * t)));+ }+ }+ line.push(raw[raw.length - 1]);+ const lengths = line.slice(1).map((p, i) => len(sub(p, line[i])));+ const total = lengths.reduce((a, b) => a + b, 0);+ const along = (d: number): CameraVec3 => {+ let left = Math.min(Math.max(d, 0), total);+ for (let i = 0; i < lengths.length; i++) {+ if (left <= lengths[i] || i === lengths.length - 1) return add(line[i], mul(sub(line[i + 1], line[i]), lengths[i] > 0 ? Math.min(left / lengths[i], 1) : 0));+ left -= lengths[i];+ }+ return line[line.length - 1];+ };+ const end = line[line.length - 1];+ const lastDir = sub(end, line[line.length - 2]);+ const lookAt = (d: number): CameraVec3 => (o.look ? o.look : d + ahead <= total ? along(d + ahead) : add(end, mul(lastDir, (d + ahead - total) / Math.max(len(lastDir), 1e-9))));+ // a key every quarter metre at the time the walker reaches it: between them the path keeps its pace+ const start = o.start ?? 0;+ const n = Math.max(1, Math.ceil(total / 0.25));+ const keys: CameraKey[] = [];+ for (let k = 0; k <= n; k++) {+ const d = (total * k) / n;+ keys.push({ at: start + (d / speed) * fps, pos: along(d), look: lookAt(d), ...(o.fov != null && k === 0 ? { fov: o.fov } : {}) });+ }+ return cameraPath(keys);+}diff --git a/systems/contact/src/lib.rs b/systems/contact/src/lib.rsindex cac2a365..5dc2385e 100644--- a/systems/contact/src/lib.rs+++ b/systems/contact/src/lib.rs@@ -23,6 +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;+mod zfight;pub use lint::lint;// a model's box and a seat's facing (scene.bounds, scene.facing)mod assets;diff --git a/systems/contact/src/lint.rs b/systems/contact/src/lint.rsindex 3b44cd16..ad62ab15 100644--- a/systems/contact/src/lint.rs+++ b/systems/contact/src/lint.rs@@ -402,14 +402,78 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {let (la, lb) = (label(&items[i], &a[h.pieces.0].name), label(&items[j], &b[h.pieces.1].name));let (small, big) = if h.small_first { (la, lb) } else { (lb, la) };errors += 1;- out.push(json!({"part": small, "into": big, "check": "clips", "level": "error", "depth": (h.depth * 1e4).round() / 1e4, "share": (h.share * 1e3).round() / 1e3,- "says": format!("{small} passes {} into {big} ({:.0}% of it inside)", mm(h.depth), h.share * 100.0)}));+ // out the shortest way (not down), and when that's sideways, settled onto what's under its new place+ // in the same move (MK9): a stool pushed out from a table drops to the floor, not left at the top's height+ let (axis, by) = super::clear_move(a, &items[i].world, b, &items[j].world, h.small_first);+ let mover = if h.small_first { i } else { j };+ let mut v = Vec3::ZERO;+ v[axis] = by;+ let axis_name = ["x", "y", "z"][axis];+ let mut fix = json!({"part": small, "axis": axis_name, "by": (by * 1e4).round() / 1e4});+ let mut then = String::new();+ if axis != 1+ && let Some((under, node, gap)) = landing(&rest_after(&parts, &insets, mover, v))+ && gap.abs() > TOUCH+ {+ fix["dy"] = json!((-gap * 1e4).round() / 1e4);+ then = format!(" and {:+.3} m along y to rest on {}", -gap, named(&parts, under, node));+ }+ 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)}));+ }+ }+ }+ // faces in one plane over each other (MK8): between two parts an error once it's a square centimetre or more,+ // inside one model a warning (a generated mesh's doubled faces flicker only where they show)+ for i in 0..parts.len() {+ if parts[i].excused || parts[i].moving {+ continue;+ }+ for j in i + 1..parts.len() {+ let near = |a: &Part, b: &Part| (a.lo - Vec3::splat(0.001)).cmple(b.hi).all() && (b.lo - Vec3::splat(0.001)).cmple(a.hi).all();+ if parts[j].excused || parts[j].moving || !near(&parts[i], &parts[j]) {+ continue;+ }+ if let Some((n, area, at)) = super::zfight::overlaps(&parts[i].tris, Some(&parts[j].tris)) {+ let level = if area >= 1e-4 { "error" } else { "warning" };+ 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],+ "says": format!("{} and {} have faces in one plane over each other ({n} pair{}, up to {:.1} cm² 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)}));}}+ if let Some((n, area, at)) = super::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{}, up to {:.1} cm²): they flicker where they show; delete the doubles (raea gen check -o)", parts[i].label, if n == 1 { "" } else { "s" }, area * 1e4)}));+ }}(out, errors)}+/// 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)> {+ match r {+ Rest::On { under, node, gap, .. } => Some((*under, *node, *gap)),+ Rest::Air { below } => *below,+ _ => None,+ }+}++/// What a part rests on after a move by `v` (MK9): the feet test again at its new place, against everything else.+fn rest_after(parts: &[Part], insets: &[Option<usize>], i: usize, v: Vec3) -> Rest {+ let mut moved: Vec<Part> = parts.to_vec();+ let p = &mut moved[i];+ for q in p.tris.iter_mut().flatten() {+ *q += v;+ }+ p.lo += v;+ p.hi += v;+ let grid = Grid::new(&moved);+ rest_of(&moved, &grid, insets, i)+}+#[cfg(test)]#[path = "lint/tests.rs"]mod tests;diff --git a/systems/contact/src/lint/tests.rs b/systems/contact/src/lint/tests.rsindex 90e35f7f..91e7e468 100644--- a/systems/contact/src/lint/tests.rs+++ b/systems/contact/src/lint/tests.rs@@ -115,3 +115,28 @@ fn a_mug_on_its_side_rests_on_its_lowest_edge() {let r = rest(&[top, mug], 1);assert!(matches!(r, Rest::On { under: 0, gap, .. } if (gap - 0.001).abs() < 3e-4), "{r:?}");}++#[test]+fn a_stool_tucked_under_a_table_rests_on_the_floor_by_its_feet() {+ // docs/make.feature MK7: its box reaches over the table's top; its feet are on the floor, and that's what it rests on+ let floor = part("floor", Vec3::new(0.0, -0.05, 0.0), Vec3::new(10.0, 0.1, 10.0));+ let top = part("table top", Vec3::new(0.0, 0.75, 0.0), Vec3::new(1.0, 0.04, 1.0));+ let stool = part("stool", Vec3::new(0.5, 0.45, 0.0), Vec3::new(0.4, 0.9, 0.4));+ let r = rest(&[floor, top, stool], 2);+ assert!(matches!(r, Rest::On { under: 0, gap, .. } if gap.abs() < 1e-4), "{r:?}");+}++#[test]+fn a_part_moved_sideways_is_settled_where_it_lands() {+ // docs/make.feature MK9: a stool on the table top pushed off its edge drops to the floor in the same move+ let floor = part("floor", Vec3::new(0.0, -0.05, 0.0), Vec3::new(10.0, 0.1, 10.0));+ let top = part("table top", Vec3::new(0.0, 0.75, 0.0), Vec3::new(1.0, 0.04, 1.0));+ let stool = part("stool", Vec3::new(0.2, 0.92, 0.0), Vec3::new(0.3, 0.3, 0.3));+ let parts = [floor, top, stool];+ let ins = insets(&parts);+ assert!(matches!(rest(&parts, 2), Rest::On { under: 1, .. }));+ let r = rest_after(&parts, &ins, 2, Vec3::new(1.2, 0.0, 0.0));+ assert!(matches!(landing(&r), Some((0, _, gap)) if (gap - 0.77).abs() < 1e-3), "{r:?}");+ // moved along the top it stays on it+ assert!(matches!(rest_after(&parts, &ins, 2, Vec3::new(-0.3, 0.0, 0.0)), Rest::On { under: 1, .. }));+}diff --git a/systems/contact/src/zfight.rs b/systems/contact/src/zfight.rsnew file mode 100644index 00000000..380e96ee--- /dev/null+++ b/systems/contact/src/zfight.rs@@ -0,0 +1,140 @@+//! Faces lying in one plane over each other (docs/make.feature MK8, the clip check FLOOR3 ran in Blender): two+//! triangles facing the same way within about a degree, their planes within 0.2 mm, overlapping by more than a+//! millimetre. The depth buffer can't order them, so the picture flickers between them as the camera moves+//! (z-fighting): between two parts (a rug's top in the floor's, two wall slabs overlapping in line) or inside one model+//! (a generated mesh's doubled faces). Faces meeting along an edge, and faces back to back (a box resting on another),+//! are left alone.++use std::collections::HashMap;++use bevy::math::{Vec2, Vec3};++/// Planes this close (metres) are one plane.+const PLANE: f32 = 0.0002;+/// Normals this aligned (the cosine) face the same way.+const PARALLEL: f32 = 0.9998;+/// Overlapping by less than this (metres) is meeting at an edge, not one face over another.+const INSIDE: f32 = 0.001;+/// A model with more faces than this isn't checked against itself (the check would cost more than the render).+const SELF_MAX: usize = 400_000;++struct Face {+ n: Vec3,+ d: f32,+ tri: [Vec3; 3],+ area: f32,+}++fn face(t: &[Vec3; 3]) -> Option<Face> {+ let c = (t[1] - t[0]).cross(t[2] - t[0]);+ let l = c.length();+ if l < 1e-10 {+ return None;+ }+ let n = c / l;+ Some(Face { n, d: n.dot(t[0]), tri: *t, area: 0.5 * l })+}++type Key = (i32, i32, i32, i64);++fn key(n: Vec3, d: f32) -> Key {+ ((n.x * 100.0).round() as i32, (n.y * 100.0).round() as i32, (n.z * 100.0).round() as i32, (d / PLANE).floor() as i64)+}++/// The keys a face's twin may sit under: its own and every neighbour (a normal or plane on a bucket's edge).+fn near(k: Key) -> impl Iterator<Item = Key> {+ (-1..=1).flat_map(move |a| (-1..=1).flat_map(move |b| (-1..=1).flat_map(move |c| (-1..=1).map(move |e| (k.0 + a, k.1 + b, k.2 + c, k.3 + e as i64)))))+}++/// Whether two coplanar faces overlap by more than INSIDE: separating axes in the plane, in an orthonormal frame.+fn overlap(a: &Face, b: &Face) -> bool {+ let u = a.n.any_orthonormal_vector();+ let v = a.n.cross(u);+ let flat = |t: &[Vec3; 3]| t.map(|p| Vec2::new(p.dot(u), p.dot(v)));+ let (p, q) = (flat(&a.tri), flat(&b.tri));+ for tri in [&p, &q] {+ for k in 0..3 {+ let e = tri[(k + 1) % 3] - tri[k];+ let axis = Vec2::new(-e.y, e.x).normalize_or_zero();+ if axis == Vec2::ZERO {+ continue;+ }+ let span = |t: &[Vec2; 3]| t.iter().map(|x| x.dot(axis)).fold((f32::MAX, f32::MIN), |(lo, hi), s| (lo.min(s), hi.max(s)));+ let (a0, a1) = span(&p);+ let (b0, b1) = span(&q);+ if a1.min(b1) - a0.max(b0) < INSIDE {+ return false;+ }+ }+ }+ true+}++fn same_plane(a: &Face, b: &Face) -> bool {+ a.n.dot(b.n) >= PARALLEL && (a.n.dot(b.tri[0]) - a.d).abs() <= PLANE+}++/// One face over another: how many pairs, about how much area (the smaller face of each pair, summed: an upper+/// bound), and where the first is. `b` None: within `a` itself.+pub fn overlaps(a: &[[Vec3; 3]], b: Option<&[[Vec3; 3]]>) -> Option<(usize, f32, Vec3)> {+ if b.is_none() && a.len() > SELF_MAX {+ return None;+ }+ let fa: Vec<Face> = a.iter().filter_map(face).collect();+ let fb: Vec<Face> = b.map(|b| b.iter().filter_map(face).collect()).unwrap_or_default();+ let others = if b.is_some() { &fb } else { &fa };+ let mut buckets: HashMap<Key, Vec<usize>> = HashMap::new();+ for (i, f) in others.iter().enumerate() {+ buckets.entry(key(f.n, f.d)).or_default().push(i);+ }+ let (mut count, mut area, mut at) = (0usize, 0f32, None);+ for (i, f) in fa.iter().enumerate() {+ let mut seen: Vec<usize> = Vec::new();+ for k in near(key(f.n, f.d)) {+ for &j in buckets.get(&k).into_iter().flatten() {+ // within one model, each pair once+ if (b.is_none() && j <= i) || seen.contains(&j) {+ continue;+ }+ seen.push(j);+ let g = &others[j];+ if same_plane(f, g) && overlap(f, g) {+ count += 1;+ area += f.area.min(g.area);+ at.get_or_insert((f.tri[0] + f.tri[1] + f.tri[2]) / 3.0);+ }+ }+ }+ }+ at.map(|at| (count, area, at))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn quad(y: f32, x0: f32, x1: f32, up: bool) -> Vec<[Vec3; 3]> {+ let (a, b, c, d) = (Vec3::new(x0, y, 0.0), Vec3::new(x1, y, 0.0), Vec3::new(x1, y, 1.0), Vec3::new(x0, y, 1.0));+ if up { vec![[a, c, b], [a, d, c]] } else { vec![[a, b, c], [a, c, d]] }+ }++ #[test]+ fn faces_in_one_plane_over_each_other_fight_and_neighbours_do_not() {+ // a floor's top and a rug's top in the same plane, facing up: they fight+ let floor = quad(0.0, -1.0, 1.0, true);+ let rug = quad(0.0001, 0.0, 0.5, true);+ let (n, area, _) = overlaps(&rug, Some(&floor)).expect("the rug's top fights the floor's");+ assert!(n >= 2 && area > 0.1, "{n} {area}");+ // 1 cm above it, it doesn't+ assert!(overlaps(&quad(0.01, 0.0, 0.5, true), Some(&floor)).is_none());+ // back to back (a box resting on another: one top up, the other's bottom down) doesn't fight+ assert!(overlaps(&quad(0.0, 0.0, 0.5, false), Some(&floor)).is_none());+ // side by side in one plane, meeting at an edge, doesn't+ assert!(overlaps(&quad(0.0, 1.0, 2.0, true), Some(&floor)).is_none());+ // a model with one face doubled flickers inside itself; a plain quad doesn't+ let mut doubled = quad(0.5, 0.0, 1.0, true);+ doubled.push(doubled[0]);+ assert_eq!(overlaps(&doubled, None).map(|o| o.0), Some(1));+ assert!(overlaps(&quad(0.5, 0.0, 1.0, true), None).is_none());+ }+}diff --git a/systems/stage/src/clearance.rs b/systems/stage/src/clearance.rsnew file mode 100644index 00000000..66723466--- /dev/null+++ b/systems/stage/src/clearance.rs@@ -0,0 +1,218 @@+//! Camera clearance (docs/make.feature MK16, from AnyShot's clearance pass): every frame, how near the camera passes to+//! each solid part, and where it comes closer than a person carrying it could (0.45 m by default). A camera that+//! grazes a door frame or pushes into a desk draws the inside of the part, or a wall filling the frame; the boxes the+//! stage keeps say it without drawing. Only solids count: volumes, decals, footage, 2D, see-through parts (glass) and+//! anything under 5 cm across are passed over. A part's box answers first; a model whose box comes close is measured+//! on its triangles (a room model round the camera, a tree's box that's mostly air).++use std::collections::HashMap;++use bevy::math::{Mat4, Vec3};+use raea_core_facts::{Finding, Level};+use raea_core_scene::Item;+use serde_json::Value;++use crate::framing::{model_box, own_box};+use crate::{View, called};++/// Parts smaller than this across (metres) are passed over: a pen the camera brushes isn't a collision.+const SMALL: f32 = 0.05;+/// Clearance the shot language asks of a carried camera, metres.+pub const DEFAULT: f32 = 0.45;++fn see_through(it: &Item) -> bool {+ let props = it.material.as_ref().map(|m| &m.props);+ let n = |k: &str| props.and_then(|p| p.get(k)).or(it.props.get(k)).and_then(Value::as_f64);+ n("specular_transmission").or(n("transmission")).is_some_and(|t| t > 0.3) || n("opacity").is_some_and(|o| o < 0.5)+}++/// The nearest distance from `p` (world) to a box [lo, hi] in a part's own space under `world`, in world metres.+pub fn to_box(world: &Mat4, lo: Vec3, hi: Vec3, p: Vec3) -> f32 {+ let local = world.inverse().transform_point3(p);+ let near = local.clamp(lo, hi);+ world.transform_point3(near).distance(p)+}++/// The nearest distance from `p` to a triangle.+pub fn to_tri(p: Vec3, t: &[Vec3; 3]) -> f32 {+ let (a, b, c) = (t[0], t[1], t[2]);+ let (ab, ac, ap) = (b - a, c - a, p - a);+ let (d1, d2) = (ab.dot(ap), ac.dot(ap));+ if d1 <= 0.0 && d2 <= 0.0 {+ return p.distance(a);+ }+ let bp = p - b;+ let (d3, d4) = (ab.dot(bp), ac.dot(bp));+ if d3 >= 0.0 && d4 <= d3 {+ return p.distance(b);+ }+ let vc = d1 * d4 - d3 * d2;+ if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {+ return p.distance(a + ab * (d1 / (d1 - d3)));+ }+ let cp = p - c;+ let (d5, d6) = (ab.dot(cp), ac.dot(cp));+ if d6 >= 0.0 && d5 <= d6 {+ return p.distance(c);+ }+ let vb = d5 * d2 - d1 * d6;+ if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {+ return p.distance(a + ac * (d2 / (d2 - d6)));+ }+ let va = d3 * d6 - d5 * d4;+ if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {+ return p.distance(b + (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))));+ }+ let denom = 1.0 / (va + vb + vc);+ p.distance(a + ab * (vb * denom) + ac * (vc * denom))+}++/// A frame's nearest solid parts to its camera: (part, distance) for each closer than `min`.+pub fn near_parts(its: &[Item], eye: Vec3, min: f32, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>, tris: &mut HashMap<String, Option<Vec<[Vec3; 3]>>>) -> Vec<(String, f32)> {+ let mut out = Vec::new();+ for it in its {+ if !matches!(it.kind, "mesh" | "model") || it.at.is_some() || see_through(it) {+ continue;+ }+ let bx = if it.kind == "mesh" { own_box(it, boxes) } else { model_box(it, boxes) };+ let Some((lo, hi)) = bx else { continue };+ let ext = (hi - lo) * it.world.to_scale_rotation_translation().0.abs();+ if ext.max_element() < SMALL {+ continue;+ }+ let mut d = to_box(&it.world, lo, hi, eye);+ if d >= min {+ continue;+ }+ if it.kind == "model" {+ let Some(src) = it.props.get("src").and_then(Value::as_str).map(raea_core_scene::src_path) else { continue };+ let t = tris.entry(src.clone()).or_insert_with(|| raea_core_scene::gltf_tris(&src).ok().map(|(g, _)| g.into_iter().flat_map(|(_, t)| t).collect()));+ if let Some(t) = t {+ let local = it.world.inverse().transform_point3(eye);+ // nearest in the model's own space, then measured in the world's (a scaled model's metres)+ if let Some(best) = t.iter().min_by(|a, b| to_tri(local, a).total_cmp(&to_tri(local, b))) {+ let near = nearest_on(local, best);+ d = it.world.transform_point3(near).distance(eye);+ }+ }+ }+ if d < min {+ out.push((called(it), d));+ }+ }+ out+}++/// The point on a triangle nearest `p` (by projecting and clamping through `to_tri`'s regions, sampled finely enough+/// to measure a clearance to the millimetre).+fn nearest_on(p: Vec3, t: &[Vec3; 3]) -> Vec3 {+ let (a, b, c) = (t[0], t[1], t[2]);+ let n = (b - a).cross(c - a);+ let l2 = n.length_squared();+ if l2 > 1e-14 {+ let q = p - n * ((p - a).dot(n) / l2);+ // barycentric: inside, the projection is the nearest point+ let (v0, v1, v2) = (b - a, c - a, q - a);+ let (d00, d01, d11, d20, d21) = (v0.dot(v0), v0.dot(v1), v1.dot(v1), v2.dot(v0), v2.dot(v1));+ let den = d00 * d11 - d01 * d01;+ if den.abs() > 1e-14 {+ let v = (d11 * d20 - d01 * d21) / den;+ let w = (d00 * d21 - d01 * d20) / den;+ if v >= 0.0 && w >= 0.0 && v + w <= 1.0 {+ return q;+ }+ }+ }+ // outside: the nearest point of the three edges+ let seg = |x: Vec3, y: Vec3| {+ let d = y - x;+ x + d * ((p - x).dot(d) / d.length_squared().max(1e-14)).clamp(0.0, 1.0)+ };+ [seg(a, b), seg(b, c), seg(c, a)].into_iter().min_by(|u, v| u.distance(p).total_cmp(&v.distance(p))).unwrap_or(a)+}++/// Every frame's camera held `min` metres off every solid part: a finding for each part and run of frames it comes+/// closer, with the nearest it gets.+pub fn clearance(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64, min: f32, by: &str) -> Vec<Finding> {+ let (mut boxes, mut tris) = (HashMap::new(), HashMap::new());+ // part -> runs of (first frame index, last, nearest)+ let mut runs: Vec<(String, usize, usize, f32)> = Vec::new();+ let mut open: HashMap<String, usize> = HashMap::new();+ for (k, its) in all.iter().enumerate() {+ let Some(v) = View::of(its, w, h) else { continue };+ let near = near_parts(its, v.eye, min, &mut boxes, &mut tris);+ let names: Vec<&String> = near.iter().map(|n| &n.0).collect();+ open.retain(|name, _| names.contains(&name));+ for (name, d) in near {+ match open.get(&name).copied() {+ Some(r) if runs[r].2 + 1 == k && frames[k] == frames[runs[r].2] + 1 => {+ runs[r].2 = k;+ runs[r].3 = runs[r].3.min(d);+ }+ _ => {+ runs.push((name.clone(), k, k, d));+ open.insert(name, runs.len() - 1);+ }+ }+ }+ }+ runs.into_iter()+ .map(|(name, a, b, d)| {+ let (fa, fb) = (frames[a], frames[b]);+ let when = if a == b { format!("at frame {fa} ({:.2} s)", fa as f64 / fps) } else { format!("over frames {fa}-{fb} ({:.2}-{:.2} s)", fa as f64 / fps, fb as f64 / fps) };+ let says = if d < 1e-3 {+ format!("the camera is inside `{name}` {when}: move the path out of it, or the part")+ } else {+ format!("the camera passes {d:.2} m from `{name}` {when}, under the {min:.2} m a carried camera keeps: move the path or the part, or pass a smaller --clearance for a camera on a rig")+ };+ Finding::new("camera-clearance", Level::Error, says, by).frames(fa, fb + 1)+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::test_items::{cam, item};+ use serde_json::json;++ #[test]+ fn distances_to_a_box_and_a_triangle() {+ let w = Mat4::from_translation(Vec3::new(0.0, 0.5, 0.0));+ let (lo, hi) = (Vec3::splat(-0.5), Vec3::splat(0.5));+ assert!((to_box(&w, lo, hi, Vec3::new(0.0, 0.5, 1.5)) - 1.0).abs() < 1e-5);+ assert_eq!(to_box(&w, lo, hi, Vec3::new(0.0, 0.5, 0.0)), 0.0);+ let t = [Vec3::ZERO, Vec3::X, Vec3::Z];+ assert!((to_tri(Vec3::new(0.25, 0.3, 0.25), &t) - 0.3).abs() < 1e-5);+ assert!((to_tri(Vec3::new(-1.0, 0.0, 0.0), &t) - 1.0).abs() < 1e-5);+ assert!((nearest_on(Vec3::new(0.25, 0.3, 0.25), &t) - Vec3::new(0.25, 0.0, 0.25)).length() < 1e-5);+ }++ fn solid(name: &str, size: [f32; 3], at: [f32; 3]) -> Item {+ let mut it = item("mesh", json!({"name": name}), Mat4::from_translation(Vec3::from(at)));+ it.shape = Some(format!("box({}, {}, {})", size[0], size[1], size[2]).into());+ it+ }++ #[test]+ fn a_camera_pushing_into_a_desk_is_found_and_a_small_or_glass_part_is_not() {+ // a desk 1.6 x 0.75 x 0.8 m standing at the origin; the camera pushes in from 2 m to 0.1 m off its front face+ let desk = solid("desk", [1.6, 0.75, 0.8], [0.0, 0.375, 0.0]);+ let pen = solid("pen", [0.04, 0.01, 0.01], [0.0, 1.0, 0.45]);+ let mut glass = solid("pane", [1.0, 1.0, 0.01], [0.0, 1.0, 0.3]);+ glass.props = std::sync::Arc::new(json!({"name": "pane", "specular_transmission": 0.9}).as_object().cloned().unwrap());+ let zs = [2.4, 1.6, 1.0, 0.7, 0.5, 2.4];+ let all: Vec<Vec<Item>> = zs.iter().map(|z| vec![cam([0.0, 0.6, *z], [0.0, 0.4, 0.0]), desk.clone(), pen.clone(), glass.clone()]).collect();+ let frames: Vec<i64> = (0..zs.len() as i64).collect();+ let f = clearance(&all, &frames, 640, 360, 30.0, DEFAULT, "t");+ // the desk's face is at z 0.4: frames 3 and 4 come within 0.3 and 0.1 m; one run, its nearest said+ assert_eq!(f.len(), 1, "{f:?}");+ assert!(f[0].says.contains("0.10 m from `desk` over frames 3-4"), "{}", f[0].says);+ assert_eq!(f[0].level, Level::Error);+ // a rig's camera may come closer+ assert!(clearance(&all, &frames, 640, 360, 30.0, 0.05, "t").is_empty());+ // inside it, said so+ let inside = vec![vec![cam([0.0, 0.3, 0.0], [0.0, 0.3, -1.0]), desk.clone()]];+ assert!(clearance(&inside, &[0], 640, 360, 30.0, DEFAULT, "t")[0].says.contains("inside `desk`"));+ }+}diff --git a/systems/stage/src/framing.rs b/systems/stage/src/framing.rsindex 413006c4..641991a5 100644--- a/systems/stage/src/framing.rs+++ b/systems/stage/src/framing.rs@@ -58,7 +58,7 @@ pub(crate) fn backdrop(it: &raea_core_scene::Item, lo: Vec3, hi: Vec3) -> bool {/// animates or can't be read. Coverage only, never sure: raea may pose its joints (a person walks off its rest box), and/// a box is mostly air round a tree, so it never makes a frame judged, nor judges words over it (SG11); but a frame/// its box fills isn't empty (Stay's pool room of wall models read empty with their origins out of view: SG14).-fn model_box(it: &raea_core_scene::Item, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>) -> Option<(Vec3, Vec3)> {+pub(crate) fn model_box(it: &raea_core_scene::Item, boxes: &mut HashMap<String, Option<(Vec3, Vec3)>>) -> Option<(Vec3, Vec3)> {let src = raea_core_scene::src_path(it.props.get("src").and_then(serde_json::Value::as_str)?);*boxes.entry(format!("model:{src}")).or_insert_with(|| {let (groups, moves) = raea_core_scene::gltf_tris(&src).ok()?;diff --git a/systems/stage/src/lib.rs b/systems/stage/src/lib.rsindex 0fd67e13..f650eaa1 100644--- a/systems/stage/src/lib.rs+++ b/systems/stage/src/lib.rs@@ -11,6 +11,7 @@ use raea_core_facts::{Finding, Level};use raea_core_scene::{Item, base_ident};use serde_json::Value;+pub mod clearance;mod cover;mod framing;mod manifest;@@ -18,6 +19,7 @@ mod motion;mod page;mod text;mod view;+pub use clearance::clearance;pub use framing::on_screen;pub use manifest::{Mounts, pages, seen};pub use page::{Page, Words};