Compare commits

...
Author SHA1 Message Date
shinyobjectz b70c8c868d raea goal check on a plan: only the cut's own exact errors stop it
A plan check's exit 1 stops raea cloud from rendering any cut, so it has to mean "this cut has something to fix".
The review of #332 found three ways it didn't:

- The project's own checks (registered, taste) and the goals' job checks (count, quotes) ran on a plan. A brief
  asking for 10 cuts with the count question still open, which is normal until a person answers it at the first
  stop, failed every plan, so nothing could ever be rendered. A plan now runs only its cut's file checks; the job
  and project checks stay with the render, publish and done moments.
- A farm failure (/v1/scene answering 503 three times) made frames and place break, and a broken check fails the
  run, with no ERROR line to act on. On a plan, a check that throws now waits and says the render's check holds it.
- Place, captions, reading and faces cut by the frame's edge read the source frames without the cut's text over
  them, or hold captions against the takes' words rather than the mix. On round 22's Body Shop each cut had at
  least one such error that the export's check didn't give. On a plan these are warnings now, marked "(on the plan
  a warning: the render's check holds it)". Floor's text rules, text too small and sound's edit points and levels
  stay errors, since a plan knows them exactly as the export does.

Tested: bun test in sdk/goal passes all 72 tests, three of them new in test/plan.test.ts (a brief's unanswered
count doesn't stop a clean plan, while the same project checked without a plan still errs on it; a farm answering
503 leaves a clean plan PASSED with frames waiting; text over a face and talking with no captions are warnings on a
plan). On raea-box-6, the four Body Shop cuts' plans went from 15-31 errors each (captions, frames, place, reading
and sound) to sound errors only (17, 22, 11, 11), which match the export's sound errors one for one.
2026-12-04 11:08:29 -08:00
shinyobjectz 1e559373fc raea goal check --at edit --manifest PLAN EDIT.tsx: a cut checked on its plan before it's drawn
In round 22 every run missed its budget the same way: a full render of every cut, and only then dozens of floor,
sound, place and frames errors, fixed, and everything rendered again. All of those can be known from the composition's
timeline, its takes' words and its sources' frames, before anything is drawn.

With a composition named and --manifest given, goal check now treats the manifest as the plan of one of its cuts (what
`raea render EDIT.tsx --composition ID --plan -o OUT.plan.json` writes: the render manifest of every frame, nothing
drawn). The file it checks is the export the plan is of (OUT.mp4, named by stripping .plan/.render/.manifest), and its
findings are written to OUT.plan.check.json as well as review/goal.json (both written whole, since several cuts' plans
are checked at once). At the edit moment, on a plan:

- floor: apps/check/text's text rules ported to TypeScript (src/plan.ts textRuns, zones, textRules): text in the app's
  UI zones and text clipped off the frame are errors, text up too briefly a warning. Contrast, freezes, flashes,
  loudness and blotching still wait for the export.
- sound: unchanged, now also run at edit; it already works from the manifest's clips against each take's words and level.
- frames and place: what each sampled frame (two a second) shows is read from the source frames its videos show. Each
  video's box, fit, object-position and clip give the part of the source picture the frame shows; that part is cut out
  of the source frame (ffmpeg crop at the scene reader's size, eight at a time), read by the farm's POST /v1/scene, and
  its faces, things, person mask and text are mapped back into the cut's frame. Reading the crop rather than the whole
  source frame gives the reader the same pixels and resolution the export's reader gets, so a face half out of the shot
  is read the way the export reads it. A video's edge inside the frame is a seam; a full-frame opaque fill beyond the
  cut's background count (an end card) hides the videos under it. Each read is kept under review/scenes/ by source,
  second and crop, so a plan checked again only asks for what changed.
- captions and reading: what the cut shows is its own text as laid out (a text on several lines read a line each, as
  the export's reader reads it), and what it says is its voice clips' takes' words where the clips put them.

media.ts's scene() posting is split out as readScenes() so the plan reads go through the same retrying farm client.

Tested: bun test (69 pass, 5 new in test/plan.test.ts: drawing and crops, mapping a crop's scene into the frame,
seams and hiding, the cut's words from its clips, the text rules, and goal check on a plan end to end with a stand-in
farm, including the kept reads). On raea cloud boxes, the changed sdk/goal (with the box image's goal.ts) was run as
`raea goal check --at edit --manifest OUT.plan.json edit.tsx` against the full render manifests of round 22's 14 cuts
(their format is the plan's) in read-only copies of the three projects, and its errors compared with each export's
.check.json from the same render. Over the 10 cuts with a check from the same render: floor 8 of 8 matched (3 more
are blotching and a flash, which only the picture shows), sound 95 of 95 with none extra, frames 4 of 5 with 3 extra,
place 20 of 32 with 8 extra (the misses are mostly captions over a person that the plan says as warnings where the
export's reader found a handbag or a face in the caption's own box), captions 5 of 14, reading 1 of 5 (its misses are
the export's reader reading signs in the footage). A first plan check took 15-41 s a cut on the box (most of it the
farm's reads); checked again with its reads kept, 2-4 s.
2026-12-04 10:25:36 -08:00
shane bec1ab1947 Merge pull request #325 from shinyobjectz/idle-real-path
A box's idle stop sees work by its folder's real path; box.sh holds the box while unpacking
2026-12-03 22:19:39 -08:00
shinyobjectz c261ecdfbc box.sh image on a clean tree: its label's dirty test ended the script under set -e, saying nothing 2026-12-03 21:18:41 -08:00
shinyobjectz 712e5ba3a0 A box's idle stop sees work in its folder by the folder's real path too; box.sh holds the box while it unpacks
On a Fly box the work folder is /home/sprite/work, a link to /home/raea/work, and /proc names a process's folder
without the link: a 64 GB unpack in it was taken for idle and the box stopped under it (12-03, raea-3).
2026-12-03 20:48:01 -08:00
shaneandshinyobjectz 51e2d87c76 HugText taught with captions (the skills gate rc3 failed on), a request counts as the box at work until it ends, and box.sh move resumes an arrived home and says what it unpacks (#324)
12-03: a box stopped as idle the moment a 19-minute upload ended (only its start counted), cutting off the unpack that
followed; an unpack of 26 GB said nothing for 3 minutes and was stopped as stalled.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 20:38:05 -08:00
shaneandshinyobjectz 9fed1783dc raea cloud's boxes as Fly Machines; 2D farm renders out at once, stragglers sent again (#323)
* raea cloud's boxes as Fly Machines, and a 2D render's runs out at once with stragglers sent again

Boxes: deploy/fly (image, start, box.sh up/move/latest), the server stops itself when idle (idle.ts), a file PUT
streams to disk, the client sends a Sprite's token only to a Sprite (CL16).
Farm: a video with no 3D goes out at once on up to the job's containers (no timed first run), a run hanging back is
sent again and the first answer kept, and containers with no GPU stay warm 180 s.

* The public guard passes raea cloud's box users' folders (/home/sprite, /home/raea); the Fly box scripts are executable

* A goal's says rules judged at once: up to 6 cuts heard by Clef together, and the critic reads while they're heard

One raea ask after another, a project's beats took 6-17 minutes of every goal check (12-03, StreetTalk).

* A box takes a request as long as its body takes (Node's 5 minutes cut a home's upload at 408); box.sh move stops when the home didn't arrive whole

* A box's files route in its own module, streamed both ways; box.sh move says what has arrived every 15 s and stops a copy that stops growing for 2 minutes

main.ts was 520 lines (tools/size.sh). Shane 12-03: fail fast at every step.

* farm: each step after the draw says how long it took when it took a second or more

A render whose every frame was kept took 64 s between "nothing to draw" and "joined" (12-03), and nothing said where.

* An agent socket whose caller answers no ping in 3 minutes is ended, and its agent with it; box.sh restarts a box only for a new image, and its copy reconnects to the Sprite

12-03: a stopped StreetTalk project's Gemini, busy so never idle, went on an hour running goal checks on raea-5: its caller
(the API, restarted) had gone with the box's half of the socket open. A Machine restarted by box.sh up after its health
check passed cut three homes' uploads off; and sprite exec lost all four copies' sessions at once, 6 minutes in, without
reconnecting while stdin was attached (--no-stdin).

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 20:02:40 -08:00
shaneandshinyobjectz 23918c2c23 Pin raea-skills at ff03a87: references for v0.1.17-rc3 (#322)
Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 19:00:17 -08:00
shaneandshinyobjectz c5c87e2cfb raea guide brief: brief.ts's types and an example, and a cut's beats typed as they are (#321)
Dutch's plan turn (12-03) spent about 2 minutes looking for raea/brief's types: raea guide brief had no guide, so it
read sdk/raea/src under /opt/raea. And what it found was wrong: brief-goal.gen.ts imported the screenplay's Beat
(onScreen, lines, cues) for a cut's beats, while cut.rs's own Beat (at, feel, story, asl, tempo, MK48) is what raea
reads and validates. tsc refused a correct cut beat and accepted a wrong one.

- core/brief: a cut's beat is CutBeat in TypeScript and declared in brief-goal.gen.ts (regenerated); montage.ts uses it.
- sdk/guides/craft/motion/brief.md: the Brief fields, a cut goal's contract, rules and who judges a says rule (raea,
  never the agent), and a fictional example that type-checks against the SDK; the router points to it.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 17:50:07 -08:00
shaneandshinyobjectz 743b35677c Judges never pick a harness: a fresh session of the project's own agent, or Clef (#320)
Shane, 12-03: nothing judges or checks with another harness, and nothing the agent reads makes it choose a harness,
model or provider. Dutch's plan turn spent about 3 minutes on raea goal judge --by claude (not signed in on a box),
--by clef (no video at plan) and --by kimi (not on PATH), because sdk/goal spawned claude -p and kimi -p itself.

- sdk/cloud/server/critic.ts: each agent session the box server starts gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN;
  POST /host/judge {cwd, prompt} starts a fresh session of that same agent (command, sign-in, environment) over ACP
  stdio, allows reads only, and returns what it says. The desktop's local cloud runs the same server.
- sdk/goal: judge() takes no critic. A rule with a piece to watch or hear goes to Clef-Omni, any other to the session's
  critic. raea goal check asks for a verdict itself when it's missing, stale or partial, so the check is the one
  command and the hooks judge with it. BY, critic() and --by are gone.
- raea judge and raea fingerprint read: the same critic through io/clef/src/critic.rs (one call for every caller);
  --by kimi|claude gone, judge eye --read in its place.
- Help, the manual and the Bevy guides name no harness.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 17:50:03 -08:00
shaneandshinyobjectz 80562f9ef7 skills pin: raea-skills fb72c5e for v0.1.17-rc2 (#318)
raea-skills #150-#153: raea show --choose and the workspace MCP line, the component library routing, the playable guide
on Bevy's PBR (#317), and the references regenerated with raea built at main 5f407a1c. SKILLS_STRICT=1
tools/skills.sh check passes on this tree with raea-feed main.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 13:43:14 -08:00
shaneandshinyobjectz 5f407a1cc2 A playable's 3D is drawn by Bevy's own PBR programs (PA11) (#317)
* A playable's 3D is drawn by Bevy's own PBR programs (PA11)

tools/bevy-glsl composes Bevy's mesh, pbr and prepass shaders with Bevy's ShaderCache for a WebGL2 device and
translates them with naga; sdk/playable/bevy/build.sh writes them, with each uniform block's field offsets, into
host/bevy/programs.ts, and apps/playable's test fails when Bevy's shaders or the translator change without a rebuild.
host/bevy.ts replaces three.js's renderer and the tone pass: it reads raea's three.js scene graph and fills Bevy's
blocks as Bevy's render world does (reverse Z, one light cluster, one directional shadow cascade, point and spot
lights, distance fog), draws into half float with 4x MSAA, and maps through TonyMcMapface's table.

A Plane3d now reaches three.js as its one face, not as a box with no depth whose top face three points down.

Against `raea render --frame`: brick-rush portrait frame 90 6.1 -> 4.3 / 255, landscape frame 300 9.8 -> 7.7; a
light test scene 0.7 to 1.3 with fog, point and spot lights and an orthographic camera. The page is about 100 KB
smaller and its first frame is as fast as before in WebKit.

* bevy-glsl gets its layer; one fewer helper and line for the gates

tools/layers.toml places bevy-glsl under tools. The translator's one-use int() helper is folded into its call (a
duplicate of uint()), so programs.from moves while programs.ts stays byte for byte. scene.ts asks geometry.ts's
planeOf for a Plane3d's face in one line, back to 500.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 13:21:21 -08:00
shaneandshinyobjectz b0437d2d08 raea show --choose: pick one of 2 to 6 named options (#314)
* raea show --choose: the person picks one of 2 to 6 named options, each its files

raea-platform home.feature HM9. `raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png
--recommend 2`: each --choose names an option and holds the files after it; --recommend N marks the one the agent
would pick (nothing is picked for the person). It goes to the app's host as intent "choose" with the options, and
the pick comes back to the inbox as {"kind":"answer","choice":"Cool grade"}. Refused: one option or more than six, an
option with no files, a file outside the options, --group, --question or --fyi with it, --recommend out of range.
Usage, the native help line and the manual page say so.

* raea show help: the pick's JSON braces escaped in the format string

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:47:53 -08:00
shaneandshinyobjectz 230f817543 raea check: contrast reads a text in the colour it has on the frame it's measured at (#316)
A text that keeps its words but changes colour (a step chip lighting up, grey on dark to dark on yellow) is one run,
and a run kept only its last frame's colour. Contrast measures at the run's middle frame, so the swipe-graph film's
chips were read as dark text on a dark chip: 1.2:1 where the pixels measure about 8:1. A run now keeps its colour on
each frame beside its box, and contrast uses the middle frame's (Run::middle_color).

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:47:46 -08:00
shaneandshinyobjectz 8dfd71eb92 The component library says when to use each piece: search by how people ask, show NAME, props and upstream names (#315)
An agent asked for "the effect template for composer animations with Claude" found nothing: the catalog had one thin
line per item and the search only read names and that line. Now:

- tools/library-meta.sh (enrich.ts, props.ts, upstream.ts, words.ts, hand.json) matches each of the 609 items by
  content to the upstream component it came from (all 609 match; snapcn's terminal-simulator and text-highlight are
  ui/terminal-session and text/highlight-sweep here) and writes into catalog.json: upstream (a search alias only),
  what (what it draws and how it moves), use_when and avoid_when (upstream's useWhen/avoidWhen in plain words, other
  libraries' names out, pointers rewritten to our category/name or dropped), asked_as (upstream's askedAs plus the
  words people use for its kind: template, effect, composer, chat input, AI prompt, terminal, Claude Code...), props
  (name, type, default and a line each, read from its Props type with the TypeScript parser), length, fps, size,
  aspect and vibe. snapcn's and React Video Editor's items have no when-to-use upstream: hand.json holds those, 134.
- raea make component list WORDS searches names, upstream names and asked_as heavily, what and use_when once; filler
  words are skipped and "template"/"effect"/"preset" alone list the items that are one with how to narrow it.
- raea make component show NAME prints one item in full; list/show --json give the same as JSON.
- sdk/guides/craft/components.md: a template, an effect or a branded screen goes to the library first.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:29:09 -08:00
shaneandshinyobjectz 2cbfa8c608 A playable carries Bevy's world as wasm for a game whose rules are raea/ecs systems (#313)
PA12: runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh: 253 KB, 105 KB gzipped,
no imports) into sdk/playable/src/host/ecs.wasm, with the hash of what it was built from beside it, which apps/playable's
test checks. The lint's walk sees a World made; the export carries the module and its entry loads host/ecs.ts before
the game, so raea/ecs's calls (native.ts ecsCall: the engine's bridge, else the page's) reach Bevy's tables in the page
as they do in the engine. A page that can't make the module keeps raea/ecs's TypeScript tables.

World.copy() is a game's next state (copied with its systems, stepped on its own), and a native store nothing holds
frees its world, so a game's let-go states don't keep theirs. examples/playables/star-catch.tsx is a game whose rules
are three systems on a World; conformance/ecs-wasm.test.ts runs one world's life on the wasm and on the TypeScript
tables and finds them equal. The playable guide shows the pattern.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-03 12:23:00 -08:00
111 changed files with 34132 additions and 1133 deletions

No files matched your search

Generated
+1
View File
@@ -13820,6 +13820,7 @@ dependencies = [
"fastrand",
"raea-app-check",
"raea-app-double",
"raea-io-clef",
"raea-io-home",
"raea-sys-columns",
"raea-sys-fingerprint",
+2 -1
View File
@@ -213,7 +213,8 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue;
}
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
let color = r.middle_color();
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let Some(ratio) = ratio else { continue };
measured += 1;
if ratio < 3.0 {
+6 -5
View File
@@ -67,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], colors: vec![], color: String::new(), size: 48.0 };
let (mut issues, mut passed) = (vec![], vec![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -267,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test]
fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
let (mut issues, mut passed) = (vec![], vec![]);
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -335,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
let (mut issues, mut passed) = (vec![], vec![]);
@@ -425,10 +425,11 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[test]
fn a_moving_text_is_read_where_it_is() {
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
}
+36 -2
View File
@@ -43,6 +43,10 @@ pub struct Run {
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
pub boxes: Vec<[f64; 4]>,
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
pub colors: Vec<String>,
/// its colour on its last frame
pub color: String,
pub size: f64,
}
@@ -57,6 +61,15 @@ impl Run {
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
}
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
pub fn middle_color(&self) -> &str {
let n = self.boxes.len();
match self.colors.get(n / 2) {
Some(c) if n > 1 && self.colors.len() == n => c,
_ => &self.color,
}
}
}
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
@@ -114,18 +127,21 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
});
let mut r = match found {
Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 },
};
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
if text.len() > r.text.len() {
r.boxes.clear();
r.colors.clear();
}
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone());
}
r.to = t + 1.0 / fps;
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
r.color = color;
r.size = x["size"].as_f64().unwrap_or(0.0);
next.push(r);
}
@@ -294,3 +310,21 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
passed.push(format!("cues: {checked} texts land on their words"));
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
}
}
+2
View File
@@ -15,6 +15,8 @@ raea-sys-fingerprint = { path = "../../systems/fingerprint" }
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
raea-app-double = { path = "../double" }
# the critic a note is read by: a fresh session of the project's own agent (critic.rs)
raea-io-clef = { path = "../../io/clef" }
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
# the encoders and the columns they make
raea-sys-columns = { path = "../../systems/columns" }
+2 -3
View File
@@ -21,13 +21,13 @@ use std::path::Path;
pub use serve::serve;
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
pub type Eval = fn(&Path) -> Result<String, String>;
/// The flags each verb takes, and whether each takes a value
pub(crate) const FLAGS: [(&str, bool); 31] = [
pub(crate) const FLAGS: [(&str, bool); 30] = [
("--fp", true),
("--was", true),
("--to", true),
@@ -51,7 +51,6 @@ pub(crate) const FLAGS: [(&str, bool); 31] = [
("--as", true),
("--against", true),
("--profile", true),
("--by", true),
("--ask", true),
("--tally", false),
("--bad", false),
+11 -32
View File
@@ -1,5 +1,5 @@
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT [--by kimi|claude]`
//! has a fresh agent session read each pinned note on the project's videos into a kind (defect, direction, praise or
//! Notes become evidence (docs/fingerprint.feature FP5a, FP5b). `raea fingerprint read PROJECT` has a fresh session of
//! the project's own agent (its host's critic, raea_io_clef::critic; never one raea or the agent picks) read each pinned note on the project's videos into a kind (defect, direction, praise or
//! both) and an axis from the fingerprint's own axes, kept in the fingerprint's readings.jsonl. Nothing trains on them
//! yet: `raea fingerprint readings --ask N` puts N readings to the person as questions in the app (`raea show
//! --question`, answers to the "fingerprint" inbox), `readings --tally` counts how often the person agreed, and only
@@ -99,30 +99,9 @@ pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
}
}
/// One fresh session's words: kimi's or claude's stream, the assistant's text joined
fn ask(by: &str, p: &str) -> Result<String, String> {
let mut c = std::process::Command::new(by);
match by {
"kimi" => c.args(["-p", p, "--output-format", "stream-json"]),
"claude" => c.args(["-p", p, "--output-format", "stream-json", "--verbose", "--allowedTools", ""]),
o => return Err(format!("--by {o}: kimi or claude")),
};
let out = c.output().map_err(|e| format!("couldn't run {by}: {e}"))?;
let mut text = String::new();
for line in String::from_utf8_lossy(&out.stdout).lines() {
let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
let content = if v["role"] == "assistant" { &v["content"] } else if v["type"] == "assistant" { &v["message"]["content"] } else if v["type"] == "result" { &v["result"] } else { continue };
match content {
Value::String(s) => text += s,
Value::Array(a) => a.iter().filter_map(|p| p["text"].as_str()).for_each(|s| text += s),
_ => {}
}
text.push('\n');
}
if text.trim().is_empty() {
return Err(format!("{by} said nothing: {}", String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("")));
}
Ok(text)
/// One fresh session of the project's own agent, through its host (raea_io_clef::critic): its words
fn ask(cwd: &Path, p: &str) -> Result<String, String> {
raea_io_clef::critic::ask(cwd, p)
}
pub fn readings_of(dir: &Folder) -> Vec<Reading> {
@@ -133,12 +112,12 @@ pub fn write_readings(dir: &Folder, r: &[Reading]) -> std::io::Result<()> {
std::fs::write(dir.dir.join("readings.jsonl"), r.iter().filter_map(|x| serde_json::to_string(x).ok()).map(|l| l + "\n").collect::<String>())
}
/// `raea fingerprint read PROJECT [--by kimi|claude]`
/// `raea fingerprint read PROJECT`
pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
let run = || -> Result<String, String> {
let w = words(args)?;
let project = w.first().map_or(cwd.to_path_buf(), |p| cwd.join(p));
let by = flag(args, "--by").unwrap_or("kimi");
let by = "agent";
let dir = crate::pick::chosen(args, Some(&crate::pick::piece_in(args, cwd))).0;
let fp = dir.read(None).map_err(|e| e.to_string())?;
let mut notes = pinned(&project);
@@ -148,15 +127,15 @@ pub(crate) fn read_here(args: &[String], cwd: &Path) -> i32 {
return Ok(format!("no new pinned notes in {}", project.display()));
}
for chunk in notes.chunks_mut(40) {
let text = ask(by, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| format!("{by} answered no readings JSON"))?;
let text = ask(&project, &prompt(&fp, chunk))?;
let ans = answer(&text).ok_or_else(|| "the critic answered no readings JSON".to_string())?;
fold(chunk, &fp, &ans, by);
eprintln!("read {} notes", chunk.len());
}
let read = notes.iter().filter(|n| !n.kind.is_empty()).count();
kept.extend(notes.into_iter().filter(|n| !n.kind.is_empty()));
write_readings(&dir, &kept).map_err(|e| e.to_string())?;
Ok(format!("{read} notes read into labels by {by}, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
Ok(format!("{read} notes read into labels by a fresh session of the project's agent, kept in {}; none trains a head until you've checked them: raea fingerprint readings --ask 50", dir.dir.join("readings.jsonl").display()))
};
match run() {
Ok(o) => {
@@ -285,7 +264,7 @@ mod tests {
let fp = raea_sys_fingerprint::taxonomy::base("me");
let mut n = vec![Reading { note: "n1".into(), ..Default::default() }, Reading { note: "n2".into(), ..Default::default() }, Reading { note: "n3".into(), ..Default::default() }];
let ans = answer("I read them.\n[{\"id\": \"n1\", \"kind\": \"defect\", \"axis\": \"glitch\"}, {\"id\": \"n2\", \"kind\": \"direction\", \"axis\": \"made up\"}, {\"id\": \"n3\", \"kind\": \"rant\", \"axis\": null}]").unwrap();
fold(&mut n, &fp, &ans, "kimi");
fold(&mut n, &fp, &ans, "agent");
assert_eq!((n[0].kind.as_str(), n[0].axis.as_deref()), ("defect", Some("glitch")));
assert_eq!((n[1].kind.as_str(), n[1].axis.as_deref()), ("direction", None), "an axis the fingerprint hasn't is dropped");
assert_eq!(n[2].kind, "", "a kind it doesn't know is no reading");
+17 -72
View File
@@ -1,8 +1,9 @@
//! A judge that is an agent CLI rather than clef-omni: `raea judge DIR --by kimi|claude` (Shane, 11-06: "use claude or
//! kimi cli as the judge"). Each call is a new session, run in DIR with only the sheets to look at (kimi's media tool;
//! claude with Read alone), given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and
//! never the code or the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --by kimi` records
//! A judge that is an agent rather than clef-omni (Shane, 11-06: an agent as the judge; 12-03: never a harness raea
//! picks or the agent names): a fresh session of the agent this project runs on, which the host that started it (raea
//! cloud's box, the raea app) offers as RAEA_JUDGE_URL. Each call is a new session, run in DIR with only the sheets to
//! look at, given the fresh-context judge prompt (sdk/guides/craft/bevy/prompts.md section 3) and never the code or
//! the builder's notes. It answers JSON: the seven scores 0-10, the blind read and every defect named;
//! the pass, done and stall are still decided in code (rubric::pass, progress). `raea judge eye DIR --read` records
//! its reading as the eye clef is calibrated against.
use std::path::Path;
@@ -11,7 +12,10 @@ use serde_json::{Map, Value, json};
use crate::rubric::{BAR, scores};
pub const BY: [&str; 2] = ["kimi", "claude"];
/// Whether this session has a critic to ask: where it has, the agent judges; else clef.
pub fn critic() -> bool {
raea_io_clef::critic::here()
}
/// 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/goal.feature MK5); none asks the rubric raea judge has always asked.
@@ -125,70 +129,11 @@ pub fn read(kind: Option<&str>, v: &Value) -> (Map<String, Value>, Vec<Value>, V
(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(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(kind, &dir, brief, target);
let mut cmd = match by {
"kimi" => {
let mut c = std::process::Command::new("kimi");
c.args(["-p", &p, "--output-format", "stream-json"]);
c
}
"claude" => {
let mut c = std::process::Command::new("claude");
c.args(["-p", &p, "--allowedTools", "Read", "--output-format", "stream-json", "--verbose"]);
c
}
o => return Err(format!("judge: --by {o}: the judges are clef (the default), {}", BY.join(", "))),
};
let mut child = cmd.current_dir(&dir).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).spawn()
.map_err(|e| format!("judge: couldn't run {by}: {e} (is the {by} CLI installed and signed in?)"))?;
let mut said = Vec::new();
let mut last = String::new();
for line in std::io::BufReader::new(child.stdout.take().ok_or("judge: no output pipe")?).lines().map_while(Result::ok) {
let Ok(v) = serde_json::from_str::<Value>(&line) else { continue };
said.extend(texts(&v));
let step = match (v["role"].as_str(), v["type"].as_str()) {
(Some("tool") | Some("user"), _) => "looked at a picture".to_string(),
(Some("assistant"), _) | (_, Some("assistant")) => texts(&v).last().map_or_else(|| "thinking".into(), |t| t[..t.floor_char_boundary(100)].to_string()),
_ => continue,
};
if step != last {
eprintln!("judge ({by}): {}", step.replace('\n', " "));
last = step;
}
}
let out = child.wait_with_output().map_err(|e| format!("judge: {by}: {e}"))?;
let text = said.join("\n");
if !out.status.success() && last_verdict(&text).is_none() {
return Err(format!("judge: {by} failed: {}", String::from_utf8_lossy(&out.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
last_verdict(&text).ok_or_else(|| format!("judge: {by} answered no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
}
/// The words in one streamed line: kimi's {role: assistant, content: "..."}; claude's {type: assistant, message:
/// {content: [{type: text, text}]}} and its final {type: result, result}.
fn texts(v: &Value) -> Vec<String> {
let mut out = Vec::new();
if v["role"] == "assistant"
&& let Some(s) = v["content"].as_str()
{
out.push(s.to_string());
}
for c in v["message"]["content"].as_array().into_iter().flatten() {
if c["type"] == "text"
&& let Some(s) = c["text"].as_str()
{
out.push(s.to_string());
}
}
if v["type"] == "result"
&& let Some(s) = v["result"].as_str()
{
out.push(s.to_string());
}
out
/// One fresh judging session of this project's own agent over DIR's sheets, through the host (RAEA_JUDGE_URL): its
/// verdict JSON.
pub fn ask(kind: Option<&str>, dir: &Path, brief: &Value, target: Option<&Path>) -> Result<Value, String> {
let dir = dunce::canonicalize(dir).map_err(|e| format!("judge: {}: {e}", dir.display()))?;
eprintln!("judge: a fresh session of this project's agent is reading the sheets");
let text = raea_io_clef::critic::ask(&dir, &prompt(kind, &dir, brief, target)).map_err(|e| format!("judge: {e}"))?;
last_verdict(&text).ok_or_else(|| format!("judge: the critic gave no verdict JSON: {}", text.trim().chars().rev().take(300).collect::<String>().chars().rev().collect::<String>()))
}
+5 -4
View File
@@ -3,7 +3,7 @@
//! ~/.raea/judge/eye.jsonl. `raea judge calibrate` fits, per category, a line from the judge's score to his
//! (least squares), and says how often the mapped judge's pass agrees with his. The judge gates only once it has 10
//! rounds or more, some passed by the eye and some not, and agrees on 8 in 10 or better; until then `gating` is false and its verdict is advice
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --by kimi|claude` records a
//! (clef has rated almost everything acceptable: docs/craft-system.md). `raea judge eye DIR --read` records a
//! fresh agent session's reading instead (Shane, 11-06), each row saying whose eye it is.
use std::path::PathBuf;
@@ -46,9 +46,10 @@ pub fn record(args: &[String]) -> Result<String, String> {
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 code
if let Some(by) = args.iter().position(|a| a == "--by").and_then(|i| args.get(i + 1)) {
let v = crate::agent::ask(kind, by, &dir, &json!({}), None)?;
// the session's agent's reading as the eye (`--read`): a fresh session's scores, and its pass by the same rule in code
if args.iter().any(|a| a == "--read") {
let by = "agent";
let v = crate::agent::ask(kind, &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()));
+8 -7
View File
@@ -2,8 +2,10 @@
//! 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 [--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 DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry]
//! raea judge eye DIR composition=6 form=5 ... [--pass yes|no] (or --read: the session's agent's reading as the eye)
//! Who judges is never asked: a fresh session of the project's own agent where its host offers one (agent.rs), else
//! clef-omni.
//! raea judge calibrate [--kind scene|kit|shot] [--json]
//!
//! `--kind` asks a `raea make` job's own rubric (docs/goal.feature MK5): a scene's, a kit's or a shot list's categories,
@@ -22,7 +24,6 @@ pub fn kind_gates(kind: &str) -> bool {
}
pub mod rubric;
pub use agent::BY;
use std::path::{Path, PathBuf};
@@ -30,7 +31,7 @@ use raea_core_facts::{Finding, Level, finding};
use raea_runtime_bundle::flag;
use serde_json::{Value, json};
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 scene, kit or shot goal'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)";
pub const USAGE: &str = "raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal'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> {
@@ -107,12 +108,12 @@ pub fn cli(args: &[String]) -> Result<String, String> {
let brief = brief_of(flag(args, "--brief").as_deref())?;
let target = flag(args, "--target").map(PathBuf::from);
let dry = args.iter().any(|a| a == "--dry");
let by = flag(args, "--by").unwrap_or_else(|| "clef".into());
let by = if agent::critic() { "agent".to_string() } else { "clef".into() };
if by != "clef" {
if dry {
return Ok(agent::prompt(kind, &dir, &brief, target.as_deref()));
}
let v = agent::ask(kind, &by, &dir, &brief, target.as_deref())?;
let v = agent::ask(kind, &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"]}));
}
@@ -190,7 +191,7 @@ fn finish(args: &[String], kind: Option<&str>, dir: &Path, scores: serde_json::M
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 model = if by == "clef" { "@cf/cloudflare/clef-omni".to_string() } else { "the project's agent".to_string() };
let found = findings(&defects, by, advice);
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)});
+3 -3
View File
@@ -70,10 +70,10 @@ fn an_agent_verdict_is_read_from_the_end_of_its_thinking() {
assert!(!pass && why[0].starts_with("blocking"));
assert!(crate::agent::last_verdict("no json here").is_none());
// what it saw, as Findings (DR3): a gating judge's blocking defect is an error, an advising one's a warn
let f = &crate::findings(&defects, "kimi", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (kimi)"));
let f = &crate::findings(&defects, "agent", false)[0];
assert_eq!((f.check.as_str(), f.level, f.fix.as_deref(), f.by.as_str()), ("judge.iso", raea_core_facts::Level::Error, Some("model legs"), "raea judge (agent)"));
assert!(f.says.starts_with("iso sheet: "), "{}", f.says);
assert_eq!(crate::findings(&defects, "kimi", true)[0].level, raea_core_facts::Level::Warn);
assert_eq!(crate::findings(&defects, "agent", true)[0].level, raea_core_facts::Level::Warn);
}
#[test]
+75 -19
View File
@@ -41,6 +41,14 @@ fn package_dir(game: &Path, home: &Path, name: &str, why: &str, add: &str) -> R<
.ok_or_else(|| format!("a playable {why} with {name}, which this project doesn't have: `raea add {add}` in it"))
}
/// runtime/ecs as wasm (sdk/playable/ecs/build.sh), base64
fn ecs_wasm(home: &Path) -> R<String> {
use base64::Engine;
let f = home.join("sdk/playable/src/host/ecs.wasm");
let b = std::fs::read(&f).map_err(|e| format!("{}: raea/ecs's world as wasm isn't there ({e}): bash sdk/playable/ecs/build.sh", f.display()))?;
Ok(base64::engine::general_purpose::STANDARD.encode(b))
}
/// What sound a game makes, as the lint found it: none, media only (<Audio>, generated sounds) or a raea/tone graph
#[derive(Clone, Copy, PartialEq, Debug)]
enum Sounds {
@@ -49,13 +57,26 @@ enum Sounds {
Tone,
}
/// The bundle's entry: the game, then the host started with three.js as its 3D drawer only for a game with 3D (PA15:
/// a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// What a page carries beside the game and the host, as the lint found the game needs it
#[derive(Clone, Copy, PartialEq, Debug)]
struct Carry {
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
with_3d: bool,
sounds: Sounds,
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
ecs: bool,
}
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// raea/tone graph (PA6)
fn entry(game: &Path, host: &Path, with_3d: bool, sounds: Sounds) -> String {
let mut e = format!("import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
let Carry { with_3d, sounds, ecs } = carry;
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
if with_3d {
e.push_str(&format!("import {{ three3d }} from {:?};\n", spec(&host.join("three.ts"))));
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
}
if sounds != Sounds::None {
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
@@ -63,9 +84,9 @@ fn entry(game: &Path, host: &Path, with_3d: bool, sounds: Sounds) -> String {
if sounds == Sounds::Tone {
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
}
let d3 = if with_3d { "three3d" } else { "undefined" };
let d3 = if with_3d { "bevy3d" } else { "undefined" };
e.push_str(&match sounds {
Sounds::None if with_3d => "start(three3d);\n".into(),
Sounds::None if with_3d => "start(bevy3d);\n".into(),
Sounds::None => "start();\n".into(),
Sounds::Media => format!("start({d3}, sound());\n"),
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
@@ -74,7 +95,8 @@ fn entry(game: &Path, host: &Path, with_3d: bool, sounds: Sounds) -> String {
}
/// The game and the host in one minified script that carries its files
fn bundle(game: &Path, home: &Path, with_3d: bool, sounds: Sounds) -> R<String> {
fn bundle(game: &Path, home: &Path, carry: Carry) -> R<String> {
let Carry { with_3d, sounds, .. } = carry;
let host = home.join("sdk/playable/src/host");
if !host.join("main.tsx").is_file() {
return Err(format!("{}: raea's playable host isn't there", host.display()));
@@ -88,7 +110,7 @@ fn bundle(game: &Path, home: &Path, with_3d: bool, sounds: Sounds) -> R<String>
flags.extend(["--alias".into(), format!("tone/={}", package_dir(game, home, "tone", "plays raea/tone", "[email protected]")?.display())]);
}
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, with_3d, sounds), &out, &flags);
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, carry), &out, &flags);
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
@@ -132,7 +154,9 @@ pub fn cli(args: &[String]) -> R<String> {
let is = |k: &str| found.sound[k].as_bool() == Some(true);
let sounds = if is("tone") { Sounds::Tone } else if is("media") { Sounds::Media } else { Sounds::None };
let js = bundle(&game, &raea_io_home::home(), !found.kinds.is_empty(), sounds)?;
let carry = Carry { with_3d: !found.kinds.is_empty(), sounds, ecs: found.ecs };
let home = raea_io_home::home();
let js = bundle(&game, &home, carry)?;
// its generated sounds, made (or found made) beside the game and carried in the page (PA6)
let assets = found.sound["assets"].as_array().cloned().unwrap_or_default();
let made = sound::make(&game, &assets)?;
@@ -140,7 +164,11 @@ pub fn cli(args: &[String]) -> R<String> {
Sounds::None => "sound: none".into(),
_ => format!("sound: {}{} generated ({} KB), played after the first touch", if sounds == Sounds::Tone { "a raea/tone graph, " } else { "" }, made.count, made.bytes / 1024),
});
let js = format!("{}{js}", made.script);
// Bevy's world, for a game on raea/ecs (PA12): the wasm the host loads before the game
let ecs = if found.ecs { ecs_wasm(&home)? } else { String::new() };
report.push(if found.ecs { format!("ecs: Bevy's world as wasm ({} KB)", ecs.len() * 3 / 4 / 1024) } else { "ecs: none".into() });
let ecs = if ecs.is_empty() { ecs } else { format!("globalThis.__raeaEcsWasm={ecs:?};") };
let js = format!("{ecs}{}{js}", made.script);
// the faces the native page draws with, for the families the game names (PA8)
let style = fonts::style(&js);
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
@@ -173,26 +201,54 @@ pub fn cli(args: &[String]) -> R<String> {
#[cfg(test)]
mod tests {
use super::{Sounds, entry};
use super::{Carry, Sounds, entry};
use std::path::Path;
fn e(with_3d: bool, sounds: Sounds, ecs: bool) -> String {
entry(Path::new("/g/game.tsx"), Path::new("/h/host"), Carry { with_3d, sounds, ecs })
}
#[test]
fn a_2d_game_starts_with_no_drawer() {
let e = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), false, Sounds::None);
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound"), "{e}");
let e = e(false, Sounds::None, false);
assert!(e.contains("start();") && !e.contains("three") && !e.contains("sound") && !e.contains("ecs"), "{e}");
}
#[test]
fn a_3d_game_starts_with_three() {
let e = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), true, Sounds::None);
assert!(e.contains("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{e}");
let e = e(true, Sounds::None, false);
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
}
#[test]
fn a_game_with_sound_starts_with_its_player_and_tone_only_for_a_graph() {
let media = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), false, Sounds::Media);
let media = e(false, Sounds::Media, false);
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
let tone = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), true, Sounds::Tone);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(three3d, sound(tone));"), "{tone}");
let tone = e(true, Sounds::Tone, false);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
}
#[test]
fn a_game_on_raea_ecs_loads_bevys_world_before_the_game() {
let e = e(false, Sounds::None, true);
assert!(e.starts_with("import \"/h/host/ecs.ts\";\nimport \"/g/game.tsx\";"), "{e}");
}
#[test]
fn the_carried_ecs_wasm_is_built_from_runtime_ecs_as_it_is() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/ecs/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
}
#[test]
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
}
}
+4 -2
View File
@@ -22,6 +22,8 @@ pub struct Found {
pub refusals: Vec<String>,
/// its sound (walk.ts): `tone` (a raea/tone graph), `media` (an <Audio>) and `assets` (each generated sound to make)
pub sound: Value,
/// whether it makes a raea/ecs World (walk.ts), whose page carries Bevy's world as wasm (PA12)
pub ecs: bool,
}
const SOURCE_RULES: &[(&str, &str)] = &[
@@ -50,7 +52,7 @@ pub fn lint(game: &Path) -> R<Found> {
let walked = match walk(game) {
Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null }),
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals, sound: Value::Null, ecs: false }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
@@ -75,7 +77,7 @@ pub fn lint(game: &Path) -> R<Found> {
for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
}
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone() })
Ok(Found { comps, kinds: strings("kinds"), notes, refusals, sound: walked["sound"].clone(), ecs: walked["ecs"].as_bool() == Some(true) })
}
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
+1 -1
View File
@@ -83,7 +83,7 @@ pub struct CutPlan {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "Beat")]
#[ts(rename = "CutBeat")]
pub struct Beat {
/// where it starts, in seconds from the cut's start (0 for the first)
pub at: f64,
+3 -3
View File
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String {
let cfg = Config::new();
// a cut's beats are a script's (script.rs Beat)
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
playable::Playable, playable::Orientation,
rules::Rule,
));
+14
View File
@@ -103,6 +103,20 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
And a worker that can't be reached fails the render unless RAEA_CLOUD_GPU_FALLBACK=cpu
And every other raea command runs on the box
Scenario: CL16. raea cloud's boxes are Fly Machines
Given the boxes were Sprites (deploy/sprites/), which ran at most 10 at once, read their disk in about 26 ms a
read and stopped at 8 cores and 16 GB (12-03)
Then each box is a Fly app of its own (raea-box-N for the box raea-N) with one Machine of deploy/fly/Dockerfile,
8 dedicated cores and 16 GB, and a volume for its home folder: the agents' sign-ins, ~/.raea-cloud.env, ~/work
And its work folder is /home/sprite/work as on a Sprite (the image links /home/sprite to /home/raea), so a moved
project's folders and paths are the same
And the server exits when the box has been idle RAEA_CLOUD_IDLE_STOP_MIN minutes (no request, connection,
process working in ~/work, or hold file touched lately: server/idle.ts), the Machine stays stopped, and Fly's
proxy starts it again at the next request
And deploy/fly/box.sh makes a box (up), moves a Sprite's (move: its token kept, its home sent from the Sprite
straight to the new box's file API), and puts every box on a release (latest)
And a file PUT to a box streams to disk and lands whole, never held in memory
Rule: it is proven end to end
Scenario: CL12. A stand-in agent, then a real one
Then test/smoke.sh builds the image, starts it, and checks CL4-CL7, CL14 and CL15 with test/echo-agent.mjs (a
+10 -4
View File
@@ -13,9 +13,12 @@ every project to import as `@shared/components/NAME`. `raea part` is the old nam
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
`components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
type (`text/reveal`), a name or the name it had upstream, the phrases people ask for it with (`"chat input"`,
`composer`, `"lower third"`, `template`), or words in what it does (`"count up"`). `show NAME` tells one in full: what
it draws and how it moves, when to use it and when not, the size and length it was designed at, and each prop with its
type, default and what it does; `--json` gives the same as JSON, for every hit of a `list`. `add NAME` copies the
component into `components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's
first line names the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
```sh
raea make component list
@@ -23,6 +26,8 @@ raea make component add captions end-card
raea make component add reel --shared
raea make component list text/reveal
raea make component list count up
raea make component list chat input
raea make component show prompt-send
raea make component add soft-blur-in
```
@@ -31,7 +36,7 @@ raea make component add soft-blur-in
## Usage
```sh
raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, "count up", "chat input", template; show tells one in full: what it draws, when to use it and when not, its props)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -41,6 +46,7 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| Flag | Takes | What it does |
| --- | --- | --- |
| `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. |
| `--json` | – | The library's items as JSON (`list`: every hit, best first; `show`: the one), each with its props, when to use it and when not, and the phrases it's asked for with. |
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
<!-- generated:end -->
+1 -2
View File
@@ -37,7 +37,7 @@ raea fingerprint things shot.mp4 --json > things.json
## Usage
```sh
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh session of the project's own agent read its pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -54,7 +54,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| `--axis` | `A` | The axis a label is for, by name, such as blur or clip |
| `--bad` | – | The moment has the problem the axis names (the default) |
| `--box` | `x0,y0,x1,y1` | Where in the frame the label is, as fractions of the width and height |
| `--by` | `kimi\|claude` | With read: which fresh session reads your notes, kimi (the default) or claude |
| `--extends` | `FP` | Another of your fingerprints to start from: the new one takes its axes and adds its own |
| `--fp` | `CHILD` | Which fingerprint to use, by name; without it, the default |
| `--from` | `LIST` | A file listing the renders to learn from, one path a line, relative to the file; lines starting with # are skipped |
+8 -7
View File
@@ -54,11 +54,13 @@ findings are then warnings.
A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds
unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's
"from A s to B s" window if it has one), else every video under out/, and reads no folder, so a rule about text it
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`.
work, judged by a fresh critic that may only read. `raea goal check` asks for the verdict itself when it's missing or
older than the work (`raea goal judge` asks now), and keeps it in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
newest file. Who judges is raea's to settle, never the agent's: a rule with a piece to watch or hear (the files it
names, in its "from A s to B s" window if it has one, else every video under out/) goes to clef-omni, as `raea ask`
reaches it; any other goes to a fresh session of the agent this project runs on, which the raea app or raea cloud
started (it offers the session's critic as `RAEA_JUDGE_URL`). Outside such a session a rule with nothing to watch
stays open and says why.
```ts
import { brief, rules } from "raea/brief"
@@ -98,7 +100,7 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
raea goal judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
```
@@ -111,7 +113,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| --- | --- | --- |
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--goal` | `NAME` | only this goal of the brief's (by its name) |
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
+7 -6
View File
@@ -6,8 +6,9 @@ sources: ["apps/judge/src/lib.rs", "apps/judge/src/rubric.rs", "apps/judge/src/a
---
`raea judge` reads the sheets [`raea render --review`](render.md) makes (`colour.png`, `clay.png`) and has them
judged without the code or the conversation that made them: by clef-omni on a frozen rubric (the default), or by a
fresh Kimi or Claude session on the judge prompt. The scores come back as data, and whether the scene passes is
judged without the code or the conversation that made them: by a fresh session of the agent this project runs on,
on the judge prompt, where the raea app or raea cloud started that agent; else by clef-omni on a frozen rubric. Who
judges is raea's to settle: there's no flag for it. The scores come back as data, and whether the scene passes is
decided 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 scene, kit or shot goal ([`raea goal`](goal.md)): a scene on layout,
@@ -21,8 +22,8 @@ own.
```sh
raea render scene.tsx --review review/
raea judge review/ --brief brief.ts
raea 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 rubric
raea judge review/ --target reference.png --json
raea judge review/r3 --kind kit --brief brief.ts # a kit job's round, on the kit rubric
raea judge eye review/ composition=4 light=3 --pass yes # record your own scores, for calibration
raea judge calibrate
```
@@ -32,7 +33,7 @@ raea judge calibrate
## Usage
```sh
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 scene, kit or shot goal'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)
raea judge DIR [--kind scene|kit|shot] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR [--read] [CATEGORY=SCORE ...] [--pass yes|no] | judge calibrate [--kind scene|kit|shot] [--json] (a --review folder's sheets judged blind: a fresh session of the project's own agent on the judge prompt where its host offers one, else clef-omni on the frozen rubric; --kind asks a scene, kit or shot goal'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.
@@ -42,11 +43,11 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| Flag | Takes | What it does |
| --- | --- | --- |
| `--brief` | `brief.ts` | The project's brief, so the judge knows what the scene is for. |
| `--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. |
| `--read` | – | With `judge eye`: a fresh session of the project's agent reads the round, recorded as its eye. |
| `--target` | `T.png` | A reference image the colour sheet is judged against. |
<!-- generated:end -->
+3 -2
View File
@@ -20,8 +20,9 @@ import the file instead), URLs and network calls, modules that need the native e
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
project (`raea add [email protected]`).
The 3D is drawn by Bevy's own PBR shaders, translated to WebGL2 when raea is built, with Bevy's light units,
shadows, fog and TonyMcMapface tone mapping. three.js reads the page's 3D parts into a scene for them, so it comes from
the project (`raea add [email protected]`). A game with no 3D ships without either.
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
+4 -1
View File
@@ -38,6 +38,7 @@ comment read as asks is a note: it closes when the person retires it, and the ap
raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?"
raea show out/cut.mp4 --replaces i-show-2f9c
raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler
raea show --choose "Warm grade" out/warm-1.png out/warm-2.png --choose "Cool grade" out/cool-1.png --recommend 2
raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \
--question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster
raea show --on i-show-2f9c --working c-3 --sub "grade pass"
@@ -51,7 +52,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {"kind":"answer","choice":LABEL}; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
@@ -63,6 +64,7 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). |
| `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. |
| `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. |
| `--choose` | `LABEL FILE...` | One option for the person to pick, named, its files after it; give it once per option, 2 to 6. Their pick comes back as `{"kind":"answer","choice":LABEL}`. |
| `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). |
| `--despite` | `CHECK WHY` | A check the render still fails, and why it goes to the person anyway; give it once per check. `raea show` refuses a render whose record still holds an error, naming each, and the why is shown on the item. |
| `--detail` | `PARAGRAPH` | The paragraph the viewer opens from the `--label` before it. |
@@ -76,6 +78,7 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. |
| `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. |
| `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. |
| `--recommend` | `N` | With `--choose`: the option you'd pick, from 1, marked on it. Nothing is picked for the person. |
| `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. |
| `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. |
| `--role` | `ROLE` | With `--as`: the role shown beside the name. |
+44 -4
View File
@@ -185,7 +185,7 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
the shading itself (the bricks' side faces a touch darker), PA11's job
@needs:PA9
@done @needs:PA9
Scenario: PA11. Bevy's own shading in the light renderer
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
export time, and the light renderer draws with them instead of three.js's own materials
@@ -204,11 +204,51 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
# Status 12-03: built. tools/bevy-glsl composes the three programs with Bevy's own ShaderCache (raea's vendored
# bevy_pbr, bevy_render and bevy_core_pipeline 0.20.0, WebGL2's defs, 10 directional lights, Gaussian shadow
# filtering, MSAA, distance fog, the projection's kind read from the view) and naga 30 translates them;
# sdk/playable/bevy/build.sh writes them into host/bevy/programs.ts (105 KB, 21 KB gzipped) with each block's field offsets and which of Bevy's bindings each
# block and sampler is, and apps/playable's test fails when Bevy's shaders or the translator change and it isn't
# rebuilt. host/bevy.ts replaces three.js's renderer (three.ts and tonemap.ts are gone): it reads raea's three.js
# scene graph (scene.ts) for the parts, geometry and transforms, and fills Bevy's blocks as Bevy's render world
# does (bevy/fill.ts: prepare_view_uniforms, prepare_lights, MeshUniform::new, StandardMaterial's uniform; the
# lights back in Bevy's units through units.ts): reverse Z, one 1x1x1 light cluster packed as Bevy packs it for
# WebGL2, one directional shadow cascade (as Bevy on WebGL2 has) fitted to what the camera sees of the scene,
# point and spot lights, distance fog (Bevy's GpuFog from the scene's Fog: linear from near to far, or
# exponential for a density, as the native engine makes it), a forward pass into half float with 4x MSAA, then
# TonyMcMapface through Bevy's table. A Plane3d is drawn as its one face (Bevy's PlaneMeshBuilder), not as the
# flat Box three.js was given, whose top face three points down. Not drawn yet, each warned once in the
# console: an environment's light, a camera's own <Fog> (Bevy's DistanceFog component), normal maps, transmission, vertex colours, point and
# spot shadows, rect lights, a shadow catcher, a paint look
# Measured on brick-rush against `raea render --frame` (mean difference over the drawn pixels / 255, both pages
# against the same native frames; landscape frame 300 rendered with --despite type-over-part): portrait frame 90
# three.js 6.1 -> Bevy 4.3 (PA10 recorded 5.4), landscape frame 300 9.8 -> 7.7, what is left in landscape mostly
# the page's pulsing hint text. star-catch portrait frame 150: 17.0 -> 15.6 over the frame, 6.7 -> 5.0 over the
# 3D above the hint text. A scene of a floor, six boxes, a ball, a sun with shadows, a point light and a spot
# light (frame 10): perspective portrait 1.3, orthographic landscape 0.8, with linear fog 0.7, with exponential
# fog 0.7. The page: brick-rush 1,889 -> 1,794 KB (three's renderer out, the programs in).
# First frame in a fresh WebKit (served from localhost, to the GPU finishing it, 25 interleaved runs): three.js
# median 131 ms, mean 129.8; Bevy median 131 ms, mean 131.8. The GL work is about 5 ms on both pages; the rest
# is script and the page. Chrome's 4x CPU throttle isn't used (raea doesn't test in Chrome); with every WebKit
# process clamped to the efficiency cores at background priority (taskpolicy -b), 142 and 145 ms over 11 runs.
# brick-rush and star-catch play to their end cards and store taps in WebKit (tools/check.ts) in portrait and
# landscape, with instant and 150 ms taps
@done
Scenario: PA12. Bevy systems in a playable
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
playable, its world drawn by the light renderer
And the status (12-03): runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh,
253 KB, 105 KB gzipped, no imports) into sdk/playable/src/host/ecs.wasm, with the hash of its sources beside it
(apps/playable's test fails when runtime/ecs changes and it isn't rebuilt). The lint's walk sees a World made;
the export carries the wasm and its entry loads host/ecs.ts before the game, so raea/ecs's calls (native.ts
ecsCall) reach Bevy's world in the page as they reach it in the engine. World.copy() is a game's next state, and
a store nothing holds frees its world. examples/playables/star-catch.tsx (spawn, aim and catch systems on a
World) exports at 1,824 KB, plays to its end card in WebKit in both orientations with instant and held taps
(7,724 calls answered), and its frame 150 holds the same stars, basket and score as `raea render --frame`
(shading 17.0/255 over the 3D pixels, 0.19% of the frame past 8%: PA11's). conformance/ecs-wasm.test.ts runs
one world's life on the wasm and on the TypeScript tables and finds them equal
@done
Scenario: PA13. `raea playable`
@@ -234,9 +274,9 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
Scenario: PA15. A 2D playable carries no three.js
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); three.ts draws it with
# three.js, and the export's entry passes it to start() only when the lint found a 3D kind, so a 2D game's
# bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); a drawer (three.ts then,
# Bevy's programs in bevy.ts since PA11) draws it, and the export's entry passes it to start() only when the lint
# found a 3D kind, so a 2D game's bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
# tiles 1,345 -> 378 KB, gates 1,347 -> 380 KB, three 2D brand playables 2,752 -> 1,782, 3,409 -> 2,440 and
# 2,693 -> 1,724 KB; brick-rush (3D, keeps three.js) 1,384 -> 1,478 KB. Each of the six played to its end card
# and its store tap in WebKit (tools/check.ts), with instant taps (TAP_MS=0) and 150 ms taps.
+36 -2
View File
@@ -1,9 +1,10 @@
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
// in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
// in it lands on a file of the library, nothing imports another video framework, the search finds by use and by the
// words people ask with, and each item carries what an agent picks by (tools/library-meta.sh writes it).
import { describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, normalize } from "node:path";
import { listed, type Item } from "../src/catalog";
import { listed, searched, shown, terms, type Item } from "../src/catalog";
const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
@@ -45,4 +46,37 @@ describe("the component library", () => {
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
});
test("each item says what it draws, when to use it and not, how it's asked for, and its props", () => {
const thin = cat.items.filter((i) => !i.what || !i.use_when?.length || !i.avoid_when?.length || !i.asked_as?.length || !Array.isArray(i.props) || !i.aspect);
expect(thin.map((i) => i.name)).toEqual([]);
// its props are the ones its file declares
const flash = cat.items.find((i) => i.name === "flash-count")!;
expect(flash.props!.find((p) => p.name === "value")).toMatchObject({ type: "number", default: "3600" });
});
test("its words name no other library or its tooling: the components are raea's", () => {
const named = cat.items.flatMap((i) => [i.what ?? "", ...(i.use_when ?? []), ...(i.avoid_when ?? [])].filter((s) => /\b(remotion|remocn|snapcn|snap-cn|shadcn)\b/i.test(s)).map((s) => `${i.name}: ${s}`));
expect(named).toEqual([]);
});
test("search by the words people use: a product's UI, a composer, a chat input, a template, an AI prompt", () => {
const top = (q: string, n = 3) => searched(cat.items, terms([q])).slice(0, n).map((i) => `${i.category}/${i.name}`);
expect(top("claude code").every((n) => /terminal|agent/.test(n))).toBe(true);
expect(top("composer")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
expect(top("chat input", 5)).toEqual(expect.arrayContaining(["ui/input", "ui/prompt-send"]));
expect(top("AI prompt").every((n) => n.startsWith("ui/prompt-"))).toBe(true);
expect(top("composer animations with claude")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
// the upstream name is a search alias: snapcn's terminal-simulator is ui/terminal-session here
expect(top("terminal simulator", 2).sort()).toEqual(["ui/terminal-session", "ui/terminal-simulator"]);
// "template" alone: the items that are one, and how to narrow it
expect(listed(cat.items, ["template"])).toContain("say what it shows to narrow it");
expect(listed(cat.items, ["cli"])).not.toContain("click-type");
});
test("show: one item in full, with its props and when to use it", () => {
const i = cat.items.find((i) => i.name === "prompt-send")!;
const s = shown(i);
for (const want of ["ui/prompt-send", "use it when:", "not when:", "props:", "text?: string", "raea make component add prompt-send", 'import { PromptSend } from "./components/ui/prompt-send"']) expect(s).toContain(want);
});
});
+1 -1
View File
@@ -15,7 +15,7 @@ pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE [\"what you see and would change\" --look \"its design at full size, beside a reference\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude)
raea goal judge [--goal NAME] (a goal's `says` rules judged now, as `raea goal check` judges them itself: a rule with a piece to watch or hear (a file it names, else the videos under out/) by clef-omni, any other by a fresh session of the agent this project runs on, which only reads; review/judge/NAME.json. Who judges is raea's to settle, never yours)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
+88 -24
View File
@@ -6,7 +6,15 @@
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { dirname, join } from "node:path";
export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
/** One of a component's props, read from its Props type: its type as written, its default, a line on what it does */
export type Prop = { name: string; type: string; default?: string; says?: string; required?: boolean };
/** An item; the fields after `from` are tools/library-meta.sh's: the upstream component it was matched to by content
* (a search alias, never its name here), what it draws and how it moves, when to use it and when not, the phrases
* people ask for it with, its props, and the length, frame rate, size, aspect and feel it was designed at */
export type Item = {
name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string;
upstream?: string; what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; props?: Prop[]; length?: number; fps?: number; size?: string; aspect?: string; vibe?: string;
};
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
export type Got = { item: Item; licence: string; files: Record<string, string> };
@@ -17,6 +25,9 @@ function home(raea: string, env: Record<string, string | undefined>): string | u
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
}
/** An item by its name, category/name or category/type/name */
export const found = (items: Item[], want: string) => items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
@@ -25,46 +36,99 @@ export function componentsHost(raea: string, env: Record<string, string | undefi
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
if (a.op !== "get") return cat.items;
const want = String(a.name).replace(/^\/+|\/+$/g, "");
const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
const item = found(cat.items, want);
if (!item) return null;
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
return { item, licence: cat.sources[item.from]?.licence ?? "", files };
}
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
// what a row says: the item's own line, or what it draws when that line is a few words
const line = (i: Item) => (i.says.length >= 40 || !i.what ? i.says : i.what).split(". ")[0];
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${line(i).slice(0, 110)}`;
// words that say nothing about which one ("a", "animation", "component") are skipped; "template", "effect" and
// "preset" narrow to the items that are one when they're all a search says, and only rank otherwise
const FILLER = new Set(["a", "an", "the", "with", "for", "of", "and", "in", "on", "to", "my", "our", "some", "please", "use", "using", "raea", "component", "components", "animation", "animations", "animated", "thing", "something", "from", "like", "one"]);
const SOFT = new Set(["template", "templates", "effect", "effects", "preset", "presets"]);
const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// a word at a word's start ("count" finds "counter"); a short one only whole ("cli" isn't "click", "ai" isn't "aim")
const finds = (w: string) => (w.length <= 3 ? new RegExp(`(^|[^a-z0-9])${esc(w)}(s|es)?($|[^a-z0-9])`, "i") : new RegExp(`(^|[^a-z0-9])${esc(w.replace(/s$/, ""))}`, "i"));
/** How well an item answers the words: 0 when a word that matters isn't anywhere in it. The name, the upstream name
* and the phrases people ask for it with count most; what it does and when to use it count once */
export function scored(i: Item, ws: string[]): number {
const asked = (i.asked_as ?? []).join(" | ");
const told = [i.says, i.what ?? "", ...(i.use_when ?? [])].join(" ");
const named = (n: string | undefined, w: string) => (!n ? 0 : n.split("-").includes(w) ? 3 : w.length > 3 && n.includes(w) ? 2 : 0);
const key = ws.filter((w) => !SOFT.has(w));
let s = 0;
// the words together, as written: a phrase people ask with, a name, or a sentence of what it does
const phrase = key.join(" ");
if (key.length > 1) s += (i.asked_as ?? []).some((a) => a.toLowerCase().includes(phrase)) ? 6 : [i.name, i.upstream ?? ""].includes(key.join("-")) ? 6 : told.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
const re = finds(w);
let got = 0;
if (w.includes("/")) got = i.category === c && (!t || i.type === t) ? 4 : 0;
else if (i.category === w || i.type === w) got = 4;
// its name (or upstream's), the phrases it's asked for with, and its own words each add
else got = Math.max(named(i.name, w), named(i.upstream, w)) + (re.test(asked) ? 3 : 0) + (re.test(told) || i.from === w ? 1 : 0);
if (!got && !SOFT.has(w)) return 0;
s += got;
}
return s;
}
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
* items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
* an item does; every word must be found, and a name's own words count first. */
* items they name. A word is a category ("text"), a category/type ("text/reveal"), a name or upstream name, or
* anything in the phrases people ask with, what it does or when to use it; every word that matters must be found */
export function listed(items: Item[], words: string[]): string {
if (!items.length) return "";
if (!words.length) {
const ws = terms(words);
if (!ws.length) {
const cats = [...new Set(items.map((i) => i.category))].sort();
const line = (c: string) => {
const of = items.filter((i) => i.category === c);
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
};
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "chat input", list "count up"; show NAME tells one in full; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
}
const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
const phrase = ws.join(" ");
const score = (i: Item) => {
// the words together, as written, in what it does: ahead of the same words scattered
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
else if (i.name.split("-").includes(w)) s += 3;
else if (i.name.includes(w)) s += 2;
else if (i.says.toLowerCase().includes(w)) s += 1;
else return 0;
}
return s;
};
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
const found = searched(items, ws);
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
return found.map(([, i]) => row(i)).join("\n") + "\n";
// "template" or "effect" alone: the items that are one, a page of them, and how to narrow it
if (ws.every((w) => SOFT.has(w))) {
const top = found.slice(0, 30);
return `${found.length} components are a ${ws[0].replace(/s$/, "")}; say what it shows to narrow it (list ${ws[0]} chat, list ${ws[0]} logo, list "${ws[0]} product demo"):\n${top.map(row).join("\n")}\n${found.length > top.length ? `... and ${found.length - top.length} more\n` : ""}`;
}
return found.map(row).join("\n") + "\n";
}
/** A search's words that matter, in lower case */
export const terms = (words: string[]) => words.join(" ").toLowerCase().split(/\s+/).filter((w) => w && !FILLER.has(w));
/** The items the words find, best first */
export function searched(items: Item[], ws: string[]): Item[] {
// equal scores: the one more of whose asked-for phrases the words are in is more about them
const res = ws.filter((w) => !w.includes("/")).map(finds);
const fit = (i: Item) => (i.asked_as ?? []).filter((a) => res.some((re) => re.test(a))).length;
return items
.map((i) => [scored(i, ws), fit(i), i] as const)
.filter(([s]) => s > 0)
.sort((a, b) => b[0] - a[0] || b[1] - a[1] || a[2].name.localeCompare(b[2].name))
.map(([, , i]) => i);
}
/** `raea make component show NAME`: everything an agent picks by, without opening the file */
export function shown(i: Item, from = "./components"): string {
const list = (head: string, xs?: string[]) => (xs?.length ? `${head}\n${xs.map((x) => ` - ${x}`).join("\n")}\n` : "");
const made = [i.size && `${i.size} (${i.aspect})`, !i.size && i.aspect, i.length && `${i.length} frames at ${i.fps ?? 30} fps`, i.vibe && `feels ${i.vibe}`].filter(Boolean).join(", ");
const props = (i.props ?? []).map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type}${p.default !== undefined ? ` = ${p.default}` : ""}${p.says ? `\n ${p.says}` : ""}`);
return `${i.category}/${i.name} (${i.type}; from ${i.from}${i.upstream ? `, ${i.upstream} there` : ""})
${i.what ?? i.says}
${list("use it when:", i.use_when)}${list("not when:", i.avoid_when)}${i.asked_as?.length ? `asked for as: ${i.asked_as.join("; ")}\n` : ""}${made ? `designed at: ${made}\n` : ""}${props.length ? `props:\n${props.join("\n")}\n` : "props: none (its words and colours are written in the file)\n"}add it: raea make component add ${i.name}
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}";
`;
}
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
+2 -2
View File
@@ -136,7 +136,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {{\"kind\":\"answer\",\"choice\":LABEL}}; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
let usage = format!("{usage}\n raea make clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder, and the first use of any step makes the Python environment the clothes run in there (by uv); no step needs Blender)");
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
@@ -149,7 +149,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, \"count up\", \"chat input\", template; show tells one in full: what it draws, when to use it and when not, its props)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
+13 -3
View File
@@ -28,7 +28,7 @@ import { absolute, fromCwd, labelsIn, showVerb } from "./show";
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
import { clothesVerb } from "./clothes";
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
import { added, listed, type Got, type Item } from "./catalog";
import { added, found, listed, searched, shown as inFull, terms, type Got, type Item } from "./catalog";
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
import { bugVerb } from "./bug";
@@ -199,8 +199,18 @@ export function raeaHandler(host?: Host, engine?: Engine) {
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
const ws = clean(args.slice(2));
// --json: the items found (each with its props, when to use it and when not) for an agent to pick from
if (args[1] === "list" && args.includes("--json")) return out(`${JSON.stringify(ws.length ? searched(shelf(), terms(ws)) : shelf(), null, 1)}\n`, 0, was);
if (args[1] === "list") return out(ws.length ? listed(shelf(), ws) : parts() + listed(shelf(), []), 0, was);
// show: one item in full, so it can be picked without opening its file
if (args[1] === "show") {
const item = ws[0] ? found(shelf(), ws[0]) : undefined;
if (!item) return out("", 1, `${was}raea make component show: no "${ws[0] ?? ""}" in the library (raea make component list WORDS finds one)\n`);
const at = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
return out(args.includes("--json") ? `${JSON.stringify(item, null, 1)}\n` : inFull(item, at), 0, was);
}
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] [--json] | show NAME [--json] | add NAME ... [--shared] [--force]\n`);
const names = clean(args.slice(2));
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
const force = args.includes("--force");
+29 -4
View File
@@ -32,6 +32,9 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
raea show FILE... --fyi
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png [--recommend 2] [--title T] [--ask TEXT]
The person picks one: 2 to 6 options, each named, its files after it. --recommend N marks the one you'd pick (from
1); nothing is picked for them. Their pick comes back as {"kind":"answer","choice":"Cool grade"}.
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
@@ -58,7 +61,7 @@ raea show FILE... --replaces ITEM --done ID...
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`;
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const WITH_VALUE = new Set(["--group", "--choose", "--recommend", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
@@ -118,6 +121,26 @@ export function parseShow(args: string[], cwd: string) {
});
const empty = groups.find((g) => !g.files.length);
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
// the options to choose from (raea-platform home.feature HM5): each --choose "Label" holds the files after it
const options: { label: string; files: string[]; recommended?: true }[] = [];
args.forEach((a, i) => {
if (a === "--choose" && args[i + 1] !== undefined) options.push({ label: args[i + 1].trim(), files: [] });
else if (a === "--group" && options.length) throw new Error(`--choose and --group don't mix: each option is its own group\n${SHOW_USAGE}`);
else if (options.length && isFile(a, i)) options.at(-1)!.files.push(abs(a));
});
if (options.length) {
if (options.length < 2 || options.length > 6) throw new Error(`--choose gives 2 to 6 options, each with its files\n${SHOW_USAGE}`);
const bare = options.find((o) => !o.label || !o.files.length);
if (bare) throw new Error(`the option "${bare.label}" ${bare.label ? "has no files: put its files after its --choose" : "needs a name"}\n${SHOW_USAGE}`);
if (files.length !== options.flatMap((o) => o.files).length) throw new Error(`with --choose, every file goes after the option it's in\n${SHOW_USAGE}`);
if (args.includes("--question") || args.includes("--fyi")) throw new Error(`--choose is its own question: no --question or --fyi with it\n${SHOW_USAGE}`);
}
const recommend = one("--recommend");
if (recommend !== undefined) {
const n = Number(recommend);
if (!options.length || !Number.isInteger(n) || n < 1 || n > options.length) throw new Error(`--recommend N names one of the --choose options, from 1${options.length ? ` to ${options.length}` : ""}\n${SHOW_USAGE}`);
options[n - 1].recommended = true;
}
const despite = args.flatMap((a, i) => {
if (a !== "--despite") return [];
const [check, why] = [args[i + 1], args[i + 2]];
@@ -157,7 +180,7 @@ export function parseShow(args: string[], cwd: string) {
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
return { groups, options, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
}
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
@@ -218,7 +241,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : a.options.length ? { intent: "choose", options: a.options } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
@@ -242,7 +265,9 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
...settled,
a.fyi
a.options.length
? `They pick one of ${a.options.length}: {"kind":"answer","choice":"<the option's name>"} comes to ${inbox}. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and carry on with their pick.`
: a.fyi
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
"",
+143
View File
@@ -0,0 +1,143 @@
// A playable whose rules are raea/ecs systems (docs/playables.feature PA12): stars fall, a basket catches them, and
// every rule (where a star starts, how it falls, what the basket catches, the score) runs on a World. Natively the
// World's tables are Bevy's, in raea's engine; in the playable they're Bevy's too, carried in the page as wasm, so the
// game plays the same in both. Each frame's state is the World copied and stepped once, with where the person points
// written into it as a resource. Rendered with `raea render`, no one touches it: the basket follows the lowest star.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { createWorld, type World } from "raea/ecs";
import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable";
const FPS = 30;
const W = 6, TOP = 8; // field: x in [-W/2, W/2], y from 0 (the basket) to TOP
const FOV = 0.733; // radians, vertical
const GOAL = 10, MISSES = 3;
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
/** The game's rules: a World with a basket, the score and misses as resources, and its systems */
function rules(): World {
const w = createWorld();
w.spawn("basket", { x: 0 });
for (const r of ["score", "missed"]) w.resource(r, 0);
for (const r of ["caught", "lost"]) w.resource(r, -99);
// a star every 20 frames, where the frame number puts it
w.system((world, f) => {
if (f % 20 === 0) world.spawn("star", { x: (((f * 7919) % 97) / 97 - 0.5) * (W - 1), y: TOP, v: 0.05 + ((f * 31) % 7) * 0.006 });
});
// the basket eases toward where the person points, or toward the lowest star before they touch
w.system((world) => {
const [b] = world.query("basket");
const x = world.get(b).x as number;
let want = world.resource<number>("aim");
if (typeof want !== "number") {
const low = world.query("star").map((id) => world.get(id)).sort((a, c) => (a.y as number) - (c.y as number))[0];
want = low ? (low.x as number) : 0;
}
world.set(b, { x: clamp(x + clamp(want - x, -0.3, 0.3), -W / 2 + 0.8, W / 2 - 0.8) });
});
// each star falls; the basket catches one at its height, and one past it is missed
w.system((world, f) => {
const bx = world.get(world.query("basket")[0]).x as number;
for (const id of world.query("star")) {
const s = world.get(id);
const y = (s.y as number) - (s.v as number);
if (y < 0.35 && y > -0.15 && Math.abs((s.x as number) - bx) < 0.85) {
world.despawn(id);
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
world.resource("caught", f);
} else if (y < -1) {
world.despawn(id);
world.resource("missed", (world.resource<number>("missed") ?? 0) + 1);
world.resource("lost", f);
} else world.set(id, { y });
}
});
return w;
}
interface Game { w: World; touched: boolean; over: "" | "won" | "lost" }
/** The camera's distance that fits the whole field on a screen of this aspect */
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
/** A pointer's x on screen, in field units at the basket's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
const p = input.touches?.[0] ?? input.pointer;
if (!p) return undefined;
const halfH = Math.tan(FOV / 2) * distance(width / height);
return ((p.x / width) * 2 - 1) * halfH * (width / height);
}
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
if (s.over) return s;
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
const w = s.w.copy();
const x = touched ? fieldX(input, width, height) : undefined;
if (x !== undefined) w.resource("aim", x);
w.step(frame);
const over = (w.resource<number>("score") ?? 0) >= GOAL ? "won" : (w.resource<number>("missed") ?? 0) >= MISSES ? "lost" : "";
return { w, touched, over };
};
const steps = new Map<string, ReturnType<typeof stepFor>>();
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
let first: Game | null = null;
function StarCatch() {
const { width, height } = useVideoConfig();
first ??= { w: rules(), touched: false, over: "" };
const g = useGameState(first, stepOf(width, height));
const now = useCurrentFrame();
const bx = g.w.get(g.w.query("basket")[0]).x as number;
const score = g.w.resource<number>("score") ?? 0;
const missed = g.w.resource<number>("missed") ?? 0;
const pop = Math.max(0, 1 - (now - (g.w.resource<number>("caught") ?? -99)) / 8);
const flash = Math.max(0, 1 - (now - (g.w.resource<number>("lost") ?? -99)) / 12);
const d = distance(width / height);
const s = width / 1080;
return (
<AbsoluteFill style={{ background: `rgb(${12 + 80 * flash}, 16, ${40 + 20 * pop})` }}>
<Camera3d transform={Transform.fromXyz(0, TOP / 2, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
<AmbientLight brightness={200} />
<DirectionalLight transform={Transform.fromXyz(2, 10, 6).lookingAt([0, 0, 0])} illuminance={9000} />
<Mesh3d transform={Transform.fromXyz(bx, 0, 0).withScale([1 + 0.2 * pop, 1 - 0.3 * pop, 1])} name="basket">
<Cuboid half_size={[0.8, 0.15, 0.3]} />
<StandardMaterial base_color="#2ec4b6" perceptual_roughness={0.45} />
</Mesh3d>
{g.w.query("star").map((id) => {
const st = g.w.get(id);
return (
<Mesh3d key={id} transform={Transform.fromXyz(st.x as number, st.y as number, 0)} name={`star-${id}`}>
<Sphere radius={0.22} />
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.7)} />
</Mesh3d>
);
})}
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
{`★ ${score} / ${GOAL}`}
</div>
<div style={{ position: "absolute", right: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#ef476f" }}>
{"✕".repeat(missed)}
</div>
{!g.touched ? (
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
{"👆 Drag to catch"}
</div>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Ten stars!" : "So close!"} subtitle={g.over === "won" ? "The night sky is waiting" : "Can you catch ten?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill>
);
}
registerRoot(() => (
<>
<Composition id="star-catch-portrait" component={StarCatch} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 40} />
<Composition id="star-catch-landscape" component={StarCatch} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 40} />
</>
));
+28
View File
@@ -0,0 +1,28 @@
//! The critic a project's rules are judged by when the judgement needs reading rather than watching (Shane, 12-03:
//! never a harness raea picks or the agent names): a fresh session of the agent this project runs on, which the host
//! that started the agent (raea cloud's box, sdk/cloud/server/critic.ts; the raea app) offers as RAEA_JUDGE_URL, with
//! the session's RAEA_JUDGE_TOKEN. `raea judge`, `raea fingerprint read` and `raea goal judge` (sdk/goal) ask it.
use serde_json::{Value, json};
/// What a person reads when there's no critic here: no tool, agent or model named, because none is theirs to pick.
pub const NONE_HERE: &str = "an agent's reading is a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has";
/// Whether this session has a critic to ask.
pub fn here() -> bool {
std::env::var("RAEA_JUDGE_URL").is_ok_and(|u| !u.is_empty())
}
/// One question to a fresh session of this project's agent, in `cwd`: what it says back.
pub fn ask(cwd: &std::path::Path, prompt: &str) -> Result<String, String> {
let url = std::env::var("RAEA_JUDGE_URL").ok().filter(|u| !u.is_empty()).ok_or(NONE_HERE)?;
let token = std::env::var("RAEA_JUDGE_TOKEN").unwrap_or_default();
let r = ureq::post(&url).set("authorization", &format!("Bearer {token}")).timeout(std::time::Duration::from_secs(15 * 60))
.send_json(json!({"cwd": cwd.display().to_string(), "prompt": prompt}));
let body: Value = match r {
Ok(r) => r.into_json().map_err(|e| format!("the critic's answer: {e}"))?,
Err(ureq::Error::Status(_, r)) => return Err(format!("the critic couldn't: {}", r.into_json::<Value>().ok().and_then(|v| v["error"].as_str().map(String::from)).unwrap_or_default())),
Err(e) => return Err(format!("the critic: {e}")),
};
body["text"].as_str().map(String::from).ok_or_else(|| "the critic gave no text".into())
}
+1
View File
@@ -4,6 +4,7 @@
pub mod cache;
pub mod client;
pub mod critic;
pub mod media;
pub mod route;
+3
View File
@@ -20,6 +20,9 @@ use serde_json::{Map, Value, json};
type R<T> = Result<T, String>;
#[cfg(target_arch = "wasm32")]
mod wasm;
/// One world: Bevy's, plus our ids, the component names, resources and this frame's events.
struct BWorld {
w: World,
+63
View File
@@ -0,0 +1,63 @@
//! The ecs.* calls as a wasm module (docs/playables.feature PA12): a playable carries Bevy's own world, so a game on
//! raea/ecs keeps the tables, queries and parent/child it has natively. sdk/playable/ecs/build.sh builds it as a
//! cdylib for wasm32-unknown-unknown; the page's host/ecs.ts calls `raea_call` the way raea's V8 calls `__raea_call`.
//! Strings cross as UTF-8 in memory the page asks for with `raea_alloc`; the answer is `o` and the value's JSON, or
//! `e` and the message, where `raea_call` returns (its address in the high 32 bits, its length in the low), until the
//! next call.
use std::cell::RefCell;
thread_local! {
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
/// `len` bytes the page writes a call's name or arguments into, freed by `raea_free`
#[unsafe(no_mangle)]
pub extern "C" fn raea_alloc(len: usize) -> *mut u8 {
let mut v = Vec::<u8>::with_capacity(len.max(1));
let p = v.as_mut_ptr();
std::mem::forget(v);
p
}
/// # Safety
/// `p` came from `raea_alloc(len)` and isn't used after
#[unsafe(no_mangle)]
pub unsafe extern "C" fn raea_free(p: *mut u8, len: usize) {
// SAFETY: raea_alloc made it with this capacity
drop(unsafe { Vec::from_raw_parts(p, 0, len.max(1)) });
}
/// # Safety
/// each pointer holds that many bytes of UTF-8 the page wrote (raea_alloc's)
#[unsafe(no_mangle)]
pub unsafe extern "C" fn raea_call(
name: *const u8,
name_len: usize,
args: *const u8,
args_len: usize,
) -> u64 {
// SAFETY: the page wrote these bytes where raea_alloc said
let (name, args) = unsafe {
(
std::slice::from_raw_parts(name, name_len),
std::slice::from_raw_parts(args, args_len),
)
};
let answer = match (
std::str::from_utf8(name),
serde_json::from_slice::<serde_json::Value>(args),
) {
(Ok(n), Ok(a)) => super::call(n, &a).map(|v| v.to_string()),
_ => Err("a call's name and arguments are UTF-8 JSON".into()),
};
OUT.with(|o| {
let mut o = o.borrow_mut();
*o = match answer {
Ok(v) => format!("o{v}"),
Err(e) => format!("e{e}"),
}
.into_bytes();
((o.as_ptr() as u64) << 32) | o.len() as u64
})
}
+43 -28
View File
@@ -4,7 +4,7 @@
// same whenever it's asked for (a frame of a video is a function of the frame, as rrl's `next:` rules make it). Under
// plain bun the tables are TypeScript's own, with the same behaviour, so tests run anywhere.
import { hasNative, native } from "./native";
import { ecsCall, hasEcs } from "./native";
export type Value = number | string | boolean;
export type Cols = Record<string, Value>;
@@ -52,76 +52,83 @@ interface Store {
free(): void;
}
/** A store's tables freed when nothing holds it any more: a game's kept states are let go (games.ts KEEP), and the
* engine's (or a playable's wasm) worlds aren't collected with them. Freeing one twice is harmless. */
const unheld = typeof FinalizationRegistry === "function" ? new FinalizationRegistry<number>((world) => ecsCall("ecs.free", { world })) : null;
class NativeStore implements Store {
constructor(readonly world: number) {}
constructor(readonly world: number) {
unheld?.register(this, world, this);
}
static create(): NativeStore {
return new NativeStore(native("ecs.new", {}).world);
return new NativeStore(ecsCall("ecs.new", {}).world);
}
spawn(kind: string, cols: Cols) {
return native("ecs.spawn", { world: this.world, kind, cols }).id;
return ecsCall("ecs.spawn", { world: this.world, kind, cols }).id;
}
spawnComponents(components: Components, parent?: number) {
return native("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
return ecsCall("ecs.spawn", parent === undefined ? { world: this.world, components } : { world: this.world, components, parent }).id;
}
insert(id: number, components: Components) {
native("ecs.insert", { world: this.world, id, components });
ecsCall("ecs.insert", { world: this.world, id, components });
}
remove(id: number, names: string[]) {
native("ecs.remove", { world: this.world, id, names });
ecsCall("ecs.remove", { world: this.world, id, names });
}
components(id: number) {
return native("ecs.components", { world: this.world, id }) as Components;
return ecsCall("ecs.components", { world: this.world, id }) as Components;
}
find(f: Find) {
return native("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
return ecsCall("ecs.find", { world: this.world, with: f.with ?? [], without: f.without ?? [], where: f.where ?? [] }).ids;
}
setParent(id: number, parent: number | null) {
native("ecs.parent", { world: this.world, id, parent });
ecsCall("ecs.parent", { world: this.world, id, parent });
}
parent(id: number) {
return native("ecs.parent", { world: this.world, id }) as number | null;
return ecsCall("ecs.parent", { world: this.world, id }) as number | null;
}
children(id: number) {
return native("ecs.children", { world: this.world, id });
return ecsCall("ecs.children", { world: this.world, id });
}
resource(name: string, value?: unknown) {
return native("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
return ecsCall("ecs.resource", value === undefined ? { world: this.world, name } : { world: this.world, name, value });
}
send(name: string, value: unknown) {
native("ecs.send", { world: this.world, name, value });
ecsCall("ecs.send", { world: this.world, name, value });
}
events(name: string) {
return native("ecs.events", { world: this.world, name });
return ecsCall("ecs.events", { world: this.world, name });
}
clearEvents() {
native("ecs.clear_events", { world: this.world });
ecsCall("ecs.clear_events", { world: this.world });
}
set(id: number, cols: Cols) {
native("ecs.set", { world: this.world, id, cols });
ecsCall("ecs.set", { world: this.world, id, cols });
}
get(id: number) {
return native("ecs.get", { world: this.world, id });
return ecsCall("ecs.get", { world: this.world, id });
}
despawn(id: number) {
native("ecs.despawn", { world: this.world, id });
ecsCall("ecs.despawn", { world: this.world, id });
}
query(kind: string, where: Where) {
return native("ecs.query", { world: this.world, kind, where }).ids;
return ecsCall("ecs.query", { world: this.world, kind, where }).ids;
}
column(kind: string, col: string) {
return native("ecs.column", { world: this.world, kind, col });
return ecsCall("ecs.column", { world: this.world, kind, col });
}
count(kind: string) {
return native("ecs.count", { world: this.world, kind });
return ecsCall("ecs.count", { world: this.world, kind });
}
rows() {
return native("ecs.rows", { world: this.world });
return ecsCall("ecs.rows", { world: this.world });
}
clone() {
return new NativeStore(native("ecs.clone", { world: this.world }).world);
return new NativeStore(ecsCall("ecs.clone", { world: this.world }).world);
}
free() {
native("ecs.free", { world: this.world });
unheld?.unregister(this);
ecsCall("ecs.free", { world: this.world });
}
}
@@ -276,7 +283,9 @@ export class World {
/** A world on `store`: the engine's tables when it has them, else TypeScript's (createWorld picks for you). */
constructor(store?: Store) {
this.native = store ? store instanceof NativeStore : hasNative();
this.native = store ? store instanceof NativeStore : hasEcs();
// a playable's export reads this to carry Bevy's world (sdk/playable export/walk.ts, PA12)
(globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed = true;
this.store = store ?? (this.native ? NativeStore.create() : new JsStore());
}
@@ -367,7 +376,7 @@ export class World {
* hands this to the renderer). From the engine's tables natively; from the world's own store in a browser (raea-web),
* the same list as runtime/calls ecs.scene makes. */
scene(): unknown[] {
if (this.store instanceof NativeStore) return native("ecs.scene", { world: this.store.world });
if (this.store instanceof NativeStore) return ecsCall("ecs.scene", { world: this.store.world });
const store = this.store;
const out: unknown[] = [];
for (const id of store.find({ with: ["Mesh"] })) {
@@ -394,6 +403,12 @@ export class World {
this.store.clearEvents();
for (const s of this.systems) s(this, frame);
}
/** A copy of the world as it is now, with its systems: a game's next state (`useGameState`), stepped on its own. */
copy(): World {
const w = new World(this.store.clone());
w.systems = this.systems;
return w;
}
/** The world after frames 0..frame-1 have run (a copy; this world as built is the state before frame 0). */
at(frame: number): World {
if (!Number.isInteger(frame) || frame < 0) throw new RangeError(`World.at: a frame number from 0, got ${frame}`);
@@ -442,7 +457,7 @@ function compose(p: number[], c: number[]): number[] {
export function createWorld(opts: { native?: boolean } = {}): World {
if (opts.native === false) return new World(new JsStore());
if (opts.native === true && !hasNative()) throw new Error("createWorld({ native: true }) needs the raea engine");
if (opts.native === true && !hasEcs()) throw new Error("createWorld({ native: true }) needs the raea engine");
return new World();
}
+17 -1
View File
@@ -20,12 +20,28 @@ export function hasNative(): boolean {
/** One native call; its answer parsed. Throws (with the engine's message) when the call fails. */
export function native<K extends NativeName>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
const call = bridge();
return through(bridge(), name, args);
}
function through<K extends NativeName>(call: NativeCall | null, name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
if (!call) throw new Error(`${name} needs the raea engine (raea render or run); it isn't available under plain bun`);
const out = call(name, JSON.stringify(args));
return (out === undefined || out === "" ? undefined : JSON.parse(out)) as NativeCalls[K]["answer"];
}
/** raea/ecs's calls: the engine's, else a playable's (Bevy's world as wasm, sdk/playable host/ecs.ts, PA12) */
function ecsBridge(): NativeCall | null {
return bridge() ?? (globalThis as { __raeaEcs?: NativeCall }).__raeaEcs ?? null;
}
/** Whether raea/ecs's calls are here: in the engine, or in a playable that carries Bevy's world. */
export function hasEcs(): boolean {
return ecsBridge() !== null;
}
/** One of raea/ecs's calls (an `ecs.*` name), wherever its world is. */
export function ecsCall<K extends NativeName & `ecs.${string}`>(name: K, args: NativeCalls[K]["args"]): NativeCalls[K]["answer"] {
return through(ecsBridge(), name, args);
}
/** Print a line from a headless run (raea run). */
export function print(...parts: unknown[]): void {
const text = parts.map((p) => (typeof p === "string" ? p : JSON.stringify(p))).join(" ");
+3
View File
@@ -2,3 +2,6 @@ node_modules
deploy
test
README.md
# a box image (deploy/fly/Dockerfile) takes these two from deploy/
!deploy/git
!deploy/fly/start.sh
+71
View File
@@ -0,0 +1,71 @@
# A raea cloud box as a Fly Machine (12-03: the boxes moved off Sprites, which ran at most 10 at once, read their disk
# in about 26 ms a read, and stopped at 8 cores and 16 GB). What deploy/sprites/setup.sh put on a Sprite is built in
# here once: Ubuntu as the Sprites ran it, raea's Linux release, Node, Chrome for the Google sign-in, ffmpeg, the PDF
# tools and brand faces, the ACP agents and sdk/cloud's server. The home folder (/home/raea: the agents' sign-ins,
# ~/.raea-cloud.env, ~/work) is the Machine's volume, so a new image changes the programs and keeps everything else.
# deploy/fly/box.sh builds it from sdk/cloud:
#
# fly deploy --build-only --push -c deploy/fly/image.toml --build-arg RAEA_VERSION=0.1.17-rc3 ...
FROM ubuntu:26.04
ENV DEBIAN_FRONTEND=noninteractive
# what setup.sh installed: raea's runtime libraries and Mesa's lavapipe (the box draws previews on its CPU; its renders
# go to the farm), ffmpeg and the PDF tools (12-02: every agent installed them itself at each project's start), Python
# (the footage prep's transcript file), the sign-in browser's display, and sudo for an agent that needs a package
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
&& apt-get install -y -qq /tmp/chrome.deb > /dev/null && rm -f /tmp/chrome.deb \
&& rm -rf /var/lib/apt/lists/*
ARG NODE=24.22.0
RUN curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | tar -xJ -C /opt \
&& ln -sf /opt/node-v$NODE-linux-x64/bin/node /opt/node-v$NODE-linux-x64/bin/npm /opt/node-v$NODE-linux-x64/bin/npx /usr/local/bin/
# the box's user, uid 1000 as the image's entrypoint expects; /home/sprite is the same folder, so the paths a project
# moved from a Sprite wrote down (its agents' transcripts, its settings) still open
RUN (userdel -r ubuntu 2> /dev/null || true) && useradd -m -u 1000 -s /bin/bash raea \
&& echo 'raea ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/raea && chmod 440 /etc/sudoers.d/raea \
&& ln -s /home/raea /home/sprite
# raea, checked against its release's .sha256
ARG RAEA_VERSION
ARG RAEA_REPO=shinyobjectz/raea
RUN set -e; : "${RAEA_VERSION:?--build-arg RAEA_VERSION}"; f=raea-$RAEA_VERSION-linux-x86_64.tar.gz; \
u=https://github.com/$RAEA_REPO/releases/download/v$RAEA_VERSION; \
cd /tmp && curl -fsSL -o $f "$u/$f" && curl -fsSL -o $f.sha256 "$u/$f.sha256" && sha256sum -c --quiet $f.sha256 \
&& mkdir -p /opt/raea && tar -xzf $f -C /opt/raea --strip-components=1 && rm -f $f $f.sha256 \
&& /opt/raea/bin/raea --version
WORKDIR /opt/raea-cloud
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-fund --no-audit --loglevel=error
# the agents, by ACP registry id, with the server they're started by (agents.ts reads its neighbours)
COPY server server
ARG AGENTS="antigravity-acp claude-acp kimi-code"
RUN node server/agents.ts install $AGENTS
COPY src src
COPY image image
COPY deploy/git deploy/git
COPY deploy/fly/start.sh image/fly-start.sh
# readable by raea whatever modes the files had where the image was built (12-03: a checkout made with umask 077 gave
# the entrypoint 711, and it re-runs itself as raea)
RUN chmod -R a+rX /opt/raea-cloud && chmod +x image/*.sh deploy/git/* \
&& ln -sf /opt/raea-cloud/image/raea.sh /usr/local/bin/raea \
&& ln -sf /opt/raea-cloud/deploy/git/repo.sh /usr/local/bin/raea-repo \
&& git lfs install --system --skip-repo > /dev/null
# the build, shown on GET /v1/health and raea cloud's /v1/admin/boxes, so which code a box runs is never a guess
ARG COMMIT=unknown
ARG DIRTY=false
RUN printf '{"commit":"%s","build":"%.12s","dirty":%s,"raea":"%s","image":"fly","built_at":"%s"}\n' \
"$COMMIT" "$COMMIT" "$DIRTY" "$RAEA_VERSION" "$(date -u +%Y-%m-%dT%H:%M:%S+00:00)" > /opt/raea-cloud/BUILD.json
# RAEA_CLOUD_IDLE_STOP_MIN: the server exits when the box has been idle this long, and the Machine stops (idle.ts)
ENV HOME=/home/raea NODE_ENV=production PORT=8080 WGPU_BACKEND=vulkan RAEA_CLOUD_DEVICE=cpu RAEA_CLOUD_IDLE_STOP_MIN=10
EXPOSE 8080
ENTRYPOINT ["/opt/raea-cloud/image/fly-start.sh"]
+234
View File
@@ -0,0 +1,234 @@
#!/bin/bash
# raea cloud's agent boxes as Fly Machines (12-03; they were Sprites, deploy/sprites/, which ran at most 10 at once and
# read their disk in about 26 ms a read). Each box is a Fly app of its own (raea-box-2 is the box raea-2) with one
# Machine of the box image (Dockerfile here) and one volume for its home folder: the agents' sign-ins, the box's
# settings (~/.raea-cloud.env) and ~/work. The Machine stops itself when the box is idle (server/idle.ts) and Fly's
# proxy starts it at the next request, so it bills while it works. From sdk/cloud:
#
# deploy/fly/box.sh image [VERSION] the box image built and pushed: raea VERSION's Linux release (the newest when
# none is named) and sdk/cloud's server from this tree (RAEA_CLOUD_REF: from
# raea's repo at that commit). Prints the image, kept in ~/.config/raea-cloud/fly-image
# deploy/fly/box.sh up NAME the box made or brought onto the last image built: its app, addresses, volume,
# settings and Machine, then its health
# deploy/fly/box.sh move NAME a Sprite box onto Fly: its settings (its token too, so raea cloud's list only
# changes address) and its home folder copied, then listed in raea cloud
# deploy/fly/box.sh register NAME the box into raea cloud's list at its Fly address (POST /v1/admin/boxes)
# deploy/fly/box.sh status NAME its address, Machine and health
# deploy/fly/box.sh token NAME its RAEA_CLOUD_TOKEN
# deploy/fly/box.sh list raea cloud's boxes in order, each one's health and build
# deploy/fly/box.sh latest [VERSION] the image built for a release and every Fly box in raea cloud's list put on it
# deploy/fly/box.sh key NAME a raea agent key (raea_ak_...) from stdin, or the clipboard, onto the box
# deploy/fly/box.sh sh NAME [CMD] a shell on the box (as root), or CMD there
#
# The org is raea's, written once in ~/.config/raea-cloud/fly.env (RAEA_FLY_ORG=raea), never another business's. Each
# box's settings are kept on this Mac too, in ~/.config/raea-cloud/boxes/NAME.env (mode 600), and go to the box as Fly
# secrets; the farm's come from ~/.config/raea-cloud/farm.env.
set -euo pipefail
REPO=shinyobjectz/raea
HERE=$(cd "$(dirname "$0")/../.." && pwd)
CONF=$HOME/.config/raea-cloud
FLY_CONF=${RAEA_FLY_ENV:-$CONF/fly.env}
ORG=$([ -f "$FLY_CONF" ] && sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1 || true)
[ -n "$ORG" ] || { echo "fly box: write RAEA_FLY_ORG=<the Fly org raea owns> in $FLY_CONF (fly orgs list)"; exit 2; }
# Content Jet's org and any other business's: never (private/cloud/sprites-denied.txt lists them for Sprites too)
DENIED=$(git -C "$HERE" rev-parse --show-toplevel 2> /dev/null)/private/cloud/sprites-denied.txt
if { [ -f "$DENIED" ] && grep -qxF "$ORG" "$DENIED"; } || [ "$ORG" = kamal-hafid ]; then
echo "fly box: $ORG belongs to another business; raea's boxes go in an org raea owns"; exit 2
fi
REGION=${RAEA_FLY_REGION:-iad}
SIZE=${RAEA_BOX_SIZE:-performance-8x}
VOLUME_GB=${RAEA_BOX_DISK_GB:-100}
IMAGE_APP=raea-box-image
FARM=${RAEA_FARM_ENV:-$CONF/farm.env}
newest() { gh release view -R "$REPO" --json tagName -q .tagName 2> /dev/null | sed 's/^v//'; }
NAME=${2:-}
app() { echo "raea-box-${1#raea-}"; }
url() { echo "https://$(app "$1").fly.dev"; }
envfile() { echo "$CONF/boxes/$1.env"; }
need_name() { [ -n "$NAME" ] || { echo "fly box: name the box (raea-2)"; exit 2; }; }
# whether the org has an app by this name (fly apps list --json: its table draws borders round each name)
has_app() { fly apps list --org "$ORG" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(a.get("Name") == sys.argv[1] for a in json.load(sys.stdin)) else 1)' "$1"; }
machine() { fly machines list -a "$(app "$1")" --json 2> /dev/null | python3 -c 'import json,sys
m=[x for x in json.load(sys.stdin) if x.get("state")!="destroyed"]
print(m[0]["id"] if m else "")'; }
healthy() {
local u t
u=$(url "$1") t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$1")")
for _ in $(seq 1 60); do
curl -fsS -m 20 -H "authorization: Bearer $t" "$u/v1/health" 2> /dev/null && return 0
sleep 5
done
return 1
}
case "${1:-}" in
image)
version=${2:-${RAEA_VERSION:-$(newest)}}
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
src=$HERE
if [ -n "${RAEA_CLOUD_REF:-}" ]; then
# sdk/cloud at that commit of raea's repo, as a release's boxes take it
src=$(mktemp -d)
git -C "$src" init -q && git -C "$src" sparse-checkout set sdk/cloud
git -C "$src" fetch -q --depth 1 --filter=blob:none "https://github.com/$REPO" "$RAEA_CLOUD_REF" && git -C "$src" checkout -q FETCH_HEAD
src=$src/sdk/cloud
commit=$RAEA_CLOUD_REF dirty=false
else
commit=$(git -C "$HERE" rev-parse HEAD)
dirty=$([ -n "$(git -C "$HERE" status --porcelain -- .)" ] && echo true || echo false)
fi
has_app "$IMAGE_APP" || fly apps create "$IMAGE_APP" --org "$ORG" > /dev/null
# (|| true: on a clean tree the test fails, and set -e ended the script there with nothing said)
label=v$version-${commit:0:10}$([ "$dirty" = true ] && echo "-dirty-$(date +%s)" || true)
(cd "$src" && fly deploy --build-only --push -a "$IMAGE_APP" -c deploy/fly/image.toml --dockerfile deploy/fly/Dockerfile \
--image-label "$label" --build-arg RAEA_VERSION="$version" --build-arg COMMIT="$commit" --build-arg DIRTY="$dirty" .) >&2
echo "registry.fly.io/$IMAGE_APP:$label" | tee "$CONF/fly-image"
;;
up)
need_name
image=${RAEA_BOX_IMAGE:-$(cat "$CONF/fly-image" 2> /dev/null || true)}
[ -n "$image" ] || { echo "fly box: no image built yet (deploy/fly/box.sh image)"; exit 2; }
a=$(app "$NAME") f=$(envfile "$NAME")
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
if [ ! -s "$f" ]; then
# a new box: its own token, and the farm's settings
[ -f "$FARM" ] || { echo "fly box: $FARM names no farm (RAEA_CLOUD_GPU_URL, RAEA_CLOUD_GPU_TOKEN)"; exit 2; }
(umask 077; { echo "RAEA_CLOUD_TOKEN=$(openssl rand -hex 32)"; grep '^RAEA_CLOUD_GPU_' "$FARM"; echo "RAEA_API=https://api.raea.cloud"; } > "$f")
echo "fly box: $NAME is new: settings in $f (its agent key: deploy/fly/box.sh key $NAME)"
fi
has_app "$a" || fly apps create "$a" --org "$ORG" > /dev/null
fly ips list -a "$a" 2> /dev/null | grep -q 'v6' || {
fly ips allocate-v4 --shared -a "$a" > /dev/null
fly ips allocate-v6 -a "$a" > /dev/null
}
# the box's settings as Fly secrets, from the file (never on a command line)
fly secrets import --stage -a "$a" < "$f" > /dev/null
fly volumes list -a "$a" --json 2> /dev/null | python3 -c 'import json,sys; sys.exit(0 if any(v.get("name") == "home" and v.get("state") != "destroyed" for v in json.load(sys.stdin)) else 1)' || fly volumes create home --size "$VOLUME_GB" --region "$REGION" -a "$a" -y > /dev/null
id=$(machine "$NAME")
if [ -z "$id" ]; then
fly machine run "$image" -a "$a" -r "$REGION" --vm-size "$SIZE" -v home:/home/raea -n box \
-p 443:8080/tcp:tls:http -p 80:8080/tcp:http --autostart --autostop=off --restart on-failure --detach > /dev/null
# a Machine made by run takes the app's secrets as it's made; from then on the box reads its settings from
# ~/.raea-cloud.env on its volume (start.sh)
fly secrets deploy -a "$a" > /dev/null 2>&1 || true
elif [ "$(fly machines list -a "$a" --json 2> /dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)[0]["config"]["image"].split("@")[0])')" != "${image%@*}" ]; then
# a new image: the Machine made again from it (it restarts; its volume stays). Only then: a restart cut off a
# home's upload that had started after the health check passed on the instance before it (12-03, raea-3, 5, 11)
fly machine update "$id" -a "$a" --image "$image" --vm-size "$SIZE" --autostart --autostop=off --restart on-failure -y > /dev/null
fly machine wait "$id" -a "$a" --state started --wait-timeout 120 > /dev/null 2>&1 || true
fi
healthy "$NAME" > /dev/null || { echo "fly box: $NAME didn't answer at $(url "$NAME")"; exit 1; }
"$0" status "$NAME"
;;
move)
need_name
# the Sprite's settings, its token among them, so raea cloud only changes the box's address
. "$(dirname "$0")/../sprites/org.sh"
f=$(envfile "$NAME")
mkdir -p "$CONF/boxes" && chmod 700 "$CONF/boxes"
(umask 077; sprite exec -o "$ORG" -s "$NAME" -- cat /home/sprite/.raea-cloud.env > "$f")
grep -q '^RAEA_CLOUD_TOKEN=' "$f" || { echo "fly box: couldn't read $NAME's settings from its Sprite"; exit 1; }
ORG=$(sed -n 's/^RAEA_FLY_ORG=//p' "$FLY_CONF" | tail -1) "$0" up "$NAME"
# its home folder, but for caches anything can make again: agents' sign-ins, their sessions, ~/work. Sent by the
# Sprite itself straight to the new box's file API (it streams to disk), never through this Mac (12-03: through
# sprite exec it came at about 4 MB/s), then unpacked there
a=$(app "$NAME")
# a home that arrived whole in a try before this one is unpacked, not sent again (a .part is only part of one)
healthy "$NAME" > /dev/null || true
if fly ssh console -a "$a" -q -C "test -s /home/raea/work/.move/home.tar.zst" > /dev/null 2>&1; then
echo "fly box: $NAME's home arrived in a try before this one: unpacking it"
else
fly ssh console -a "$a" -q -C "rm -rf /home/raea/work/.move" > /dev/null 2>&1 || true
echo "fly box: sending $NAME's home from its Sprite to $(url "$NAME")"
# --no-stdin: a dropped link to the Sprite reconnects to the same session (12-03: all four copies lost theirs at
# once, 6 minutes in, and with stdin attached sprite exec refuses to reconnect)
sprite exec --no-stdin -o "$ORG" -s "$NAME" -- bash -c ". ~/.raea-cloud.env && tar -C /home/sprite --exclude=./.cache --exclude=./.npm --exclude=./.raea-cloud.env --exclude=./work/.move -cf - . | zstd -q -T0 -3 | curl -fsS --retry 0 -T - -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" '$(url "$NAME")/v1/files?path=.move/home.tar.zst' && echo SENT-WHOLE" > "$CONF/boxes/$NAME.move.log" 2>&1 &
sending=$!
# what has arrived, every 15 s; nothing more in MOVE_STILL_S (2 minutes) and the copy is stopped there, never waited
# out (12-03, Shane: fail fast at every step)
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$f" | tail -1)
got=-1 since=$SECONDS
while kill -0 "$sending" 2> /dev/null; do
n=$(curl -s -m 20 -H "authorization: Bearer $tok" "$(url "$NAME")/v1/files?path=.move" | python3 -c 'import json, sys
try: print(sum(d.get("bytes") or 0 for d in json.load(sys.stdin)))
except Exception: print(-1)')
if [ "${n:--1}" -gt "$got" ]; then
echo "fly box: $NAME: $((n / 1048576)) MB arrived"
got=$n since=$SECONDS
elif [ $((SECONDS - since)) -ge "${MOVE_STILL_S:-120}" ]; then
kill "$sending" 2> /dev/null
echo "fly box: $NAME's upload stopped growing at $((got / 1048576)) MB for $((SECONDS - since)) s: stopped; run move again"
exit 1
fi
sleep 15
done
wait "$sending"
grep -v 'bind: warning' "$CONF/boxes/$NAME.move.log"
grep -q SENT-WHOLE "$CONF/boxes/$NAME.move.log" || { echo "fly box: $NAME's home didn't arrive whole (above); nothing unpacked, run move again"; exit 1; }
fi
# unpacked there, saying so every 500 MB (a silent unpack of 26 GB looked stalled: 12-03, raea-4 and raea-6)
# run from inside the work folder, which the box's idle stop sees as work going on (server/idle.ts); the box woken
# first, as fly ssh doesn't start a stopped Machine
healthy "$NAME" > /dev/null || true
# and the box held while it unpacks (~/.raea-hold, which its idle stop reads): its image may be older than idle.ts's
# real-path match
fly ssh console -a "$a" -q -C "sh -c '(while kill -0 \$\$ 2> /dev/null; do touch /home/raea/.raea-hold; sleep 60; done) & cd /home/raea/work/.move && zstd -dqc home.tar.zst | tar -C /home/raea -xf - --checkpoint=50000 --checkpoint-action=echo=\"fly box: $NAME: %{}T unpacked\" && cd /home/raea && rm -rf work/.move && chown -R raea:raea /home/raea && du -sh /home/raea'"
# its own settings on its disk too, as a Sprite kept them
fly ssh console -a "$a" -q -C "sh -c 'umask 077; cat > /home/raea/.raea-cloud.env && chown raea:raea /home/raea/.raea-cloud.env'" < "$f"
# RAEA_BOX_REGISTER=0: copied, but raea cloud still sends work to the Sprite until deploy/fly/box.sh register NAME
if [ "${RAEA_BOX_REGISTER:-1}" = 0 ]; then echo "fly box: $NAME copied; not registered yet"; else "$0" register "$NAME"; fi
;;
register)
need_name
api=${RAEA_CLOUD_API:-https://api.raea.cloud}
key=${RAEA_CLOUD_ADMIN_KEY:-$(security find-generic-password -s raea-cloud-prod-staff-key -w 2> /dev/null || true)}
[ -n "$key" ] || { echo "fly box: no staff key (RAEA_CLOUD_ADMIN_KEY, or raea-cloud-prod-staff-key in the keychain)"; exit 2; }
tok=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
body=$(python3 -c 'import json,sys; print(json.dumps({"name": sys.argv[1], "url": sys.argv[2], "token": sys.argv[3], "first": sys.argv[4] == "1"}))' "$NAME" "$(url "$NAME")" "$tok" "${RAEA_BOX_FIRST:-0}")
curl -fsS -X POST -H "authorization: Bearer $key" -H 'content-type: application/json' --data-binary @- "$api/v1/admin/boxes" <<< "$body" > /dev/null || { echo "fly box: raea cloud refused $NAME"; exit 1; }
echo "fly box: $NAME is listed in raea cloud at $(url "$NAME")"
;;
status)
need_name
echo "$(url "$NAME") machine $(machine "$NAME")"
t=$(sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")")
curl -fsS -m 60 -H "authorization: Bearer $t" "$(url "$NAME")/v1/health" | head -c 600
echo
;;
token) need_name; sed -n 's/^RAEA_CLOUD_TOKEN=//p' "$(envfile "$NAME")" ;;
list) exec "$(dirname "$0")/../sprites/box.sh" list ;;
latest)
version=${2:-$(newest)}
[ -n "$version" ] || { echo "fly box: couldn't read raea's newest release (gh signed in?)"; exit 2; }
linux=raea-$version-linux-x86_64.tar.gz
gh release view "v$version" -R "$REPO" --json assets -q '.assets[].name' 2> /dev/null | grep -qx "$linux" || { echo "fly box: v$version has no $linux yet: no box changed"; exit 1; }
ref=$(gh api "repos/$REPO/commits/v$version" -q .sha) || { echo "fly box: couldn't read v$version's commit"; exit 1; }
RAEA_CLOUD_REF=$ref "$0" image "$version" > /dev/null
names=$("$0" list | sed 's/^[* ] *//' | awk '{print $1}' | grep '^raea-' || true)
failed=""
for b in $names; do
[ -s "$(envfile "$b")" ] || { echo "fly box: $b isn't a Fly box here (no $(envfile "$b")): passed over"; continue; }
echo "fly box: $b onto raea $version (${ref:0:10})"
"$0" up "$b" > /dev/null || failed+=" $b"
done
[ -z "$failed" ] || { echo "fly box: not on $version:$failed"; exit 1; }
echo "fly box: every Fly box is on raea $version"
;;
key)
need_name
if [ -t 0 ]; then k=$(pbpaste); else k=$(cat); fi
k=$(printf %s "$k" | tr -d '[:space:]')
case "$k" in raea_ak_*) ;; *) echo "fly box: that isn't a raea agent key (raea_ak_...)"; exit 2 ;; esac
f=$(envfile "$NAME")
(umask 077; { grep -v '^RAEA_AGENT_KEY=' "$f" || true; echo "RAEA_AGENT_KEY=$k"; } > "$f.new" && mv "$f.new" "$f")
printf 'RAEA_AGENT_KEY=%s\n' "$k" | fly secrets import -a "$(app "$NAME")" > /dev/null && echo "fly box: agent key on $NAME, its Machine restarted"
;;
sh)
need_name
if [ -n "${3:-}" ]; then fly ssh console -a "$(app "$NAME")" -q -C "$3"; else fly ssh console -a "$(app "$NAME")"; fi
;;
*)
sed -n '2,25p' "$0"
exit 2
;;
esac
+7
View File
@@ -0,0 +1,7 @@
# The app whose registry holds the box image (deploy/fly/box.sh image): it runs no machines of its own. Each box is an
# app of its own (raea-box-2, ...) whose one Machine runs this image with its volume.
app = "raea-box-image"
primary_region = "iad"
[build]
dockerfile = "Dockerfile"
+43
View File
@@ -0,0 +1,43 @@
#!/bin/bash
# A Fly box's start, as root: the volume made the box's home, the box's own settings read from it, then the image's
# entrypoint (image/entrypoint.sh), which goes on as raea and runs the server. The server exits 0 when the box has been
# idle RAEA_CLOUD_IDLE_STOP_MIN minutes (server/idle.ts), and with the Machine's restart policy on-failure it then stays
# stopped until Fly's proxy starts it for the next request.
set -uo pipefail
H=/home/raea
# the box's name: RAEA_BOX, else the app's (raea-box-2 is the box raea-2)
BOX=${RAEA_BOX:-${FLY_APP_NAME:-box}}
BOX=${BOX/raea-box-/raea-}
mkdir -p "$H/work"
[ "$(stat -c %u "$H")" = 1000 ] || chown -R raea:raea "$H"
[ "$(stat -c %u "$H/work")" = 1000 ] || chown raea:raea "$H/work"
# footage is read 16 MB ahead (setup.sh's 12-01 measure on a Sprite; a volume gains the same on long reads)
for b in /sys/block/*/queue/read_ahead_kb; do echo 16384 > "$b" 2> /dev/null || true; done
# the box's own token, the farm's address and key, the agent key and raea cloud's address: kept on the volume, as a
# Sprite kept them (box.sh writes it; a box moved from a Sprite brings its own). Fly secrets, when set, come first.
if [ -s "$H/.raea-cloud.env" ]; then
while IFS='=' read -r k v; do
[[ "$k" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
[ -n "${!k:-}" ] || export "$k=$v"
done < "$H/.raea-cloud.env"
fi
: "${RAEA_CLOUD_TOKEN:?the box has no RAEA_CLOUD_TOKEN: a Fly secret, or a line of ~/.raea-cloud.env}"
# what the box runs with, written back to its disk: raea cloud's fleet makes a new box from a healthy one by reading it
(umask 077; for k in RAEA_CLOUD_TOKEN RAEA_AGENT_KEY RAEA_API RAEA_CLOUD_GPU_URL RAEA_CLOUD_GPU_TOKEN; do
[ -n "${!k:-}" ] && echo "$k=${!k}"
done > "$H/.raea-cloud.env.new" && mv "$H/.raea-cloud.env.new" "$H/.raea-cloud.env" && chown 1000:1000 "$H/.raea-cloud.env")
# the work folder by the path raea cloud names it on every box (/home/sprite is /home/raea: the image links it), so
# the folders and paths of projects made on a Sprite are the same here
export RAEA_CLOUD_WORK=/home/sprite/work
# the box's commits say which box made them
[ -s "$H/.gitconfig" ] || {
sudo -u raea HOME=$H git config --global user.name "raea cloud $BOX"
sudo -u raea HOME=$H git config --global user.email "$BOX@box.raea.io"
sudo -u raea HOME=$H git config --global init.defaultBranch main
}
python3 - "$BOX" << 'PY'
import json, sys
p = "/opt/raea-cloud/BUILD.json"
b = json.load(open(p)); b["box"] = sys.argv[1]; json.dump(b, open(p, "w"))
PY
exec /opt/raea-cloud/image/entrypoint.sh
+4 -2
View File
@@ -247,8 +247,10 @@ class Log:
SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
CPU_SCALEDOWN = 60
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it. 180 since
# 12-03: an agent renders all its cuts at once, then each one its fix touched a minute or two later, and every one of
# those started cold at 60 (Shane: "no workflow should take more than 20 minutes")
CPU_SCALEDOWN = 180
def on(gpus, job):
+115 -4
View File
@@ -94,6 +94,19 @@ PARTS = 4
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
CPU_PARTS = 2
# A video with no 3D (its keys say so) is planned for the time it takes, not the containers' seconds (12-03, Shane: "no
# workflow should take more than 20 minutes"): its runs go out at once, with no timed first run before them (that run
# and its wait were 15-25 s of every render), each run at least FLAT_PART frames, on as many containers as the job may
# have. A 1080x1920 ad cut drew 0.46-0.69 s a frame on a container with no GPU (11-30, 12-03), which FLAT_FRAME_S plans
# the bill by.
FLAT_PART = 24
FLAT_FRAME_S = 0.6
# a run still out once this share of a job's runs are in, and after HEDGE_AFTER times the slowest finished one (or
# HEDGE_MIN_S more than it), is sent again to another container, and the first answer is kept (12-03: one of 21 runs took
# 81 s where the others took 11-15, and the whole render waited on it)
HEDGE_SHARE = 0.7
HEDGE_AFTER = 1.5
HEDGE_MIN_S = 8.0
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
PART_START = 5.0
@@ -254,6 +267,81 @@ def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=Non
return code
def _ready(h):
"""a spawned run's answer, the exception it raised, or None while it's still running"""
try:
return h.get(timeout=0)
except Exception as e:
# Modal's "not yet" is a TimeoutError; its FunctionTimeoutError (the run ran out of time) is the run's answer
if isinstance(e, TimeoutError) and type(e).__name__ != "FunctionTimeoutError":
return None
return e
def hedged(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None, clock=time.time, pause=None, wait_s=0.5):
"""`calls` on `fn` as spread() runs them, each spawned at once (at most `most` containers), and a run still out
once HEDGE_SHARE of them are in and it has taken HEDGE_AFTER times the slowest finished one (HEDGE_MIN_S more at
least) sent once more: the first answer of the two is kept and the other cancelled. A run draws the same frames
to the same files wherever it runs, so either answer is the run's."""
if not calls:
return 0
pause = pause or time.sleep
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
code = 0
t0 = clock()
out = {c[3]: {"call": c, "h": [fn.spawn(*c)], "at": t0, "again": False} for c in calls}
took = []
while out:
for first in list(out):
o = out[first]
r = None
for h in o["h"]:
r = _ready(h)
if r is not None:
break
if r is None:
continue
for h in o["h"]:
try:
h.cancel()
except Exception:
pass
del out[first]
took.append(clock() - o["at"])
if isinstance(r, Exception):
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
if again is not None:
again.append(o["call"])
else:
code = code or 1
continue
if bill:
bill.add(r)
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
again.append(o["call"])
continue
if got is not None:
got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]:
log(r["out"], err=True)
code = code or r["code"]
if not out:
break
if took and len(calls) - len(out) >= HEDGE_SHARE * len(calls):
slow = max(took)
for first, o in out.items():
if not o["again"] and clock() - o["at"] > max(slow * HEDGE_AFTER, slow + HEDGE_MIN_S):
o["again"] = True
o["h"].append(fn.spawn(*o["call"]))
log(f"raea farm: frames from {first} still out after {clock() - o['at']:.0f} s (the others took {slow:.0f} s at most): sent again, the first answer kept")
pause(wait_s)
return code
def timed(r, n):
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
@@ -324,6 +412,10 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
nv = bool((p.get("manifest") or {}).get("has3d"))
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
r0 = None
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
quick = bool(flat and p.get("keys"))
if quick:
n0 = 0
first = list(range(at0, at0 + n0))
if flat and n0:
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
@@ -344,17 +436,22 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if r0 and r0["code"]:
log(r0["out"], err=True)
return r0["code"]
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0)
frame_s, start_s = timed(r0, n0) if r0 else ((FLAT_FRAME_S, PART_START) if quick else (0.0, 0.0))
left = todo - n0
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
k = gpus_for(left, frame_s, cold_s, most)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
if quick:
k, m = (max(1, min(most, -(-left // FLAT_PART))) if left else 0), 1
else:
k = gpus_for(left, frame_s, cold_s, most)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
parts = f" in {k * m} parts" if m > 1 else ""
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
if r0:
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
elif quick and left:
log(f"raea farm: {left} frames on {on}, all at once, about ${cost:.3f} in all")
else:
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
@@ -365,24 +462,38 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
got = [r0] if r0 else []
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
again = [] if flat else None
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
code = (hedged if quick else spread)(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
if code:
return code
# each step from here says how long it took when it took a second or more (12-03: a render whose every frame was
# kept still took 64 s between "nothing to draw" and "joined", and nothing said where; Shane: fail fast at every step)
def took(what, t0):
if time.time() - t0 >= 1:
log(f"raea farm: {what} took {time.time() - t0:.1f} s")
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
# containers' frames (11-25: "the volume wouldn't reload ... cwd of raea render")
if video:
t0 = time.time()
t.join()
took("the sound", t0)
t0 = time.time()
reload() # the other containers' frames
took("reloading the volume", t0)
frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out)
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
t0 = time.time()
farm_keys.put(store, keyed["keys"], got, frames)
took("keeping the runs drawn", t0)
t0 = time.time()
got += farm_keys.take(hits, frames)
took(f"bringing {len(hits)} kept runs", t0)
if manifest and p.get("manifest"):
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+27
View File
@@ -0,0 +1,27 @@
// An agent socket kept alive, and ended when its caller is gone (the /v1/acp socket, main.ts).
// A message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two minutes
// without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven "socket
// closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent never sees it.
// And a ping with it: a caller that answers none for CALLER_GONE_MS is gone though its half of the socket stayed open
// (an API restart), and the socket is ended, which stops its agent (12-03: a stopped project's Gemini, busy, so never
// idle, went on an hour running goal checks on raea-5).
import type { WebSocket } from "ws"
export const CALLER_GONE_MS = 3 * 60_000
const EVERY_MS = 20_000
/** the keepalive's timer: clear it when the socket closes */
export function keepAlive(ws: WebSocket, who: string, goneMs = CALLER_GONE_MS, everyMs = EVERY_MS): ReturnType<typeof setInterval> {
let pong = Date.now()
ws.on("pong", () => (pong = Date.now()))
return setInterval(() => {
if (ws.readyState !== ws.OPEN) return
if (Date.now() - pong > goneMs) {
process.stderr.write(`raea-cloud: ${who}'s caller answered no ping in ${Math.round(goneMs / 1000)} s: ended\n`)
ws.terminate()
return
}
ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}')
ws.ping()
}, everyMs)
}
+107
View File
@@ -0,0 +1,107 @@
// The critic a project's rules are judged by on this box (Shane, 12-03: "nothing should judge or check with another
// harness ... the context should never tell the agent to even have to decide what harness or model or provider"):
// a fresh session of the same agent the project runs on, with the same sign-in, asked one question and given nothing
// it could change. Each agent session started here (WS /v1/acp) gets RAEA_JUDGE_URL and RAEA_JUDGE_TOKEN in its
// environment; `raea goal judge` and `raea judge` in that agent's shell POST to it, and the critic runs as that agent.
//
// POST /host/judge {cwd, prompt} authorization: Bearer RAEA_JUDGE_TOKEN -> {text}
//
// The token is the session's: it names the agent and environment to start, and is forgotten when the session ends.
import { spawn } from "node:child_process"
import { randomBytes } from "node:crypto"
import path from "node:path"
interface Critic {
command: string
args: string[]
env: NodeJS.ProcessEnv
root: string
}
const critics = new Map<string, Critic>()
/** the environment an agent session adds so its shell can ask for a critic: the URL and the session's token */
export function register(c: Critic, port: number): { env: Record<string, string>; forget: () => void } {
const token = randomBytes(24).toString("hex")
critics.set(token, c)
return { env: { RAEA_JUDGE_URL: `http://127.0.0.1:${port}/host/judge`, RAEA_JUDGE_TOKEN: token }, forget: () => critics.delete(token) }
}
/** the critic a token names, or null */
export const criticFor = (token: string | null | undefined): Critic | null => (token ? (critics.get(token) ?? null) : null)
/** a permission the critic asks for: what only reads is allowed once, anything else refused (it judges, it changes nothing) */
type Option = { optionId: string; kind: string }
export function answerPermission(p: { options: Option[]; toolCall?: { kind?: string } }): string {
const reads = ["read", "search", "fetch", "think"].includes(String(p.toolCall?.kind ?? ""))
const want = reads ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"]
return (p.options.find((o) => want.includes(o.kind)) ?? p.options.find((o) => (reads ? o.kind.startsWith("allow") : o.kind.startsWith("reject"))) ?? p.options[0]).optionId
}
/** one question to a fresh session of the critic's agent in `cwd`: what it says back */
export function ask(c: Critic, cwd: string, prompt: string, timeoutMs = 10 * 60_000): Promise<string> {
const dir = path.resolve(c.root, cwd)
if (dir !== c.root && !dir.startsWith(c.root + path.sep)) return Promise.reject(new Error(`${cwd} isn't in the workspace`))
return new Promise((done, fail) => {
const child = spawn(c.command, c.args, { cwd: dir, env: c.env, stdio: ["pipe", "pipe", "pipe"], detached: true })
let said = ""
let err = ""
let n = 0
let finished = false
const waiting = new Map<number, (m: { result?: unknown; error?: { message?: string } }) => void>()
const stop = () => {
try {
if (child.pid) process.kill(-child.pid, "SIGTERM")
} catch {}
}
const end = (e: Error | null) => {
if (finished) return
finished = true
clearTimeout(timer)
stop()
e ? fail(e) : done(said)
}
const timer = setTimeout(() => end(new Error(`the critic said nothing final in ${Math.round(timeoutMs / 60_000)} min`)), timeoutMs)
const send = (m: object) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...m })}\n`)
const call = (method: string, params: object) =>
new Promise<any>((ok, no) => {
const id = ++n
waiting.set(id, (m) => (m.error ? no(new Error(m.error.message ?? JSON.stringify(m.error))) : ok(m.result)))
send({ id, method, params })
})
let buf = ""
child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
buf += chunk
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) {
let m: any
try {
m = JSON.parse(buf.slice(0, i))
} catch {
continue
}
if (m.id != null && !m.method && waiting.has(m.id)) {
const w = waiting.get(m.id)!
waiting.delete(m.id)
w(m)
} else if (m.method === "session/update") {
const u = m.params?.update
if (u?.sessionUpdate === "agent_message_chunk" && u.content?.type === "text") said += u.content.text ?? ""
} else if (m.method === "session/request_permission") {
send({ id: m.id, result: { outcome: { outcome: "selected", optionId: answerPermission(m.params) } } })
} else if (m.id != null && m.method) {
// a client method this critic doesn't offer (it reads with its own tools)
send({ id: m.id, error: { code: -32601, message: `${m.method} isn't offered here` } })
}
}
})
child.stderr.setEncoding("utf8").on("data", (c: string) => (err = (err + c).slice(-4000)))
child.on("error", (e) => end(new Error(`the critic didn't start: ${e.message}`)))
child.on("exit", (code) => end(finished ? null : new Error(`the critic ended (${code}) before it answered: ${err.trim().slice(-300)}`)))
;(async () => {
await call("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } })
const s = await call("session/new", { cwd: dir, mcpServers: [] })
await call("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: prompt }] })
end(null)
})().catch((e) => end(e as Error))
})
}
+37
View File
@@ -0,0 +1,37 @@
// GET and PUT /v1/files: a file of the work folder read or written, or a folder listed. Both ways stream: a body is
// never held in memory (12-03: a box's home folder, gigabytes, moved from a Sprite to a Fly Machine in one request).
import { createReadStream, createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
import type { IncomingMessage, ServerResponse } from "node:http"
import path from "node:path"
import { pipeline } from "node:stream/promises"
type Json = (res: ServerResponse, v: unknown, status?: number) => unknown
export function files(req: IncomingMessage, res: ServerResponse, url: URL, o: { resolve: (p: string) => string; work: string; json: Json }) {
const { json } = o
const p = o.resolve(url.searchParams.get("path") ?? ".")
if (req.method === "PUT") {
// to disk as it comes, beside the file, then put in its place whole
mkdirSync(path.dirname(p), { recursive: true })
const part = `${p}.part-${process.pid}-${Date.now()}`
return pipeline(req, createWriteStream(part)).then(
() => {
renameSync(part, p)
json(res, { path: path.relative(o.work, p), bytes: statSync(p).size })
},
(e) => {
rmSync(part, { force: true })
if (!res.headersSent) json(res, { error: `the file didn't arrive whole: ${(e as Error).message}` }, 500)
},
)
}
let st
try {
st = statSync(p)
} catch {
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
}
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size })
return pipeline(createReadStream(p), res).catch(() => res.destroy())
}
+98
View File
@@ -0,0 +1,98 @@
// A box on a Fly Machine stops itself when nothing is going on (12-03: the boxes moved off Sprites, which paused on
// their own; a Machine runs, and bills, until something stops it). Fly's proxy starts a stopped Machine again on the
// next request, so a box only has to know when it's idle: then the server exits 0, the entrypoint saves and exits, and
// the Machine (restart policy on-failure) stays stopped.
//
// Idle is all of: no request for `quietMs`, no connection open (an agent's ACP socket, a shell's stream), nothing the
// server runs, no process anywhere working in the box's work folder (a render, the footage prep, an agent's
// background job: each runs in a project's folder), and no hold. A hold is the file HOLD_FILE touched within
// `holdMs`: raea cloud touches it while a project is unfinished (its awake alarm), as it held a Sprite's task before.
//
// Off unless RAEA_CLOUD_IDLE_STOP_MIN is set (the Fly image sets it), so a box elsewhere never stops itself.
import { readdirSync, readFileSync, readlinkSync, realpathSync, statSync } from "node:fs"
import type { Server } from "node:http"
import path from "node:path"
export const HOLD_FILE = ".raea-hold"
/** a process other than this one (and its parents) whose working folder is under `work` */
export function workingIn(work: string, self = process.pid): number[] {
const mine = new Set<number>()
for (let p = self; p > 1; ) {
mine.add(p)
try {
// /proc/PID/stat: "PID (name) STATE PPID ...", the name in brackets may hold spaces
const stat = readFileSync(`/proc/${p}/stat`, "utf8")
p = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
} catch {
break
}
}
const out: number[] = []
let pids: string[] = []
try {
pids = readdirSync("/proc").filter((d) => /^\d+$/.test(d))
} catch {
return out
}
// the folder by the name it's given and by its real one: /proc says where a process is with no symlink in the way, and
// a Fly box's work folder is /home/sprite/work, a link to /home/raea/work (12-03: a 64 GB unpack in it was taken for
// idle and the box stopped under it)
const roots = [path.resolve(work) + "/"]
try {
roots.push(realpathSync(work) + "/")
} catch {}
for (const d of pids) {
const pid = Number(d)
if (mine.has(pid)) continue
try {
const cwd = readlinkSync(`/proc/${d}/cwd`) + "/"
if (roots.some((r) => cwd.startsWith(r))) out.push(pid)
} catch {}
}
return out
}
export interface IdleOptions {
server: Server
work: string
home: string
/** whether the server itself has something running (an agent, a shell, a job) */
busy: () => boolean
quietMs: number
holdMs?: number
everyMs?: number
log?: (line: string) => void
exit?: () => void
}
/** watches for the box going idle and exits when it has been idle a whole `quietMs`; returns what marks a request */
export function stopWhenIdle(o: IdleOptions): { touch: () => void; stop: () => void } {
let last = Date.now()
const holdMs = o.holdMs ?? 10 * 60_000
const log = o.log ?? ((l) => process.stderr.write(l + "\n"))
const exit = o.exit ?? (() => process.exit(0))
const why = (): string | null => {
if (Date.now() - last < o.quietMs) return "a request came lately"
if (o.busy()) return "the server runs something"
try {
const held = statSync(path.join(o.home, HOLD_FILE)).mtimeMs
if (Date.now() - held < holdMs) return "a project holds it"
} catch {}
const w = workingIn(o.work)
if (w.length) return `${w.length} processes work in ${o.work}`
return null
}
const timer = setInterval(() => {
o.server.getConnections((e, n) => {
if (!e && n > 0) return
if (why()) return
log(`raea-cloud: idle for ${Math.round(o.quietMs / 60_000)} min (no request, connection, process or hold): stopping, so the machine stops`)
clearInterval(timer)
o.server.close()
exit()
})
}, o.everyMs ?? 30_000)
timer.unref()
return { touch: () => void (last = Date.now()), stop: () => clearInterval(timer) }
}
+41 -27
View File
@@ -19,6 +19,8 @@
// browser): {credential, email?}, handed back once, or {pending: true}
// WS /v1/google-token/ID/screen the box's own browser for that sign-in, over VNC (google-screen.ts)
// POST /v1/google-token/check {credential} one short Antigravity turn on it (or a Gemini API key): {ok, said, models}
// POST /host/judge {cwd, prompt} a fresh session of the asking agent session's own agent, as the critic its rules are
// judged by: {text}. Its token is the session's RAEA_JUDGE_TOKEN (critic.ts)
// WS /v1/acp?agent=ID one agent process per socket: a text frame is one ACP message to its stdin,
// each line it prints is one frame back. A caller signing the agent in as one of
// its own clients (raea cloud, per workspace) sends x-raea-agent-env: JSON of the
@@ -37,9 +39,13 @@
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
import { execFile, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, readFileSync, symlinkSync } from "node:fs"
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
import path from "node:path"
import { homedir } from "node:os"
import { keepAlive } from "./alive.ts"
import { files } from "./files.ts"
import { stopWhenIdle } from "./idle.ts"
import { WebSocketServer } from "ws"
import { installed, spawnFor } from "./agents.ts"
import { guard } from "./memguard.ts"
@@ -50,6 +56,7 @@ import { checkGoogle, finishGoogleSignIn, screenPort, startGoogleSignIn, unpackC
import { connect as tcp } from "node:net"
import { login, loginState } from "./login.ts"
import { Outside, resolve, WORK } from "./workspace.ts"
import { ask as askCritic, criticFor, register as registerCritic } from "./critic.ts"
const TOKEN = process.env.RAEA_CLOUD_TOKEN ?? ""
if (TOKEN.length < 16) {
@@ -170,24 +177,6 @@ async function body(req: IncomingMessage): Promise<Buffer> {
return Buffer.concat(parts)
}
function files(req: IncomingMessage, res: ServerResponse, url: URL) {
const p = resolve(url.searchParams.get("path") ?? ".")
if (req.method === "PUT")
return body(req).then((b) => {
mkdirSync(path.dirname(p), { recursive: true })
writeFileSync(p, b)
json(res, { path: path.relative(WORK, p), bytes: b.length })
})
let st
try {
st = statSync(p)
} catch {
return json(res, { error: `${url.searchParams.get("path")} doesn't exist` }, 404)
}
if (st.isDirectory()) return json(res, readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, dir: d.isDirectory(), bytes: d.isFile() ? statSync(path.join(p, d.name)).size : undefined })))
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
}
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
@@ -250,7 +239,23 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://raea-cloud")
// a request (other than a platform's health check) keeps an idle box up (idle.ts)
// a request is the box at work from when it starts until it ends: a 19-minute upload counted only its start, and the
// box stopped as idle the moment it ended (12-03)
if (url.pathname !== "/healthz") (idle?.touch(), res.on("close", () => idle?.touch()))
if (url.pathname === "/healthz") return res.writeHead(200, { "content-type": "text/plain" }).end("ok")
// the critic an agent's shell asks (critic.ts): its own session's token, not the box's
if (url.pathname === "/host/judge" && req.method === "POST") {
const c = criticFor(/^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1])
if (!c) return json(res, { error: "no agent session with that token here" }, 401)
try {
const b = JSON.parse(String(await body(req)))
if (typeof b.prompt !== "string" || !b.prompt) return json(res, { error: "prompt is the question" }, 400)
return json(res, { text: await askCritic(c, typeof b.cwd === "string" ? b.cwd : ".", b.prompt) })
} catch (e) {
return json(res, { error: (e as Error).message }, 502)
}
}
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
try {
if (url.pathname === "/v1/health" && req.method === "GET") {
@@ -278,7 +283,7 @@ const server = createServer(async (req, res) => {
running: running.size,
})
}
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url)
if (url.pathname === "/v1/files" && (req.method === "GET" || req.method === "PUT")) return await files(req, res, url, { resolve, work: WORK, json })
if (url.pathname === "/v1/run" && req.method === "POST") return await run(req, res)
if (url.pathname === "/v1/shell" && req.method === "POST") return await shell(req, res)
if (url.pathname === "/v1/jobs" && req.method === "POST") {
@@ -370,7 +375,10 @@ server.on("upgrade", (req, socket, head) => {
} catch (e) {
return socket.end(`HTTP/1.1 400 Bad Request\r\ncontent-type: text/plain\r\n\r\n${(e as Error).message}`)
}
const env = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
const base = own ? { ...withoutKeys(childEnv()), ...agent.env, ...RUN_DEFAULTS, ...own } : { ...childEnv(), ...agent.env }
// this session's critic (critic.ts): the same agent, sign-in and environment, which `raea goal judge` in its shell asks
const critic = registerCritic({ command: agent.command, args: agent.args, env: base, root: WORK }, PORT)
const env = { ...base, ...critic.env }
wss.handleUpgrade(req, socket, head, (ws) => {
// its own process group, so what it started (a render left running in the background) stops with it: a killed
// agent's renders went on as orphans, 4 GB of them on raea-2 (11-25)
@@ -388,11 +396,7 @@ server.on("upgrade", (req, socket, head) => {
}
running.add(child)
agentSockets.add(ws)
// a message every 20 s, so the socket is never idle: between raea cloud and the box it's closed after about two
// minutes without traffic, and an agent waiting on a long render sends nothing (11-25: five of StreetTalk's seven
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
// never sees it
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
const beat = keepAlive(ws, agent.id)
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
@@ -404,7 +408,7 @@ server.on("upgrade", (req, socket, head) => {
ws.terminate()
stopAll()
}, Math.min(60_000, IDLE_AGENT_MS / 2))
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle)))
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle), critic.forget()))
child.on("exit", () => (running.delete(child), clearInterval(idle)))
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
@@ -471,6 +475,16 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
process.stderr.write(line + "\n")
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
})
// a box on a Fly Machine stops itself when nothing is going on, and Fly's proxy starts it at the next request (idle.ts)
const idleMin = Number(process.env.RAEA_CLOUD_IDLE_STOP_MIN ?? 0)
const idle =
idleMin > 0
? stopWhenIdle({ server, work: WORK, home: homedir(), busy: () => running.size > 0 || agentSockets.size > 0, quietMs: idleMin * 60_000 })
: null
// a request may take as long as its body takes to come: Node's 5 minutes cut a home folder's upload off at 408
// (12-03, a Sprite's home moved to a Fly box). A client still has 60 s to send its headers.
server.requestTimeout = 0
server.headersTimeout = 60_000
server.listen(PORT, async () => {
await versionKnown
const d = device(childEnv())
+11 -1
View File
@@ -91,6 +91,15 @@ async function follow(res: Response, onOutput: ((text: string, stream: "out" | "
throw new Error(`${what} ended without an exit code`)
}
/** whether a box's address is a Sprite's (behind the Sprite's own auth) */
export const onSprite = (url: string): boolean => {
try {
return new URL(url).hostname.endsWith(".sprites.app")
} catch {
return false
}
}
export class RaeaCloud {
readonly url: string
private token: string
@@ -103,7 +112,8 @@ export class RaeaCloud {
constructor(o: { url: string; token: string; spriteToken?: string }) {
this.url = o.url.replace(/\/+$/, "")
this.token = o.token
this.spriteToken = o.spriteToken
// only a box on a Sprite is behind the Sprite's auth; a box elsewhere (a Fly Machine's own app) takes its token
this.spriteToken = onSprite(this.url) ? o.spriteToken : undefined
}
/** A request to the box, its response as it comes, for a caller that reads the body itself (a stream of a file
+52
View File
@@ -69,6 +69,11 @@ class FakeGpu:
def starmap(self, calls, order_outputs=False, return_exceptions=True):
return [self.remote(*c) for c in calls]
def spawn(self, *a, **kw):
# a run spawned on its own (farm_plan.hedged, waited): answered at once
r = self.remote(*a, **kw)
return type("Done", (), {"get": lambda self, timeout=None: r, "cancel": lambda self: None})()
lines = []
log = lambda t, err=False: lines.append(t)
@@ -344,3 +349,50 @@ assert not any("waiting" in l for l in lines), lines
ok("a GPU run that timed out fails the job instead of being waited on forever")
shutil.rmtree(root)
# a flat video's runs go out at once, and a run that hangs back is sent again (farm_plan.hedged, 12-03)
class Call:
def __init__(self, answer_at, r, clock):
self.answer_at, self.r, self.clock, self.cancelled = answer_at, r, clock, False
def get(self, timeout=None):
if self.clock() >= self.answer_at:
return self.r
raise TimeoutError()
def cancel(self):
self.cancelled = True
class Straggly:
"""runs that answer after 10 s, but the first try of the run from frame 40 answers only after 500 s"""
def __init__(self, clock):
self.clock, self.spawned = clock, []
def with_options(self, **kw):
return self
def spawn(self, id, args, frames, first, *rest):
late = first == 40 and not any(f == 40 for f, _ in self.spawned)
c = Call(self.clock() + (500 if late else 10), {"code": 0, "s": 10.0, "frames": len(frames), "first": first}, self.clock)
self.spawned.append((first, c))
return c
now = [0.0]
clock = lambda: now[0]
def tick(_s):
now[0] += 1
st = Straggly(clock)
lines.clear()
calls = [("jh", ["render"], list(range(a, a + 10)), a, False, True) for a in range(0, 60, 10)]
got = []
assert fp.hedged(st, "CPU", calls, log, "frames", got=got, again=[], clock=clock, pause=tick) == 0, lines
assert sorted(r["first"] for r in got) == [0, 10, 20, 30, 40, 50], got
assert [f for f, _ in st.spawned].count(40) == 2, st.spawned
assert now[0] < 100, now
assert any("sent again" in l for l in lines), lines
assert [c.cancelled for f, c in st.spawned if f == 40] == [True, True]
ok("a run that hangs back while the rest are in is sent again, and the first answer kept: the render doesn't wait on it")
+51 -1
View File
@@ -4,7 +4,7 @@
import assert from "node:assert/strict"
import { execSync } from "node:child_process"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
@@ -13,6 +13,8 @@ import { shellEnv } from "../server/shell-os.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, sessionIn, transcriptOf, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
import { localSources } from "../server/media.ts"
import { keepAlive } from "../server/alive.ts"
import { answerPermission, ask as askCritic, criticFor, register as registerCritic } from "../server/critic.ts"
const L4 = `Devices:
========
@@ -213,3 +215,51 @@ console.log("units: ok")
assert.equal(localSources({}, [], "/x"), 0)
console.log("ok localSources")
}
{
// the critic (critic.ts): a session's token names its agent; a fresh session of it answers; reads only
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "critic-")))
mkdirSync(path.join(root, "proj"))
const agent = { command: process.execPath, args: [path.join(import.meta.dirname, "echo-agent.mjs")], env: { ...process.env }, root }
const r = registerCritic(agent, 8080)
assert.equal(r.env.RAEA_JUDGE_URL, "http://127.0.0.1:8080/host/judge")
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), agent)
assert.equal(criticFor("nope"), null)
const said = await askCritic(agent, "proj", "is the plan complete?")
assert.match(said, /echo: is the plan complete\?/)
assert.match(said, new RegExp(`cwd: ${path.join(root, "proj").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`))
// the echo agent's permission names no kind of tool: refused, as anything but a read is
assert.match(said, /permission: no/)
await assert.rejects(askCritic(agent, "../elsewhere", "x"), /isn't in the workspace/)
assert.equal(answerPermission({ toolCall: { kind: "read" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "a")
assert.equal(answerPermission({ toolCall: { kind: "edit" }, options: [{ optionId: "a", kind: "allow_once" }, { optionId: "r", kind: "reject_once" }] }), "r")
r.forget()
assert.equal(criticFor(r.env.RAEA_JUDGE_TOKEN), null)
rmSync(root, { recursive: true, force: true })
console.log("ok critic")
}
{
// a caller that answers pings keeps its socket; one that answers none is ended, which stops its agent (alive.ts)
const { WebSocketServer, WebSocket } = await import("ws")
const wss = new WebSocketServer({ port: 0 })
const port = (wss.address() as { port: number }).port
const ended: boolean[] = []
wss.on("connection", (ws) => {
const beat = keepAlive(ws, "test", 120, 20)
ws.on("close", () => (clearInterval(beat), ended.push(true)))
})
const live = new WebSocket(`ws://127.0.0.1:${port}`)
await new Promise((ok) => live.on("open", ok))
await new Promise((ok) => setTimeout(ok, 400))
assert.equal(live.readyState, WebSocket.OPEN, "a caller that answers pings was ended")
live.close()
await new Promise((ok) => setTimeout(ok, 50))
// autoPong off: this caller answers nothing, as one whose half stayed open after it went away
const gone = new WebSocket(`ws://127.0.0.1:${port}`, { autoPong: false } as never)
await new Promise((ok) => gone.on("open", ok))
const closed = await new Promise<boolean>((ok) => (gone.on("close", () => ok(true)), setTimeout(() => ok(false), 1000)))
assert.ok(closed, "a caller that answered no ping wasn't ended")
wss.close()
console.log("ok an agent socket's caller gone is ended")
}
+66 -3
View File
@@ -9,14 +9,19 @@ import type { Contract } from "./contract.ts"
import * as media from "./media.ts"
import type { Faces, Levels, Word } from "./media.ts"
import type { Scene } from "./packs/place.ts"
import { outOf, planScene, said } from "./plan.ts"
import type { Project } from "./project.ts"
/** a sound clip in a render's manifest: its comp frames, its source and the source second at `from` */
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
/** a text on a frame, in render pixels: its layout box and its ink */
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number; lines?: number }
/** a video on a frame, in render pixels: its source and the source second it shows, its box (and what of it a box it's
* in leaves showing, `clip`), its object-fit and object-position ([x px, x share of the free space, y px, y share]) */
export type ManifestVideo = { src: string; at: number; box: number[]; clip?: number[]; fit?: string; position?: number[]; opacity?: number }
/** `raea render --manifest`: the frames with their texts and videos, and the sound's clips; `plan`: written by `raea
* render --plan`, which draws nothing (every frame laid out, no picture) */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; plan?: boolean; frames?: { frame: number; text?: ManifestText[]; videos?: ManifestVideo[]; pictures?: { kind?: string; box?: number[]; opacity?: number }[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
@@ -37,6 +42,9 @@ export interface FileFacts {
height: number | null
fps: number
manifest: Manifest | null
/** a cut checked on its plan, before it's drawn (plan.ts): `manifest` is the plan, `path` and `abs` name the export
* it's of (which may not be there yet), and its words and scene are what its takes say and its sources show */
plan: boolean
moment: Moment
contract: Contract | null
/** what it says, word by word */
@@ -125,6 +133,7 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
height: shape?.height ?? manifest?.height ?? null,
fps: manifest?.fps ?? shape?.fps ?? 30,
manifest,
plan: false,
moment,
contract,
words: once(() => media.words(abs)),
@@ -167,3 +176,57 @@ export function runIn(dir: string) {
return r.status === 0 ? { ok: true, said: "passes" } : { ok: false, said: `exits ${r.status ?? "by a signal"}${last ? `: ${last}` : ""}` }
}
}
/** a composition checked on a plan of one of its cuts (`raea goal check --at edit --manifest OUT.plan.json EDIT.tsx`):
* the facts of the export the plan is of (OUT.mp4 beside the plan), known before it's drawn. Its words are its voice
* clips' takes' words where the clips put them, its scene its videos' source frames' (plan.ts); its own level, sheet
* and look wait for the export */
export function planFacts(plan: Manifest, planAbs: string, root: string, moment: Moment, contract: Contract | null): FileFacts {
const abs = `${outOf(planAbs)}.mp4`
const roots = [root, path.dirname(planAbs)]
const fps = Number(plan.fps) || 30
const takeWords = new Map<string, Promise<Word[]>>()
const take = (src: string) => onMachine(src, roots)
const wordsOfTake = (src: string) => {
const f = take(src)
if (!f) return Promise.reject(new media.Unmet(`${src} isn't on this machine`))
if (!takeWords.has(f)) takeWords.set(f, media.words(f, true))
return takeWords.get(f)!
}
const st = statSync(planAbs)
return {
path: path.relative(root, abs),
abs,
root,
kind: "other",
made: true,
stamp: `${Math.round(st.mtimeMs)} ${st.size}`,
seconds: (Number(plan.length) || plan.frames?.length || 0) / fps,
width: Number(plan.width) || null,
height: Number(plan.height) || null,
fps,
manifest: plan,
plan: true,
moment,
contract,
words: once(async () => {
const clips = plan.sounds?.clips ?? []
const got = new Map<string, Word[]>()
for (const c of clips) {
if (got.has(c.src)) continue
try {
got.set(c.src, await wordsOfTake(c.src))
} catch {}
}
return said(clips, plan.sounds?.fps ?? fps, (src) => got.get(src) ?? null)
}),
take,
takeWords: wordsOfTake,
levels: (a, b, src) => (src ? media.levels(take(src) ?? src, a, b) : { start: a ?? 0, db: [] }),
scene: once(() => planScene(root, plan, take)),
sheet: () => {
throw new media.Unmet("a plan has no picture to make a sheet of: render it")
},
seen: () => null,
}
}
+31 -18
View File
@@ -233,24 +233,7 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const faces: Faces[] = []
const scenes: Scene[] = []
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
const r = await post("/v1/scene", body, "application/json")
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
for (const g of (JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames) {
if (!g) {
faces.push(null)
scenes.push(null)
continue
}
const fs = (g.faces as any[][]) ?? []
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
}
const { faces, scenes } = await readScenes(jpgs.map((n) => readFileSync(path.join(dir, n))))
if (whole && scenes.length) {
try {
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
@@ -262,6 +245,36 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
}
}
/** frames (JPEGs, a null where there's none) read by the farm's scene reader, 300 a request: each one's faces and seams,
* and its scene (people, faces, things, words in the shot) */
export async function readScenes(jpgs: (Buffer | null)[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
if (!farm()) throw new Unmet("no scene reader on this machine (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)")
const faces: Faces[] = []
const scenes: Scene[] = []
const real = jpgs.flatMap((j, i) => (j ? [i] : []))
const got = new Map<number, Record<string, any> | null>()
for (let i = 0; i < real.length; i += 300) {
const part = real.slice(i, i + 300)
const body = JSON.stringify({ frames: part.map((k) => jpgs[k]!.toString("base64")) })
const r = await post("/v1/scene", body, "application/json")
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
;(JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames.forEach((g, n) => got.set(part[n], g))
}
for (let i = 0; i < jpgs.length; i++) {
const g = got.get(i)
if (!g) {
faces.push(null)
scenes.push(null)
continue
}
const fs = (g.faces as any[][]) ?? []
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
return { faces, scenes }
}
/** a video's contact sheet beside it (FILE.sheet.jpg, `raea media sheet`), made again when older than the video */
export function sheet(file: string): string {
const out = `${stem(file)}.sheet.jpg`
+8 -5
View File
@@ -16,7 +16,8 @@
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { RATE, type Word } from "../media.ts"
import { samples, textFrames } from "../plan.ts"
import type { TextLine } from "./place.ts"
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
@@ -235,13 +236,15 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
}
export default check<FileFacts>(
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
if (!f.made || (f.kind !== "video" && !f.plan)) return
const heard = await f.words()
if (!heard.length) return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
// a cut's plan (plan.ts): what it shows is its own text, as laid out, and what it says its takes' words where its
// clips put them; an export's is what the reader reads and hears in it
const sc = f.plan && f.manifest ? { rate: RATE, scenes: [] } : await f.scene()
const frames: Frame[] = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
const shown = captionsOf(frames, sc.rate || 2, heard)
const rate = sc.rate || 2
+8 -1
View File
@@ -10,6 +10,7 @@ import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { textRules, ZONE_FIX } from "../plan.ts"
import { bookkeeping } from "./naming.ts"
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
@@ -53,7 +54,13 @@ export function floorOf(abs: string, manifest: string | undefined, cwd: string,
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["edit", "render", "publish", "done"] }, async (f) => {
// a cut's plan (plan.ts): the text rules raea check holds a manifest to, on every frame, before it's drawn; what only
// the picture and the mix show (contrast, freezes, flashing, loudness, blotching) waits for the export
if (f.plan && f.manifest) {
for (const x of textRules(f.manifest)) found({ level: x.level, says: x.says, fix: x.rule === "safe-area" ? ZONE_FIX : undefined, seconds: x.at })
return
}
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
for (const x of floorOf(f.abs, m, f.root)) say(x)
+8 -3
View File
@@ -13,6 +13,7 @@ import { existsSync, readFileSync } from "node:fs"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RATE, stem, type Faces } from "../media.ts"
import { PLAN_SOFT } from "../plan.ts"
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
export const FACE_MIN = 0.05
@@ -141,13 +142,17 @@ export const despite = (abs: string) => {
}
export default check<FileFacts>(
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
// at edit only a cut's plan (plan.ts): its faces are its sources' frames, mapped into the cut's
if (!f.made || (f.kind !== "video" && !f.plan)) return
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
if (f.manifest) for (const x of smallText(f.manifest)) say(x)
// the text's sizes are said even where the faces wait for a scene reader
const why = despite(f.abs)
for (const x of cutFaces((await f.scene()).faces, RATE)) say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : x)
// on a plan a face cut by the edge is a warning (plan.ts ON_PLAN_WARNS): its source frames are read without the cut's
// text over them, and the render's check holds it
for (const x of cutFaces((await f.scene()).faces, RATE))
say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : f.plan && x.kind === "face-cut" && x.level === "error" ? { ...x, level: "warn", says: `${x.says}${PLAN_SOFT}` } : x)
},
)
+99 -44
View File
@@ -5,7 +5,7 @@
// says a fresh critic (`raea goal judge`) found it true of the work, after the work's last change
// (file rules are deliverables: the deliverables pack holds them)
// The critic's verdict is review/judge/NAME.json (the goal's name): {at, by, goal, rules: {ID: {pass, why}}}.
import { spawnSync } from "node:child_process"
import { spawn } from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { check, found } from "raea/check"
@@ -76,13 +76,23 @@ export const runPack = check<Job>({ id: "run", text: "each command rule exits 0"
export const saysPack = check<Job>({ id: "says", text: "each `says` rule found true by a fresh critic after the work's last change", over: "job", at: ["done"] }, async (j) => {
const says = saysOf(goalOf(j) ?? null)
if (!says.length) return
const v = verdict(j.root, j.contract!)
const changed = newest(j.root)
let v = verdict(j.root, j.contract!)
// at whole seconds, as the verdict keeps its time: work saved in the second the critic was asked counts as judged
const fresh = !!v && (changed === null || v.at >= Math.floor(changed / 1000))
const freshOf = (x: Verdict | null) => !!x && (newest(j.root) === null || x.at >= Math.floor(newest(j.root)! / 1000))
// a verdict missing, stale or short of a rule is asked for here (the check is the one command; the agent never
// judges by hand), where this session has a critic to ask
if (!(freshOf(v) && says.every((r) => v!.rules?.[r.id])) && hasCritic(j.root, says)) {
try {
v = await judge(j.contract!, j.root)
} catch (e) {
found({ says: `the critic couldn't judge: ${(e as Error).message}` })
return
}
}
const fresh = freshOf(v)
for (const r of says) {
const one = v?.rules?.[r.id]
const fix = `raea goal judge${j.contract?.name ? ` --goal ${j.contract.name}` : ""}`
const fix = NO_CRITIC
if (!v) found({ says: `${r.id}: not judged yet`, about: [r.id], fix })
else if (!one) found({ says: `${r.id}: the last judging didn't cover it`, about: [r.id], fix })
else if (!fresh) found({ says: `${r.id}: the work changed after the critic judged it`, about: [r.id], fix })
@@ -91,8 +101,8 @@ export const saysPack = check<Job>({ id: "says", text: "each `says` rule found t
})
/** what the critic is asked: the goal, each `says` rule by id, and the answer's shape. It reads; it changes nothing */
export function prompt(g: Contract, dir: string): string {
const rules = saysOf(g).map((r) => `- ${r.id}: ${r.says}`)
export function prompt(g: Contract, dir: string, only: Said[] = saysOf(g)): string {
const rules = only.map((r) => `- ${r.id}: ${r.says}`)
return `You are a fresh critic. You did none of this work and owe it nothing. The work is in ${dir}: read whatever you need there (its files, its renders, NOTES.md), and change nothing.\n\nThe goal, as the person said it: ${g.aim ?? nameOf(g)}\n\nFor each rule below, decide whether it is true of the work as it is on disk now. Count it true only when you have seen it hold; if you can't tell, it isn't true yet. Say why in one sentence, naming what you looked at.\n\n${rules.join("\n")}\n\nAnswer last with one JSON object and nothing after it: {"rules": {"ID": {"pass": true, "why": "..."}}}`
}
@@ -124,11 +134,15 @@ export function lastVerdict(text: string): Verdict | null {
return null
}
export const BY = ["claude", "kimi", "clef"] as const
/** the critic when none is named: clef where an agent key is set (a raea cloud box, whose shell has no Claude
* sign-in: 12-01, every judging there answered "Not logged in"), else Claude Code */
export const critic = () => (process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? "clef" : "claude")
/** where a rule is judged, chosen here and never by the agent (Shane, 12-03): a rule with a piece to watch or hear
* (a file it names, or the videos under out/) by Clef-Omni; any other by a fresh session of the agent this project
* runs on, which the host that started the agent offers as RAEA_JUDGE_URL (raea cloud's box, critic.ts; the raea app) */
const criticUrl = () => process.env.RAEA_JUDGE_URL || null
export const NO_CRITIC = "it's judged by a fresh session of the agent this project runs on, which only an agent session the raea app or raea cloud started has: it's judged when that session checks the goal"
/** whether every rule here can be judged in this session */
export function hasCritic(dir: string, rules: Said[]): boolean {
return !!criticUrl() || rules.every((r) => piecesOf(r, dir).length > 0)
}
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
@@ -148,13 +162,31 @@ function made(dir: string): string[] {
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["rules"] {
const all = made(dir)
/** the pieces a rule is about: the files it names that are on disk, else the newest videos under out/ */
function piecesOf(r: Said, dir: string): string[] {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
return named.length ? named : made(dir).slice(0, CLEF_PIECES)
}
/** how many `raea ask`s run at once: each is one cut (or one stretch of it) heard and watched; one after another, a
* project's beats took 6-17 minutes of every goal check (12-03, StreetTalk: 18 of them, a cut's beats each a stretch) */
export const CLEF_AT_ONCE = 6
/** `f` on each item, at most `n` at once, the answers in the items' order */
async function pool<T, R>(items: T[], n: number, f: (t: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length)
let next = 0
const worker = async () => {
for (let i = next++; i < items.length; i = next++) out[i] = await f(items[i])
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker))
return out
}
export async function clefVerdict(g: Contract, dir: string, ask: Ask = askClef, only: Said[] = saysOf(g)): Promise<Verdict["rules"]> {
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of saysOf(g)) {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
const files = named.length ? named : all.slice(0, CLEF_PIECES)
for (const r of only) {
const files = piecesOf(r, dir)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
@@ -165,47 +197,70 @@ export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["r
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
for (const k of groups.values()) {
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
const list = [...groups.values()]
const heard = await pool(list, CLEF_AT_ONCE, async (k) => ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to))
for (const [j, k] of list.entries()) {
const answers = heard[j]
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of saysOf(g)) {
for (const r of only) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "clef watches and hears a piece, and this rule names no file on disk while out/ holds no video: name the file in the rule, or judge it --by claude where Claude Code is signed in" }
? { pass: false, why: "it names no file on disk and out/ holds no video yet, so there's nothing to watch or hear" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
if (rows.length !== says.length) throw new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`)
return rows
type Ask = (dir: string, file: string, says: string[], from?: string, to?: string) => Answer[] | Promise<Answer[]>
/** `raea ask` on one file (or a stretch of it): run as a child, so several hear at once */
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Promise<Answer[]> {
return new Promise((ok, no) => {
const c = spawn(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, stdio: ["ignore", "pipe", "pipe"] })
let out = "", err = ""
c.stdout.setEncoding("utf8").on("data", (t: string) => (out += t))
c.stderr.setEncoding("utf8").on("data", (t: string) => (err = (err + t).slice(-4000)))
c.on("error", (e) => no(new Error(`couldn't run raea ask: ${e.message}`)))
c.on("close", () => {
const rows = out.split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
if (rows.length !== says.length) return no(new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${err.trim().slice(-300) || out.trim().slice(-300)}`))
ok(rows)
})
})
}
/** one fresh critic over a goal's `says` rules (`raea goal judge`): its verdict kept at review/judge/NAME.json,
* stamped with when it was asked (so work changed while it judged counts as changed after) */
export function judge(g: Contract, dir: string, by: string): Verdict {
if (!saysOf(g).length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
/** the goal's `says` rules judged (`raea goal check` asks this itself; `raea goal judge` too): each where it's judged
* (criticUrl above), its verdict kept at review/judge/NAME.json, stamped with when it was asked (so work changed while
* it judged counts as changed after) */
export async function judge(g: Contract, dir: string, o: { ask?: typeof askClef; agent?: (cwd: string, prompt: string) => Promise<string> } = {}): Promise<Verdict> {
const all = saysOf(g)
if (!all.length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
const asked = Math.floor(Date.now() / 1000)
if (by === "clef") return keep(g, dir, { at: asked, by, goal: g.aim ?? nameOf(g), rules: clefVerdict(g, dir) })
const p = prompt(g, dir)
const r = by === "claude" ? spawnSync("claude", ["-p", p, "--allowedTools", "Read Grep Glob", "--output-format", "json"], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) : spawnSync("kimi", ["-p", p], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`)
let words = String(r.stdout ?? "")
try {
const o = JSON.parse(words)
if (typeof o.result === "string") words = o.result
} catch {}
const v = lastVerdict(words)
if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`)
return keep(g, dir, { ...v, at: asked, by, goal: g.aim ?? nameOf(g) })
const watched = all.filter((r) => piecesOf(r, dir).length > 0)
const read = all.filter((r) => !watched.includes(r))
// what's watched and heard, and what's read, at once: neither waits on the other
const [heard, said] = await Promise.all([
watched.length ? clefVerdict(g, dir, o.ask ?? askClef, watched) : Promise.resolve({} as Verdict["rules"]),
read.length ? (o.agent ?? askAgent)(dir, prompt(g, dir, read)) : Promise.resolve(null),
])
const rules: Verdict["rules"] = { ...heard }
if (said !== null) {
const v = lastVerdict(said)
if (!v) throw new Error(`the critic gave no verdict: ${said.slice(-300).trim()}`)
for (const r of read) rules[r.id] = v.rules?.[r.id] ?? { pass: false, why: "the critic didn't answer this rule" }
}
return keep(g, dir, { at: asked, by: [watched.length ? "clef" : "", read.length ? "agent" : ""].filter(Boolean).join("+"), goal: g.aim ?? nameOf(g), rules })
}
/** a fresh session of this project's own agent, through the host that started it (RAEA_JUDGE_URL): what it says */
async function askAgent(cwd: string, p: string): Promise<string> {
const url = criticUrl()
if (!url) throw new Error(NO_CRITIC)
const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${process.env.RAEA_JUDGE_TOKEN ?? ""}` }, body: JSON.stringify({ cwd, prompt: p }), signal: AbortSignal.timeout(15 * 60_000) })
const j = (await r.json().catch(() => ({}))) as { text?: string; error?: string }
if (!r.ok || typeof j.text !== "string") throw new Error(j.error ?? `the critic answered ${r.status}`)
return j.text
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g))
+1 -1
View File
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
import type { Beat } from "raea/brief.gen"
import type { CutBeat as Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts"
import { type Faces, Unmet } from "../media.ts"
import { cutOf } from "./cut.ts"
+2 -2
View File
@@ -294,9 +294,9 @@ export function placeReport(file: string, scenes: Scene[], size: [number, number
}
export default check<FileFacts>(
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
async (f) => {
if (!f.made || f.kind !== "video" || !f.manifest?.frames?.length) return
if (!f.made || (f.kind !== "video" && !f.plan) || !f.manifest?.frames?.length) return
const { scenes } = await f.scene()
for (const x of textOver(f.manifest, scenes, RATE)) found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
},
+9 -5
View File
@@ -11,7 +11,8 @@
// editor holds (and the skill's end card rule: few words, held long enough).
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { RATE, type Word } from "../media.ts"
import { samples, textFrames } from "../plan.ts"
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
export type Block = { text: string; words: number; from: number; to: number; size?: number }
@@ -105,11 +106,14 @@ export function reading(blocks: Block[]): Finding[] {
}
export default check<FileFacts>(
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!f.made || (f.kind !== "video" && !f.plan)) return
// a cut's plan (plan.ts): its own text as laid out (a sign in the footage isn't meant to be read); an export's,
// what the reader reads in it
const planned = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : null
const sc = planned ? { rate: RATE, scenes: [] } : await f.scene()
const frames: Frame[] = planned ?? sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = sc.rate || 2
const heard = await f.words()
+3 -2
View File
@@ -229,9 +229,10 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
}
export default check<FileFacts>(
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (f.kind !== "video" && f.kind !== "audio") return
// at edit only a cut's plan (plan.ts), whose clips are the export's
if (f.kind !== "video" && f.kind !== "audio" && !f.plan) return
if (!f.made) return
if (!f.manifest) {
if (f.moment !== "edit") found({ level: "note", says: `${path.basename(f.path)} has no render manifest beside it (FILE.render.json), so its edit points and levels aren't checked: render it with raea, which writes one` })
+475
View File
@@ -0,0 +1,475 @@
// A cut checked before it's drawn (12-04, round 22: every run missed its budget the same way, a full render of every cut
// and only then dozens of errors, fixed, and everything rendered again). `raea render EDIT.tsx --composition ID --plan
// -o OUT.plan.json` runs each frame through React and layout and gathers the sound, drawing nothing: its plan is a render
// manifest of every frame. `raea goal check --at edit --manifest OUT.plan.json EDIT.tsx` holds the plan to what can be
// known from it:
//
// floor its text clipped by the frame or in the app's UI zones, and up too briefly (apps/check/text's rules)
// frames text too small, and faces cut by the frame or a split screen's seam
// place text over a face, a person or what the shot is about
// sound clips cut inside a word or on sound, lines and effects at uneven levels (from each take's words and level)
// captions what's said with no caption over it, and a caption that isn't what's said there
// reading text up too briefly to read
//
// What the cut says is its voice clips' takes' words, laid where the clips put them. What its frames show is the scene of
// each SOURCE frame a video shows there (the farm's POST /v1/scene, as for an export), mapped through the video's box,
// fit and object-position into the cut's frame: the picture the render would draw, read without drawing it. Each
// source frame's reading is kept under review/scenes/, so a plan checked again asks only for frames it hasn't read.
// What only the export has (the words heard in the mix, its loudness, contrast, blotching) waits for --at render.
//
// A plan's errors stop the renders (raea cloud renders a batch only when every cut's plan passes), so on a plan an error
// is only what the plan knows as exactly as the export's check: floor's text rules, text too small, sound's edit points
// and levels. Place, captions, reading and faces cut by the edge are read from the source frames without the cut's own
// text over them, or held against the takes' words rather than the mix, and on round 22's Body Shop each cut had one
// such error the export's check didn't give (ON_PLAN_WARNS): on a plan they're warnings, and the render's check holds
// them. The plan holds its own cut alone: the project's checks and the goals' job checks (the count, the brief's quotes)
// don't run on it, and a check that can't run (the farm busy) waits instead of failing it.
import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import type { Clip, Manifest, ManifestVideo } from "./facts.ts"
import * as media from "./media.ts"
import type { Faces, Word } from "./media.ts"
import { busOf } from "./packs/sound.ts"
import type { Scene, Thing } from "./packs/place.ts"
/** a file a plan is checked for: a composition (the plan of one of its compositions) */
export const COMPOSITION = /\.(tsx|jsx|ts|js|mjs)$/i
/** the export a plan is of: OUT.plan.json (or OUT.render.json, OUT.manifest.json) is OUT's */
export const outOf = (plan: string) => media.stem(plan).replace(/\.(plan|render|manifest)$/i, "")
/** checks whose errors are warnings on a plan (frames' faces cut by the edge too, in frames.ts; its text sizes stay
* errors): each is read or heard otherwise than the export's check reads and hears it */
export const ON_PLAN_WARNS = new Set(["place", "captions", "reading"])
/** said after each error a plan tells and doesn't hold */
export const PLAN_SOFT = " (on the plan a warning: the render's check holds it)"
/** the width the scene reader reads a frame at (media.ts SIDE), so sizes are the export's */
const SIDE = 540
/** a grid cell's side, as the farm's scene reader makes them (540x960: 27x48) */
const CELL = 20
/** a video under this opacity is fading: what's under it, or over it, is what's seen */
const SEEN = 0.5
/** a thing or a face with less than this share of it inside its video's visible box is out of the shot */
const VISIBLE = 0.25
/** a thing this much covered by a video drawn over it is hidden */
const HIDDEN = 0.75
type Rect = [number, number, number, number]
/** the times a plan's frames are read at: RATE a second, from 0 to its end */
export function samples(m: Manifest, rate = media.RATE): number[] {
const fps = Number(m.fps) || 30
const len = Number(m.length) || m.frames?.length || 0
const n = Math.max(0, Math.ceil((len / fps) * rate - 1e-9))
return Array.from({ length: n }, (_, i) => i / rate)
}
/** where a picture sw x sh is drawn in a video's box: its fit, then its object-position ([x px, x share of the free
* space, y px, y share], centred when unset); `native`: the picture's own size, for fit none and scale-down */
export function drawn(v: ManifestVideo, sw: number, sh: number, native: [number, number] = [sw, sh]): Rect {
const [bx, by, bw, bh] = v.box
let dw = bw
let dh = bh
const contain = Math.min(bw / sw, bh / sh)
const fit = v.fit ?? "fill"
if (fit === "cover" || fit === "contain" || fit === "scale-down" || fit === "none") {
const s = fit === "cover" ? Math.max(bw / sw, bh / sh) : fit === "contain" ? contain : fit === "none" ? native[0] / sw : Math.min(contain, native[0] / sw)
dw = sw * s
dh = sh * s
}
const p = v.position ?? [0, 0.5, 0, 0.5]
return [bx + p[0] + p[1] * (bw - dw), by + p[2] + p[3] * (bh - dh), dw, dh]
}
const meet = (a: Rect, b: Rect): Rect | null => {
const x0 = Math.max(a[0], b[0])
const y0 = Math.max(a[1], b[1])
const x1 = Math.min(a[0] + a[2], b[0] + b[2])
const y1 = Math.min(a[1] + a[3], b[1] + b[3])
return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null
}
const area = (r: Rect | null) => (r ? r[2] * r[3] : 0)
/** what a video shows in a frame: where its picture (`size`, as decoded: rotation applied) is drawn, what of it is seen
* in the frame (cut px), and that part of the picture as shares of it ([x, y, w, h], the `crop` read for its scene) */
export type Layer = { v: ManifestVideo; size: [number, number]; draw: Rect; seen: Rect; crop: Rect }
/** the videos a frame shows, bottom first: each drawn by its box, fit and position, cut to what its box (and the box
* clipping it) leaves showing in the frame. A fading video (under SEEN) only when nothing else shows */
export function layersOf(videos: ManifestVideo[], W: number, H: number, sizeOf: (v: ManifestVideo) => [number, number] | null): Layer[] {
const frame: Rect = [0, 0, W, H]
const opaque = videos.filter((v) => (v.opacity ?? 1) >= SEEN)
const shown = opaque.length ? opaque : [...videos].sort((a, b) => (b.opacity ?? 1) - (a.opacity ?? 1)).slice(0, 1)
const out: Layer[] = []
for (const v of shown) {
if (!v.box || v.box.length < 4) continue
const size = sizeOf(v)
if (!size) continue
const seen = meet(meet(v.box as Rect, (v.clip as Rect | undefined) ?? frame) ?? [0, 0, 0, 0], frame)
if (!seen) continue
const draw = drawn(v, size[0], size[1], size)
const round = (x: number) => Math.round(x * 1000) / 1000
const x0 = Math.max(0, (seen[0] - draw[0]) / draw[2])
const y0 = Math.max(0, (seen[1] - draw[1]) / draw[3])
const x1 = Math.min(1, (seen[0] + seen[2] - draw[0]) / draw[2])
const y1 = Math.min(1, (seen[1] + seen[3] - draw[1]) / draw[3])
if (x1 <= x0 || y1 <= y0) continue
out.push({ v, size, draw, seen, crop: [round(x0), round(y0), round(x1 - x0), round(y1 - y0)] })
}
return out
}
/** the scene read of the part of a source frame a layer shows (its crop, at the reader's size, as the export's reader
* sees it: a face half out of the shot is read as the export reads it) */
export type Source = { scene: NonNullable<Scene>; faces: NonNullable<Faces> }
/** what a frame of the cut shows, from the scenes of the parts of the source frames its videos show: each one's things,
* faces and person mask mapped through its crop and its drawn box into the cut's frame (SIDE wide), and hidden where a
* video is drawn over it. A video's edge inside the frame is a seam (a split screen, a picture in a picture). Null
* when no video shows there */
export function compose(all: Layer[], W: number, H: number, sourceOf: (l: Layer) => Source | null): { scene: Scene; faces: Faces } {
const k = SIDE / Math.min(W, H)
const w = Math.round(W * k)
const h = Math.round(H * k)
const layers = all.flatMap((l) => {
const src = sourceOf(l)
return src ? [{ ...l, src }] : []
})
if (!layers.length) return { scene: null, faces: null }
type Read = (typeof layers)[number]
// a box in a crop's scene, in the cut's pixels
const toCut = (l: Read, t: readonly unknown[]): Rect => {
const [x, y, bw, bh] = [0, 1, 2, 3].map((i) => Number(t[i]) || 0)
const sx = (v: number) => (l.crop[0] + (v / l.src.scene.w) * l.crop[2]) * l.draw[2]
const sy = (v: number) => (l.crop[1] + (v / l.src.scene.h) * l.crop[3]) * l.draw[3]
return [l.draw[0] + sx(x), l.draw[1] + sy(y), sx(x + bw) - sx(x), sy(y + bh) - sy(y)]
}
const scaled = (r: Rect): [number, number, number, number] => [r[0] * k, r[1] * k, r[2] * k, r[3] * k]
// what of a box is seen: inside its layer's visible box, and not hidden by a layer over it
const seenOf = (i: number, b: readonly unknown[]): Rect | null => {
const l = layers[i]
const r = toCut(l, b)
const vis = meet(r, l.seen)
if (!vis || area(vis) < VISIBLE * area(r)) return null
for (const o of layers.slice(i + 1)) if (area(meet(vis, o.seen)) >= HIDDEN * area(vis)) return null
return vis
}
const things: Thing[] = []
const faces: Thing[] = []
layers.forEach((l, i) => {
for (const t of l.src.scene.things) {
const r = seenOf(i, t)
if (r) things.push([...scaled(r), t[4], t[5]] as Thing)
}
for (const f of l.src.scene.faces) {
const r = seenOf(i, f)
if (r) faces.push([...scaled(r), "face", Number(f[5] ?? f[4]) || 0] as Thing)
}
})
// the person mask: each cell's centre, in the topmost layer that shows there, read from its crop's grid
const cols = Math.round(w / CELL)
const rows = Math.round(h / CELL)
const people: string[] = []
for (let r = 0; r < rows; r++) {
let line = ""
for (let c = 0; c < cols; c++) {
const x = ((c + 0.5) / cols) * W
const y = ((r + 0.5) / rows) * H
const l = layers.findLast((o) => x >= o.seen[0] && x < o.seen[0] + o.seen[2] && y >= o.seen[1] && y < o.seen[1] + o.seen[3])
if (!l) {
line += "0"
continue
}
const g = l.src.scene.grid
const sc = Math.floor((((x - l.draw[0]) / l.draw[2] - l.crop[0]) / l.crop[2]) * g.cols)
const sr = Math.floor((((y - l.draw[1]) / l.draw[3] - l.crop[1]) / l.crop[3]) * g.rows)
line += g.people[sr]?.[sc] ?? "0"
}
people.push(line)
}
// a video's edge inside the frame: a seam, where it shows over a good part of the frame's other side
const seams: media.Seam[] = []
for (const l of layers) {
const [x, y, sw, sh] = l.seen
if (sw >= W * 0.5) for (const e of [y, y + sh]) if (e > H * 0.02 && e < H * 0.98) seams.push(["h", Math.round(e * k), sw / W])
if (sh >= H * 0.5) for (const e of [x, x + sw]) if (e > W * 0.02 && e < W * 0.98) seams.push(["v", Math.round(e * k), sh / H])
}
const texts = layers.flatMap((l, i) => (l.src.scene.texts ?? []).flatMap((t) => {
const r = seenOf(i, t)
return r ? [[...scaled(r), t[4], t[5]] as [number, number, number, number, string, number]] : []
}))
return {
scene: { w, h, grid: { cols, rows, people }, things, faces, texts },
faces: { w, h, faces: faces.map((f) => [f[0], f[1], f[2], f[3], f[5]]), seams },
}
}
/** what a plan's cut says: each voice clip's take's words that fall inside it, laid where the clip puts them (a word
* the clip cuts into is said if most of it is inside; the sound pack holds the cut itself) */
export function said(clips: Clip[], fps: number, wordsOf: (src: string) => Word[] | null): Word[] {
const out: Word[] = []
for (const c of clips) {
if (busOf(c) !== "voice") continue
const ws = wordsOf(c.src)
if (!ws) continue
const a = c.at
const b = c.at + (c.to - c.from) / fps
for (const w of ws) {
const inside = Math.min(b, w.end) - Math.max(a, w.start)
// a word the clip cuts into is heard when much of it is in (a transcriber hears half a word)
if (inside <= 0 || inside < Math.min(0.12, 0.4 * Math.max(0.01, w.end - w.start))) continue
const shift = c.from / fps - a
out.push({ text: w.text, start: Math.max(c.from / fps, w.start + shift), end: Math.min(c.to / fps, w.end + shift) })
}
}
return out.sort((x, y) => x.start - y.start)
}
/** a plan's frames by number */
export function byFrame(m: Manifest): Map<number, NonNullable<Manifest["frames"]>[number]> {
return new Map((m.frames ?? []).map((f) => [Number(f.frame), f]))
}
type Line = [number, number, number, number, string, number]
/** a text laid out on `n` lines, as the reader reads it: a line each, its words shared out by their letters (where
* layout broke it isn't in the manifest, only how many lines it made) */
export function linesOf(text: string, b: number[], n: number): Line[] {
const words = text.split(/\s+/).filter(Boolean)
if (n <= 1 || words.length < 2) return [[b[0], b[1], b[2], b[3], text, 1]]
const k = Math.min(n, words.length)
const total = words.reduce((s, w) => s + w.length + 1, 0)
const parts: string[][] = Array.from({ length: k }, () => [])
let at = 0
for (const w of words) {
// each word on the line its middle letter falls on
parts[Math.min(k - 1, Math.floor(((at + w.length / 2) / total) * k))].push(w)
at += w.length + 1
}
return parts.flatMap((p, l) => (p.length ? [[b[0], b[1] + (b[3] * l) / k, b[2], b[3] / k, p.join(" "), 1] as Line] : []))
}
/** the frame nearest a time, and the text it shows, as the scene reader would read lines: [x, y, w, h, text, score] in
* the pixels of a frame `h` high, a text laid out on several lines a line each */
export function textFrames(m: Manifest, at: number[]): { h: number; lines: Line[] }[] {
const fps = Number(m.fps) || 30
const H = Number(m.height) || 1920
const frames = byFrame(m)
return at.map((t) => {
const fr = frames.get(Math.round(t * fps))
const lines = (fr?.text ?? []).filter((x) => (x.opacity ?? 1) > 0.3 && String(x.text ?? "").trim()).flatMap((x) => linesOf(String(x.text).trim(), (x.ink ?? x.box ?? [0, 0, 0, 0]) as number[], Number(x.lines) || 1))
return { h: H, lines }
})
}
/** a frame's opaque fills over the whole frame: a cut's backgrounds are on every frame, so a frame with more than the
* fewest any frame with a video has holds a card over its videos (an end card), which hides them. (The manifest says
* where a fill is, not whether it's over a video or under it.) */
const covers = (fr: NonNullable<Manifest["frames"]>[number] | undefined, W: number, H: number) =>
(fr?.pictures ?? []).filter((p) => (p.opacity ?? 1) >= 0.9 && p.box && p.box[0] <= 1 && p.box[1] <= 1 && p.box[0] + p.box[2] >= W - 1 && p.box[1] + p.box[3] >= H - 1).length
// ---- the source frames' scenes, read by the farm and kept ------------------------------------------------------------
type Kept = { stamp: string; side: number; at: Record<string, Source> }
/** a read's key in a source's keeping: its second and its crop */
export const readKey = (at: number, crop: Rect) => `${at.toFixed(2)} ${crop.join(",")}`
type Want = { file: string; at: number; crop: Rect }
/** parts of source frames read for a plan, each (file, second, crop) once: from review/scenes/ when read before, else
* extracted (several ffmpeg at once where there's a shell) and read by the farm. Unmet when there's no farm here */
export async function sourceScenes(root: string, wants: Want[]): Promise<Map<string, Source>> {
const out = new Map<string, Source>()
const byFile = new Map<string, Map<string, Want>>()
for (const w of wants) byFile.set(w.file, (byFile.get(w.file) ?? new Map()).set(readKey(w.at, w.crop), w))
const dir = path.join(root, "review", "scenes")
for (const [file, mine] of byFile) {
const st = statSync(file)
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
const keep = path.join(dir, `${path.basename(file)}.json`)
let kept: Kept = { stamp, side: SIDE, at: {} }
try {
const k = JSON.parse(readFileSync(keep, "utf8")) as Kept
if (k.stamp === stamp && k.side === SIDE) kept = k
} catch {}
const need = [...mine.entries()].filter(([k]) => !kept.at[k])
if (need.length) {
const read = await readAt(file, need.map(([, w]) => w))
need.forEach(([k], i) => {
const s = read.scenes[i]
const f = read.faces[i]
if (s && f) kept.at[k] = { scene: s, faces: f }
})
try {
mkdirSync(dir, { recursive: true })
// read again just before writing: a plan of another cut may have read other frames of the same file meanwhile
try {
const now = JSON.parse(readFileSync(keep, "utf8")) as Kept
if (now.stamp === stamp && now.side === SIDE) kept.at = { ...now.at, ...kept.at }
} catch {}
const tmp = `${keep}.${process.pid}.tmp`
writeFileSync(tmp, JSON.stringify(kept))
renameSync(tmp, keep)
} catch {}
}
for (const k of mine.keys()) if (kept.at[k]) out.set(`${file}@${k}`, kept.at[k])
}
return out
}
/** parts of a file's frames (a second and a crop, in shares of the picture), read by the farm's scene reader at the
* reader's size, as the export's reader reads that part of the cut's frame */
async function readAt(file: string, wants: Want[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
if (!process.env.RAEA_CLOUD_GPU_URL) throw new media.Unmet(`no scene reader on this machine for ${path.basename(file)}'s frames (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-plan-"))
try {
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
const jpgs = wants.map((_, i) => path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`))
const one = (w: Want, i: number) => {
const [x, y, cw, ch] = w.crop
const crop = `crop=iw*${cw}:ih*${ch}:iw*${x}:ih*${y}`
return ["-v", "error", "-y", "-ss", w.at.toFixed(3), "-i", file, "-frames:v", "1", "-vf", `${crop},${scale}`, "-q:v", "4", jpgs[i]]
}
if (process.platform !== "win32" && spawnSync("ffmpeg", ["-version"], { encoding: "utf8" }).status === 0) {
// eight at a time through the shell: this runtime has only spawnSync, and a plan reads 60-80 frames
const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
const lines = wants.map((w, i) => `ffmpeg ${one(w, i).map(q).join(" ")} &${(i + 1) % 8 === 0 ? "\nwait" : ""}`)
spawnSync("sh", ["-c", `${lines.join("\n")}\nwait`], { encoding: "utf8", maxBuffer: 1 << 24 })
}
wants.forEach((w, i) => {
if (!existsSync(jpgs[i])) media.ffmpeg(one(w, i))
})
return await media.readScenes(jpgs.map((j) => (existsSync(j) ? readFileSync(j) : null)))
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** a video file's picture as decoded: its width and height, swapped when it's stored rotated a quarter turn */
export function pictureOf(file: string): [number, number] | null {
const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_tags=rotate:stream_side_data=rotation", "-of", "json", file], { encoding: "utf8" })
try {
const s = JSON.parse(r.stdout ?? "").streams?.[0]
if (s?.width) {
const rot = Math.abs(Number(s.tags?.rotate ?? s.side_data_list?.find((d: { rotation?: number }) => d.rotation !== undefined)?.rotation ?? 0)) % 180
return rot === 90 ? [s.height, s.width] : [s.width, s.height]
}
} catch {}
const sh = media.shape(file)
return sh ? [sh.width, sh.height] : null
}
/** the scenes of a plan's frames, RATE a second: each composed from the parts of its videos' source frames it shows
* (`file`: a source on this machine, or null) */
export async function planScene(root: string, m: Manifest, file: (src: string) => string | null): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
const W = Number(m.width) || 1080
const H = Number(m.height) || 1920
const fps = Number(m.fps) || 30
const at = samples(m)
const frames = byFrame(m)
const withVideo = [...frames.values()].filter((f) => f.videos?.length)
const backgrounds = withVideo.length ? Math.min(...withVideo.map((f) => covers(f, W, H))) : 0
const missing = new Set<string>()
const sizes = new Map<string, [number, number] | null>()
const sizeOf = (v: ManifestVideo) => {
const f = file(v.src)
if (!f) {
missing.add(v.src)
return null
}
if (!sizes.has(f)) sizes.set(f, pictureOf(f))
return sizes.get(f) ?? null
}
const shows = at.map((t) => {
const fr = frames.get(Math.round(t * fps))
return covers(fr, W, H) > backgrounds ? [] : layersOf((fr?.videos ?? []) as ManifestVideo[], W, H, sizeOf)
})
const wants = shows.flatMap((ls) => ls.map((l) => ({ file: file(l.v.src)!, at: l.v.at, crop: l.crop })))
if (!wants.length && missing.size) throw new media.Unmet(`the plan's videos aren't on this machine (${[...missing].slice(0, 3).join(", ")}), so what its frames show can't be read`)
const read = await sourceScenes(root, wants)
const out = shows.map((ls) => compose(ls, W, H, (l) => read.get(`${file(l.v.src)}@${readKey(l.v.at, l.crop)}`) ?? null))
return { rate: media.RATE, faces: out.map((o) => o.faces), scenes: out.map((o) => o.scene) }
}
// ---- the floor's text rules, from the plan (apps/check/text's text_runs and text_rules) --------------------------------
export type Run = { text: string; from: number; to: number; box: Rect; boxes: Rect[]; size: number }
/** a text as it stays on screen, from the frame it comes on to the frame it leaves; typing (a text growing into the next)
* and counting (only its digits changing) are one run, judged by its last text */
export function textRuns(m: Manifest): Run[] {
const fps = Number(m.fps) || 30
const key = (s: string) => s.replace(/[0-9]/g, "").trim().toLowerCase()
let open: Run[] = []
const done: Run[] = []
for (const f of [...(m.frames ?? [])].sort((a, b) => a.frame - b.frame)) {
const t = Number(f.frame) / fps
const next: Run[] = []
for (const x of f.text ?? []) {
const text = String(x.text ?? "").trim()
if ((x.opacity ?? 1) <= 0.05 || !text) continue
const quad = (b?: number[]): Rect | null => (b ? [0, 1, 2, 3].map((i) => Number(b[i]) || 0) as Rect : null)
const b = quad(x.box) ?? [0, 0, 0, 0]
const ink = quad(x.ink)
const k = key(text)
const i = open.findIndex((r) => {
const rk = key(r.text)
return rk === k || (rk !== "" && k.startsWith(rk)) || (k !== "" && rk.startsWith(k) && k.length * 2 > rk.length)
})
const r: Run = i >= 0 ? open.splice(i, 1)[0] : { text, from: t, to: t, box: b, boxes: [], size: 0 }
if (text.length > r.text.length) r.boxes = []
if (text.length >= r.text.length) {
r.text = text
r.box = b
r.boxes.push(ink ?? b)
}
r.to = t + 1 / fps
r.size = Number(x.size) || 0
next.push(r)
}
done.push(...open)
open = next
}
done.push(...open)
return done.sort((a, b) => a.from - b.from)
}
/** the zones where text can't go, [top, right, bottom, left] at the frame's width (apps/check/text zones(): default) */
export function zones(w: number, h: number): [number, number, number, number] {
const r = w / h
const z: [number, number, number, number] | null = r < 0.7 ? [220, 140, 420, 60] : r < 0.9 ? [110, 60, 170, 60] : r < 1.2 ? [70, 60, 120, 60] : null
if (!z) return [(120 * h) / 1080, (60 * w) / 1920, (120 * h) / 1080, (60 * w) / 1920]
return z.map((v) => (v * w) / 1080) as [number, number, number, number]
}
const quote = (s: string) => `“${[...s].slice(0, 40).join("")}”`
/** what `raea check` says of a render's text from its manifest: clipped off the frame (an error), in the app's UI zones
* (an error), up too briefly to read (a warning, the reading pack holds it to its words) */
export function textRules(m: Manifest): { level: "error" | "warn"; rule: string; at: number; says: string }[] {
const w = Number(m.width) || 1080
const h = Number(m.height) || 1920
const [zt, zr, zb, zl] = zones(w, h)
const out: { level: "error" | "warn"; rule: string; at: number; says: string }[] = []
for (const r of textRuns(m)) {
const [x, y, bw, bh] = r.box
const q = quote(r.text)
const boxes = r.boxes.length ? r.boxes : [r.box]
const off = ([x, y, bw, bh]: Rect) => x < -1 || y < -1 || x + bw > w + 1 || y + bh > h + 1
const zoned = ([x, y, bw, bh]: Rect) => y < zt || x + bw > w - zr || y + bh > h - zb || x < zl
if (boxes.every(off)) out.push({ level: "error", rule: "clipped", at: r.from, says: `${q} runs off the frame (box ${x.toFixed(0)},${y.toFixed(0)} ${bw.toFixed(0)}x${bh.toFixed(0)} in ${w}x${h}); fit it or break the line` })
else if (boxes.every(zoned)) {
const [ix, iy, iw, ih] = boxes[boxes.length - 1]
const edge = iy < zt ? `the top (keep ${zt.toFixed(0)} px clear)` : iy + ih > h - zb ? `the bottom (keep ${zb.toFixed(0)} px clear)` : ix < zl ? `the left (keep ${zl.toFixed(0)} px clear)` : `the right (keep ${zr.toFixed(0)} px clear)`
out.push({ level: "error", rule: "safe-area", at: r.from, says: `${q} sits in the app's UI zone at ${edge}: its ${r.boxes.length && boxes[boxes.length - 1] !== r.box ? "letters" : "box"} ${ix.toFixed(0)},${iy.toFixed(0)} ${iw.toFixed(0)}x${ih.toFixed(0)} in ${w}x${h}` })
}
const words = r.text.split(/\s+/).filter(Boolean).length
const need = Math.max(1, 0.3 * words)
const held = r.to - r.from
if (held + 0.05 < need && r.size >= 24) out.push({ level: "warn", rule: "reading", at: r.from, says: `${q} is on for ${held.toFixed(1)} s; ${words} words need ${need.toFixed(1)} s to read` })
}
return out
}
/** the fix a UI-zone finding asks for, said once */
export const ZONE_FIX = "keep text inside the safe area: 220 px from the top, 420 px from the bottom, 140 px from the right and 60 px from the left of a 1080x1920 frame"
+60 -23
View File
@@ -3,6 +3,9 @@
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
//
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// (EDIT.tsx --at edit --manifest OUT.plan.json: one cut of the composition checked on its plan, `raea render
// --plan`, before it's drawn: plan.ts. Only that cut's file checks run, only what the plan knows exactly is an
// error, and a check that can't run waits, so exit 1 always names something in the cut to fix)
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
// `goal`, and with none, the floor (every made video looked at, its faces whole and its text big enough). The
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/.
@@ -13,18 +16,19 @@
// says what for; it holds nothing.
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
// raea goal judge [--goal NAME] [--by claude|kimi|clef] a fresh critic over a goal's `says` rules (review/judge/)
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, saysOf, unknownPacks } from "./contract.ts"
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import { fileFacts, type FileFacts, type Job, kindOf, planFacts, runIn } from "./facts.ts"
import { COMPOSITION, ON_PLAN_WARNS, PLAN_SOFT } from "./plan.ts"
import * as media from "./media.ts"
import { registeredPack } from "./packs/job.ts"
import { tastePack } from "./packs/taste.ts"
import { loadProject, type Project } from "./project.ts"
import { critic, judge } from "./packs/goal.ts"
import { judge } from "./packs/goal.ts"
import { PACK_CHECKS } from "./packs/index.ts"
import { second } from "./packs/look.ts"
import { deliverablesOf } from "./packs/job.ts"
@@ -137,13 +141,22 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const broke: Report["broke"] = []
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
const fps = file?.fps ?? 30
for (const x of r.findings)
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
for (const x of r.findings) {
// on a plan, what's read from the source frames or held against the takes' words is told, not held (ON_PLAN_WARNS)
const soft = file?.plan && x.level === "error" && ON_PLAN_WARNS.has(x.check)
findings.push({ goal, check: x.check, level: soft ? "warn" : x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: soft ? `${x.says}${PLAN_SOFT}` : x.says, fix: x.fix, by: x.by })
}
// on a plan, a check that couldn't run (the farm busy or down, a frame that wouldn't extract) waits: nothing in the
// cut to fix, and the render's own check runs it again
for (const t of r.threw) (t.waits || file?.plan ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.waits || !file?.plan ? t.says : `couldn't check the plan, so the render's check holds it: ${t.says}` })
}
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
// a composition named with a manifest: one of its cuts checked on its plan (`raea render --plan`), before it's drawn
// (plan.ts). It holds that cut alone: the project's own checks and the goals' job checks (the count, the brief's
// quotes) are the render's and publish's to hold, never a reason not to draw one cut
const planned = cutPlan(o.manifest, named, cwd)
// the project's own: once, whatever its goals
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
const once = planned ? [] : ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
const verdicts: GoalVerdict[] = []
const allFiles = new Set<string>()
@@ -155,10 +168,16 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
: at === "publish" || at === "done"
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
: []
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
const checks = checksOf(contract, at, o.only)
// a cut's plan (above), else a render's manifest kept away from its export (`raea render --manifest M`): the one
// file named reads it
const files: FileFacts[] = planned
? [planFacts(planned.manifest, planned.abs, root, at, contract)]
: wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
if (o.manifest && !planned && files.length === 1) {
files[0].manifest = JSON.parse(readFileSync(path.resolve(cwd, o.manifest), "utf8")) as FileFacts["manifest"]
files[0].fps = files[0].manifest?.fps ?? files[0].fps
}
const checks = checksOf(contract, at, o.only).filter((c) => !planned || c.over !== "job")
const before = findings.length
const brokeBefore = broke.length
const j = job(contract, deliverables, files)
@@ -191,16 +210,32 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
}
}
/** a composition's plan: `--manifest` naming a plan (or any manifest) with one composition named */
export function cutPlan(manifest: string | undefined, named: string[], cwd = process.cwd()): { abs: string; manifest: FileFacts["manifest"] & object } | null {
if (!manifest || named.length !== 1 || !COMPOSITION.test(named[0])) return null
const abs = path.resolve(cwd, manifest)
return { abs, manifest: JSON.parse(readFileSync(abs, "utf8")) }
}
/** written whole or not at all: plans of several cuts are checked at once, each writing review/goal.json */
const writeWhole = (p: string, text: string) => {
const tmp = `${p}.${process.pid}.tmp`
writeFileSync(tmp, text)
renameSync(tmp, p)
}
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
* each file named */
export function writeReport(r: Report, named: string[]) {
* each file named (a plan's beside the plan: OUT.plan.check.json) */
export function writeReport(r: Report, named: string[], plan?: string) {
const dir = path.join(r.root, "review")
mkdirSync(dir, { recursive: true })
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) {
writeWhole(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
const one = (f: string, out: string) => {
const mine = r.findings.filter((x) => x.file === f)
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
writeWhole(out, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
}
for (const f of named) one(f, `${media.stem(path.join(r.root, f))}.check.json`)
if (plan) for (const f of r.files) one(f, `${media.stem(plan)}.check.json`)
}
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
@@ -226,11 +261,12 @@ function flag(a: string[], name: string): string | undefined {
}
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
raea goal check EDIT.tsx --at edit --manifest OUT.plan.json (a cut checked on its plan, raea render --plan, before it's drawn)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
raea goal judge [--goal NAME] [--by claude|kimi|clef]
raea goal judge [--goal NAME]
raea make place FILE [--at S[,S...]] [--box WxH]`
export async function main(argv: string[]): Promise<number> {
@@ -249,7 +285,8 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal check: ${(e as Error).message}`)
return 2
}
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
const plan = cutPlan(flag(a, "--manifest"), files.map((n) => path.relative(r.root, path.resolve(n))))
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))), plan?.abs)
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
return r.passed ? 0 : 1
}
@@ -260,8 +297,8 @@ export async function main(argv: string[]): Promise<number> {
if (!said?.trim()) {
const sheet = media.sheet(path.resolve(file))
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
// on raea cloud (where the critic is clef), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && critic() === "clef" ? second(path.resolve(file)) : null
// on raea cloud (where Clef-Omni is paid for), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? second(path.resolve(file)) : null
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
return 0
@@ -312,7 +349,7 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal judge: ${!root ? "no brief.ts here or above" : !said.length ? `no goal${name ? ` named ${name}` : ""} here has \`says\` rules` : `several goals have \`says\` rules (${said.map(nameOf).join(", ")}): name one with --goal`}`)
return 2
}
const v = judge(said[0], root, flag(a, "--by") ?? critic())
const v = await judge(said[0], root)
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
return 0
}
+80 -5
View File
@@ -4,7 +4,7 @@ import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
import { clefVerdict, judge, lastVerdict, NO_CRITIC, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts"
@@ -30,7 +30,8 @@ test("words need a fresh critic", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
put(d, "work.txt", "the work")
const says = async () => (await goalCheck({ cwd: d })).findings.filter((x) => x.check === "says")
expect((await says())[0].fix).toBe("raea goal judge")
// no critic in this session: it says so, and names no tool or agent to run
expect((await says())[0].fix).toBe(NO_CRITIC)
const later = Math.floor(Date.now() / 1000) + 5
mkdirSync(path.join(d, "review/judge"), { recursive: true })
writeFileSync(path.join(d, VERDICT), JSON.stringify({ at: later, by: "claude", rules: { friendly: { pass: true, why: "it says hello warmly" } } }))
@@ -43,6 +44,63 @@ test("words need a fresh critic", async () => {
expect((await says())[0].says).toContain("it is curt")
})
test("the check asks this session's critic itself", async () => {
const d = project(goal([{ id: "friendly", says: "the reply is friendly" }]))
put(d, "work.txt", "the work")
const heard: { auth: string | null; cwd: string; prompt: string }[] = []
const server = Bun.serve({
port: 0,
async fetch(req) {
const b = (await req.json()) as { cwd: string; prompt: string }
heard.push({ auth: req.headers.get("authorization"), ...b })
return Response.json({ text: 'thinking... {"rules": {"friendly": {"pass": true, "why": "it says hello warmly"}}}' })
},
})
process.env.RAEA_JUDGE_URL = `http://127.0.0.1:${server.port}/host/judge`
process.env.RAEA_JUDGE_TOKEN = "t0k"
try {
const r = await goalCheck({ cwd: d })
expect(r.findings.filter((x) => x.check === "says")).toEqual([])
expect(heard).toHaveLength(1)
expect(heard[0].auth).toBe("Bearer t0k")
expect(heard[0].prompt).toContain("friendly: the reply is friendly")
// judged once: a second check reads the kept verdict
await goalCheck({ cwd: d })
expect(heard).toHaveLength(1)
} finally {
delete process.env.RAEA_JUDGE_URL
delete process.env.RAEA_JUDGE_TOKEN
server.stop(true)
}
})
test("a rule with a piece to watch goes to clef, any other to the agent", async () => {
const g = goal([
{ id: "plan", says: "plan.md names every cut" },
{ id: "cut", says: "out/a.mp4 opens on the hook" },
])
const d = project(g)
put(d, "out/a.mp4", "video")
const clefAsked: string[] = []
const agentAsked: string[] = []
const v = await judge(g as never, d, {
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}}}'),
})
// out/ holds a video, so both are about a piece: clef judges both, and nothing asks the agent
expect(agentAsked).toEqual([])
expect(Object.keys(v.rules).sort()).toEqual(["cut", "plan"])
const bare = project(g)
const v2 = await judge(g as never, bare, {
ask: (_dir, file, says) => (clefAsked.push(file), says.map(() => ({ choice: "true" }))),
agent: async (_cwd, p) => (agentAsked.push(p), '{"rules": {"plan": {"pass": false, "why": "cut 3 is missing"}, "cut": {"pass": false, "why": "no cut yet"}}}'),
})
expect(agentAsked).toHaveLength(1)
expect(agentAsked[0]).toContain("plan: plan.md names every cut")
expect(v2.rules.plan?.why).toBe("cut 3 is missing")
expect(v2.by).toBe("agent")
})
test("file rules are deliverables", async () => {
const d = project(goal([{ id: "export", file: "out/final.txt" }]))
expect((await goalCheck({ cwd: d })).findings.map((x) => [x.check, x.says])).toEqual([["deliverables", "missing: out/final.txt"]])
@@ -63,13 +121,13 @@ test("a check runs only at its moments", async () => {
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
})
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", () => {
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x")
const g = { name: "rules", rules: [{ id: "named", says: "In out/cuts/a_9x16.mp4, from 0 s to 3 s, the host is speaking" }, { id: "all", says: "No caption covers a face" }] } as never
const asked: string[] = []
const rules = clefVerdict(g, d, (_dir, file, says, from, to) => {
const rules = await clefVerdict(g, d, (_dir, file, says, from, to) => {
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
})
@@ -78,7 +136,7 @@ test("clef judges a rule on the file it names, else on every video made, and say
expect(rules.all?.pass).toBe(false)
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
expect((await clefVerdict(g, empty, () => [])).all?.why).toContain("names no file on disk")
})
test("a reading kept beside a file isn't the work changing", () => {
@@ -92,3 +150,20 @@ test("a reading kept beside a file isn't the work changing", () => {
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
expect(newest(d)!).toBeGreaterThan(1_000_000)
})
test("clef hears several cuts at once, and the critic reads while it does", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-at-once-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const names = ["a", "b", "c", "d", "e", "f", "g", "h"]
for (const n of names) writeFileSync(path.join(d, `out/cuts/${n}_9x16.mp4`), "x")
const g = { name: "rules", rules: [{ id: "seen", says: "No caption covers a face" }] } as never
let now = 0, most = 0
const rules = await clefVerdict(g, d, async (_dir, _file, says) => {
most = Math.max(most, ++now)
await new Promise((ok) => setTimeout(ok, 20))
now--
return says.map(() => ({ choice: "true", says: "fine" }))
})
expect(most).toBe(6)
expect(rules.seen?.pass).toBe(true)
})
+201
View File
@@ -0,0 +1,201 @@
// A cut checked on its plan before it's drawn (src/plan.ts): what its frames show read from its sources' frames, what it
// says from its takes' words, and the floor's text rules on every frame
import { expect, test } from "bun:test"
import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { type Answer, useSender } from "../src/media.ts"
import { compose, drawn, layersOf, linesOf, PLAN_SOFT, said, samples, textRules, textRuns } from "../src/plan.ts"
import { goalCheck, text, writeReport } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
const full = (over: Record<string, unknown> = {}) => ({ src: "a.mp4", at: 1, box: [0, 0, 1080, 1920], fit: "cover", ...over })
test("a video is drawn by its fit and object-position, and what of it the frame shows is its crop", () => {
// a 16:9 picture covering a 9:16 frame, centred: 3413 px wide, 1167 px of it off each side
const c = drawn(full(), 1920, 1080)
expect(c.map(Math.round)).toEqual([-1167, 0, 3413, 1920])
// object-position 76% across (as `position: [0, 0.76, 0, 0.5]` says it)
expect(Math.round(drawn(full({ position: [0, 0.76, 0, 0.5] }), 1920, 1080)[0])).toBe(Math.round(0.76 * (1080 - 3413.33)))
// contain letterboxes it; fill stretches it
expect(drawn(full({ fit: "contain" }), 1920, 1080).map(Math.round)).toEqual([0, 656, 1080, 608])
expect(drawn(full({ fit: "fill" }), 1920, 1080)).toEqual([0, 0, 1080, 1920])
const [l] = layersOf([full() as never], 1080, 1920, () => [1920, 1080])
expect(l.crop).toEqual([0.342, 0, 0.316, 1])
// a box clipped by its parent (`clip`) shows only that part of it
const [h] = layersOf([full({ box: [-566, 0, 4096, 2304], clip: [0, 0, 1080, 1920] }) as never], 1080, 1920, () => [3840, 2160])
expect(h.seen).toEqual([0, 0, 1080, 1920])
expect(h.crop[3]).toBeCloseTo(1920 / 2304, 3)
// a fading video is left out while another shows; alone it's what's seen
expect(layersOf([full() as never, full({ opacity: 0.2 }) as never], 1080, 1920, () => [1920, 1080])).toHaveLength(1)
})
test("a source's scene, read of its crop, lands in the cut's frame: a face at the crop's edge is a face at the frame's", () => {
// the reader read the crop (304x540 of a 960x540 picture) at 540 wide: a face touching its right edge, a person
const scene = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array.from({ length: 48 }, (_, r) => (r > 20 ? "7".repeat(27) : "0".repeat(27))) }, things: [[100, 300, 300, 660, "person", 0.9]], faces: [[480, 200, 60, 80, "face", 0.9]] }
const faces = { w: 540, h: 960, faces: [[480, 200, 60, 80, 0.9]] }
const ls = layersOf([full() as never], 1080, 1920, () => [960, 540])
const out = compose(ls, 1080, 1920, () => ({ scene, faces }) as never)
expect(out.scene?.w).toBe(540)
const [x, y, w, h] = out.faces!.faces[0]
expect(Math.round(x + w)).toBe(540)
expect([Math.round(y), Math.round(h)]).toEqual([200, 80])
expect(out.scene!.grid.people[30]).toBe("7".repeat(27))
expect(out.scene!.things[0][4]).toBe("person")
// a video drawn over the bottom half hides what's under it there, and its top edge is a seam
const two = layersOf([full() as never, full({ box: [0, 960, 1080, 960] }) as never], 1080, 1920, () => [960, 540])
const low = { ...scene, things: [[100, 600, 300, 300, "dog", 0.9]] }
const o2 = compose(two, 1080, 1920, (l) => (l.v.box[1] ? ({ scene: { ...scene, things: [], faces: [] }, faces: { ...faces, faces: [] } } as never) : ({ scene: low, faces } as never)))
expect(o2.faces!.seams).toContainEqual(["h", 480, 1])
expect(o2.scene!.things).toEqual([])
})
test("what a plan's cut says is its voice clips' takes' words, where the clips put them", () => {
const take = [{ text: "one", start: 10, end: 10.4 }, { text: "two", start: 10.5, end: 10.9 }, { text: "three", start: 11, end: 11.5 }, { text: "four", start: 11.6, end: 12 }]
// frames 30-75 at 30 fps (1.0-2.5 s) show the take from 10.45 s: "one" is out, "three" whole, "four" cut a little
const w = said([{ from: 30, to: 75, src: "media/take.mp4", at: 10.45 }], 30, () => take)
expect(w.map((x) => x.text)).toEqual(["two", "three", "four"])
expect(w[0].start).toBeCloseTo(1.05, 5)
// music isn't speech
expect(said([{ from: 0, to: 30, src: "music/bed.mp3", at: 0 }], 30, () => take)).toEqual([])
})
test("the floor's text rules hold every frame of a plan: the UI zones, the frame's edges", () => {
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, text: [
{ text: "In the zone at the right", box: [100, 830, 900, 93], ink: [139, 830, 860, 93], size: 58 },
{ text: "Clear of everything", box: [200, 1000, 680, 93], size: 58 },
{ text: "Off the frame entirely here", box: [900, 1200, 600, 93], ink: [900, 1200, 600, 93], size: 58 },
] }))
const m = { width: 1080, height: 1920, fps: 30, length: 60, frames }
const r = textRules(m)
expect(r.map((x) => [x.rule, x.level])).toEqual([["safe-area", "error"], ["clipped", "error"]])
expect(r[0].says).toMatch(/sits in the app's UI zone at the right \(keep 140 px clear\)/)
// a typed text (growing into the next) is one run, judged by its last text
const typed = textRuns({ fps: 30, frames: ["Hel", "Hello", "Hello there"].map((t, f) => ({ frame: f, text: [{ text: t, box: [300, 900, 400, 80], size: 60 }] })) })
expect(typed.map((x) => x.text)).toEqual(["Hello there"])
expect(samples(m)).toEqual([0, 0.5, 1, 1.5])
// a text laid out on several lines is read a line each, as the export's reader reads it
expect(linesOf("Make your Wishlist and organize your Gift Exchange", [0, 100, 600, 200], 2).map((l) => l[4])).toEqual(["Make your Wishlist and", "organize your Gift Exchange"])
})
test("raea goal check --at edit --manifest PLAN EDIT.tsx: the cut's plan is checked, named for its export, before it's drawn", async () => {
const d = project(null)
put(d, "edit.tsx", "export default 1\n")
put(d, "media/take.mp4", readFileSync(CLIP))
const frames = Array.from({ length: 90 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Down in the bottom zone", box: [140, 1600, 800, 90], size: 60 }] }))
const plan = put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 90, plan: true, frames, sounds: { fps: 30, clips: [] } }))
// the farm's reader, standing in: every crop read has a face cut by its right edge
const before = process.env.RAEA_CLOUD_GPU_URL
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
let read = 0
useSender(async (_url, body): Promise<Answer> => {
const n = (JSON.parse(String(body)) as { frames: string[] }).frames.length
read += n
const g = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [[470, 300, 70, 120, "face", 0.9]], seams: [] }
return { status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(g) }) }
})
try {
const r = await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
const mine = r.findings.filter((x) => x.file === "out/cuts/ad_concept_v1_9x16.mp4")
expect(mine.some((x) => x.check === "floor" && x.level === "error" && /UI zone at the bottom/.test(x.says))).toBe(true)
// a face cut by the edge is read from the source frames: on a plan it's told, and the render's check holds it
expect(mine.some((x) => x.check === "frames" && x.level === "warn" && /right edge/.test(x.says) && x.says.endsWith(PLAN_SOFT))).toBe(true)
// only what the plan knows exactly holds it: floor, sound and text sizes
expect(mine.filter((x) => x.level === "error").every((x) => x.check === "floor" || x.check === "sound" || (x.check === "frames" && /px/.test(x.says)))).toBe(true)
expect(r.passed).toBe(false)
expect(read).toBe(6)
// each source frame's reading is kept: the plan checked again reads nothing
await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
expect(read).toBe(6)
writeReport(r, [], plan)
expect(existsSync(path.join(d, "out/cuts/ad_concept_v1_9x16.plan.check.json"))).toBe(true)
} finally {
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
else process.env.RAEA_CLOUD_GPU_URL = before
}
})
/** a plan of one cut with nothing in it to fix: its text inside the safe area, over the test clip */
function cleanPlan(d: string, name = "out/cuts/ad_concept_v1_9x16.plan.json") {
put(d, "edit.tsx", "export default 1\n")
put(d, "media/take.mp4", readFileSync(CLIP))
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Safe in the middle", box: [140, 900, 800, 90], size: 60 }] }))
return put(d, name, JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 60, plan: true, frames, sounds: { fps: 30, clips: [] } }))
}
/** the farm's reader, standing in for a test: `answer` gives each POST's reply */
async function withFarm<T>(answer: (n: number) => Answer, run: () => Promise<T>): Promise<T> {
const before = process.env.RAEA_CLOUD_GPU_URL
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
useSender(async (_url, body) => answer((JSON.parse(String(body)) as { frames: string[] }).frames.length))
try {
return await run()
} finally {
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
else process.env.RAEA_CLOUD_GPU_URL = before
}
}
const EMPTY = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [], seams: [] }
test("a plan holds its own cut alone: the brief's count, its quotes and the project's checks don't stop it being drawn", async () => {
// the brief asks for 10 cuts, 1 is planned, and the open item about the count waits for a person (who answers at the
// first stop, after the first render); the brief's text isn't in the project either
const asked = { question: "Only 2 interviews came: cut fewer?", from: "10 total videos", about: "count" }
const d = project({ kind: "cut", packs: { naming: false }, cut: { brief: "media/brief.txt", count: { value: 10, from: "10 total videos" }, formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }], open: [asked] } })
const plan = cleanPlan(d)
const r = await withFarm(
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(EMPTY) }) }),
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
expect(r.checks).not.toContain("count")
expect(r.checks).not.toContain("quotes")
expect(r.checks).not.toContain("registered")
expect(r.passed).toBe(true)
// the same project checked at edit without a plan still holds the count
const whole = await goalCheck({ cwd: d, at: "edit" })
expect(whole.findings.some((x) => x.check === "count" && x.level === "error")).toBe(true)
})
test("a plan the farm can't read waits: nothing to fix, so it doesn't fail", async () => {
const d = project(null)
const plan = cleanPlan(d)
let asked = 0
const r = await withFarm(
() => {
asked++
return { status: 503, ok: false, text: "busy" }
},
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
expect(asked).toBeGreaterThan(0)
expect(r.broke).toEqual([])
expect(r.waits.map((w) => w.check)).toContain("frames")
expect(r.waits.find((w) => w.check === "frames")?.says).toMatch(/render's check holds it.*503/)
expect(r.errors).toBe(0)
expect(r.passed).toBe(true)
expect(text(r)).toMatch(/^PASSED .*waiting/m)
})
test("on a plan, text over a face and talking with no captions are warnings: the render's check holds them", async () => {
const d = project({ kind: "cut", packs: { naming: false }, cut: { formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }] } })
// a caption with nothing said under it, straight over a face the farm reads in every frame
const plan = cleanPlan(d)
const m = JSON.parse(readFileSync(plan, "utf8"))
m.length = 240
m.frames = Array.from({ length: 240 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: (f % 90) / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: f < 60 ? [{ text: "Nobody says this at all", box: [140, 300, 800, 300], size: 60 }] : [] }))
// ... and from 5 s, past a text hook's opening, the take talks with no caption up
put(d, "media/take.words.json", JSON.stringify("so this is what we said".split(" ").map((t, i) => ({ text: t, start: 0.3 + i * 0.4, end: 0.6 + i * 0.4 }))))
m.sounds.clips = [{ key: "v", from: 150, to: 240, src: "media/take.mp4", at: 0 }]
put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify(m))
const face = { ...EMPTY, faces: [[170, 150, 200, 200, "face", 0.95]] }
const r = await withFarm(
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(face) }) }),
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
const soft = r.findings.filter((x) => x.says.endsWith(PLAN_SOFT))
expect(soft.length).toBeGreaterThan(0)
expect(soft.every((x) => x.level === "warn" && ["place", "captions", "reading", "frames"].includes(x.check))).toBe(true)
expect(soft.some((x) => x.check === "place" && /covers a face/.test(x.says))).toBe(true)
expect(soft.some((x) => x.check === "captions" && /no captions over the talking/.test(x.says))).toBe(true)
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
expect(r.passed).toBe(true)
})
+2 -1
View File
@@ -20,7 +20,8 @@ Run `raea context PROJECT` before anything else and read all of it. It prints, i
every project. A line there beats any guide.
2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),
what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction.
Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction. To write one,
`raea guide brief` has its types, a cut goal's contract and an example.
3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.
4. **The floor**: what breaks a piece, read again right before every edit.
5. **One guide per mode**: what that kind of piece has to do.
+1 -1
View File
@@ -32,7 +32,7 @@ and the Stop hook won't let you end before it says done.
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
`raea judge review/rN --kind kit --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 goal check` passes.
+7 -10
View File
@@ -3,12 +3,11 @@
There are three texts to copy and fill: a brief template, a builder prompt and a judge prompt for a fresh context.
`bevy/scenes` says why each step exists. This page gives the words.
Who plays which role:
- **In Claude Code:** the session is the builder. The judge is a new subagent every round, plus `raea judge` (clef-omni)
for the numbers.
- **In the raea app's feed:** Kimi is the builder and `raea judge` is the judge.
Who plays which role: you are the builder; `raea judge` is the judge, a fresh session every round that raea starts
for you (the agent this project runs on where the raea app or raea cloud started it, else clef-omni for the numbers).
You never pick it.
Either way, the judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
The judge sees only pictures and the brief's words, never the code or the builder's notes. Code decides
the pass, and the builder never sees the pass line. A figure the builder can read becomes a target to game.
Where these texts come from: the published Blender + Claude workflows.
@@ -144,11 +143,9 @@ STEP R: REVIEW (after every stage, and after every fix)
the same cameras every round.
- Open both sheets and look at every tile yourself. Write your own list. "Looks good" is not a review. Name each
problem precisely ("the dryer doors are flat grey discs", not "the dryers look off"), with its tile and its fix.
- Run `raea judge review/r<n> --by kimi` (or `--by claude`; plain `raea judge` is clef-omni, cheap but advice only
until calibrated). Each is a new session that sees only the sheets. In Claude Code you can also hand the sheets to a
NEW subagent with the judge prompt. Give it only the
brief's words, the target, the real photos, this round's sheets, and last round's sheets and verdict. Never give it
your code, your log or your list.
- Run `raea judge review/r<n>`. It's a new session that sees only the sheets, the brief's words, the target, the real
photos, this round's sheets, and last round's sheets and verdict: never your code, your log or your list. Who reads
them is raea's to settle, not yours.
- Fix every blocking defect named, or write in review/log.md why it is wrong and what you checked. A judge can be
wrong: a shadow read as a hole. Change one material per round. Every fix is code in the scene.
- Re-run the stage's checks after every fix. A fix that breaks a check is not done.
+2 -2
View File
@@ -159,8 +159,8 @@ Three tiers, each gating once it has earned it (`raea goal check` lists them):
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.
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,
3. **A fresh critic for the fixes.** `raea judge review/rN --kind scene --brief brief.ts --target
media/ref/target.png --json` 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.
+1 -1
View File
@@ -44,7 +44,7 @@ before it says done.
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).
judge it (`raea judge review --kind shot`: 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,
+23 -2
View File
@@ -12,8 +12,9 @@ docs/components.md in the raea repository.
every thing the piece needs as a component: `Kitchen`, `Kettle`, `Steam`, `BrushedSteel`, `MorningLook`,
`PriceCard`. One component is one concern: one object, one surface, one effect, one card.
2. **Look before making.** `raea make component list` shows raea's own and the library's categories; `raea make
component list WORDS` searches the library by what a piece is for (`text/reveal`, `numbers/counter`, `transitions`,
`"count up"`): several hundred open-source text reveals, counters, charts, logo stings, HUDs and screen demos. A
component list WORDS` searches the library by what a piece is for and how people ask for it (`text/reveal`,
`numbers/counter`, `"count up"`, `"chat input"`, `template`): several hundred open-source text reveals, counters,
charts, logo stings, HUDs and screen demos, and `raea make component show NAME` says when to use one and its props. A
project's `components/` and the workspace's `shared/components/` hold what this person already has; `raea library
search "WORDS"` finds their assets. Interface pieces (forms, tables, dashboards) come from shadcn, never rebuilt:
see "shadcn" below. A library piece arrives with its source's sample words, colours and fonts: pass the brief's.
@@ -28,6 +29,26 @@ docs/components.md in the raea repository.
A piece written as one long file of meshes and numbers can't be reused, checked part by part, tuned by a person or
fixed by a note that names a thing. Write components even for a one-off: the next note will name one of them.
## A template, an effect, a branded screen: the library first
When the person asks for a template, an effect, a preset, "something from remocn" (or snapcn), or a known kind of app
screen moving (a chat box or composer, an AI prompt, a terminal, an agent at work, a phone or laptop showing an app),
the library has it more often than not, already made and timed. Look there before drawing anything:
1. `raea make component list WORDS`, with the person's own words: `list composer`, `list "chat input"`, `list "AI
prompt"`, `list "claude code"`, `list terminal`, `list template product`, `list "lower third"`. It searches each
component's name, the name it had upstream, the phrases people ask for it with, and what it does; `list template`
or `list effect` alone lists the ones that are and says how to narrow it.
2. `raea make component show NAME` for the best hits: what it draws and how it moves, when to use it and when not
(naming the better pick for the other case), the size, length and frame rate it was designed at, and every prop
with its type, default and what it does. `list WORDS --json` gives the same for every hit. Pick from these;
there's no need to open the files, and never fetch the upstream sources by hand.
3. `raea make component add NAME`, then pass the brief's words, colours, fonts and logo through its props. A
component with no props (some templates) has them written in its file: change them there.
Only when nothing fits is it written new, as a component (step 4). A brand's own product UI that isn't in the library
(a particular app's chat window, say) is built from the nearest one: `add` it and restyle it.
## What a component is
A component is a React function component that draws one thing from its props and the frame:
+126
View File
@@ -0,0 +1,126 @@
# brief.ts: the brief as code
A project's brief.ts is a module whose default export is `brief({...})` from `raea/brief`. raea runs it, `raea goal
check` holds the work to its `goal`, and tsc checks it against the same types raea reads. Everything you need to write
one is on this page, so you don't need to open the SDK.
## The shape
```ts
import { brief, cut, rules } from "raea/brief"
export default brief({
title: string, // the project as people name it
for?: string, // the client or person it's for
audience?: string, // who watches, and where
believe?: string, // the one thing they should think afterwards
voice?: string, look?: string, sound?: string,
notDoing?: string[], // the anti-goals
assumed?: string[], // facts you wrote that the person hasn't confirmed, by key ("audience")
sections?: { heading: string, text: string }[],
goal?: Goal | Goal[], // what the work is held to: cut(), rules(), scene(), kit(), shot(), playable()
plan?: PlanFile, // tasks (raea/task plan()), inline or imported
})
```
A goal made with `cut({...})` or `rules({...})` takes these fields:
| Field | What it is |
| --- | --- |
| `aim` | what the goal is, in the person's words |
| `rules` | `{ id, run? , timeout?, file?, says? }[]`: what must hold before you stop (below) |
| `cut` | a cut job's contract, the brief as rules (below) |
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
| `checks` | the project's own `check()`s from raea/check, imported into brief.ts |
| `name`, `after`, `step` | for several goals in order: a goal's name, the goals before it, its workflow step |
## A cut job's contract (`cut: {...}`)
Every `from` is the brief's own words, copied from its text file as they are, so a person can find the line the
rule came from. raea refuses a `from` it can't find.
| Field | Type | What it holds |
| --- | --- | --- |
| `brief` | `string` | the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf brief_docs/brief.txt`) |
| `count` | `{ value: number, from }` | how many cuts the brief asks for. Fewer planned stays open until a person answers an `open` item about `"count"` |
| `seconds` | `[least, most]` | a cut's length when the cut doesn't give its own |
| `formats` | `string[]` | `"9:16"`, `"16:9"`, `"1:1"`, `"4:5"`: every cut's formats when the cut doesn't give its own |
| `cuts` | `CutPlan[]` | one per cut: `{ id, angle?, kind?, hook?, text?, formats?, seconds?, beats? }` |
| `say` | `{ text, from, every? }[]` | what is said or shown in every cut (`every: false`: one cut is enough) |
| `never` | `{ text, from }[]` | what no cut says or shows: a banned claim, a word, a name |
| `cta` | `{ text, from, also?, within? }` | the line every cut ends on, heard or shown in its last `within` seconds (8 by default); `also` lists other lines the brief rotates |
| `open` | `{ question, from, about?, answer?, by? }[]` | the brief's open items (TBD, to confirm). Each holds the job open until a person's answer is written in, with who gave it |
| `frames` | `boolean` | every face whole and every text big enough, in every frame (true by default) |
A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<format with x>.mp4`, for example
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
one of the brief's hook types, as the brief names it.
A cut's `beats` are decided before it's cut, in order: `{ at, feel, story?, asl?, tempo? }[]`. `at` is where the beat
starts, in seconds from the cut's start (0 for the first). `feel` is what the viewer feels there, in the person's
words, and `story` is what they understand by its end. A fresh critic watches each beat for both. `asl` is the beat's
average shot length in seconds, and `tempo` is how its shot lengths move: `"build"` (shorter as it goes), `"release"`
(longer) or `"hold"` (even). The montage check holds the cut to them.
## Rules
| Kind | Example | How it's checked |
| --- | --- | --- |
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
| `says` | `{ id: "logo_end", says: "The wordmark is on screen in each cut's last 3 seconds" }` | words that must be true of the work, judged by a fresh critic, never by you |
You don't run the critic yourself or choose it: `raea goal check` asks for a verdict when one is missing or older than
the work. A `says` rule about a video ("in each cut's last 3 seconds") is watched and heard. One about files or text
is read.
## An example
```ts
// brief.ts
import { brief, cut } from "raea/brief"
export default brief({
title: "Juniper Tea · street interviews, round 1",
for: "Juniper Tea",
audience: "TikTok and Reels, 25-40, already buying loose-leaf",
believe: "Juniper tastes like the tea shop, at home",
goal: cut({
aim: "Ten 9:16 cuts from the street interviews, each ending on the free-trial line",
cut: {
brief: "brief_docs/brief.txt",
count: { value: 10, from: "10 unique cuts total" },
seconds: [20, 40],
formats: ["9:16"],
cuts: [
{
id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions",
beats: [
{ at: 0, feel: "caught off guard, curious", story: "she's a real tea drinker, not an actor", asl: 1.5, tempo: "build" },
{ at: 4, feel: "the small sadness of bad tea at home", story: "bagged tea tastes like paper to her", asl: 3, tempo: "hold" },
{ at: 14, feel: "the surprise of a good first sip", story: "Juniper is the shop's taste at home", asl: 2, tempo: "release" },
],
},
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
],
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
never: [{ text: "cures", from: "Never claim the tea cures or treats anything" }],
cta: { text: "Try Juniper free for 30 days", from: "CTA: \"Try Juniper free for 30 days\"" },
open: [
{
question: "The footage holds 4 usable interviews, not 10: deliver 4 this round?",
from: "10 unique cuts total", about: "count",
// left out until the person answers; then their words and who gave them
answer: "Yes, 4 now and the rest after the reshoot", by: "the client's producer",
},
],
},
rules: [
{ id: "wordmark_end", says: "The Juniper wordmark is on screen in each cut's last 3 seconds" },
],
}),
})
```
Write it, then run `raea goal check`. It names each rule that doesn't hold and the line of the brief it came from.
+28 -3
View File
@@ -57,6 +57,31 @@ import { EndCard, InstallButton, install } from "raea/playable";
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone
mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
The host draws that 3D with Bevy's own PBR shaders, so a frame of the playable matches `raea render --frame` closely.
It has the sun's shadow, point and spot lights, fog from `<Fog>` and Bevy's tone mapping. Some things are left out,
and the page's console names each one once: normal maps, transmission, vertex colours, point and spot shadows, rect
lights, an environment's light, a camera's own `<Fog>` child, a shadow catcher and a paint look. Check how the 3D looks
in the `preview` page, not only in the video ad.
## Rules on raea/ecs
A game whose rules are systems on a raea/ecs `World` keeps Bevy's world in the playable: the export sees a World made
and carries runtime/ecs as wasm (about 250 KB in the page), loaded before the game, so the tables, queries, parents and
`scene()` answer as they do in `raea render`. Keep the World as the game's state: each step copies it, writes the
input in as a resource, and runs its systems once.
```tsx
const step = (s: Game, input: FrameInput, frame: number): Game => {
const w = s.w.copy(); // the next state, with the World's systems
if (input.pointer) w.resource("aim", input.pointer.x);
w.step(frame);
return { w, over: (w.resource<number>("score") ?? 0) >= 10 };
};
```
Draw its entities with the elements the host draws (`<Mesh3d>` with a `<Cuboid>` or `<Sphere>`), not `<Entities>`,
whose Manifold shapes need the engine. examples/playables/star-catch.tsx is the whole pattern.
## Sound
A playable is silent until the person touches it, as every network requires, and then plays what the video ad
@@ -76,14 +101,14 @@ carried for you, as the video ad draws them. Any other family named but not impo
## Export and check
```sh
raea add three@0.185.0 # once per project: the playable's 3D renderer
raea add three@0.185.0 # once per project with 3D: it reads the scene for the playable
raea add tone@15.1.22 # once per project, if it uses raea/tone
raea render game.tsx -o out/video-ad.mp4 # the video ad
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
```
It prints each network's file and its size against the 5 MB cap. A 2D game's page is about 400 KB; three.js adds about
1 MB for 3D and Tone.js about 360 KB for raea/tone, and the rest is the game's own pictures and sounds. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
It prints each network's file and its size against the 5 MB cap. A 2D game's page is about 400 KB; 3D adds about
1 MB (three.js's scene graph and Bevy's shaders) and Tone.js about 360 KB for raea/tone, and the rest is the game's own pictures and sounds. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
`--orientation` sets what Google and TikTok are told.
Play the `preview` page yourself before handing it over: open it at a phone's size, drag, lose, and tap the card. In
+5
View File
@@ -16,6 +16,11 @@
- Size captions at 60 px or more at 1080 wide (scale with the width), with at least 3:1 contrast against the pixels
behind them. Keep them in one place unless a move means something, and keep them off cards, logos, burned-in text
and the face (`motion/placement`).
- To put a caption or hook in a box that hugs each line, as TikTok draws its text, use `HugText` from
`raea/hug-text`: `<HugText lines={[...]} fill="#E8423F" color="#fff" className="..." />`. Each line gets a fill as
wide as its words, with one rounded shape around them all. You give the lines, so you decide where each breaks
(a caption's come from its word groups). Its emoji draw in colour on any machine, as `EmojiText` from the same
module also does. The box is allowed, never required.
- Mark each caption: `data-raea-role="caption"` on the element holding its words. A layered export (`raea export
capcut`, `raea export xml`; `motion/delivery`) then puts the captions on a track of their own, styled as they're
drawn, and writes their words as an .srt beside them; unmarked, they're part of the graphics.
+12 -2
View File
@@ -9,5 +9,15 @@ src/host/tony.bin is the tone-mapping table Tony McMapface, resampled by tools/t
https://github.com/bevyengine/bevy
Licensed under MIT OR Apache-2.0.
host/tonemap.ts samples it as Bevy's tonemapping shader does. The rest of raea/playable is raea's own, under the
repository's licence.
host/bevy.ts samples it as Bevy's tonemapping shader does.
src/host/bevy/programs.ts holds Bevy's PBR shaders (bevy_pbr's mesh, pbr and prepass programs, with bevy_render's
and bevy_core_pipeline's shader imports), composed by Bevy's shader cache and translated to GLSL ES by naga
(tools/bevy-glsl).
Bevy
By the Bevy contributors
https://github.com/bevyengine/bevy
Licensed under MIT OR Apache-2.0.
The rest of raea/playable is raea's own, under the repository's licence.
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Bevy's PBR programs for a playable (docs/playables.feature PA11): tools/bevy-glsl composes Bevy's mesh, pbr and
# prepass shaders with WebGL2's defs and translates them to GLSL ES 3.00, into sdk/playable/src/host/bevy/programs.ts,
# with the hash of what they were made from beside it (programs.from). apps/playable's test fails when Bevy's shaders
# or the translator change and this isn't run.
# usage: bash sdk/playable/bevy/build.sh [TARGET_DIR]
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
target=${1:-$root/target/bevy-glsl}
out=$root/sdk/playable/src/host/bevy
work=$(mktemp -d)
trap 'rm -r "$work"' EXIT
cargo run -q --release --manifest-path "$root/tools/bevy-glsl/Cargo.toml" --target-dir "$target" -- "$root" "$work"
cp "$work/programs.ts" "$out/programs.ts"
bash "$root/sdk/playable/bevy/from.sh" > "$out/programs.from"
echo "programs.ts: $(wc -c < "$out/programs.ts" | tr -d ' ') bytes, $(gzip -9c "$out/programs.ts" | wc -c | tr -d ' ') gzipped"
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# what programs.ts is made from (build.sh): the translator, raea's vendored bevy_pbr shaders, and the Bevy and naga it
# composes them with (Cargo.lock's lines)
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
{
cat "$root"/tools/bevy-glsl/Cargo.toml "$root"/tools/bevy-glsl/src/*.rs
find "$root/vendor/bevy_pbr/src" \( -name '*.wesl' -o -name '*.wgsl' \) | LC_ALL=C sort | xargs cat
grep -A1 -E '^name = "(bevy_render|bevy_core_pipeline|bevy_shader)"$' "$root/Cargo.lock"
} | shasum -a 256 | cut -c1-64
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# raea/ecs's world as wasm for a playable (docs/playables.feature PA12): runtime/ecs built for wasm32-unknown-unknown
# as a cdylib, size-optimised (wasm-opt -Oz when it's here), into sdk/playable/src/host/ecs.wasm, with the hash of what
# it was built from beside it (ecs.wasm.from). apps/playable's test fails when runtime/ecs changes and this isn't run.
# usage: bash sdk/playable/ecs/build.sh [TARGET_DIR]
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
target=${1:-$root/target}
out=$root/sdk/playable/src/host
cargo rustc --manifest-path "$root/Cargo.toml" -p raea-runtime-ecs --lib --crate-type cdylib --target wasm32-unknown-unknown \
--profile release --target-dir "$target" \
--config 'profile.release.opt-level="z"' --config 'profile.release.lto=true' --config 'profile.release.codegen-units=1' \
--config 'profile.release.panic="abort"' --config 'profile.release.strip=true' --config 'profile.release.debug=false'
wasm=$target/wasm32-unknown-unknown/release/raea_runtime_ecs.wasm
if command -v wasm-opt > /dev/null; then wasm-opt -Oz --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals "$wasm" -o "$out/ecs.wasm"; else cp "$wasm" "$out/ecs.wasm"; fi
bash "$root/sdk/playable/ecs/from.sh" > "$out/ecs.wasm.from"
echo "ecs.wasm: $(wc -c < "$out/ecs.wasm" | tr -d ' ') bytes, $(gzip -9c "$out/ecs.wasm" | wc -c | tr -d ' ') gzipped"
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# what ecs.wasm is built from (build.sh): runtime/ecs's sources and manifest, and the Bevy it's on (Cargo.lock's line)
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
{ cat "$root"/runtime/ecs/Cargo.toml "$root"/runtime/ecs/src/*.rs; grep -A1 '^name = "bevy_ecs"$' "$root/Cargo.lock"; } | shasum -a 256 | cut -c1-64
+3 -1
View File
@@ -31,5 +31,7 @@ export default function walk() {
const params = { ...(a.options ?? {}), seconds: a.seconds };
return { src: a.src, model: a.kind, prompt: a.prompt, seed: typeof a.options?.seed === "number" ? a.options.seed : 1, params };
});
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)), sound: { tone, media: media || assets.length > 0, assets } };
// a raea/ecs World made (as the game's module loaded, or as it rendered): the page carries Bevy's world (PA12)
const ecs = (globalThis as { __raeaEcsUsed?: boolean }).__raeaEcsUsed === true;
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)), sound: { tone, media: media || assets.length > 0, assets }, ecs };
}
+415
View File
@@ -0,0 +1,415 @@
// A playable's 3D drawn by Bevy's own PBR programs (docs/playables.feature PA11): Bevy's mesh, pbr and prepass shaders
// as Bevy composes them for a WebGL2 device, translated to GLSL ES by naga (tools/bevy-glsl, bevy/programs.ts), fed the
// uniform blocks Bevy's render world fills (bevy/fill.ts). The page's parts are read by raea's three.js host into a
// scene graph (scene.ts), which this reads back without three's renderer: each mesh's geometry and world transform,
// each material's values, each light in Bevy's units. As Bevy on WebGL2 draws: one directional shadow cascade, a
// forward pass into half float with 4x MSAA and reverse Z, the point and spot lights in one cluster, distance fog; then
// Bevy's TonyMcMapface through its own table, as the native engine's frame pass does. The export bundles it only for a
// game whose lint found a 3D kind (PA15).
import * as THREE from "three";
import type { Draw3d } from "./draw3d";
import { Scene3d } from "./scene";
import tony from "./tony.bin";
import { Block } from "./bevy/block";
import { Meshes, POINTS, Program, Textures, UNITS, programs } from "./bevy/gl";
import { PBR_FRAG, PBR_VERT, SHADOW_VERT } from "./bevy/programs";
import { ambientOf, cascade, fillFog, fillLights, fillMaterial, fillMesh, fillView, toLight, type Cascade, type Lights, type Surface } from "./bevy/fill";
const BATCH = 93; // PER_OBJECT_BUFFER_BATCH_SIZE: the meshes one uniform block holds
const N = Math.round(Math.cbrt(tony.length / 3));
const EMPTY_FS = "#version 300 es\nprecision highp float;\nvoid main() {}\n";
const TONE_VS = `#version 300 es
out vec2 uv;
void main() { vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); uv = p; gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }`;
// the HDR target is drawn upside down (naga's coordinate flip): its first row is the picture's top
const TONE_FS = `#version 300 es
precision highp float;
precision highp sampler3D;
uniform sampler2D scene;
uniform sampler3D lut;
uniform float exposure;
in vec2 uv;
out vec4 color;
void main() {
vec4 c = texture(scene, vec2(uv.x, 1.0 - uv.y));
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0)) * exposure;
vec3 t = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
color = vec4(texture(lut, clamp(t, 0.0, 1.0)).rgb * c.a, c.a);
}`;
/** One draw: a mesh (or one of an instanced mesh's copies), its geometry's range and its material's slot */
type Draw = {
geometry: THREE.BufferGeometry;
world: THREE.Matrix4;
material: number;
surface: Surface;
start: number;
count: number;
casts: boolean;
receives: boolean;
depth: number;
};
const ALIGN = (n: number, a: number) => Math.ceil(n / a) * a;
export function bevy3d(canvas: HTMLCanvasElement): Draw3d {
const gl = canvas.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: "high-performance" });
if (!gl) throw new Error("raea playable: this browser has no WebGL2");
const hdr = !!gl.getExtension("EXT_color_buffer_float") || !!gl.getExtension("EXT_color_buffer_half_float");
const warned = new Set<string>();
const warn = (why: string) => {
if (warned.has(why)) return;
warned.add(why);
console.warn(`raea playable: ${why}`);
};
if (!hdr) warn("this browser can't draw into half float: the 3D's highlights clip before the tone curve");
// linked while the page's first frame is built; bound at the first draw
const [pbr, shadowProgram, tone] = programs(gl, [[PBR_VERT, PBR_FRAG], [SHADOW_VERT, EMPTY_FS], [TONE_VS, TONE_FS]]) as [Program, Program, Program];
let exposureAt: WebGLUniformLocation | null = null;
const align = gl.getParameter(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT) as number;
const blocks = {
view: new Block("view"),
lightView: new Block("view"),
lights: new Block("lights"),
clustered: new Block("clustered_lights"),
offsets: new Block("cluster_offsets_and_counts"),
lists: new Block("clusterable_object_index_lists"),
globals: new Block("globals"),
fog: new Block("fog"),
metadata: new Block("metadata"),
mesh: new Block("mesh", 1, ALIGN(new Block("mesh").size, align)),
material: new Block("material", 1, ALIGN(new Block("material").size, align)),
};
const buffers = new Map<Block, { b: WebGLBuffer; bytes: number }>();
const upload = (block: Block) => {
let k = buffers.get(block);
if (!k) buffers.set(block, (k = { b: gl.createBuffer()!, bytes: 0 }));
gl.bindBuffer(gl.UNIFORM_BUFFER, k.b);
if (k.bytes !== block.bytes.byteLength) {
gl.bufferData(gl.UNIFORM_BUFFER, block.bytes, gl.DYNAMIC_DRAW);
k.bytes = block.bytes.byteLength;
} else gl.bufferSubData(gl.UNIFORM_BUFFER, 0, block.bytes);
return k.b;
};
const bind = (name: string, block: Block, copy = 0) => {
const k = buffers.get(block)!;
gl.bindBufferRange(gl.UNIFORM_BUFFER, POINTS[name], k.b, copy * block.stride, block.size);
};
const textures = new Textures(gl);
const meshes = new Meshes(gl);
// Bevy's table for TonyMcMapface (tools/tony.ts), sRGB bytes already
const lut = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_3D, lut);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage3D(gl.TEXTURE_3D, 0, gl.RGB8, N, N, N, 0, gl.RGB, gl.UNSIGNED_BYTE, tony);
for (const [k, v] of [[gl.TEXTURE_MIN_FILTER, gl.LINEAR], [gl.TEXTURE_MAG_FILTER, gl.LINEAR], [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE]]) gl.texParameteri(gl.TEXTURE_3D, k, v);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
// a depth texture sampled with comparison, as Bevy's shadow samplers are (reverse Z: greater-or-equal is lit)
const depthTexture = (target: number, size: number) => {
const t = gl.createTexture()!;
gl.bindTexture(target, t);
if (target === gl.TEXTURE_CUBE_MAP) for (let f = 0; f < 6; f++) gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gl.DEPTH_COMPONENT32F, size, size, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
else gl.texImage2D(target, 0, gl.DEPTH_COMPONENT32F, size, size, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, gl.GEQUAL);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
};
// point lights' shadows aren't drawn: their cube is one texel, never sampled
const pointShadows = depthTexture(gl.TEXTURE_CUBE_MAP, 1);
let shadowSize = 0;
let shadowMap: WebGLTexture | null = null;
const shadowFbo = gl.createFramebuffer()!;
const shadowTarget = (size: number) => {
if (size === shadowSize && shadowMap) return;
if (shadowMap) gl.deleteTexture(shadowMap);
shadowSize = size;
shadowMap = depthTexture(gl.TEXTURE_2D, size);
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowMap, 0);
gl.drawBuffers([gl.NONE]);
gl.readBuffer(gl.NONE);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
shadowTarget(2048);
// the forward pass's targets: multisampled colour and depth, resolved into a texture the tone pass reads
const samples = Math.min(4, gl.getParameter(gl.MAX_SAMPLES) as number);
const msaaFbo = gl.createFramebuffer()!;
const resolveFbo = gl.createFramebuffer()!;
let color: WebGLRenderbuffer | null = null;
let depth: WebGLRenderbuffer | null = null;
let resolved: WebGLTexture | null = null;
let width = 1;
let height = 1;
const targets = () => {
if (color) gl.deleteRenderbuffer(color);
if (depth) gl.deleteRenderbuffer(depth);
if (resolved) gl.deleteTexture(resolved);
const format = hdr ? gl.RGBA16F : gl.RGBA8;
color = gl.createRenderbuffer()!;
gl.bindRenderbuffer(gl.RENDERBUFFER, color);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, format, width, height);
depth = gl.createRenderbuffer()!;
gl.bindRenderbuffer(gl.RENDERBUFFER, depth);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT32F, width, height);
gl.bindFramebuffer(gl.FRAMEBUFFER, msaaFbo);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, color);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
resolved = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, resolved);
gl.texStorage2D(gl.TEXTURE_2D, 1, format, width, height);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, resolveFbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, resolved, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
const scene = new Scene3d();
let frame = 0;
let seconds = 0;
/** The scene's meshes and lights, as Bevy's extraction would find them */
const gather = () => {
const draws: Draw[] = [];
const lights: Lights = { ambient: null, directional: [], points: [], spots: [] };
const materials = new Map<string, { slot: number; surface: Surface }>();
const ids = new WeakMap<THREE.Material, number>();
let nextId = 0;
const order: { m: THREE.Material; tint: THREE.Color | null; surface: Surface }[] = [];
const slotOf = (m: THREE.Material, tint: THREE.Color | null) => {
let id = ids.get(m);
if (id === undefined) ids.set(m, (id = nextId++));
const key = tint ? `${id}:${tint.getHexString()}` : `${id}`;
let k = materials.get(key);
if (!k) {
k = { slot: order.length, surface: { blend: false, doubleSided: false } };
materials.set(key, k);
order.push({ m, tint, surface: k.surface });
}
return k;
};
const camInv = scene.camera.matrixWorldInverse;
const p = new THREE.Vector3();
const add = (mesh: THREE.Mesh, world: THREE.Matrix4, tint: THREE.Color | null) => {
const g = mesh.geometry;
const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
const groups = Array.isArray(mesh.material) && g.groups.length ? g.groups : [{ start: 0, count: Infinity, materialIndex: 0 }];
for (const gr of groups) {
const m = mats[gr.materialIndex ?? 0];
if (!m || !m.visible) continue;
if (m instanceof THREE.ShadowMaterial) {
warn("a shadow catcher isn't drawn in a playable yet");
continue;
}
const k = slotOf(m, tint);
p.setFromMatrixPosition(world).applyMatrix4(camInv);
draws.push({ geometry: g, world, material: k.slot, surface: k.surface, start: gr.start, count: gr.count, casts: mesh.castShadow, receives: mesh.receiveShadow, depth: p.z });
}
};
scene.scene.updateMatrixWorld();
scene.scene.traverseVisible((o) => {
if (o instanceof THREE.InstancedMesh) {
const one = new THREE.Matrix4();
for (let i = 0; i < o.count; i++) {
o.getMatrixAt(i, one);
const tint = o.instanceColor ? new THREE.Color().fromArray(o.instanceColor.array, i * 3) : null;
add(o, o.matrixWorld.clone().multiply(one), tint);
}
} else if (o instanceof THREE.Mesh) add(o, o.matrixWorld, null);
else if (o instanceof THREE.AmbientLight || o instanceof THREE.HemisphereLight) lights.ambient = ambientOf(o, lights.ambient);
else if (o instanceof THREE.DirectionalLight) lights.directional.push(o);
else if (o instanceof THREE.SpotLight) {
lights.spots.push(o);
if (o.castShadow) warn("a spot light's shadow isn't drawn in a playable yet");
} else if (o instanceof THREE.PointLight) {
lights.points.push(o);
if (o.castShadow) warn("a point light's shadow isn't drawn in a playable yet");
} else if (o instanceof THREE.RectAreaLight) warn("a rect light isn't drawn in a playable yet");
else if (o instanceof THREE.Points || o instanceof THREE.Line || o instanceof THREE.Sprite) warn(`a ${o.type} isn't drawn in a playable yet`);
});
if (scene.scene.userData.raeaEnvironment) warn("an environment's light isn't drawn in a playable yet");
if (scene.effects.some((e) => e.kind === "Look")) warn("a paint look isn't drawn in a playable yet");
blocks.material.resize(order.length);
order.forEach(({ m, tint, surface }, slot) => Object.assign(surface, fillMaterial(blocks.material, slot, m, tint, warn)));
return { draws, lights, materials: order.length };
};
const drawAll = (list: Draw[], program: Program, main: boolean) => {
let batch = -1;
let cull: boolean | null = null;
for (let i = 0; i < list.length; i++) {
const d = list[i];
const m = meshes.get(d.geometry);
if (!m) continue;
const at = (d as Draw & { at: number }).at;
const b = Math.floor(at / BATCH);
if (b !== batch) {
bind("mesh", blocks.mesh, b);
batch = b;
}
gl.uniform1ui(program.first, at % BATCH);
const two = d.surface.doubleSided;
if (cull !== !two) {
if (two) gl.disable(gl.CULL_FACE);
else gl.enable(gl.CULL_FACE);
cull = !two;
}
if (main) {
bind("material", blocks.material, d.material);
const s = d.surface;
const tex = (unit: number, t: THREE.Texture | null | undefined) => {
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, textures.get(t) ?? textures.white);
};
tex(UNITS.base_color_texture, s.map);
tex(UNITS.emissive_texture, s.emissiveMap);
tex(UNITS.metallic_roughness_texture, s.mrMap);
tex(UNITS.occlusion_texture, s.aoMap);
}
gl.bindVertexArray(m.vao);
const start = d.start;
const count = Math.min(d.count, m.count - start);
if (m.index) gl.drawElements(gl.TRIANGLES, count, m.index, start * (m.index === gl.UNSIGNED_INT ? 4 : 2));
else gl.drawArrays(gl.TRIANGLES, start, count);
}
gl.bindVertexArray(null);
};
return {
fit(w, h, scale) {
// the canvas is drawn at the screen's pixels, not the composition's
const ratio = Math.min(2, devicePixelRatio || 1) * scale;
const cw = Math.max(1, Math.floor(w * ratio));
const ch = Math.max(1, Math.floor(h * ratio));
if (cw !== width || ch !== height || !color) {
width = canvas.width = cw;
height = canvas.height = ch;
targets();
}
scene.fit(w, h);
},
sync(page, s) {
seconds = s;
scene.sync(page, s);
return scene.any;
},
draw() {
frame++;
const { draws, lights } = gather();
draws.forEach((d, i) => ((d as Draw & { at: number }).at = i));
blocks.mesh.resize(Math.ceil(draws.length / BATCH));
draws.forEach((d, i) => fillMesh(blocks.mesh, Math.floor(i / BATCH), i % BATCH, d.world, d.receives));
// the shadow: the first directional light that casts one, its cascade over what casts and catches
const sun = scene.settings.shadows ? lights.directional.find((l) => l.castShadow) : undefined;
let shadow: { light: THREE.DirectionalLight; cascade: Cascade } | null = null;
if (sun) {
shadowTarget(Math.min(scene.settings.shadowMap || 2048, gl.getParameter(gl.MAX_TEXTURE_SIZE) as number));
const bounds = new THREE.Box3();
const box = new THREE.Box3();
for (const d of draws) {
if (!d.geometry.boundingBox) d.geometry.computeBoundingBox();
bounds.union(box.copy(d.geometry.boundingBox!).applyMatrix4(d.world));
}
const c = cascade(toLight(sun), bounds, scene.camera, shadowSize);
if (c) shadow = { light: sun, cascade: c };
}
for (const b of [blocks.view, blocks.lightView, blocks.lights, blocks.clustered, blocks.offsets, blocks.lists, blocks.globals, blocks.fog]) b.resize(1);
fillFog(blocks.fog, scene.scene.fog as THREE.Fog | THREE.FogExp2 | null);
fillView(blocks.view, scene.camera, width, height, frame);
fillLights(blocks.lights, blocks.clustered, blocks.offsets, blocks.lists, lights, shadow, width, height);
blocks.globals.f("time", seconds);
blocks.globals.u("frame_count", frame);
for (const b of Object.values(blocks)) upload(b);
for (const [name, b] of [["lights", blocks.lights], ["clustered_lights", blocks.clustered], ["cluster_offsets_and_counts", blocks.offsets], ["clusterable_object_index_lists", blocks.lists], ["globals", blocks.globals], ["metadata", blocks.metadata], ["fog", blocks.fog]] as [string, Block][]) bind(name, b);
// Bevy's clip space flipped in y by naga: front faces wind clockwise in GL's
gl.frontFace(gl.CW);
gl.cullFace(gl.BACK);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.GEQUAL);
gl.clearDepth(0);
// the shadow pass, from the light, as Bevy's prepass draws it
if (shadow) {
fillView(blocks.lightView, scene.camera, shadowSize, shadowSize, frame, undefined);
blocks.lightView.f("clip_from_world", shadow.cascade.clipFromWorld.elements);
upload(blocks.lightView);
bind("view", blocks.lightView);
// not sampled while it's drawn into
gl.activeTexture(gl.TEXTURE0 + UNITS.directional_shadow_textures);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFbo);
gl.viewport(0, 0, shadowSize, shadowSize);
gl.depthMask(true);
gl.disable(gl.BLEND);
gl.clear(gl.DEPTH_BUFFER_BIT);
shadowProgram.use();
drawAll(draws.filter((d) => d.casts && !d.surface.blend), shadowProgram, false);
}
// the forward pass: opaque, then blended back to front without writing depth
bind("view", blocks.view);
gl.bindFramebuffer(gl.FRAMEBUFFER, msaaFbo);
gl.viewport(0, 0, width, height);
gl.clearColor(0, 0, 0, 0);
gl.depthMask(true);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
pbr.use();
gl.activeTexture(gl.TEXTURE0 + UNITS.directional_shadow_textures);
gl.bindTexture(gl.TEXTURE_2D, shadowMap);
gl.activeTexture(gl.TEXTURE0 + UNITS.point_shadow_textures);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, pointShadows);
gl.activeTexture(gl.TEXTURE0 + UNITS.raea_gi);
gl.bindTexture(gl.TEXTURE_2D, textures.none);
gl.disable(gl.BLEND);
drawAll(draws.filter((d) => !d.surface.blend), pbr, true);
const blended = draws.filter((d) => d.surface.blend).sort((a, b) => a.depth - b.depth);
if (blended.length) {
gl.enable(gl.BLEND);
// BlendState::ALPHA_BLENDING
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.depthMask(false);
drawAll(blended, pbr, true);
gl.depthMask(true);
gl.disable(gl.BLEND);
}
// resolved, then tone-mapped onto the canvas
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msaaFbo);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, resolveFbo);
gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, width, height);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
if (!exposureAt) {
tone.use();
gl.uniform1i(gl.getUniformLocation(tone.p, "scene"), 0);
gl.uniform1i(gl.getUniformLocation(tone.p, "lut"), 1);
exposureAt = gl.getUniformLocation(tone.p, "exposure");
}
tone.use();
gl.uniform1f(exposureAt, scene.settings.exposure * scene.settings.grade);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, resolved);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_3D, lut);
gl.drawArrays(gl.TRIANGLES, 0, 3);
textures.done();
meshes.done();
},
};
}
+82
View File
@@ -0,0 +1,82 @@
// One of Bevy's uniform blocks as bytes (docs/playables.feature PA11): its fields written by their names in Bevy's
// shader structs, at the offsets naga laid them out (programs.ts LAYOUT), so the host fills a block as Bevy's render
// world fills its buffer. A path names nested fields with dots; each array on the way takes the next index.
import { LAYOUT } from "./programs";
type Plan = { at: number; strides: number[] };
export class Block {
readonly size: number;
bytes: ArrayBuffer;
f32: Float32Array;
u32: Uint32Array;
i32: Int32Array;
private readonly layout: Record<string, number>;
private readonly plans = new Map<string, Plan>();
/** `name` is the binding's name in Bevy's files (view, lights, mesh, material ...); `count` copies of it, each
* `stride` bytes apart (a buffer of many materials, or of batches of meshes) */
constructor(readonly name: string, count = 1, readonly stride = 0) {
const layout = LAYOUT[name];
if (!layout) throw new Error(`raea playable: Bevy's programs have no ${name} block`);
this.layout = layout;
this.size = layout.$size;
this.bytes = new ArrayBuffer(0);
this.f32 = new Float32Array(0);
this.u32 = new Uint32Array(0);
this.i32 = new Int32Array(0);
this.resize(count);
}
/** Room for `count` copies, cleared */
resize(count: number) {
const bytes = Math.max(1, count) * Math.max(this.stride, this.size);
if (bytes !== this.bytes.byteLength) {
this.bytes = new ArrayBuffer(bytes);
this.f32 = new Float32Array(this.bytes);
this.u32 = new Uint32Array(this.bytes);
this.i32 = new Int32Array(this.bytes);
} else new Uint8Array(this.bytes).fill(0);
}
private plan(path: string): Plan {
let p = this.plans.get(path);
if (p) return p;
p = { at: 0, strides: [] };
const top = this.layout["[]"];
if (top !== undefined) p.strides.push(top);
let pre = "";
for (const seg of path.split(".")) {
pre = pre ? `${pre}.${seg}` : seg;
const at = this.layout[pre];
if (at === undefined) throw new Error(`raea playable: Bevy's ${this.name} has no ${pre}`);
p.at += at;
const s = this.layout[`${pre}[]`];
if (s !== undefined) p.strides.push(s);
}
this.plans.set(path, p);
return p;
}
/** A field's byte offset in copy `copy`, each array on its path at the index given in turn */
at(path: string, copy = 0, ...index: number[]): number {
const p = this.plan(path);
let at = copy * this.stride + p.at;
for (let k = 0; k < p.strides.length; k++) at += (index[k] ?? 0) * p.strides[k];
return at;
}
f(path: string, v: number | ArrayLike<number>, copy = 0, ...index: number[]) {
const at = this.at(path, copy, ...index) >> 2;
if (typeof v === "number") this.f32[at] = v;
else this.f32.set(v, at);
}
u(path: string, v: number, copy = 0, ...index: number[]) {
this.u32[this.at(path, copy, ...index) >> 2] = v >>> 0;
}
i(path: string, v: number, copy = 0, ...index: number[]) {
this.i32[this.at(path, copy, ...index) >> 2] = v | 0;
}
}
+319
View File
@@ -0,0 +1,319 @@
// Bevy's uniform blocks filled from the scene (docs/playables.feature PA11), as Bevy's render world fills them:
// bevy_render's prepare_view_uniforms (the view), bevy_pbr's prepare_lights (lights, clustered lights, the light
// cluster's lists), MeshUniform::new (each mesh) and StandardMaterial's as_bind_group_shader_type (each material).
// The scene is raea's three.js scene graph (scene.ts); its lights are back in Bevy's units through units.ts, and its
// colours are linear already (three's working space is linear sRGB, Bevy's LinearRgba).
import * as THREE from "three";
import { AMBIENT, LUMENS, LUX, toRaea } from "@raea/r3f/units";
import type { Block } from "./block";
/** Bevy's default camera exposure, EV100 9.7 (Exposure::default) */
export const EXPOSURE = 1 / (1.2 * 2 ** 9.7);
const MAX_DIRECTIONAL = 10; // the programs' MAX_DIRECTIONAL_LIGHTS
const MAX_CLUSTERED = 204; // the clustered lights' array in a uniform block
const SQRT_2 = Math.SQRT2;
/** Bevy's matrices for a three.js camera: clip_from_view as Bevy makes it (reverse Z; a perspective one with no far
* plane), from three's projection's own terms so its zoom and view offset carry */
export function clipFromView(cam: THREE.Camera): THREE.Matrix4 {
const p = cam.projectionMatrix.elements;
const m = new THREE.Matrix4();
if (cam instanceof THREE.OrthographicCamera) {
const r = 1 / (cam.far - cam.near);
// glam's orthographic_rh(left, right, bottom, top, far, near): Bevy swaps near and far for reverse Z
m.set(p[0], 0, 0, p[12], 0, p[5], 0, p[13], 0, 0, r, cam.far * r, 0, 0, 0, 1);
} else {
const near = (cam as THREE.PerspectiveCamera).near ?? 0.1;
// perspective_infinite_reverse_rh, with three's x and y terms
m.set(p[0], 0, p[8], 0, 0, p[5], p[9], 0, 0, 0, 0, near, 0, 0, -1, 0);
}
return m;
}
/** The View block for a camera on a viewport of `width` x `height` pixels */
export function fillView(b: Block, cam: THREE.Camera, width: number, height: number, frame: number, clip?: THREE.Matrix4) {
const clipFromViewM = clip ?? clipFromView(cam);
const worldFromView = cam.matrixWorld.clone();
const viewFromWorld = worldFromView.clone().invert();
const viewFromClip = clipFromViewM.clone().invert();
const clipFromWorld = clipFromViewM.clone().multiply(viewFromWorld);
b.f("clip_from_world", clipFromWorld.elements);
b.f("unjittered_clip_from_world", clipFromWorld.elements);
b.f("world_from_clip", worldFromView.clone().multiply(viewFromClip).elements);
b.f("world_from_view", worldFromView.elements);
b.f("view_from_world", viewFromWorld.elements);
b.f("clip_from_view", clipFromViewM.elements);
b.f("view_from_clip", viewFromClip.elements);
const at = new THREE.Vector3().setFromMatrixPosition(worldFromView);
b.f("world_position", [at.x, at.y, at.z]);
b.f("lod_view_world_position", [at.x, at.y, at.z]);
b.f("exposure", EXPOSURE);
b.f("viewport", [0, 0, width, height]);
b.f("main_pass_viewport", [0, 0, width, height]);
// ColorGrading::default (it acts only where the tone curve is in this pass; the tone curve is the frame pass's)
b.f("color_grading.balance", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]);
for (const k of ["saturation", "contrast", "gamma", "gain"]) b.f(`color_grading.${k}`, [1, 1, 1]);
b.f("color_grading.midtone_range", [0.2, 0.7]);
b.f("color_grading.post_saturation", 1);
b.u("frame_count", frame);
}
/** A three.js light's colour in Bevy's LinearRgba */
const rgb = (c: THREE.Color, k: number) => [c.r * k, c.g * k, c.b * k, 1];
/** The scene's lights, found by walking it */
export type Lights = {
ambient: THREE.Color | null;
directional: THREE.DirectionalLight[];
points: THREE.PointLight[];
spots: THREE.SpotLight[];
};
/** The one shadow cascade (WebGL2 has room for one, as Bevy on WebGL2 does) */
export type Cascade = { clipFromWorld: THREE.Matrix4; texel: number };
/** The light's world rotation as Bevy's looking_to gives it: -Z along the light, +Z back toward it */
function worldFromLight(toLight: THREE.Vector3): THREE.Matrix4 {
const z = toLight.clone().normalize();
const up = Math.abs(z.y) > 0.9999 ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(0, 1, 0);
const x = new THREE.Vector3().crossVectors(up, z).normalize();
const y = new THREE.Vector3().crossVectors(z, x);
return new THREE.Matrix4().makeBasis(x, y, z);
}
/** Where a directional light shines from: its position less its target's */
export function toLight(l: THREE.DirectionalLight | THREE.SpotLight): THREE.Vector3 {
const from = new THREE.Vector3().setFromMatrixPosition(l.matrixWorld);
const to = new THREE.Vector3().setFromMatrixPosition(l.target.matrixWorld);
const d = from.sub(to);
return d.lengthSq() > 0 ? d.normalize() : new THREE.Vector3(0, 1, 0);
}
/** One cascade as bevy_light's calculate_cascade makes it, fitted to what casts and catches shadow: the scene's
* bounds, narrowed (across the light) to what the camera sees of them, as Bevy's cascades cover the view */
export function cascade(toward: THREE.Vector3, bounds: THREE.Box3, cam: THREE.Camera, size: number): Cascade | null {
if (bounds.isEmpty()) return null;
const wfl = worldFromLight(toward);
const lfw = wfl.clone().transpose();
const box = new THREE.Box3();
const p = new THREE.Vector3();
for (let i = 0; i < 8; i++) {
p.set(i & 1 ? bounds.max.x : bounds.min.x, i & 2 ? bounds.max.y : bounds.min.y, i & 4 ? bounds.max.z : bounds.min.z);
box.expandByPoint(p.applyMatrix4(lfw));
}
// what the camera sees, as far as the scene reaches from it: its frustum's corners in the light's space
const eye = new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld);
const reach = Math.max(1, Math.sqrt(Math.max(bounds.distanceToPoint(eye) ** 2, ...[0, 1, 2, 3, 4, 5, 6, 7].map((i) => eye.distanceToSquared(new THREE.Vector3(i & 1 ? bounds.max.x : bounds.min.x, i & 2 ? bounds.max.y : bounds.min.y, i & 4 ? bounds.max.z : bounds.min.z))))));
const seen = new THREE.Box3();
const lfc = lfw.clone().multiply(cam.matrixWorld);
const inv = cam.projectionMatrixInverse;
for (let i = 0; i < 8; i++) {
// three's NDC corner, at the near plane or at `reach` along the view
p.set(i & 1 ? 1 : -1, i & 2 ? 1 : -1, -1).applyMatrix4(inv);
if (i & 4) {
if (cam instanceof THREE.OrthographicCamera) p.z = -reach;
else p.multiplyScalar(reach / Math.max(1e-6, -p.z));
}
seen.expandByPoint(p.applyMatrix4(lfc));
}
const min = new THREE.Vector2(Math.max(box.min.x, seen.min.x), Math.max(box.min.y, seen.min.y));
const max = new THREE.Vector2(Math.min(box.max.x, seen.max.x), Math.min(box.max.y, seen.max.y));
if (min.x >= max.x || min.y >= max.y) return null;
const margin = 0.02 * Math.max(max.x - min.x, max.y - min.y) + 0.05;
const diameter = Math.max(max.x - min.x, max.y - min.y) + 2 * margin;
const texel = diameter / size;
const near = new THREE.Vector3(
Math.floor((0.5 * (min.x + max.x)) / texel) * texel,
Math.floor((0.5 * (min.y + max.y)) / texel) * texel,
box.max.z + margin,
);
const cascadeFromWorld = lfw.clone().setPosition(-near.x, -near.y, -near.z);
const r = 1 / (near.z - (box.min.z - margin));
const clipFromCascade = new THREE.Matrix4().set(2 / diameter, 0, 0, 0, 0, 2 / diameter, 0, 0, 0, 0, r, 1, 0, 0, 0, 1);
return { clipFromWorld: clipFromCascade.multiply(cascadeFromWorld), texel };
}
/** The Lights block, the clustered lights and the one cluster's lists, as prepare_lights fills them for a 1x1x1
* cluster grid: every point and spot light in the one cluster */
export function fillLights(lights: Block, clustered: Block, offsets: Block, lists: Block, l: Lights, shadow: { light: THREE.DirectionalLight; cascade: Cascade } | null, width: number, height: number) {
const ambient = l.ambient ?? new THREE.Color(1, 1, 1).multiplyScalar(80);
lights.f("ambient_color", [ambient.r, ambient.g, ambient.b, 1]);
const dirs = l.directional.slice(0, MAX_DIRECTIONAL);
dirs.forEach((d, i) => {
const lux = toRaea("DirectionalLight", d.intensity) * LUX;
lights.f("directional_lights.color", rgb(d.color, lux), 0, i);
const t = toLight(d);
lights.f("directional_lights.direction_to_light", [t.x, t.y, t.z], 0, i);
const casts = shadow?.light === d;
lights.u("directional_lights.flags", casts ? 1 : 0, 0, i); // SHADOW_MAPS_ENABLED
lights.f("directional_lights.shadow_depth_bias", 0.02, 0, i);
lights.f("directional_lights.shadow_normal_bias", 1.8 * SQRT_2, 0, i);
lights.u("directional_lights.num_cascades", casts ? 1 : 0, 0, i);
lights.f("directional_lights.cascades_overlap_proportion", 0.3, 0, i);
lights.u("directional_lights.depth_texture_base_index", 0, 0, i);
lights.u("directional_lights.decal_index", 0xffffffff, 0, i);
lights.f("directional_lights.sun_disk_angular_size", 0.00930842, 0, i);
lights.f("directional_lights.sun_disk_intensity", 1, 0, i);
if (casts && shadow) {
lights.f("directional_lights.cascades.clip_from_world", shadow.cascade.clipFromWorld.elements, 0, i, 0);
lights.f("directional_lights.cascades.texel_size", shadow.cascade.texel, 0, i, 0);
lights.f("directional_lights.cascades.far_bound", 1e9, 0, i, 0);
}
});
const points = l.points.slice(0, MAX_CLUSTERED);
const spots = l.spots.slice(0, MAX_CLUSTERED - points.length);
const p = new THREE.Vector3();
const put = (k: number, light: THREE.PointLight | THREE.SpotLight, lumens: number) => {
const range = light.distance > 0 ? light.distance : 1000;
const c = rgb(light.color, lumens / (4 * Math.PI));
clustered.f("data.color_inverse_square_range", [c[0], c[1], c[2], 1 / (range * range)], 0, k);
p.setFromMatrixPosition(light.matrixWorld);
clustered.f("data.position_radius", [p.x, p.y, p.z, 0], 0, k);
clustered.f("data.shadow_depth_bias", 0.08, 0, k);
clustered.f("data.shadow_normal_bias", 0.6, 0, k);
clustered.f("data.shadow_map_near_z", 0.1, 0, k);
clustered.u("data.decal_index", 0xffffffff, 0, k);
clustered.f("data.range", range, 0, k);
};
points.forEach((pl, k) => put(k, pl, toRaea("PointLight", pl.intensity) * LUMENS));
spots.forEach((s, j) => {
const k = points.length + j;
put(k, s, toRaea("SpotLight", s.intensity) * LUMENS);
const dir = toLight(s).negate();
const outer = s.angle;
const inner = outer * (1 - s.penumbra);
const scale = 1 / Math.max(Math.cos(inner) - Math.cos(outer), 1e-4);
clustered.f("data.light_custom_data", [dir.x, dir.z, scale, -Math.cos(outer) * scale], 0, k);
clustered.u("data.flags", (1 << 5) | (dir.y < 0 ? 1 << 1 : 0), 0, k); // SPOT_LIGHT, SPOT_LIGHT_Y_NEGATIVE
clustered.f("data.spot_light_tan_angle", Math.tan(outer), 0, k);
});
// the one cluster: its lights from offset 0, its point lights then its spot lights (9 bits a count), and their
// indices four to a u32 (clustered_forward.wesl's WebGL2 unpacking)
offsets.u32[offsets.at("data") >> 2] = (points.length << 9) | spots.length;
for (let k = 0; k < points.length + spots.length; k++) lists.u32[(lists.at("data", 0, k >> 4) >> 2) + ((k >> 2) & 3)] |= k << (8 * (k & 3));
lights.u("cluster_dimensions", 1);
lights.u32[(lights.at("cluster_dimensions") >> 2) + 1] = 1;
lights.u32[(lights.at("cluster_dimensions") >> 2) + 2] = 1;
lights.u32[(lights.at("cluster_dimensions") >> 2) + 3] = 1;
lights.f("cluster_factors", [1 / width, 1 / height, 0, 0]);
lights.u("n_directional_lights", dirs.length);
lights.i("spot_light_shadowmap_offset", (shadow ? 1 : 0) - points.length);
lights.u("ambient_light_flags", 1); // AFFECTS_LIGHTMAPPED_MESHES
lights.u("n_rect_lights", 0);
}
/** One mesh's MeshUniform in its batch's slot */
export function fillMesh(b: Block, copy: number, slot: number, world: THREE.Matrix4, receives: boolean) {
const e = world.elements;
// world_from_local as Affine3::to_transpose: the affine's three rows, its translation in each w
const rows = [e[0], e[4], e[8], e[12], e[1], e[5], e[9], e[13], e[2], e[6], e[10], e[14]];
b.f("world_from_local", rows, copy, slot);
b.f("previous_world_from_local", rows, copy, slot);
// inverse_transpose_3x3, packed into a mat2x4 and an f32
const n = new THREE.Matrix3().getNormalMatrix(world).elements;
b.f("local_from_world_transpose_a", [n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]], copy, slot);
b.f("local_from_world_transpose_b", n[8], copy, slot);
// no LOD (u16::MAX), SHADOW_RECEIVER, SIGN_DETERMINANT_MODEL_3X3
b.u("flags", 0xffff | (receives ? 1 << 29 : 0) | (world.determinant() > 0 ? 1 << 31 : 0), copy, slot);
b.u("current_skin_index", 0xffffffff, copy, slot);
b.u("material_and_lightmap_bind_group_slot", 0xffff << 16, copy, slot);
b.u("morph_descriptor_index", 0xffffffff, copy, slot);
}
/** What a material draws with: its block's flags say which pictures it samples */
export type Surface = {
map?: THREE.Texture | null;
emissiveMap?: THREE.Texture | null;
mrMap?: THREE.Texture | null;
aoMap?: THREE.Texture | null;
blend: boolean;
doubleSided: boolean;
};
type AnyMaterial = THREE.Material & Partial<THREE.MeshPhysicalMaterial> & { color?: THREE.Color; map?: THREE.Texture | null };
/** One material's StandardMaterialUniform, from a three.js material raea's host made (materials.ts), times an
* instance's colour */
export function fillMaterial(b: Block, copy: number, material: THREE.Material, tint: THREE.Color | null, warn: (why: string) => void): Surface {
const m = material as AnyMaterial;
const c = m.color ?? new THREE.Color(1, 1, 1);
const t = tint ?? { r: 1, g: 1, b: 1 };
b.f("base_color", [c.r * t.r, c.g * t.g, c.b * t.b, m.opacity], copy);
const unlit = m instanceof THREE.MeshBasicMaterial;
const e = m.emissive;
const k = m.emissiveIntensity ?? 1;
// a StandardMaterial's emissive in nits, its exposure weight 0 (it skips the camera's exposure, as natively)
if (e) b.f("emissive", [e.r * k, e.g * k, e.b * k, 0], copy);
b.f("attenuation_color", [1, 1, 1, 1], copy);
const map = m.map ?? null;
const uv = map ? (map.matrixAutoUpdate && map.updateMatrix(), map.matrix.elements) : [1, 0, 0, 0, 1, 0, 0, 0, 1];
b.f("uv_transform", [uv[0], uv[1], uv[2], 0, uv[3], uv[4], uv[5], 0, uv[6], uv[7], uv[8], 0], copy);
// Bevy's reflectance 0.5 is three's specularIntensity 1 (materials.ts), tinted by the specular colour
const r = 0.5 * (m.specularIntensity ?? 1);
const st = m.specularColor ?? { r: 1, g: 1, b: 1 };
b.f("reflectance", [st.r * r, st.g * r, st.b * r], copy);
b.f("perceptual_roughness", m.roughness ?? 0.5, copy);
b.f("metallic", m.metalness ?? 0, copy);
b.f("ior", m.ior ?? 1.5, copy);
b.f("attenuation_distance", Infinity, copy);
b.f("clearcoat", m.clearcoat ?? 0, copy);
b.f("clearcoat_perceptual_roughness", m.clearcoatRoughness ?? 0.5, copy);
b.f("anisotropy_rotation", [1, 0], copy);
b.f("parallax_depth_scale", 0.1, copy);
b.f("max_parallax_layer_count", 16, copy);
b.f("lightmap_exposure", 1, copy);
b.u("max_relief_mapping_search_steps", 5, copy);
b.u("deferred_lighting_pass_id", 1, copy);
if ((m.transmission ?? 0) > 0) warn("transmission isn't drawn in a playable yet");
if (m.normalMap) warn("a normal map isn't drawn in a playable yet");
if ((m as { vertexColors?: boolean }).vertexColors) warn("vertex colours aren't drawn in a playable yet");
const s: Surface = { map, emissiveMap: m.emissiveMap, aoMap: m.aoMap, blend: false, doubleSided: m.side === THREE.DoubleSide };
if (m.roughnessMap || m.metalnessMap) {
if (!m.roughnessMap || m.roughnessMap === m.metalnessMap) s.mrMap = m.roughnessMap ?? m.metalnessMap;
else warn("separate roughness and metalness maps aren't drawn in a playable yet (one metallic-roughness map is)");
}
let flags = 1 << 8; // FOG_ENABLED
if (s.map) flags |= 1 << 0;
if (s.emissiveMap) flags |= 1 << 1;
if (s.mrMap) flags |= 1 << 2;
if (s.aoMap) flags |= 1 << 3;
if (s.doubleSided) flags |= 1 << 4;
if (unlit) flags |= 1 << 5;
let cutoff = 0.5;
if (m.alphaTest > 0) {
flags |= 1 << 29; // ALPHA_MODE_MASK
cutoff = m.alphaTest;
} else if (m.transparent && (m.opacity < 1 || !!map)) {
flags |= 2 << 29; // ALPHA_MODE_BLEND
s.blend = true;
}
b.u("flags", flags, copy);
b.f("alpha_cutoff", cutoff, copy);
return s;
}
/** The ambient light's colour times its brightness in cd/m² (a hemisphere light is drawn as the ambient between its
* two colours) */
export function ambientOf(l: THREE.AmbientLight | THREE.HemisphereLight, had: THREE.Color | null): THREE.Color {
const nits = toRaea("AmbientLight", l.intensity) * AMBIENT;
const c = l instanceof THREE.HemisphereLight ? l.color.clone().lerp(l.groundColor, 0.5) : l.color.clone();
return (had ?? new THREE.Color(0, 0, 0)).add(c.multiplyScalar(nits));
}
/** Bevy's distance fog (prepare_fog's GpuFog) from the scene's, as the native engine makes it from a Fog part: a
* density makes it exponential, else linear from near to far; none is mode 0, which the shader passes over */
export function fillFog(b: Block, fog: THREE.Fog | THREE.FogExp2 | null) {
if (!fog) return;
const c = fog.color;
b.f("base_color", [c.r, c.g, c.b, 1]);
b.f("directional_light_color", [0, 0, 0, 0]);
b.f("directional_light_exponent", 8);
if (fog instanceof THREE.FogExp2) {
b.f("be", [fog.density, 0, 0]);
b.u("mode", 2);
} else {
b.f("be", [fog.near, fog.far, 0]);
b.u("mode", 1);
}
}
+214
View File
@@ -0,0 +1,214 @@
// WebGL2 plumbing for Bevy's programs in a playable (docs/playables.feature PA11): programs linked with each uniform
// block on its binding's point and each sampler on its unit, by the names Bevy's files give them (programs.ts), and
// the scene's geometry and pictures as GL buffers and textures, kept while the scene holds them.
import * as THREE from "three";
import { BLOCKS, SAMPLERS } from "./programs";
/** Each of Bevy's uniform bindings on its own binding point */
export const POINTS: Record<string, number> = {
view: 0, lights: 1, cluster_offsets_and_counts: 2, clusterable_object_index_lists: 3, clustered_lights: 4,
globals: 5, mesh: 6, material: 7, metadata: 8, fog: 9,
};
/** Each of Bevy's textures on its own unit */
export const UNITS: Record<string, number> = {
base_color_texture: 0, emissive_texture: 1, metallic_roughness_texture: 2, occlusion_texture: 3,
directional_shadow_textures: 4, point_shadow_textures: 5, raea_gi: 6,
};
/** A program linking: compiled and linked as soon as it's asked for, its blocks and samplers bound (which waits for
* the link) only when it's first drawn with, so the driver compiles it while the page's first frame is being built */
export class Program {
private done = false;
first: WebGLUniformLocation | null = null;
constructor(private gl: WebGL2RenderingContext, readonly p: WebGLProgram, private shaders: WebGLShader[]) {}
/** Linked and bound; throws when it didn't link */
use() {
const gl = this.gl;
gl.useProgram(this.p);
if (this.done) return;
this.done = true;
const p = this.p;
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
const why = this.shaders.map((s) => gl.getShaderInfoLog(s)).find(Boolean) || gl.getProgramInfoLog(p);
throw new Error(`raea playable: Bevy's programs didn't link: ${why}`);
}
for (const s of this.shaders) gl.deleteShader(s);
const blocks = gl.getProgramParameter(p, gl.ACTIVE_UNIFORM_BLOCKS) as number;
for (let i = 0; i < blocks; i++) {
const name = gl.getActiveUniformBlockName(p, i) ?? "";
const point = POINTS[BLOCKS[name] ?? ""];
if (point === undefined) throw new Error(`raea playable: Bevy's uniform block ${name} has no binding`);
gl.uniformBlockBinding(p, i, point);
}
for (const [name, texture] of Object.entries(SAMPLERS)) {
const at = gl.getUniformLocation(p, name);
if (at) gl.uniform1i(at, UNITS[texture]);
}
this.first = gl.getUniformLocation(p, "naga_vs_first_instance");
}
}
function shader(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
return s;
}
/** Programs compiled and linked, without waiting for either */
export function programs(gl: WebGL2RenderingContext, pairs: [string, string][]): Program[] {
return pairs.map(([vs, fs]) => {
const p = gl.createProgram()!;
const v = shader(gl, gl.VERTEX_SHADER, vs);
const f = shader(gl, gl.FRAGMENT_SHADER, fs);
gl.attachShader(p, v);
gl.attachShader(p, f);
gl.linkProgram(p);
return new Program(gl, p, [v, f]);
});
}
/** One picture's texture, made again when three.js marks it changed */
type Kept = { tex: WebGLTexture; version: number; seen: number };
const WRAP: Record<number, number> = { [THREE.RepeatWrapping]: 0x2901, [THREE.ClampToEdgeWrapping]: 0x812f, [THREE.MirroredRepeatWrapping]: 0x8370 };
/** The scene's pictures as textures: a colour picture in sRGB (sampled as linear, as Bevy's Rgba8UnormSrgb is) */
export class Textures {
private kept = new Map<THREE.Texture, Kept>();
private frame = 0;
/** Bevy's fallback for a texture a material doesn't have: white */
readonly white: WebGLTexture;
/** raea GI's screen with nothing in it: every pixel's light comes from the ambient light, as natively without GI */
readonly none: WebGLTexture;
constructor(private gl: WebGL2RenderingContext) {
this.white = this.pixel([255, 255, 255, 255]);
this.none = this.pixel([0, 0, 0, 0]);
}
private pixel(rgba: number[]): WebGLTexture {
const gl = this.gl;
const t = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(rgba));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
return t;
}
/** A three.js texture's GL texture, or undefined until its picture has loaded */
get(t: THREE.Texture | null | undefined): WebGLTexture | undefined {
if (!t) return undefined;
const img = t.image as (TexImageSource & { width?: number; height?: number; complete?: boolean; data?: ArrayBufferView }) | undefined;
if (!img || img.complete === false || !(img.width ?? 0)) return undefined;
const gl = this.gl;
let k = this.kept.get(t);
if (k && k.version === t.version) {
k.seen = this.frame;
return k.tex;
}
const tex = k?.tex ?? gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, t.flipY);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, t.premultiplyAlpha);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, t.unpackAlignment);
const srgb = t.colorSpace === THREE.SRGBColorSpace;
const internal = srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8;
if (img.data) gl.texImage2D(gl.TEXTURE_2D, 0, internal, img.width!, img.height!, 0, gl.RGBA, gl.UNSIGNED_BYTE, img.data);
else gl.texImage2D(gl.TEXTURE_2D, 0, internal, gl.RGBA, gl.UNSIGNED_BYTE, img);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, WRAP[t.wrapS] ?? gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, WRAP[t.wrapT] ?? gl.CLAMP_TO_EDGE);
this.kept.set(t, { tex, version: t.version, seen: this.frame });
return tex;
}
/** The end of a frame: a texture the scene no longer draws is let go */
done() {
for (const [t, k] of this.kept)
if (k.seen < this.frame - 1) {
this.gl.deleteTexture(k.tex);
this.kept.delete(t);
}
this.frame++;
}
}
/** One geometry's vertex array: positions, normals and UVs at Bevy's locations 0, 1 and 2, and its indices */
export type Mesh = { vao: WebGLVertexArrayObject; count: number; index: number; buffers: WebGLBuffer[]; version: string; seen: number };
export class Meshes {
private kept = new Map<THREE.BufferGeometry, Mesh>();
private frame = 0;
constructor(private gl: WebGL2RenderingContext) {}
get(g: THREE.BufferGeometry): Mesh | undefined {
const pos = g.attributes.position as THREE.BufferAttribute | undefined;
if (!pos) return undefined;
const nor = g.attributes.normal as THREE.BufferAttribute | undefined;
const uv = g.attributes.uv as THREE.BufferAttribute | undefined;
const version = `${pos.version}.${nor?.version ?? -1}.${uv?.version ?? -1}.${g.index?.version ?? -1}`;
let m = this.kept.get(g);
if (m && m.version === version) {
m.seen = this.frame;
return m;
}
const gl = this.gl;
if (m) this.free(m);
const vao = gl.createVertexArray()!;
gl.bindVertexArray(vao);
const buffers: WebGLBuffer[] = [];
const attr = (loc: number, a: THREE.BufferAttribute | undefined, size: number) => {
if (!a) {
gl.disableVertexAttribArray(loc);
gl.vertexAttrib4f(loc, 0, 0, 0, 0);
return;
}
const b = gl.createBuffer()!;
buffers.push(b);
gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, a.array as Float32Array, gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
};
attr(0, pos, 3);
attr(1, nor, 3);
attr(2, uv, 2);
let index = 0;
if (g.index) {
const b = gl.createBuffer()!;
buffers.push(b);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b);
const arr = g.index.array;
const wide = arr instanceof Uint32Array || (!(arr instanceof Uint16Array) && pos.count > 65535);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, wide ? Uint32Array.from(arr) : Uint16Array.from(arr), gl.STATIC_DRAW);
index = wide ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT;
}
gl.bindVertexArray(null);
m = { vao, count: g.index ? g.index.count : pos.count, index, buffers, version, seen: this.frame };
this.kept.set(g, m);
return m;
}
private free(m: Mesh) {
this.gl.deleteVertexArray(m.vao);
for (const b of m.buffers) this.gl.deleteBuffer(b);
}
done() {
for (const [g, m] of this.kept)
if (m.seen < this.frame - 1) {
this.free(m);
this.kept.delete(g);
}
this.frame++;
}
}
+1
View File
@@ -0,0 +1 @@
e79d0a380e1b6a00a0c7a9f21f1d6aa19fa1ec3673f1aea423c4ba4f087b9a65
+10
View File
@@ -0,0 +1,10 @@
// Bevy's PBR programs for a playable, as tools/bevy-glsl makes them (docs/playables.feature PA11): generated by
// sdk/playable/bevy/build.sh, not edited. Each program's GLSL ES 3.00; which of Bevy's bindings each uniform block
// and sampler is; each binding's fields at their byte offsets (nested fields from their struct's start, an array's
// stride under `name[]`).
export const PBR_VERT = "#version 300 es\nprecision highp float;\nprecision highp int;\nuniform uint naga_vs_first_instance;\nstruct _1bevy_pbr_render_1forward_io_Vertex {\nuint instance_index;\nvec3 position;\nvec3 normal;\nvec2 uv;\n};\nstruct _1bevy_pbr_render_1forward_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nvec3 world_normal;\nvec2 uv;\nuint instance_index;\n};\nstruct _1bevy_pbr_render_1forward_io_UncompressedVertex {\nuint instance_index;\nvec3 position;\nvec3 normal;\nvec2 uv;\n};\nstruct _1bevy_render_mesh_1metadata_types_MeshMetadata {\nvec3 aabb_center;\nuint pad_a;\nvec3 aabb_half_extents;\nuint pad_b;\nvec4 uv_channels_min_and_extents[2];\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nlayout(std140) uniform _1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex { _1bevy_render_mesh_1metadata_types_MeshMetadata _group_2_binding_9_vs; };\nlayout(std140) uniform type_10_block_1Vertex { _1bevy_pbr_render_1mesh_types_Mesh _group_2_binding_0_vs[93]; };\nlayout(std140) uniform _1bevy_render_view_View_block_2Vertex { _1bevy_render_view_View _group_0_binding_0_vs; };\nlayout(location = 0) in vec3 _p2vs_location0;\nlayout(location = 1) in vec3 _p2vs_location1;\nlayout(location = 2) in vec2 _p2vs_location2;\nsmooth out vec4 _vs2fs_location0;\nsmooth out vec3 _vs2fs_location1;\nsmooth out vec2 _vs2fs_location2;\nflat out uint _vs2fs_location6;\n_1bevy_render_mesh_1metadata_types_MeshMetadata _1bevy_pbr_render_1mesh_functions_1get_metadata(uint instance_index) {\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _group_2_binding_9_vs;\nreturn _e2;\n}\n_1bevy_pbr_render_1forward_io_UncompressedVertex _1bevy_pbr_render_1forward_io_1decompress_vertex(_1bevy_pbr_render_1forward_io_Vertex vertex_in, uint instance_index_1) {\n_1bevy_pbr_render_1forward_io_UncompressedVertex uncompressed_vertex = _1bevy_pbr_render_1forward_io_UncompressedVertex(0u, vec3(0.0), vec3(0.0), vec2(0.0));\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _1bevy_pbr_render_1mesh_functions_1get_metadata(instance_index_1);\nuncompressed_vertex.instance_index = instance_index_1;\nuncompressed_vertex.position = vertex_in.position;\nuncompressed_vertex.normal = vertex_in.normal;\nuncompressed_vertex.uv = vertex_in.uv;\n_1bevy_pbr_render_1forward_io_UncompressedVertex _e11 = uncompressed_vertex;\nreturn _e11;\n}\nmat4x4 _1bevy_render_maths_2affine3_to_square(mat3x4 affine) {\nreturn transpose(mat4x4(affine[0], affine[1], affine[2], vec4(0.0, 0.0, 0.0, 1.0)));\n}\nmat4x4 _1bevy_pbr_render_1mesh_functions_3get_world_from_local(uint instance_index_2) {\nmat3x4 _e4 = _group_2_binding_0_vs[instance_index_2].world_from_local;\nmat4x4 _e5 = _1bevy_render_maths_2affine3_to_square(_e4);\nreturn _e5;\n}\nmat3x3 _1bevy_render_maths_4mat2x4_f32_to_mat3x3_unpack(mat2x4 a, float b) {\nreturn mat3x3(a[0].xyz, vec3(a[0].w, a[1].xy), vec3(a[1].zw, b));\n}\nvec3 _1bevy_pbr_render_1mesh_functions_4mesh_normal_local_to_world(vec3 vertex_normal, uint instance_index_3) {\nif (any(notEqual(vertex_normal, vec3(0.0)))) {\nmat2x4 _e9 = _group_2_binding_0_vs[instance_index_3].local_from_world_transpose_a;\nfloat _e13 = _group_2_binding_0_vs[instance_index_3].local_from_world_transpose_b;\nmat3x3 _e14 = _1bevy_render_maths_4mat2x4_f32_to_mat3x3_unpack(_e9, _e13);\nreturn normalize((_e14 * vertex_normal));\n} else {\nreturn vertex_normal;\n}\n}\nvec4 _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(mat4x4 world_from_local_1, vec4 vertex_position) {\nreturn (world_from_local_1 * vertex_position);\n}\nvec4 _1bevy_pbr_render_1view_transformations_3position_world_to_clip(vec3 world_pos) {\nmat4x4 _e3 = _group_0_binding_0_vs.clip_from_world;\nvec4 clip_pos = (_e3 * vec4(world_pos, 1.0));\nreturn clip_pos;\n}\nvoid main() {\n_1bevy_pbr_render_1forward_io_Vertex vertex_no_morph = _1bevy_pbr_render_1forward_io_Vertex((uint(gl_InstanceID) + naga_vs_first_instance), _p2vs_location0, _p2vs_location1, _p2vs_location2);\n_1bevy_pbr_render_1forward_io_VertexOutput out_ = _1Line truncated
export const PBR_FRAG = "#version 300 es\nprecision highp float;\nprecision highp int;\nstruct _1bevy_pbr_render_1forward_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nvec3 world_normal;\nvec2 uv;\nuint instance_index;\n};\nstruct _1bevy_pbr_render_1forward_io_FragmentOutput {\nvec4 color;\n};\nstruct _1bevy_pbr_render_1pbr_types_StandardMaterial {\nvec4 base_color;\nvec4 emissive;\nvec4 attenuation_color;\nmat3x3 uv_transform;\nvec3 reflectance;\nfloat perceptual_roughness;\nfloat metallic;\nfloat diffuse_transmission;\nfloat specular_transmission;\nfloat thickness;\nfloat ior;\nfloat attenuation_distance;\nfloat clearcoat;\nfloat clearcoat_perceptual_roughness;\nfloat anisotropy_strength;\nvec2 anisotropy_rotation;\nuint flags;\nfloat alpha_cutoff;\nfloat parallax_depth_scale;\nfloat max_parallax_layer_count;\nfloat lightmap_exposure;\nuint max_relief_mapping_search_steps;\nuint deferred_lighting_pass_id;\n};\nstruct _1bevy_pbr_render_1pbr_types_PbrInput {\n_1bevy_pbr_render_1pbr_types_StandardMaterial material;\nvec3 diffuse_occlusion;\nfloat specular_occlusion;\nvec4 frag_coord;\nvec4 world_position;\nvec3 world_normal;\nvec3 N;\nvec3 V;\nvec3 lightmap_light;\nvec3 clearcoat_N;\nfloat anisotropy_strength;\nvec3 anisotropy_T;\nvec3 anisotropy_B;\nbool is_orthographic;\nuint flags;\nfloat directional_shadow_factor;\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nstruct _1bevy_pbr_render_1pbr_functions_SampleBias {\nfloat mip_bias;\n};\nstruct _1bevy_pbr_render_1pbr_lighting_LayerLightingInput {\nvec3 N;\nvec3 R;\nfloat NdotV;\nfloat perceptual_roughness;\nfloat roughness;\n};\nstruct _1bevy_pbr_render_1pbr_lighting_LightingInput {\n_1bevy_pbr_render_1pbr_lighting_LayerLightingInput layers[1];\nvec3 P;\nvec3 V;\nvec3 diffuse_color;\nfloat metallic;\nvec3 F0_dielectric;\nvec3 F0_metallic;\nvec2 F_ab;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_DirectionalCascade {\nmat4x4 clip_from_world;\nfloat texel_size;\nfloat far_bound;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_DirectionalLight {\n_1bevy_pbr_render_2mesh_view_types_DirectionalCascade cascades[1];\nvec4 color;\nvec3 direction_to_light;\nuint flags;\nfloat soft_shadow_size;\nfloat shadow_depth_bias;\nfloat shadow_normal_bias;\nuint num_cascades;\nfloat cascades_overlap_proportion;\nuint depth_texture_base_index;\nuint decal_index;\nfloat sun_disk_angular_size;\nfloat sun_disk_intensity;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_RectLight {\nvec4 color;\nvec3 position;\nfloat width;\nvec3 right;\nfloat height;\nvec3 up;\nfloat range;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_Lights {\n_1bevy_pbr_render_2mesh_view_types_DirectionalLight directional_lights[10];\nvec4 ambient_color;\nuvec4 cluster_dimensions;\nvec4 cluster_factors;\nuint n_directional_lights;\nint spot_light_shadowmap_offset;\nuint ambient_light_flags;\nuint n_rect_lights;\n_1bevy_pbr_render_2mesh_view_types_RectLight rect_lights[8];\n};\nstruct _1bevy_pbr_render_1clustered_forward_ClusterableObjectIndexRanges {\nuint first_point_light_index_offset;\nuint first_spot_light_index_offset;\nuint first_rect_light_index_offset;\nuint first_reflection_probe_index_offset;\nuint first_irradiance_volume_index_offset;\nuint first_decal_offset;\nuint last_clusterable_object_index_offset;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusterOffsetsAndCounts {\nuvec4 data[1024];\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusterableObjectIndexLists {\nuvec4 data[1024];\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusteredLight {\nvec4 light_custom_data;\nvec4 color_inverse_square_range;\nvec4 position_radius;\nuint flags;\nfloat shadow_depth_bias;\nfloat shadow_normal_bias;\nfloat spot_light_tan_angle;\nfloat soft_shadow_size;\nfloat shadow_map_near_z;\nuint decal_index;\nfloat range;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusteredLights {\n_1bevy_pbr_render_2mesh_view_types_ClusteredLight data[204];\n};\nstruct _1bevy_render_globals_Globals {\nfloat time;\nfloat delta_time;\nuint frame_count;\Line truncated
export const SHADOW_VERT = "#version 300 es\nprecision highp float;\nprecision highp int;\nuniform uint naga_vs_first_instance;\nstruct _1bevy_pbr_prepass_io_Vertex {\nuint instance_index;\nvec3 position;\n};\nstruct _1bevy_pbr_prepass_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nfloat unclipped_depth;\nuint instance_index;\n};\nstruct _1bevy_pbr_prepass_io_UncompressedVertex {\nuint instance_index;\nvec3 position;\n};\nstruct _1bevy_render_mesh_1metadata_types_MeshMetadata {\nvec3 aabb_center;\nuint pad_a;\nvec3 aabb_half_extents;\nuint pad_b;\nvec4 uv_channels_min_and_extents[2];\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nlayout(std140) uniform _1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex { _1bevy_render_mesh_1metadata_types_MeshMetadata _group_2_binding_9_vs; };\nlayout(std140) uniform type_9_block_1Vertex { _1bevy_pbr_render_1mesh_types_Mesh _group_2_binding_0_vs[93]; };\nlayout(std140) uniform _1bevy_render_view_View_block_2Vertex { _1bevy_render_view_View _group_0_binding_0_vs; };\nlayout(location = 0) in vec3 _p2vs_location0;\nsmooth out vec4 _vs2fs_location4;\nsmooth out float _vs2fs_location6;\nflat out uint _vs2fs_location7;\n_1bevy_render_mesh_1metadata_types_MeshMetadata _1bevy_pbr_render_1mesh_functions_1get_metadata(uint instance_index) {\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _group_2_binding_9_vs;\nreturn _e2;\n}\n_1bevy_pbr_prepass_io_UncompressedVertex _1bevy_pbr_prepass_io_1decompress_vertex(_1bevy_pbr_prepass_io_Vertex vertex_in, uint instance_index_1) {\n_1bevy_pbr_prepass_io_UncompressedVertex uncompressed_vertex = _1bevy_pbr_prepass_io_UncompressedVertex(0u, vec3(0.0));\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _1bevy_pbr_render_1mesh_functions_1get_metadata(instance_index_1);\nuncompressed_vertex.instance_index = instance_index_1;\nuncompressed_vertex.position = vertex_in.position;\n_1bevy_pbr_prepass_io_UncompressedVertex _e7 = uncompressed_vertex;\nreturn _e7;\n}\nmat4x4 _1bevy_render_maths_2affine3_to_square(mat3x4 affine) {\nreturn transpose(mat4x4(affine[0], affine[1], affine[2], vec4(0.0, 0.0, 0.0, 1.0)));\n}\nmat4x4 _1bevy_pbr_render_1mesh_functions_3get_world_from_local(uint instance_index_2) {\nmat3x4 _e4 = _group_2_binding_0_vs[instance_index_2].world_from_local;\nmat4x4 _e5 = _1bevy_render_maths_2affine3_to_square(_e4);\nreturn _e5;\n}\nvec4 _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(mat4x4 world_from_local_1, vec4 vertex_position) {\nreturn (world_from_local_1 * vertex_position);\n}\nvec4 _1bevy_pbr_render_1view_transformations_3position_world_to_clip(vec3 world_pos) {\nmat4x4 _e3 = _group_0_binding_0_vs.clip_from_world;\nvec4 clip_pos = (_e3 * vec4(world_pos, 1.0));\nreturn clip_pos;\n}\nvoid main() {\n_1bevy_pbr_prepass_io_Vertex vertex_no_morph = _1bevy_pbr_prepass_io_Vertex((uint(gl_InstanceID) + naga_vs_first_instance), _p2vs_location0);\n_1bevy_pbr_prepass_io_VertexOutput out_ = _1bevy_pbr_prepass_io_VertexOutput(vec4(0.0), vec4(0.0), 0.0, 0u);\n_1bevy_pbr_prepass_io_UncompressedVertex vertex_1 = _1bevy_pbr_prepass_io_UncompressedVertex(0u, vec3(0.0));\nmat4x4 world_from_local = mat4x4(0.0);\n_1bevy_pbr_prepass_io_UncompressedVertex _e3 = _1bevy_pbr_prepass_io_1decompress_vertex(vertex_no_morph, vertex_no_morph.instance_index);\nvertex_1 = _e3;\nmat4x4 _e6 = _1bevy_pbr_render_1mesh_functions_3get_world_from_local(vertex_no_morph.instance_index);\nworld_from_local = _e6;\nmat4x4 _e9 = world_from_local;\nvec3 _e11 = vertex_1.position;\nvec4 _e14 = _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(_e9, vec4(_e11, 1.0));\nout_.world_position = _e14;\nvec4 _e17 = out_.world_position;\nvec4 _e19 = _1bevy_pbr_render_1view_transformations_3position_world_to_clip(_e17.xyz);\nout_.position = _e19;\nfloat _e23 = out_.position.z;\nout_.unclipped_depth = _e23;\nfloat _e28 = out_.position.z;\nout_.position.z = min(_e28, 1.0);\nout_.instance_index = vertex_no_morph.instance_index;\n_1bevy_pbr_prepass_io_VertexOutput _eLine truncated
export const BLOCKS: Record<string, string> = {"_1bevy_pbr_render_1pbr_types_StandardMaterial_block_1Fragment":"material","_1bevy_pbr_render_2mesh_view_types_ClusterOffsetsAndCounts_block_4Fragment":"cluster_offsets_and_counts","_1bevy_pbr_render_2mesh_view_types_ClusterableObjectIndexLists_block_5Fragment":"clusterable_object_index_lists","_1bevy_pbr_render_2mesh_view_types_ClusteredLights_block_6Fragment":"clustered_lights","_1bevy_pbr_render_2mesh_view_types_Fog_block_8Fragment":"fog","_1bevy_pbr_render_2mesh_view_types_Lights_block_3Fragment":"lights","_1bevy_render_globals_Globals_block_7Fragment":"globals","_1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex":"metadata","_1bevy_render_view_View_block_2Fragment":"view","_1bevy_render_view_View_block_2Vertex":"view","type_10_block_0Fragment":"mesh","type_10_block_1Vertex":"mesh","type_9_block_1Vertex":"mesh"};
export const SAMPLERS: Record<string, string> = {"_group_0_binding_2_fs":"point_shadow_textures","_group_0_binding_41_fs":"raea_gi","_group_0_binding_5_fs":"directional_shadow_textures","_group_3_binding_1_fs":"base_color_texture","_group_3_binding_3_fs":"emissive_texture","_group_3_binding_5_fs":"metallic_roughness_texture","_group_3_binding_7_fs":"occlusion_texture"};
export const LAYOUT: Record<string, Record<string, number>> = {"cluster_offsets_and_counts":{"$size":16384,"data":0,"data[]":16},"clusterable_object_index_lists":{"$size":16384,"data":0,"data[]":16},"clustered_lights":{"$size":16320,"data":0,"data.color_inverse_square_range":16,"data.decal_index":72,"data.flags":48,"data.light_custom_data":0,"data.position_radius":32,"data.range":76,"data.shadow_depth_bias":52,"data.shadow_map_near_z":68,"data.shadow_normal_bias":56,"data.soft_shadow_size":64,"data.spot_light_tan_angle":60,"data[]":80},"fog":{"$size":64,"base_color":0,"be":32,"bi":48,"directional_light_color":16,"directional_light_exponent":44,"mode":60},"globals":{"$size":16,"_webgl2_padding":12,"delta_time":4,"frame_count":8,"time":0},"lights":{"$size":2176,"ambient_color":1600,"ambient_light_flags":1656,"cluster_dimensions":1616,"cluster_factors":1632,"directional_lights":0,"directional_lights.cascades":0,"directional_lights.cascades.clip_from_world":0,"directional_lights.cascades.far_bound":68,"directional_lights.cascades.texel_size":64,"directional_lights.cascades[]":80,"directional_lights.cascades_overlap_proportion":128,"directional_lights.color":80,"directional_lights.decal_index":136,"directional_lights.depth_texture_base_index":132,"directional_lights.direction_to_light":96,"directional_lights.flags":108,"directional_lights.num_cascades":124,"directional_lights.shadow_depth_bias":116,"directional_lights.shadow_normal_bias":120,"directional_lights.soft_shadow_size":112,"directional_lights.sun_disk_angular_size":140,"directional_lights.sun_disk_intensity":144,"directional_lights[]":160,"n_directional_lights":1648,"n_rect_lights":1660,"rect_lights":1664,"rect_lights.color":0,"rect_lights.height":44,"rect_lights.position":16,"rect_lights.range":60,"rect_lights.right":32,"rect_lights.up":48,"rect_lights.width":28,"rect_lights[]":64,"spot_light_shadowmap_offset":1652},"material":{"$size":192,"alpha_cutoff":164,"anisotropy_rotation":152,"anisotropy_strength":144,"attenuation_color":32,"attenuation_distance":132,"base_color":0,"clearcoat":136,"clearcoat_perceptual_roughness":140,"deferred_lighting_pass_id":184,"diffuse_transmission":116,"emissive":16,"flags":160,"ior":128,"lightmap_exposure":176,"max_parallax_layer_count":172,"max_relief_mapping_search_steps":180,"metallic":112,"parallax_depth_scale":168,"perceptual_roughness":108,"reflectance":96,"specular_transmission":120,"thickness":124,"uv_transform":48},"mesh":{"$size":16368,"[]":176,"current_skin_index":148,"first_vertex_index":144,"flags":132,"lightmap_uv_rect":136,"local_from_world_transpose_a":96,"local_from_world_transpose_b":128,"material_and_lightmap_bind_group_slot":152,"metadata_index":164,"morph_descriptor_index":160,"previous_world_from_local":48,"tag":156,"world_from_local":0},"metadata":{"$size":64,"aabb_center":0,"aabb_half_extents":16,"pad_a":12,"pad_b":28,"uv_channels_min_and_extents":32,"uv_channels_min_and_extents[]":16},"view":{"$size":784,"clip_from_view":320,"clip_from_world":0,"color_grading":608,"color_grading.balance":0,"color_grading.contrast":64,"color_grading.exposure":136,"color_grading.gain":96,"color_grading.gamma":80,"color_grading.hue":140,"color_grading.lift":112,"color_grading.midtone_range":128,"color_grading.post_saturation":144,"color_grading.saturation":48,"exposure":460,"frame_count":772,"frustum":496,"frustum[]":16,"lod_view_world_position":592,"main_pass_viewport":480,"mip_bias":768,"unjittered_clip_from_world":64,"view_from_clip":384,"view_from_world":256,"viewport":464,"world_from_clip":128,"world_from_view":192,"world_position":448}};
+51
View File
@@ -0,0 +1,51 @@
// raea/ecs's world in a playable (docs/playables.feature PA12): Bevy's own ECS (runtime/ecs, built to ecs.wasm by
// sdk/playable/ecs/build.sh), which the export carries as __raeaEcsWasm for a game that makes a World. The entry
// imports this before the game, so a World made as the game's module loads is already Bevy's. Calls go through
// __raeaEcs as raea's V8 sends them through __raea_call (sdk/app native.ts ecsCall); a page where the module can't be
// made keeps raea/ecs's TypeScript tables, which behave the same.
type Exports = {
memory: WebAssembly.Memory;
raea_alloc(len: number): number;
raea_free(p: number, len: number): void;
/** where the answer is: its address in the high 32 bits, its length in the low */
raea_call(np: number, nl: number, ap: number, al: number): bigint;
};
/** What ran, for tools/check.ts: the calls the world answered */
export type EcsStats = { calls: number; bytes: number };
const g = globalThis as { __raeaEcsWasm?: string; __raeaEcs?: (name: string, json: string) => string; __raeaEcsStats?: EcsStats; __raea_call?: unknown };
if (g.__raeaEcsWasm && typeof g.__raea_call !== "function") {
try {
const s = atob(g.__raeaEcsWasm);
const bin = new Uint8Array(s.length);
for (let i = 0; i < s.length; i++) bin[i] = s.charCodeAt(i);
// synchronous, as raea/ecs's calls are: WebKit compiles a module of any size on the page's thread
const x = new WebAssembly.Instance(new WebAssembly.Module(bin), {}).exports as unknown as Exports;
const enc = new TextEncoder();
const dec = new TextDecoder();
const stats: EcsStats = (g.__raeaEcsStats = { calls: 0, bytes: bin.length });
const put = (text: string): [number, number] => {
const b = enc.encode(text);
const p = x.raea_alloc(b.length);
new Uint8Array(x.memory.buffer, p, b.length).set(b);
return [p, b.length];
};
g.__raeaEcs = (name, json) => {
const [np, nl] = put(name);
const [ap, al] = put(json);
const at = x.raea_call(np, nl, ap, al);
x.raea_free(np, nl);
x.raea_free(ap, al);
const out = dec.decode(new Uint8Array(x.memory.buffer, Number(at >> 32n), Number(at & 0xffffffffn)));
stats.calls++;
if (out[0] !== "o") throw new Error(`${name}: ${out.slice(1)}`);
return out.slice(1);
};
} catch (e) {
console.warn("raea playable: Bevy's world didn't load, so raea/ecs keeps its TypeScript tables", e);
}
}
delete g.__raeaEcsWasm;
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
2e6fac7b3f0fba3852f43ff79bba2546e489eb6afabfb55c70dbe42828d4c72c
-31
View File
@@ -1,31 +0,0 @@
// A playable's 3D drawn by three.js (raea's three.js host, sdk/r3f/src/three, through scene.ts), tone-mapped by
// Bevy's own curve (tonemap.ts). The export bundles it only for a game whose lint found a 3D kind (PA15).
import * as THREE from "three";
import type { Draw3d } from "./draw3d";
import { Scene3d } from "./scene";
import { Tonemap } from "./tonemap";
export function three3d(canvas: HTMLCanvasElement): Draw3d {
// the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const tonemap = new Tonemap(renderer);
const scene = new Scene3d();
return {
fit(width, height, scale) {
// the canvas is drawn at the screen's pixels, not the composition's
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * scale);
renderer.setSize(width, height, false);
tonemap.resize();
scene.fit(width, height);
},
sync(page, seconds) {
scene.sync(page, seconds);
return scene.any;
},
draw() {
tonemap.render(scene.scene, scene.camera);
},
};
}
-65
View File
@@ -1,65 +0,0 @@
// Bevy's tone mapping in the playable (docs/playables.feature PA10): the 3D drawn into a half-float target with no
// tone curve, then one full-screen pass maps it through TonyMcMapface (Bevy's default, tools/tony.ts's table) and
// encodes sRGB, as bevy_core_pipeline's tonemapping.wesl does. Where nothing was drawn it stays transparent, so the
// page's background shows through as it does under the native engine's 3D.
import * as THREE from "three";
import tony from "./tony.bin";
const N = Math.round(Math.cbrt(tony.length / 3));
const FRAG = /* glsl */ `
precision highp float;
precision highp sampler3D;
uniform sampler2D scene;
uniform sampler3D lut;
in vec2 vUv;
out vec4 color;
void main() {
vec4 c = texture(scene, vUv);
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0));
vec3 uv = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
// the table holds sRGB-encoded bytes, already the screen's values
color = vec4(texture(lut, clamp(uv, 0.0, 1.0)).rgb * c.a, c.a);
}`;
const VERT = /* glsl */ `
in vec3 position;
in vec2 uv;
out vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
export class Tonemap {
private target: THREE.WebGLRenderTarget;
private quad: THREE.Mesh;
private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
constructor(private renderer: THREE.WebGLRenderer) {
renderer.toneMapping = THREE.NoToneMapping;
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4, colorSpace: THREE.LinearSRGBColorSpace });
const rgba = new Uint8Array(N * N * N * 4);
for (let i = 0; i < N * N * N; i++) rgba.set([tony[i * 3], tony[i * 3 + 1], tony[i * 3 + 2], 255], i * 4);
const lut = new THREE.Data3DTexture(rgba, N, N, N);
lut.minFilter = lut.magFilter = THREE.LinearFilter;
lut.unpackAlignment = 1;
lut.needsUpdate = true;
const material = new THREE.RawShaderMaterial({ glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: { scene: { value: this.target.texture }, lut: { value: lut } }, transparent: true, premultipliedAlpha: true, blending: THREE.NoBlending, depthTest: false, depthWrite: false });
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
}
/** The target sized to the canvas's drawing buffer */
resize() {
const s = this.renderer.getDrawingBufferSize(new THREE.Vector2());
this.target.setSize(s.x, s.y);
}
render(scene: THREE.Scene, camera: THREE.Camera) {
const r = this.renderer;
r.setRenderTarget(this.target);
r.setClearColor(0x000000, 0);
r.clear();
r.render(scene, camera);
r.setRenderTarget(null);
r.render(this.quad, this.camera);
}
}
+3 -1
View File
@@ -78,7 +78,9 @@ const state = (await p.evaluate(() => ({
events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [],
// a game with sound (PA6): what played after the first touch (host/sound.ts)
sound: (globalThis as { __raeaSound?: { events: number; clips: number; decoded: number; failed: number } }).__raeaSound ?? null,
}))) as { canvas: boolean; parts: number; page: number; events: unknown[]; sound: { events: number; clips: number; decoded: number; failed: number } | null };
// a game on raea/ecs: the calls Bevy's world (the page's wasm) answered (PA12)
ecs: (globalThis as { __raeaEcsStats?: { calls: number; bytes: number } }).__raeaEcsStats ?? null,
}))) as { canvas: boolean; parts: number; page: number; events: unknown[]; sound: { events: number; clips: number; decoded: number; failed: number } | null; ecs: { calls: number; bytes: number } | null };
console.log(`page: ${JSON.stringify(state)}`);
if (!state.page && !state.parts) problems.push("nothing drew: the game's page is empty");
if (more > 0 && !JSON.stringify(state.events).includes("install")) problems.push("the end card was tapped but no install event came back");
+1 -1
View File
@@ -1,6 +1,6 @@
// Bevy's TonyMcMapface tone-mapping table for the playable host (docs/playables.feature PA10): bevy_core_pipeline's
// tony_mc_mapface.ktx2 (48³, E5B9G9R9 floats, zstd; MIT, Tomasz Stachowiak) resampled to N³ and stored as sRGB-encoded
// RGB bytes, which host/tonemap.ts samples as Bevy's tonemapping.wesl does.
// RGB bytes, which host/bevy.ts's tone pass samples as Bevy's tonemapping.wesl does.
// `bun tools/tony.ts N OUT.bin` (N = 48 keeps Bevy's own size).
import { readdirSync } from "node:fs";
import { homedir } from "node:os";
+12
View File
@@ -16,6 +16,18 @@ export const GEOMETRY: Record<string, (a: number[]) => THREE.BufferGeometry> = {
Ring: (a) => new THREE.RingGeometry(a[0] ?? 0.5, a[1] ?? 1, 48),
};
/** A Plane3d's one face (its Mesh's data-shape "plane(nx, ny, nz, w, h)"), as Bevy's PlaneMeshBuilder makes it: the +Y
* plane, w along x and h along -z, turned to its normal by the shortest arc. Its Box child (a box with no depth, for
* three's sake) would face both ways, and three's BoxGeometry points a flat side's normal down */
export function planeOf(kind: string, el: Element): THREE.BufferGeometry | undefined {
const m = kind === "Box" ? /^plane\(([^)]*)\)$/.exec(el.parentElement?.getAttribute("data-shape") ?? "") : null;
if (!m) return undefined;
const [nx, ny, nz, w, h] = m[1].split(",").map(Number);
const g = new THREE.PlaneGeometry(w, h).rotateX(-Math.PI / 2);
const n = new THREE.Vector3(nx, ny, nz).normalize();
return g.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), n));
}
interface BufferSpec {
positions: number[];
indices?: number[];
+2 -2
View File
@@ -8,7 +8,7 @@ import { HDRLoader } from "three/examples/jsm/loaders/HDRLoader.js";
import type { Sky } from "three/examples/jsm/objects/Sky.js";
import { paintLook, paintTone } from "./paint";
import { fire, flat, grass, placeFlat, plateTexture, richText, screenCard, sky, splatPoints } from "./extras";
import { GEOMETRY, geometryOfShape, shapesReady } from "./geometry";
import { GEOMETRY, geometryOfShape, planeOf, shapesReady } from "./geometry";
import { KINDS, PRIMITIVES } from "./kinds";
import { TONE, fitCamera, makeLight, setCamera, setLight, vec } from "./lights";
import { MATERIAL, paint, texture, vertexColoured } from "./materials";
@@ -390,7 +390,7 @@ export class Scene3d {
const mesh = owner?.obj instanceof THREE.Mesh ? owner.obj : undefined;
if (mesh) {
k.geometry?.dispose();
k.geometry = GEOMETRY[kind](Array.isArray(p.args) ? (p.args as number[]) : []);
k.geometry = planeOf(kind, el) ?? GEOMETRY[kind](Array.isArray(p.args) ? (p.args as number[]) : []);
mesh.geometry = k.geometry;
}
return k;
+24
View File
@@ -0,0 +1,24 @@
// raea/ecs on a playable's Bevy world (docs/playables.feature PA12): the world the page carries as wasm (sdk/playable
// host/ecs.ts, runtime/ecs built by sdk/playable/ecs/build.sh) answers a world's life as raea/ecs's TypeScript tables
// do: spawns, queries, columns, parents, scene(), resources, events, copies stepped on their own and at(frame).
// Each run is its own process, so the page's bridge never reaches another test.
import { expect, test } from "bun:test";
import { join } from "node:path";
const run = (wasm: boolean) => {
const r = Bun.spawnSync([process.execPath, join(import.meta.dir, "ecs-wasm/run.ts")], { env: { ...process.env, WASM: wasm ? "1" : "0" }, stderr: "pipe" });
expect(r.stderr.toString()).not.toMatch(/didn't load|Error/);
expect(r.exitCode).toBe(0);
return JSON.parse(r.stdout.toString()) as Record<string, unknown>;
};
test("a playable's Bevy world (wasm) and raea/ecs's TypeScript tables live the same life", () => {
const bevy = run(true);
const ts = run(false);
expect(bevy.native).toBe(true);
expect(ts.native).toBe(false);
const { native: _a, ...b } = bevy;
const { native: _b, ...t } = ts;
expect(b).toEqual(t);
expect(b.after).toEqual({ score: 12, stars: 0, first: 12, caught: 12, basket: { id: expect.any(Number), kind: "basket", x: 0 } });
});
+44
View File
@@ -0,0 +1,44 @@
// One world's life, printed as JSON: on a playable's Bevy world (the page's ecs.wasm, loaded as its host loads it)
// when run with WASM=1, else on raea/ecs's TypeScript tables. ecs-wasm.test.ts runs it both ways and compares.
import { readFileSync } from "node:fs";
import { join } from "node:path";
if (process.env.WASM === "1") {
(globalThis as { __raeaEcsWasm?: string }).__raeaEcsWasm = readFileSync(join(import.meta.dir, "../../../playable/src/host/ecs.wasm")).toString("base64");
await import("../../../playable/src/host/ecs.ts");
}
const { createWorld } = await import("raea/ecs");
const w = createWorld();
const out: Record<string, unknown> = { native: w.native };
for (let i = 0; i < 12; i++) w.spawn("star", { x: i - 6, y: 10 + (i % 3), side: i % 2 ? "odd" : "even" });
const basket = w.spawn("basket", { x: 0 });
w.resource("score", 0);
w.system((world, f) => {
for (const id of world.query("star")) {
const y = (world.get(id).y as number) - 1;
if (y < 0) {
world.despawn(id);
world.resource("score", (world.resource<number>("score") ?? 0) + 1);
world.send("caught", { id, f });
} else world.set(id, { y });
}
});
out.query = w.query("star", [["side", "==", "odd"], ["x", ">", -3]]);
out.column = w.column("star", "y");
const parent = w.add({ Transform: { x: 1, y: 0, z: 0 }, Mesh: { shape: "box" } });
const child = w.add({ Transform: { x: 0, y: 2, z: 0 }, Mesh: { shape: "ball" } }, { parent });
out.children = w.children(parent).length === 1 && w.parent(child) === parent;
out.find = w.find({ with: ["Mesh"], where: [["Transform.y", ">", 1]] }).length;
out.scene = w.scene();
// a game's next state: copied, stepped on its own, the first left as it was
let s = w;
const caught: unknown[] = [];
for (let f = 0; f < 14; f++) {
s = s.copy();
s.step(f);
caught.push(...s.events("caught"));
}
out.after = { score: s.resource("score"), stars: s.count("star"), first: w.count("star"), caught: caught.length, basket: s.get(basket) };
out.at = w.at(11).resource("score");
console.log(JSON.stringify(out));
File diff suppressed because it is too large. Load diff
+23 -2
View File
@@ -1,5 +1,4 @@
// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.
import type { Beat } from "./brief.gen";
export type Goal = { kind: GoalKind,
/**
@@ -233,7 +232,29 @@ text?: string, formats?: Array<string>, seconds?: [number, number],
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
* before the cut (Murch: emotion and story weigh most), and its pace
*/
beats?: Array<Beat>, };
beats?: Array<CutBeat>, };
export type CutBeat = {
/**
* where it starts, in seconds from the cut's start (0 for the first)
*/
at: number,
/**
* what the viewer feels here, in the person's words ("the itch of a chore left undone")
*/
feel: string,
/**
* what the viewer understands by its end ("the app does the reminding")
*/
story?: string,
/**
* its average shot length in seconds: the shots inside it average within a third of this
*/
asl?: number,
/**
* how its shot lengths move: "build" (shorter as it goes), "release" (longer) or "hold" (even)
*/
tempo?: string, };
export type Phrase = {
/**
+1 -1
Submodule skills updated: a2481c23ef...6c71231e97.
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more